예제 #1
0
        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);
        }
예제 #2
0
        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;
                    }
                }
            }
        }
예제 #4
0
        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;
                        }
                    }
                }
            }
        }
예제 #7
0
    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));
        }
예제 #10
0
 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);
 }
예제 #11
0
        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);
        }
예제 #14
0
파일: DiskCache.cs 프로젝트: gabilic/Oplan
 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);
        }
예제 #16
0
 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");
            }
        }
예제 #18
0
        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();
            }
        }
예제 #19
0
 public MainViewModel()
 {
     toast           = new Toast();
     Json            = new Json();
     ResourceCounter = new ResourceCounter();
     Dispatch        = Application.Current.Dispatcher;
     rulesList       = Json.GetRulesListFromJson();
     processList     = new ObservableCollection <Proc>();
     Start();
 }
예제 #20
0
            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);
            }
예제 #21
0
        /// <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();
        }
예제 #22
0
    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);
    }
예제 #23
0
 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;
                }
            }
        }
예제 #25
0
        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));
        }
예제 #26
0
        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);
        }
예제 #27
0
        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);
            }
        }
예제 #28
0
    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());
        });
    }
예제 #29
0
        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);
        }
예제 #30
0
        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();
        }