public void ObtainAndRecycle() { object expected = null; Action<object> initialize = s => { Assert.IsNotNull(s); if (expected != null) Assert.AreSame(expected, s); }; Action<object> uninitialize = s => { Assert.IsNotNull(s); if (expected != null) Assert.AreSame(expected, s); }; var resourcePool = new ResourcePool<object>(() => new object(), initialize, uninitialize); object item1 = resourcePool.Obtain(); Assert.IsNotNull(item1); object item2 = resourcePool.Obtain(); expected = item2; resourcePool.Recycle(item2); object item3 = resourcePool.Obtain(); Assert.AreEqual(item2, item3); }
public async override Task Load(ResourcePool pool, CancellationToken token) { buffer = await pool.GetBuffer(); var loader = new SpriteLoader(BufferUsageHint.DynamicDraw, buffer); tileSet.LoadTileMap(loader, mapIndices, depth); sprites = loader.Load(); }
public CollisionManager() { _listPool = new ResourcePool<List<ICollidable>>(); _candidatePairs = new Dictionary<ICollidable, List<ICollidable>>(); _empty = new List<ICollidable>(); _sweep = new SelectiveSweep(); _sweep.Collision += CollisionHandler; }
public void NewElementCell_ShouldCreate() { var user = new User("User"); var newElement = new ResourcePool(user, "CMRP") .AddElement("Element"); var newField = newElement.AddField("Field", ElementFieldDataType.String); newElement.AddItem("Item").AddCell(newField); }
//simple singleton, has to actually be placed private void Awake() { if (_inst != null) { DestroyImmediate(this); } else { _inst = this; } }
/// <summary> /// Creates an instance of the <see cref="ArcSegment2F"/> class. (This method reuses a /// previously recycled instance or allocates a new instance if necessary.) /// </summary> /// <returns> /// A new or reusable instance of the <see cref="ArcSegment2F"/> class. /// </returns> /// <remarks> /// <para> /// This method tries to obtain a previously recycled instance from a resource pool if resource /// pooling is enabled (see <see cref="ResourcePool.Enabled">ResourcePool.Enabled</see>). If no /// object is available, a new instance is automatically allocated on the heap. /// </para> /// <para> /// The owner of the object should call <see cref="Recycle"/> when the instance is no longer /// needed. /// </para> /// </remarks> public static ArcSegment2F Create() { if (_pool == null) { _pool = new ResourcePool <ArcSegment2F>( () => new ArcSegment2F(), // Create null, // Initialize null); // Uninitialize } return(_pool.Obtain()); }
public void Add(Type type) { if (ResourcePool.IsPooledResource(type)) { Add(type, -1); if (m_MyTypes.IndexOf(typeof(CommodityDeed)) == -1) { Add(typeof(CommodityDeed), 0); } } }
public static AllocationCapabilities GetAllocationCapabilities(ResourcePool ResourcePool) { // TODO: refactor this for general usage return (ElementCapabilities.GetInstances() .Cast <ElementCapabilities>() .Where((ec) => string.Compare(ec.ManagedElement.Path, ResourcePool.Path.Path, true, CultureInfo.InvariantCulture) == 0) .Select((ec) => new AllocationCapabilities(ec.Capabilities)) .ToList() .First()); }
public void Preparation() { container = MockHelper.InitializeContainer(new[] { typeof(IProjectionsCollector).Assembly, typeof(Element).Assembly }, new Type[0]); var pool = new ResourcePool(); var writer = new TestWriter(); container.ComposeExportedValue(container); container.ComposeExportedValue(pool); container.ComposeExportedValue(writer); container.GetExportedValue <ICacheServicing>().Initialize(); }
public static T GetOrCreate <T>(this ResourcePool <T> pool) where T : new() { T instance = pool.Get(); if (instance == null) { instance = new T(); } return(instance); }
public Level1Activator() { container = MockHelper.InitializeContainer(AssembliesWhichShouldProvideExport, ExportedTypes); var pool = new ResourcePool(); container.ComposeExportedValue(pool); container.ComposeExportedValue(container); Transporter = container.GetExportedValue <TransporterToLevel2>(); Transporter._activator = this; container.GetExportedValue <ICacheServicing>().Initialize(); }
public void ResourceHandle_should_return_instance_to_pool_upon_disposal_even_if_not_fully_obtained() { using (var pool = new ResourcePool <IDisposable>(new InstanceHolder().CreateInstance, 1)) { using (var handle = pool.CreateHandle()) { var _ = handle.ObtainAsync(); } using (var handle2 = pool.CreateHandle()) Assert.DoesNotThrowAsync(() => handle2.ObtainAsync(new CancellationTokenSource(1000).Token)); } }
public void NewUserElementFieldIndex_ShouldCreate() { var user = new User("User", "*****@*****.**"); var resourcePool = new ResourcePool(user, "CMRP"); resourcePool .AddElement("Element") .AddField("Field", ElementFieldDataType.Decimal, true) .EnableIndex() .AddUserRating(0); }
void SetupPools() { var totalTilesInWorld = (int)(Settings.GetWorldSize().x *Settings.GetWorldSize().y); GroundTilePool = new ResourcePool(totalTilesInWorld, GroundTile); EndpointTilePool = new ResourcePool(Settings.GetNumberOfConsumers() + Settings.GetNumberOfProducers(), EndpointTile); ConsumerPool = new ResourcePool(Settings.GetNumberOfConsumers(), ConsumerBuilding); ProducerPool = new ResourcePool(Settings.GetNumberOfProducers(), ProducerBuilding); VehiclePool = new ResourcePool(Settings.GetNumberOfVehicles(), Vehicle); }
/*public*/ void IStateClientManager.ConfigInit(SessionStateSectionHandler.Config config, SessionOnEndTarget onEndTarget) { int hr; try { /* * stateConnection string has the following format: * * "tcpip=<server>:<port>" */ string [] parts = config._stateConnectionString.Split(new char[] { '=' }); if (parts.Length != 2 || parts[0] != "tcpip") { throw new ArgumentException(); } parts = parts[1].Split(new char[] { ':' }); if (parts.Length != 2) { throw new ArgumentException(); } s_server = parts[0]; s_port = (int)System.UInt16.Parse(parts[1]); s_networkTimeout = config._stateNetworkTimeout; // At v1, we won't accept server name that has non-ascii characters foreach (char c in s_server) { if (c > 0x7F) { throw new ArgumentException(); } } } catch { throw new ConfigurationException( HttpRuntime.FormatResourceString(SR.Invalid_value_for_sessionstate_stateConnectionString, config._stateConnectionString), config._configFileName, config._stateLine); } string appId = HttpRuntime.AppDomainAppIdInternal; string idHash = MachineKey.HashAndBase64EncodeString(appId); s_uribase = "/" + appId + "(" + idHash + ")/"; s_rpool = new ResourcePool(new TimeSpan(0, 0, 5), int.MaxValue); hr = UnsafeNativeMethods.SessionNDConnectToService(s_server); if (hr != 0) { throw new HttpException(HttpRuntime.FormatResourceString(SR.Cant_connect_to_session_service), hr); } }
public RendererWithResourcePool(Func <ITemplateRenderer> creater, int maxParallelism) { _rendererPool = ResourcePool.Create(creater, maxParallelism); using var lease = _rendererPool.Rent(); var inner = lease.Resource; Raw = inner.Raw; Dependencies = inner.Dependencies; Path = inner.Path; Name = inner.Name; }
public Level(ICore core) { if (core == null) { throw new ArgumentNullException(nameof(core)); } _core = core; _core.Layers.Reset(NonNullList.Of(0)); _core.ActivateActions(); _resourcePool = new ResourcePool(); }
public async Task DuplicateClientsAreTheSameObject() { var capacity = 2; var context = new Context(TestGlobal.Logger); var pool = new ResourcePool <Key, Resource>(context, maxResourceCount: capacity, maxAgeMinutes: 1, resourceFactory: _ => new Resource()); using var obj0 = await pool.CreateAsync(new Key (0)); using var obj1 = await pool.CreateAsync(new Key (0)); Assert.Same(obj0.Value, obj1.Value); }
public Machine(Simulation env, string name, MachineBrands brand, ResourcePool repairman) : base(env) { Brand = brand; Name = name; PartsMade = 0; Broken = false; // Start "working" and "break_machine" processes for this machine. Process = env.Process(Working(repairman)); env.Process(BreakMachine()); }
public BlockingStream() { pool = new ResourcePool<ReusableMemoryStream>(chunksInPool, () => new ReusableMemoryStream(chunkSize)); chunks = new Queue<IReleasable<ReusableMemoryStream>>(); doneWriting = new ManualResetEvent(false); dataAvailable = new ManualResetEvent(false); events = new WaitHandle[] { dataAvailable, doneWriting }; doneWritingHandleIndex = Array.FindIndex(events, handle => handle == doneWriting); lockForAll = new object(); lockForRead = new object(); canWrite = true; }
public void NewUserElementFieldIndex_ShouldCreate() { var user = new User("Email"); var resourcePool = new ResourcePool(user, "CMRP"); var newIndex = resourcePool .AddElement("Element") .AddField("Field", ElementFieldDataType.Boolean, true) .EnableIndex(ElementFieldIndexSortType.HighestToLowest) .AddUserRating(user, 0); }
public static bool PutIfType <T>(this ResourcePool <T> pool, object item) { if (item is T) { pool.Put((T)item); return(true); } else { return(false); } }
protected override void Awake() { base.Awake(); cube = ResourcePool.RentDisplay <RoundedPlaneResource>(transform); cube.Radius = 3f; cube.Layer = LayerType.IgnoreRaycast; cube.ShadowsEnabled = false; cube.Metallic = 1f; cube.Smoothness = 1f; //BackgroundColor = Color.blue; //CaptionColor = Color.white; }
public void NewUserElementFieldIndex_ShouldCreate() { var user = new User("User", "*****@*****.**"); var resourcePool = new ResourcePool(user, "CMRP"); var newIndex = resourcePool .AddElement("Element") .AddField("Field", ElementFieldDataType.Boolean, true) .EnableIndex(ElementFieldIndexSortType.HighestToLowest) .AddUserRating(0); }
public void Get_resource_from_resource_pool() { var resource1 = new Resource("Resource1"); var avaliable = new List <Resource>() { resource1 }; var respurcePool = new ResourcePool(null, avaliable); respurcePool.GetResource("Resource1"); Assert.Equal(1, respurcePool.GetAllocatedResourceCount()); }
public GenericBuyInfo(Type type) { if (!ResourcePool.IsPooledResource(type)) { throw new Exception(type.FullName + " is not a pooled resource."); } m_Type = type; // will load all props dynamically from ResourcePool m_MinAmount = 20; m_MaxAmount = 100; m_Amount = restock_amount = 20; }
public ActionResult ExportTable(string tableBodyJson) { return(ActionUtils.Json(() => { var table = tableBodyJson.ToDataTable(); var ms = ExcelUtils.ToExcelMemoryStream(table, "TaskTable.xlsx", CurrentUserName); var resource = ResourcePool.RegisterMemoryStream(CurrentUserName, "TaskTable.xlsx", ms); return ActionUtils.Success(resource.Guid); })); }
private static Task _Load(Scene scene, ResourcePool pool) { PendingScene pendingScene; lock (loadedScenes) { if (loadedScenes.TryGetValue(scene, out pendingScene)) { return pendingScene.task; } else { return (loadedScenes[scene] = new PendingScene(scene, pool)).task; } } }
/// <summary> /// TheadSafe and no locks internally /// </summary> /// <param name="key"></param> /// <param name="eventType">Should contain one type i.e. should not be used as a flag. /// Every EventType should be executed from another thread</param> /// <param name="item"></param> /// <param name="oldItem"></param> /// <param name="reason"></param> /// <param name="notifyAsync"></param> internal void RaiseGeneralCacheNotification(string key, EventType eventType, EventCacheItem item, EventCacheItem oldItem, CacheItemRemovedReason reason, bool notifyAsync) { try { object[] registeredDiscriptors = null; ResourcePool eventPool = GetEventPool(eventType); if (eventPool != null) { registeredDiscriptors = eventPool.GetAllResourceKeys(); } if (registeredDiscriptors != null && registeredDiscriptors.Length > 0) { for (int i = 0; i < registeredDiscriptors.Length; i++) { CacheEventDescriptor discriptor = registeredDiscriptors[i] as CacheEventDescriptor; if (discriptor == null) { continue; } var arg = CreateCacheEventArgument(discriptor.DataFilter, key, _cacheName, eventType, item, oldItem, reason); arg.Descriptor = discriptor; if (notifyAsync) { #if !NETCORE discriptor.CacheDataNotificationCallback.BeginInvoke(key, arg, asyn, null); #elif NETCORE TaskFactory factory = new TaskFactory(); Task task = factory.StartNew(() => discriptor.CacheDataNotificationCallback(key, arg)); #endif } else { discriptor.CacheDataNotificationCallback.Invoke(key, arg); } } } } catch (Exception ex) { if (_logger != null && _logger.IsErrorEnabled) { _logger.CriticalInfo(ex.ToString()); } } }
/// <summary> /// TheadSafe and no locks internally /// </summary> /// <param name="key"></param> /// <param name="eventType">Should contain one type i.e. should not be used as a flag. /// Every EventType should be executed from another thread</param> /// <param name="item"></param> /// <param name="oldItem"></param> /// <param name="reason"></param> /// <param name="_notifyAsync"></param> /// <param name="eventhandle"></param> internal void RaiseSelectiveCacheNotification(string key, EventType eventType, EventCacheItem item, EventCacheItem oldItem, CacheItemRemovedReason reason, bool _notifyAsync, EventHandle eventhandle, EventDataFilter dataFilter) { try { ResourcePool poolID = null; CacheEventArg arg = null; if ((eventType & EventType.ItemUpdated) != 0) { poolID = _selectiveUpdateEventIDPool; } else if ((eventType & EventType.ItemRemoved) != 0) { poolID = _selectiveRemoveEventIDPool; } arg = CreateCacheEventArgument(dataFilter, key, _cacheName, eventType, item, oldItem, reason); if (poolID == null) { return; } CacheDataNotificationCallback callback = poolID.GetResource((short)eventhandle.Handle) as CacheDataNotificationCallback; if (callback == null) { return; } if (_notifyAsync) { System.Threading.ThreadPool.QueueUserWorkItem(waitC, new object[] { callback, key, arg }); } else { callback.Invoke(key, arg); } } catch (Exception ex) { if (_logger != null && _logger.IsErrorEnabled) { _logger.CriticalInfo(ex.ToString()); } } }
public TMXLoader(IBindableVertexBuffer buffer, ResourcePool pool, string fileName) : base(BufferUsageHint.DynamicDraw, buffer) { textures = new Dictionary<int,Texture>(); this.pool = pool; Layers = new Dictionary<string, IEnumerable<Sprite>>(); _lazyTileMap = new Lazy<TiledMap>( () => (new TiledReader()).Read(fileName)); _lazyLayers = new Lazy<Dictionary<string, TiledLayer>>( () => TileMap.Layers.ToDictionary(ts => ts.Name, ts => ts)); }
public void AddField_SortOrder_ShouldCalculate() { // Arrange var user = new User("User", "*****@*****.**"); var element = new ResourcePool(user, "CMRP") .AddElement("Element"); // Act var secondField = element.AddField("Second field after default Name field", ElementFieldDataType.String); // Assert Assert.IsTrue(secondField.SortOrder == 2); }
public async Task CreateFailsAfterDispose() { var capacity = 2; var context = new Context(TestGlobal.Logger); var pool = new ResourcePool <Key, Resource>(context, maxResourceCount: capacity, maxAgeMinutes: 1, resourceFactory: _ => new Resource()); pool.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(async() => { using var obj1 = await pool.CreateAsync(new Key(0)); }); }
public void TestPoolThrowsExceptionIfResourcesInUse() { var resources = 0; var factoryMock = new Mock <IStringFactory>(); factoryMock.Setup(x => x.GetString()) .Returns(() => resources++ < 5 ? Guid.NewGuid().ToString() : null); var pool = new ResourcePool <string>(x => factoryMock.Object.GetString()); var item = pool.GetItem(); Assert.Throws <InvalidOperationException>(() => pool.Dispose()); }
private void InitializeBulletResourcePool() { pool = new ResourcePool(bullet, poolSize); string bulletsContainerName = "Bullets"; bulletObjContainer = GameObject.Find(bulletsContainerName); if (bulletObjContainer == null) { bulletObjContainer = new GameObject(bulletsContainerName); } }
public async Task Pool_should_accept_preset_instances_and_allow_controlling_their_disposal(bool shouldDispose) { var holder = new InstanceHolder(); var instances = Enumerable.Range(0, 5).Select(x => holder.CreateInstance()).ToArray(); using (var pool = new ResourcePool <IDisposable>(instances, shouldDispose)) await RunTasks(pool, instances.Length * 3); foreach (var instance in holder.Instances) { instance.Verify(x => x.Dispose(), Times.Exactly(shouldDispose ? 1 : 0)); } }
public void AddField_SortOrder_ShouldCalculate() { // Arrange var user = new User("User"); var element = new ResourcePool(user, "CMRP") .AddElement("Element"); // Act var secondField = element.AddField("Second field after default Name field", ElementFieldDataType.String); // Assert Assert.IsTrue(secondField.SortOrder == 2); }
void UpdateElementFieldComputedFields(ResourcePool resourcePool) { var list = ElementFieldStore.AllLiveIncluding(field => field.UserElementFieldSet) .Where(field => field.Element.ResourcePool.Id == resourcePool.Id && field.IndexEnabled) .AsEnumerable(); foreach (var field in list) { field.IndexRatingTotal = field.UserElementFieldSet.Sum(userElementField => userElementField.Rating); field.IndexRatingCount = field.UserElementFieldSet.Count(); } }
public void CreatePool(AssetID id, out IPool pool) { //IPool pool = null; pool = new ResourcePool(id); //赋值策略 //TODO 通过资源管理器加载后赋值 并加入到总池 这里不回调 //Debug.Log(id.AssetName); Debug.LogError("新建池子"); Object res = Resources.Load(id.AssetName) as Object; pool.Strategy = defaultStrategy; AddPool(pool, res); //return pool; }
public void NewUserElementCell_ShouldCreate() { var newUser = new User("Email"); var newElement = new ResourcePool(newUser, "CMRP") .AddElement("Element"); var newField = newElement.AddField("Field", ElementFieldDataType.Integer, false); newElement .AddItem("Item") .AddCell(newField) .SetValue(0); }
public static GameObject LoadResource(string resourceName) { if (resourcePools == null) { resourcePools = new Dictionary<string, ResourcePool>(); } ResourcePool rpool; if(!resourcePools.TryGetValue(resourceName,out rpool)) { rpool = new ResourcePool(resourceName); resourcePools.Add(resourceName, rpool); } return rpool.getResource(); }
public static void AddResourcePool(ResourcePool pool) { if (_resourcePools == null) _resourcePools = new Dictionary<GameObject, ResourcePool>(); _resourcePools.Add(pool.Prefab, pool); }
public MatchMaker(int maxPoolItemReuse) { replies = new Dictionary<short, ReplyBucket>(32); idPool = new ResourcePool<short>(new ResourcePool<short>.BuildItemDelegate(GetNextMessageId), maxPoolItemReuse); replyLock = new MsReaderWriterLock(System.Threading.LockRecursionPolicy.NoRecursion); }
public EntityCollisionManager() { _collidableMap = new Dictionary<Entity, ICollidable>(); _entityMap = new Dictionary<ICollidable, Entity>(); _listPool = new ResourcePool<List<Entity>>(); _candidatePairs = new Dictionary<Entity, List<Entity>>(); _empty = new List<Entity>(); _sweep = new SelectiveSweep(); _sweep.Collision += CollisionHandler; }
/* event handlers */ protected override void OnLoad(EventArgs e) { base.OnLoad(e); UseGraphicsMode(new Texturing2DMode()); var pool = new ResourcePool( new Pool<Texture>(Texture.Allocate), new Pool<VertexBuffer>(VertexBuffer.Allocate) ); rootState = new GameState(this, pool); Debug.Assert(mainWindow == null); mainWindow = this; }
public ResourcePool CreateDefaultResourcePool(User user, string resourcePoolName, bool useFixedResourcePoolRate, string mainElementName, bool addDirectIncomeField, bool addMultiplierField, bool addImportanceIndex, int numberOfItems) { // Resource pool, main element, fields var resourcePool = new ResourcePool(user, resourcePoolName); if (useFixedResourcePoolRate) { resourcePool.UseFixedResourcePoolRate = true; resourcePool.AddUserResourcePool(10); } // Main element var element = resourcePool.AddElement(mainElementName); element.IsMainElement = true; // Resource pool field if (addDirectIncomeField) element.AddField("Direct Income", ElementFieldDataType.DirectIncome, true); // Multiplier field if (addMultiplierField) element.AddField("Multiplier", ElementFieldDataType.Multiplier); // Importance field ElementField importanceField = null; if (addImportanceIndex) { importanceField = element.AddField("Importance Field", ElementFieldDataType.Decimal, false); importanceField.EnableIndex(); } // Items, cells, user cells for (var i = 1; i <= numberOfItems; i++) { var itemName = string.Format("Item {0}", i); var item = element.AddItem(itemName); if (addDirectIncomeField) item.AddCell(element.DirectIncomeField).SetValue(100M); // Default value if (addMultiplierField) item.AddCell(element.MultiplierField); if (addImportanceIndex) item.AddCell(importanceField); } // Return return resourcePool; }
public void OnInitialise(InitialiseMessage msg) { // Initialise scene manager Console.WriteLine("Initialising scene manager..."); // Initialise messages queuemsg = new PopulateRenderQueue(); queuemsg.SceneManager = this; cameramsg = new PopulateCameraList(); cameramsg.Cameras = new OrderedList<Camera>(new CameraComparer()); cameramsg.ShadowCasters = new HashSet<ShadowCaster>(); lightmsg = new PopulateLightList(); lightmsg.Lights = new OrderedList<Light>(new LightComparer()); psysmsg = new PopulateParticleSystemList(); psysmsg.ParticleSystems = new List<ParticleSystem>(); // Create render queue workitempool = new ResourcePool<RenderWorkItem>(); renderqueue = new OrderedList<RenderWorkItem>(new RenderWorkItemComparer()); effectqueue = new OrderedList<PostProcessEffect>(new PostProcessEffectComparer()); // Setup GBuffer Renderer renderer = Owner.GetComponent<Renderer>(); gbuffer = renderer.CreateRenderTarget(1, "GBuffer"); gbuffer.ClearColour = new Color4(0.0f, 0.0f, 0.0f, 0.0f); gbuffer.AddDepthComponent(); gbuffer_colour = gbuffer.AddTextureComponent(); gbuffer_normal = gbuffer.AddTextureComponent(SlimDX.DXGI.Format.R32G32B32A32_Float); gbuffer_position = gbuffer.AddTextureComponent(SlimDX.DXGI.Format.R32G32B32A32_Float); gbuffer_material = gbuffer.AddTextureComponent(SlimDX.DXGI.Format.R32G32B32A32_Float); gbuffer.Finish(); // Setup light accumulation buffer lightaccum = renderer.CreateRenderTarget(1, "LightAccum"); lightaccum.ClearColour = new Color4(1.0f, 0.0f, 0.0f, 0.0f); lightaccum_diffuse = lightaccum.AddTextureComponent(SlimDX.DXGI.Format.R32G32B32A32_Float); lightaccum_specular = lightaccum.AddTextureComponent(SlimDX.DXGI.Format.R32G32B32A32_Float); lightaccum.Finish(); // Setup particle accumulation buffer particleaccum = renderer.CreateRenderTarget(1, "ParticleAccum"); particleaccum.ClearColour = new Color4(0.0f, 0.0f, 0.0f, 0.0f); particleaccum_colour = particleaccum.AddTextureComponent(); particleaccum.Finish(); // Setup swap buffers swapA = renderer.CreateRenderTarget(1, "SwapA"); swapA_colour = swapA.AddTextureComponent(); swapA.Finish(); swapB = renderer.CreateRenderTarget(1, "SwapB"); swapB_colour = swapB.AddTextureComponent(); swapB.Finish(); // Setup materials MaterialSystem matsys = Owner.GetComponent<MaterialSystem>(); mat_blit = matsys.CreateMaterial("blit", "blit"); mat_blit.SetParameter("smpTexture", renderer.Sampler_Clamp); mat_blitlight = matsys.CreateMaterial("blit_light", "blit_light"); mat_blitlight.SetParameter("smpTexture", renderer.Sampler_Clamp); mat_blitlight.SetParameter("texColour", gbuffer.GetTexture(gbuffer_colour)); mat_blitlight.SetParameter("texDiffuseLight", lightaccum.GetTexture(lightaccum_diffuse)); mat_blitlight.SetParameter("texSpecularLight", lightaccum.GetTexture(lightaccum_specular)); // Setup lights mat_lights = new Dictionary<LightType, Material>(); mat_lights.Add(LightType.Ambient, matsys.CreateMaterial("light_ambient", "light_ambient")); mat_lights.Add(LightType.Directional, matsys.CreateMaterial("light_directional", "light_directional")); mat_lights.Add(LightType.Point, matsys.CreateMaterial("light_point", "light_point")); foreach (Material mat in mat_lights.Values) { mat.SetParameter("texNormal", gbuffer.GetTexture(gbuffer_normal)); mat.SetParameter("texPosition", gbuffer.GetTexture(gbuffer_position)); mat.SetParameter("texMaterial", gbuffer.GetTexture(gbuffer_material)); mat.SetParameter("smpTexture", renderer.Sampler_Clamp); } // Setup meshes mesh_fs = MeshBuilder.BuildFullscreenQuad(); mesh_skybox = MeshBuilder.BuildCube(); }
public void ShouldBeRegistered() { var resourcePool = new ResourcePool<object>(() => new object(), null, null); Assert.IsTrue(ResourcePool.Pools.Contains(resourcePool)); }
public static Task Load(Scene scene, ResourcePool pool) { return Task.Run(() => _Load(scene, pool).Wait()); }
public void ConstructorShouldThrowWhenNull() { var resourcePool = new ResourcePool<object>(null, null, null); }
public override Task Load(ResourcePool pool, CancellationToken token) { return Task.WhenAll(scenes.Select((scene) => scene.Load(pool, token))); }
public PendingScene(Scene s, ResourcePool p) { pool = p.Copy(); task = s.Load(pool, cancelSource.Token); }
/// <summary> /// Start listening for connections. /// </summary> /// <param name="connectionWhiteList">An optional <see cref="ConnectionWhitelist"/> /// used to evaluate whether incoming and existing connections are /// whitelisted.</param> public void Start(ConnectionWhitelist connectionWhiteList) { if (isRunning) { if (log.IsWarnEnabled) log.Warn("Attempt to start already running socket server on port " + this.portNumber); return; } this.connectionWhitelist = connectionWhiteList; InitializeCounters(); GetConfig(); if (log.IsInfoEnabled) log.InfoFormat("Using a memory stream pool with an initial size of {0} bytes, reusing buffers {1} times. Reusing connectionstates {2} times. Using {3} sync threads and {4} one way threads", config.InitialMessageSize, config.BufferPoolReuses, config.ConnectionStateReuses, SyncThreads, OnewayThreads); bufferPool = new MemoryStreamPool(config.InitialMessageSize, config.BufferPoolReuses); if (countersInitialized) { bufferPool.AllocatedItemsCounter = this.allocatedBuffers; } buildConnectionStateDelegate = new ResourcePool<ConnectionState>.BuildItemDelegate(BuildConnectionState); resetConnectionStateDelegate = new ResourcePool<ConnectionState>.ResetItemDelegate(ResetConnectionState); connectionStatePool = new ResourcePool<ConnectionState>(buildConnectionStateDelegate, resetConnectionStateDelegate); connectionStatePool.MaxItemReuses = config.ConnectionStateReuses; listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connections = new ConnectionList(socketCountCounter); connectionCheckInterval = config.ConnectionCheckIntervalSeconds * 1000; connectionWatcher = new Timer(new TimerCallback(CheckConnections), null, connectionCheckInterval, connectionCheckInterval); int currentWorker, currentCompletion, oldWorker, oldCompletion; ThreadPool.GetAvailableThreads(out currentWorker, out currentCompletion); oldWorker = currentWorker; oldCompletion= currentCompletion; if (config.MaximumWorkerThreads > 0) currentWorker = config.MaximumWorkerThreads; if (config.MaximumCompletionPortThreads > 0) currentCompletion = config.MaximumCompletionPortThreads; bool maxSet = ThreadPool.SetMaxThreads(currentWorker, currentCompletion); if (config.MaximumWorkerThreads > 0 || config.MaximumCompletionPortThreads > 0) { if (maxSet == false) { if (log.IsWarnEnabled) { log.WarnFormat("FAILED to change max ThreadPool threads from ({0}worker/{1}completion) to ({2}worker/{3}completion)", oldWorker, oldCompletion, currentWorker, currentCompletion); } } else { if (log.IsInfoEnabled) log.InfoFormat("Successfully changed max ThreadPool threads from ({0}worker/{1}completion) to ({2}worker/{3}completion)", oldWorker, oldCompletion, currentWorker, currentCompletion); } } //kick off CCR OnewayDispatcher = new Dispatcher(OnewayThreads, ThreadPriority.Normal, true, "Socket Server OneWay:" + portNumber.ToString()); SyncDispatcher = new Dispatcher(SyncThreads, ThreadPriority.AboveNormal, true, "Socket Server Sync:" + portNumber.ToString()); OnewayMessageQueue = new DispatcherQueue("Socket Server " + portNumber.ToString() + " one way", OnewayDispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, config.OnewayQueueDepth); SyncMessageQueue = new DispatcherQueue("Socket Server " + portNumber.ToString() + " sync", SyncDispatcher, TaskExecutionPolicy.ConstrainQueueDepthThrottleExecution, config.SyncQueueDepth); Arbiter.Activate(OnewayMessageQueue, Arbiter.Receive<ProcessState>(true, OnewayMessagePort, delegate(ProcessState state) { ProcessCall(state); })); Arbiter.Activate(SyncMessageQueue, Arbiter.Receive<ProcessState>(true, SyncMessagePort, delegate(ProcessState state) { ProcessCall(state); })); listener.Bind(new IPEndPoint(IPAddress.Any, this.portNumber)); listener.Listen(500); isRunning = true; listener.BeginAccept(acceptCallBack, listener); timerThread = new Thread(TimerStart); timerThread.IsBackground = true; timerThread.Start(); if (log.IsInfoEnabled) log.Info("MySpace SocketTransport Server started on port " + this.portNumber); }
public void Update(DX11RenderContext context) { ResourcePool resourcePool; lock (FTexturePoolLock) { if (!FTexturePool.ContainsKey(context)) { resourcePool = new ResourcePool(context, FWidth, FHeight); FTexturePool.Add(context, resourcePool); } else { resourcePool = FTexturePool[context]; } Resource[context] = resourcePool.GetTexture(Index); } }
public void NewUserResourcePool_ShouldCreate() { var user = new User("Email"); var resourcePool = new ResourcePool(user, "CMRP") .AddUserResourcePool(user, 0); }
public abstract Task Load(ResourcePool pool, CancellationToken token);
//-------------------------------------------------------------- #region Creation & Cleanup //-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="Skeleton"/> class. /// </summary> /// <param name="boneParents"> /// The bone parents. This list contains one entry per bone. The list element is the /// parent bone index for each bone. If a bone has no parent, the array should contain -1. /// </param> /// <param name="boneNames"> /// The bone names. This list contains one entry per bone. The list element is the name /// of the bone or <see langword="null"/> if the bone is unnamed. /// </param> /// <param name="bindPosesRelative"> /// The bind poses. This list contains one entry per bone. The list element is the bone /// pose transformation relative to the parent bone. /// </param> /// <remarks> /// The bone data must be specified in lists. The index in the list is the bone index. The /// bones must be sorted so that parent bones come before their child bones. /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="boneParents"/>, <paramref name="boneNames"/> or /// <paramref name="bindPosesRelative"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// Either the given lists are empty, have different length, or the /// <paramref name="boneParents"/> are invalid (parent bones must come be before their child /// bones). /// </exception> public Skeleton(IList<int> boneParents, IList<string> boneNames, IList<SrtTransform> bindPosesRelative) { Initialize(boneParents, boneNames, bindPosesRelative); // If skeleton has been initialized successfully, create resource pools // used by SkeletonPoses. SkeletonPosePool = new ResourcePool<SkeletonPose>( () => new SkeletonPose(this), null, null); SkeletonBoneAccessorPool = new ResourcePool<SkeletonBoneAccessor>( () => new SkeletonBoneAccessor(), null, null); AnimatableBoneTransformsPool = new ResourcePool<AnimatableBoneTransform[]>( () => { var animatableBoneTransforms = new AnimatableBoneTransform[NumberOfBones]; for (int i = 0; i < animatableBoneTransforms.Length; i++) animatableBoneTransforms[i] = new AnimatableBoneTransform(i); return animatableBoneTransforms; }, null, null); }