public static float TotalWater(this ResourceCounter rc) { var num = 0.0f; foreach (var current in rc.AllCountedAmounts) { var compprop = (CompProperties_WaterSource)current.Key.comps?.Find(c => c.compClass == typeof(CompWaterSource)); if (compprop == null) { continue; } if (compprop.sourceType != CompProperties_WaterSource.SourceType.Item) { continue; } if (compprop.waterAmount > 0.0f) { num += compprop.waterAmount * current.Value; } } return(num); }
public static float TotalWater(this ResourceCounter rc) { float num = 0.0f; foreach (KeyValuePair <ThingDef, int> current in rc.AllCountedAmounts) { if (current.Key.comps == null) { continue; } var compprop = (CompProperties_WaterSource)current.Key.comps.Find((c) => c.compClass == typeof(CompWaterSource)); if (compprop == null) { continue; } if (compprop.sourceType != CompProperties_WaterSource.SourceType.Item) { continue; } if (compprop.waterAmount > 0.0f) { num += compprop.waterAmount * (float)current.Value; } } return(num); }
static void Postfix(ResourceCounter __instance) { if (countedAmountsFI == null) { countedAmountsFI = typeof(ResourceCounter).GetField("countedAmounts", BindingFlags.Instance | BindingFlags.NonPublic); } Dictionary <ThingDef, int> countedAmounts = (Dictionary <ThingDef, int>)countedAmountsFI.GetValue(__instance); foreach (Building_InfiniteStorage ts in WorldComp.GetInfiniteStorages(Find.CurrentMap)) { foreach (Thing thing in ts.StoredThings) { if (thing.def.EverStorable(true) && thing.def.CountAsResource && !thing.IsNotFresh()) { int count; if (countedAmounts.TryGetValue(thing.def, out count)) { count += thing.stackCount; } else { count = thing.stackCount; } countedAmounts[thing.def] = count; } } } }
public async Task ResetsCountWhenConnectionClosed() { var requestTcs = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var releasedTcs = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var lockedTcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously); var counter = new EventRaisingResourceCounter(ResourceCounter.Quota(1)); counter.OnLock += (s, e) => lockedTcs.TrySetResult(e); counter.OnRelease += (s, e) => releasedTcs.TrySetResult(null); using (var server = CreateServerWithMaxConnections(async context => { await context.Response.WriteAsync("Hello"); await requestTcs.Task; }, counter)) using (var connection = server.CreateConnection()) { await connection.SendEmptyGetAsKeepAlive();; await connection.Receive("HTTP/1.1 200 OK"); Assert.True(await lockedTcs.Task.DefaultTimeout()); requestTcs.TrySetResult(null); } await releasedTcs.Task.DefaultTimeout(); }
public static void Postfix(ResourceCounter __instance) { if (TickUtility.NoOverlapTickMod(204)) { __instance.UpdateResourceCounts(); } }
static void Postfix(ResourceCounter __instance, Dictionary <ThingDef, int> ___countedAmounts, Map ___map) { int i = 0; PRFGameComponent gamecomp = Current.Game.GetComponent <PRFGameComponent>(); for (i = 0; i < gamecomp.AssemblerQueue.Count; i++) { //Don't count Recorces of other maps if (gamecomp.AssemblerQueue[i].Map != ___map) { continue; } foreach (Thing heldThing in gamecomp.AssemblerQueue[i].GetThingQueue()) { Thing innerIfMinified = heldThing.GetInnerIfMinified(); //Added Should Count Checks //EverStorable is form HeldThings //Fresh Check is from ShouldCount (maybe we can hit that via harmony/reflection somhow) if (innerIfMinified.def.EverStorable(false) && !innerIfMinified.IsNotFresh()) { //Causes an error otherwise #345 (seems to be clothing that causes it) if (___countedAmounts.ContainsKey(innerIfMinified.def)) { ___countedAmounts[innerIfMinified.def] += innerIfMinified.stackCount; } } } } }
public void QuotaAcceptsUpToButNotMoreThanMax() { var counter = ResourceCounter.Quota(1); Assert.True(counter.TryLockOne()); Assert.False(counter.TryLockOne()); }
public void GivenEmptyResourceCounterThenShouldReturnZeroCountOnDecrement() { var resourceCounter = new ResourceCounter(); Assert.AreEqual(0, resourceCounter.Decrement(ID)); Assert.AreEqual(0, resourceCounter.Decrement(ID)); }
public void GivenMultipleIncrementThenEachDecrementShouldDecreaseTheCountToZero() { var resourceCounter = new ResourceCounter(); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); resourceCounter.Increment(ID); Assert.AreEqual(9, resourceCounter.Decrement(ID)); Assert.AreEqual(8, resourceCounter.Decrement(ID)); Assert.AreEqual(7, resourceCounter.Decrement(ID)); Assert.AreEqual(6, resourceCounter.Decrement(ID)); Assert.AreEqual(5, resourceCounter.Decrement(ID)); Assert.AreEqual(4, resourceCounter.Decrement(ID)); Assert.AreEqual(3, resourceCounter.Decrement(ID)); Assert.AreEqual(2, resourceCounter.Decrement(ID)); Assert.AreEqual(1, resourceCounter.Decrement(ID)); Assert.AreEqual(0, resourceCounter.Decrement(ID)); Assert.AreEqual(0, resourceCounter.Decrement(ID)); }
public static bool UpdateResourceCounts(ResourceCounter __instance) { lock (lockObject) { __instance.ResetResourceCounts(); Dictionary <ThingDef, int> newCountedAmounts = new Dictionary <ThingDef, int>(__instance.AllCountedAmounts); bool changed = false; List <SlotGroup> allGroupsListForReading = __instance.map.haulDestinationManager.AllGroupsListForReading; for (int i = 0; i < allGroupsListForReading.Count; i++) { foreach (Thing heldThing in allGroupsListForReading[i].HeldThings) { Thing innerIfMinified = heldThing.GetInnerIfMinified(); if (innerIfMinified.def.CountAsResource && !innerIfMinified.IsNotFresh()) { newCountedAmounts[innerIfMinified.def] += innerIfMinified.stackCount; changed = true; } } } if (changed) { __instance.countedAmounts = newCountedAmounts; } } return(false); }
static void ResourceCounterPostfix(ResourceCounter __instance) { Dictionary <ThingDef, int> countedAmounts = Traverse.Create(__instance).Field("countedAmounts").GetValue <Dictionary <ThingDef, int> >(); Map map = Traverse.Create(__instance).Field("map").GetValue <Map>(); try { map.listerBuildings.allBuildingsColonist.OfType <Building_MassStorageDevice>().ToList() .FindAll((Building_MassStorageDevice b) => b.internalStoredDef != null && b.ThingCount > 0) .ForEach((Building_MassStorageDevice storage) => { if (storage.internalStoredDef.CountAsResource) { countedAmounts[storage.internalStoredDef] += storage.ThingCount; } }); } catch (Exception ex) { Log.Error("SS Mass Storage caught exception while editing resource counts: " + ex.ToString()); } finally { Traverse.Create(__instance).Field("countedAmounts").SetValue(countedAmounts); } }
public void GivenOneIncrementAndOneDecrementThenShouldReturnZeroCountOnDecrement() { var resourceCounter = new ResourceCounter(); resourceCounter.Increment(ID); Assert.AreEqual(0, resourceCounter.Decrement(ID)); }
private (TestServiceContext serviceContext, EventRaisingResourceCounter counter) SetupMaxConnections(long max) { var counter = new EventRaisingResourceCounter(ResourceCounter.Quota(max)); var serviceContext = new TestServiceContext(); serviceContext.ConnectionManager = new FrameConnectionManager(serviceContext.Log, counter, ResourceCounter.Unlimited); return(serviceContext, counter); }
public DiskCache() { this.cacheDir = Path.Combine(Environment.GetEnvironmentVariable("TMP"), "mapcache\\"); this.stableFreshCountPathname = Path.Combine(this.cacheDir, "FreshCount.txt"); this.CreateCacheDirIfNeeded(); DebugThreadInterrupter.theInstance.AddThread("DiskCache.DeferredWriteThread", new ThreadStart(this.DeferredWriteThread), ThreadPriority.Normal); DebugThreadInterrupter.theInstance.AddThread("DiskCache.EvictThread", new ThreadStart(this.EvictThread), ThreadPriority.Normal); this.resourceCounter = DiagnosticUI.theDiagnostics.fetchResourceCounter("DiskCache", -1); }
// Loading ctor public FactionMapData(Map map) { this.map = map; haulDestinationManager = new HaulDestinationManager(map); listerHaulables = new ListerHaulables(map); resourceCounter = new ResourceCounter(map); listerFilthInHomeArea = new ListerFilthInHomeArea(map); }
static bool Prefix(ref ResourceCounter __instance) { if (Find.TickManager.TicksGame % 204 > RefcellRespeedConfig.currentTimeMultiplier - 1) { return(false); } __instance.UpdateResourceCounts(); return(false); }
static void Postfix() { if (SeedDef.AddMissingSeeds()) { ResourceCounter.ResetDefs(); Log.Warning("SeedsPlease :: Don't rely on autogenerated seeds, share the generated xml for proper support"); } }
public async Task ConnectionCountingReturnsToZero() { const int count = 100; var opened = 0; var closed = 0; var openedTcs = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var closedTcs = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously); var counter = new EventRaisingResourceCounter(ResourceCounter.Quota(uint.MaxValue)); counter.OnLock += (o, e) => { if (e && Interlocked.Increment(ref opened) >= count) { openedTcs.TrySetResult(null); } }; counter.OnRelease += (o, e) => { if (Interlocked.Increment(ref closed) >= count) { closedTcs.TrySetResult(null); } }; using (var server = CreateServerWithMaxConnections(_ => Task.CompletedTask, counter)) { // open a bunch of connections in parallel Parallel.For(0, count, async i => { try { using (var connection = server.CreateConnection()) { await connection.SendEmptyGetAsKeepAlive(); await connection.Receive("HTTP/1.1 200"); } } catch (Exception ex) { openedTcs.TrySetException(ex); } }); // wait until resource counter has called lock for each connection await openedTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); // wait until resource counter has released all normal connections await closedTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(120)); Assert.Equal(count, opened); Assert.Equal(count, closed); await server.StopAsync(); } }
public MainViewModel() { toast = new Toast(); Json = new Json(); ResourceCounter = new ResourceCounter(); Dispatch = Application.Current.Dispatcher; rulesList = Json.GetRulesListFromJson(); processList = new ObservableCollection <Proc>(); Start(); }
private static bool Prefix(ResourceCounter __instance, Map ___map) { try { var ZTracker = ZUtils.ZTracker; if (ZTracker.ZLevelsTracker.ContainsKey(___map.Tile)) { Dictionary <ThingDef, int> countedAllAmounts = new Dictionary <ThingDef, int>(); foreach (var map1 in ZTracker.ZLevelsTracker[___map.Tile].ZLevels.Values) { if (map1.resourceCounter != null) { map1.resourceCounter.ResetResourceCounts(); List <SlotGroup> allGroupsListForReading = map1.haulDestinationManager.AllGroupsListForReading; for (int i = 0; i < allGroupsListForReading.Count; i++) { foreach (Thing outerThing in allGroupsListForReading[i].HeldThings) { Thing innerIfMinified = outerThing.GetInnerIfMinified(); if (innerIfMinified.def.CountAsResource && !innerIfMinified.IsNotFresh()) { ThingDef def = innerIfMinified.def; if (countedAllAmounts.ContainsKey(def)) { countedAllAmounts[def] += innerIfMinified.stackCount; } else { countedAllAmounts[def] = innerIfMinified.stackCount; } } } } } } foreach (var map1 in ZTracker.ZLevelsTracker[___map.Tile].ZLevels.Values) { if (map1.resourceCounter != null) { foreach (var d in countedAllAmounts) { map1.resourceCounter.AllCountedAmounts[d.Key] = d.Value; } } } return(false); } } catch (Exception ex) { Log.Error("[Z-Levels] UpdateResourceCounts patch produced an error. That should not happen and will break things. Send a Hugslib log to the Z-Levels developers. Error message: " + ex, true); }; return(true); }
/// <summary> /// Generates the genomes. /// </summary> internal static void GenerateGenomes() { if (_allImplicitGenomes != null) { Log.Error("trying to generate genomes more then once!"); return; } _allImplicitGenomes = new List <ThingDef>(); var catDef = PMThingCategoryDefOf.PM_MutationGenome; catDef.childThingDefs = catDef?.childThingDefs ?? new List <ThingDef>(); foreach (MutationCategoryDef mDef in AllImplicitGenomeMutations) { ThingDef tDef = GenerateMutationGenome(mDef); mDef.implicitGenomeDef = tDef; _allImplicitGenomes.Add(tDef); } foreach (PawnKindDef pk in AllPKsWithGenomes) { ThingDef tDef = GenerateAnimalGenome(pk); _genomeDict[pk] = tDef; _allImplicitGenomes.Add(tDef); } foreach (ThingDef allImplicitGenome in _allImplicitGenomes) { try { Init(allImplicitGenome); DefDatabase <ThingDef> .Add(allImplicitGenome); catDef.childThingDefs.Add(allImplicitGenome); } catch (Exception e) { Log.Error($"could not initialize genome {allImplicitGenome.defName ?? "NO DEF NAME"}\n{e}"); } } if (DebugLogUtils.ShouldLog(LogLevel.Messages)) { var builder = new StringBuilder(); builder.Append($"Generated {_allImplicitGenomes.Count} genomes!:"); builder.AppendLine(_allImplicitGenomes.Join(t => t.defName, "\n")); Log.Message(builder.ToString()); } ResourceCounter.ResetDefs(); }
public async Task RejectsUpgradeWhenLimitReached() { const int limit = 10; var upgradeTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var serviceContext = new TestServiceContext(LoggerFactory); serviceContext.ConnectionManager = new ConnectionManager(serviceContext.Log, ResourceCounter.Quota(limit)); await using (var server = new TestServer(async context => { var feature = context.Features.Get <IHttpUpgradeFeature>(); if (feature.IsUpgradableRequest) { try { var stream = await feature.UpgradeAsync(); while (!context.RequestAborted.IsCancellationRequested) { await Task.Delay(100); } } catch (InvalidOperationException ex) { upgradeTcs.TrySetException(ex); } } }, serviceContext)) { using (var disposables = new DisposableStack <InMemoryConnection>()) { for (var i = 0; i < limit; i++) { var connection = server.CreateConnection(); disposables.Push(connection); await connection.SendEmptyGetWithUpgradeAndKeepAlive(); await connection.Receive("HTTP/1.1 101"); } using (var connection = server.CreateConnection()) { await connection.SendEmptyGetWithUpgradeAndKeepAlive(); await connection.Receive("HTTP/1.1 200"); } } } var exception = await Assert.ThrowsAsync <InvalidOperationException>(async() => await upgradeTcs.Task.TimeoutAfter(TimeSpan.FromSeconds(60))); Assert.Equal(CoreStrings.UpgradedConnectionLimitReached, exception.Message); }
public static bool ResetDefs(ResourceCounter __instance) { lock (resources) { resources.Clear(); resources.AddRange(from def in DefDatabase <ThingDef> .AllDefs where def.CountAsResource orderby def.resourceReadoutPriority descending select def); } return(false); }
static void Postfix(ResourceCounter __instance, Dictionary <ThingDef, int> ___countedAmounts) { int i = 0; for (i = 0; i < PRFGameComponent.AssemblerQueue.Count; i++) { foreach (Thing heldThing in PRFGameComponent.AssemblerQueue[i].GetThingQueue()) { Thing innerIfMinified = heldThing.GetInnerIfMinified(); ___countedAmounts[innerIfMinified.def] += innerIfMinified.stackCount; } } }
private TestServer CreateServerWithMaxConnections(RequestDelegate app, ResourceCounter concurrentConnectionCounter) { var serviceContext = new TestServiceContext(LoggerFactory); var listenOptions = new ListenOptions(new IPEndPoint(IPAddress.Loopback, 0)); listenOptions.Use(next => { var middleware = new ConnectionLimitMiddleware(next, concurrentConnectionCounter, serviceContext.Log); return(middleware.OnConnectionAsync); }); return(new TestServer(app, serviceContext, listenOptions)); }
public static void GenerateAllShards() { foreach (ThingDef def in ThingDefGenerator_Techshards.ImpliedTechshardDefs() ?? Enumerable.Empty <ThingDef>()) { DefGenerator.AddImpliedDef <ThingDef>(def); def.ResolveReferences(); } ResourceCounter.ResetDefs(); DefDatabase <ThingCategoryDef> .ResolveAllReferences(true, false); DefDatabase <RecipeDef> .ResolveAllReferences(true, true); }
static void Postfix() { var report = new System.Text.StringBuilder(); if (SeedDef.AddMissingSeeds(report)) { ResourceCounter.ResetDefs(); Log.Warning("SeedsPlease :: Some Seeds were autogenerated." + " Don't rely on autogenerated seeds," + " share the generated xml for proper support.\n\n" + report); } }
public void QuotaValid(long max) { var counter = ResourceCounter.Quota(max); Parallel.For(0, max, i => { Assert.True(counter.TryLockOne()); }); Parallel.For(0, 10, i => { Assert.False(counter.TryLockOne()); }); }
public static bool ResetResourceCounts(ResourceCounter __instance) { lock (lockObject) { Dictionary <ThingDef, int> newCountedAmounts = new Dictionary <ThingDef, int>(); List <ThingDef> tempResources = ResourceCounter.resources; for (int i = 0; i < tempResources.Count; i++) { newCountedAmounts.Add(tempResources[i], 0); } __instance.countedAmounts = newCountedAmounts; } return(false); }
static StaticConstructorClass() { var thingDefs = DefDatabase <ThingDef> .AllDefsListForReading; for (int i = 0; i < thingDefs.Count; i++) { var tDef = thingDefs[i]; // Implied stuffProps for stone chunks if (tDef.IsWithinCategory(ThingCategoryDefOf.StoneChunks) && !tDef.butcherProducts.NullOrEmpty() && tDef.butcherProducts.FirstOrDefault(t => t.thingDef.IsStuff)?.thingDef is ThingDef firstStuffProduct) { ResolveImpliedStoneChunkStuffProperties(tDef, firstStuffProduct.stuffProps); } } ResourceCounter.ResetDefs(); }