void Awake() {
		sm = SimulationManager.sharedSimManager;
		sm.Hud = this;

		hud = GetComponent<HUD>();
		hudView = GetComponent<HUDView>();
	}
	void Awake() {
		sm = SimulationManager.sharedSimManager;
		sm.TimeTracker = this;


		//sm.getSimulationRunTime();
	}
 public void OnLevelLoaded(SimulationManager.UpdateMode mode)
 {
     ProcessLoadingExtensions(mode, " OnLevelLoaded", (e, m) =>
     {
         e.OnLevelLoaded((LoadMode)m);
         return true;
     });
 }
        public static void UpdateData(TerrainManager _this, SimulationManager.UpdateMode mode)
        {
            DataExtension.instance.OnUpdateData();

            // Call original method
            UpdateDataRedirector.Revert();
            _this.UpdateData(mode);
            UpdateDataRedirector.Apply();
        }
        public override void UpdateData(SimulationManager.UpdateMode mode)
        {
            // Call
            EventUpdateDataPre?.Invoke(mode);
            EventUpdateData?.Invoke(mode);
            EventUpdateDataPost?.Invoke(mode);

            // Execute original method
            RedirectionHelper.RevertRedirect(_RenderManager_UpdateData_original, _RenderManager_UpdateData_state);
            RenderManager.instance.UpdateData(mode);
            RedirectionHelper.RedirectCalls(_RenderManager_UpdateData_original, _RenderManager_UpdateData_detour);
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        public void ISignalReceiverPassiveBehaviorConditions()
        {
            if (this.gameObject.tag == "SignalReceiverPassive")

            {
                base.signalReceiverPassiveCounter++;
                base.CalculateEnergyLevels(SimulationManager.Get().gridDistribution_6Neighbours, SimulationManager.Get()._12Neighbours, SimulationManager.Get().is3D, SimulationManager.Get().is2D);
                base.EnergyLevelSharing(this.gameObject.GetComponent <Agent>());

                //   StartCoroutine(ApplyWindForce(SimulationManager.Get().windForce, SimulationManager.Get().windForceIntervalSeconds));

                //////////////////// set display////////////////////////////////

                base.ChangeDisplayInspectorInput(gameObject.GetComponent <Agent>(), false);

                //////////////////// set display////////////////////////////////

                if (base.signalReceiverPassiveCounter > 100)
                {
                    base.ChangeStateToSignalEmmiter(this.gameObject.GetComponent <Agent>(), 0);
                }
            } /// END CONDITIONS SIGNAL RECEIVER PASSIVE
        }
Example #7
0
        public void DeactivatedAgentBehaviorConditions()
        {
            if (this.gameObject.tag == "De-Activated")
            {
                if (SimulationManager.Get().addWindForce)
                {
                    StartCoroutine(ApplyWindForce(SimulationManager.Get().windForce, SimulationManager.Get().windForceIntervalSeconds));
                }

                //////////////////// set display////////////////////////////////

                base.ChangeDisplayInspectorInput(gameObject.GetComponent <Agent>(), false);

                //////////////////// set display////////////////////////////////

                //Pixel currentPixel;
                //PixelDataLookUp3D(pixelPop, out currentPixel);
                //base.currentPixel = currentPixel.PixelName;

                base.CalculateEnergyLevels(SimulationManager.Get().gridDistribution_6Neighbours, SimulationManager.Get()._12Neighbours, SimulationManager.Get().is3D, SimulationManager.Get().is2D);
                base.EnergyLevelSharing(this.gameObject.GetComponent <Agent>());
            }
        }
        public void TestLogic(Tuple <int, int> plateauSize, List <RoverTestData> roverTestData)
        {
            SimulationManager simMan = new SimulationManager(plateauSize.Item1, plateauSize.Item2);

            foreach (RoverTestData td in roverTestData)
            {
                int roverId = simMan.LandRover(new RoverNasa("Pathfinder")
                {
                    Position          = td.LandingLocation,
                    CardinalDirection = td.LandingOrientation,
                    Speed             = 1
                });

                simMan.ProcessRoverCommands(roverId, td.Instructions);
                IRover rover = simMan.GetRover(roverId);
                TestContext.WriteLine($"Rover id: {rover.Id} Rover XY: {rover.Position.X} {rover.Position.Y} Rover Direction: {rover.CardinalDirection.ToString()}");
                Assert.IsTrue(
                    rover.Position.X == td.ExpectedEndLocation.X &&
                    rover.Position.Y == td.ExpectedEndLocation.Y &&
                    rover.CardinalDirection == td.ExpectedEndOrientation
                    );
            }
        }
Example #9
0
        public IEnumerator FramesScheduledBySensorConfig()
        {
            var ego = SimulationManager.RegisterEgo("ego");
            var firstCaptureTime = 1.5f;
            var period           = .4f;

            SimulationManager.RegisterSensor(ego, "cam", "", period, firstCaptureTime);

            float[] deltaTimeSamplesExpected =
            {
                firstCaptureTime,
                period,
                period,
                period
            };
            float[] deltaTimeSamples = new float[deltaTimeSamplesExpected.Length];
            for (int i = 0; i < deltaTimeSamples.Length; i++)
            {
                yield return(null);

                Assert.AreEqual(deltaTimeSamplesExpected[i], Time.deltaTime, 0.0001f);
            }
        }
Example #10
0
    // Start is called before the first frame update
    void Awake()
    {
        instance       = this;
        content        = PlayerPrefs.GetString("sim");
        title          = PlayerPrefs.GetString("title");
        titleText.text = title;
        string[] arrLeftRight = content.Split(char.Parse("a"));
        //right arm
        print(arrLeftRight[0]);
        string[] arrRight = arrLeftRight[0].Split(char.Parse("\n"));

        Vector3[] rightPoints = new Vector3[arrRight.Length - 1];
        for (int i = 0; i < arrRight.Length - 1; i++)
        {
            string[] numbers = arrRight[i].Split(char.Parse(","));

            rightPoints[i] = new Vector3(float.Parse(numbers[0]), float.Parse(numbers[1]), float.Parse(numbers[2]));
            print(rightPoints[i]);
        }
        print("============================================");
        //left arm
        string[]  arrLeft    = arrLeftRight[1].Split(char.Parse("\n"));
        Vector3[] leftPoints = new Vector3[arrLeft.Length - 1];
        for (int i = 0; i < arrLeft.Length - 1; i++)
        {
            string[] numbers = arrLeft[i + 1].Split(char.Parse(","));
            leftPoints[i] = new Vector3(float.Parse(numbers[0]), float.Parse(numbers[1]), float.Parse(numbers[2]));
            print(leftPoints[i]);
        }
        print(leftPoints[0]);
        print(leftPoints[leftPoints.Length - 1]);
        rightArm.points = rightPoints;
        leftArm.points  = leftPoints;
        //rightArm.pointString = arrLeftRight[0];

        //leftArm.pointString = arrLeftRight[1];
    }
Example #11
0
        public void Update()
        {
            SimulationManager _simulationManager = Singleton <SimulationManager> .instance;
            float             currentHour        = _simulationManager.m_currentDayTimeHour;

            if (currentHour < 1D && m_lastDayTimeHour > 23D)
            {
                m_baseTime = m_baseTime.AddDays(1D);
                LoggingWrapper.Log("New day " + m_baseTime.ToShortDateString() + " " + m_baseTime.ToShortTimeString());

                Data.CityTime.year  = m_baseTime.Year;
                Data.CityTime.month = m_baseTime.Month;
                Data.CityTime.day   = m_baseTime.Day;

                Debug.Log("Current date: " + m_baseTime.ToLongTimeString() + ", " + m_baseTime.ToShortDateString());
            }

            if (currentHour > 23D && m_lastDayTimeHour < 1D)
            {
                LoggingWrapper.LogWarning("Time jumped back, but it was prevented.");
            }
            else
            {
                m_lastDayTimeHour = currentHour;
            }

            CITY_TIME = m_baseTime.AddHours(currentHour);

            if (ExperimentsToggle.AllowForcedXMLEvents)
            {
                m_xmlEvents.Clear();
                LoadEvents();
                ExperimentsToggle.AllowForcedXMLEvents = false;
            }

            UpdateEvents();
        }
        // re-draw
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics g = e.Graphics;
            Color    color;

            // check if the current working-on script already has a START state or not
            bool alreadyHasStartState = ModelManager.CurrentSelectedScriptIndex >= 0 &&
                                        ModelManager
                                        .getScriptModelByIndex()
                                        .hasStartStateOnScript();

            // select the color of this start-state-view
            if (!mIsInstanceOnScript && mIsMouseMovingOn && !alreadyHasStartState)
            {
                color = Color.FromArgb(255, 100, 100, 100);
            }
            else
            {
                color = Color.Black;
            }

            // render the start-state-view
            if (SimulationManager.isSimulating() == false)
            {
                g.FillEllipse(new SolidBrush(color), 0, 0, Size.Width - 1, Size.Height - 1);
            }

            // if already has a START state, render the forbidden sign on the shell
            if (alreadyHasStartState && !mIsInstanceOnScript)
            {
                Pen pen4ForbiddenSign = new Pen(Color.Red, 5);
                g.DrawLine(pen4ForbiddenSign, 0, 0, Size.Width - 1, Size.Height - 1);
                g.DrawLine(pen4ForbiddenSign, Size.Width - 1, 0, 0, Size.Height - 1);
            }
        }
        private void OnCollisionEnter(Collision collision)
        {
            if (GenerationManager.generationCount != 0 && SimulationManager.Get().addRigidBodyCollider == true)
            {
                if (SimulationManager.Get().addFixedJoints)
                {
                    AddFixedJoint(collision);
                }

                if (collision.gameObject.tag == "SignalEmmiter" && this.gameObject.tag != "Freezed")
                {
                    base.ChangeStateToSignalReceiverPassive(this.gameObject.GetComponent <Agent>(), 0);
                }


                if (collision.gameObject.tag != "De-Activated" && collision.gameObject.tag != "ActivatedPlaceHolder" &&
                    collision.gameObject.tag != "CollidedPlaceHolder")
                {
                    base.neighboursTemp.Add(collision.gameObject.GetComponent <Agent>());
                    base.neighboursTempVector.Add(collision.gameObject.transform.position);
                }
            }


            ///Keeps track of neighbours of generation 0
            if (GenerationManager.generationCount == 0 && SimulationManager.Get().addRigidBodyCollider == true)
            {
                if (collision.gameObject.tag != "De-Activated" && collision.gameObject.tag != "ActivatedPlaceHolder" && collision.gameObject.tag != "CollidedPlaceHolder")
                {
                    /// Increment the collision history of the Agent. during first collision, SystemCollisionHistory = 1
                    base.neighboursTemp.Add(collision.gameObject.GetComponent <Agent>());
                    base.neighboursTempVector.Add(collision.gameObject.transform.position);
                    base.neighbourHistory.Add(collision.gameObject.GetComponent <Agent>());
                    base.localCollisionHistory++;
                }
            }
        }
Example #14
0
    protected void Initialize()
    {
        m_Rand            = new Random(2);
        m_CurriculumQuery = EntityManager.CreateEntityQuery(typeof(CurriculumState));

        const string globalInitParamsName      = "Management";
        var          globalInitParamsContainer = GameObject.Find(globalInitParamsName);

        if (globalInitParamsContainer == null)
        {
            Debug.Log($"Cannot find a {globalInitParamsName} object to init parameters from.");
            return;
        }

        var init = globalInitParamsContainer.GetComponent <ProjectInitialization>();

        m_AppParams = init.AppParameters;
        var perceptionCamera = init.PerceptionCamera;

        camera             = perceptionCamera.GetComponentInParent <Camera>();
        m_ForegroundCenter =
            camera.transform.position + m_CameraForward * ForegroundObjectPlacer.k_ForegroundLayerDistance;
        // Compute the bottom left corner of the view frustum
        // IMPORTANT: We're assuming the camera is facing along the positive z-axis
        container = new GameObject("BackgroundContainer");
        container.transform.SetPositionAndRotation(
            m_CameraForward * k_PlacementDistance + camera.transform.position,
            Quaternion.identity);
        var statics = EntityManager.GetComponentObject <PlacementStatics>(m_CurriculumQuery.GetSingletonEntity());

        objectCache = new GameObjectOneWayCache(container.transform, statics.BackgroundPrefabs);

        backgroundHueMaxOffset = init.AppParameters.BackgroundHueMaxOffset;
        initialized            = true;

        m_ScaleRangeMetric = SimulationManager.RegisterMetricDefinition("background scale range", "The range of scale factors used to place background objects each frame", k_BackgroundScaleMetricId);
    }
            public void GetAJob(uint citizenIndex)
            {
                CitizenManager citizenManager = Singleton <CitizenManager> .instance;

                if (citizenManager.m_citizens.m_buffer[citizenIndex].m_workBuilding == 0 && citizenManager.m_citizens.m_buffer[citizenIndex].m_homeBuilding != 0)
                {
                    SimulationManager simulationManager = Singleton <SimulationManager> .instance;
                    BuildingManager   buildingManager   = Singleton <BuildingManager> .instance;
                    TransferManager   transferManager   = Singleton <TransferManager> .instance;
                    Vector3           position          = buildingManager.m_buildings.m_buffer[citizenManager.m_citizens.m_buffer[citizenIndex].m_homeBuilding].m_position;

                    TransferManager.TransferOffer offer = default(TransferManager.TransferOffer);
                    offer.Priority = simulationManager.m_randomizer.Int32(8);
                    offer.Citizen  = citizenIndex;
                    offer.Position = position;
                    offer.Amount   = 1;
                    offer.Active   = true;
                    switch (citizenManager.m_citizens.m_buffer[citizenIndex].EducationLevel)
                    {
                    case Citizen.Education.Uneducated:
                        transferManager.AddOutgoingOffer(TransferManager.TransferReason.Worker0, offer);
                        break;

                    case Citizen.Education.OneSchool:
                        transferManager.AddOutgoingOffer(TransferManager.TransferReason.Worker1, offer);
                        break;

                    case Citizen.Education.TwoSchools:
                        transferManager.AddOutgoingOffer(TransferManager.TransferReason.Worker2, offer);
                        break;

                    case Citizen.Education.ThreeSchools:
                        transferManager.AddOutgoingOffer(TransferManager.TransferReason.Worker3, offer);
                        break;
                    }
                }
            }
        public IEnumerator EnableBoundingBoxes_GeneratesCorrectDataset()
        {
            //set resolution to ensure we don't have rounding in rendering leading to bounding boxes to change height/width
            Screen.SetResolution(400, 400, false);
            //give the screen a chance to resize
            yield return(null);

            var jsonExpected          = $@"            {{
              ""label_id"": 0,
              ""label_name"": ""label"",
              ""instance_id"": 1,
              ""x"": 0.0,
              ""y"": {Screen.height / 4:F1},
              ""width"": {Screen.width:F1},
              ""height"": {Screen.height / 2:F1}
            }}";
            var labelingConfiguration = CreateLabelingConfiguration();

            SetupCamera(labelingConfiguration, pc =>
            {
                pc.produceBoundingBoxAnnotations = true;
            });

            var plane = TestHelper.CreateLabeledPlane();

            AddTestObjectForCleanup(plane);
            //a plane is 10x10 by default, so scale it down to be 10x1 to cover the center half of the image
            plane.transform.localScale = new Vector3(10f, -1f, .1f);
            yield return(null);

            SimulationManager.ResetSimulation();

            var capturesPath = Path.Combine(SimulationManager.OutputDirectory, "captures_000.json");
            var capturesJson = File.ReadAllText(capturesPath);

            StringAssert.Contains(jsonExpected, capturesJson);
        }
Example #17
0
        public static TransferManager.TransferReason GetRandomTransferReason(int doNothingProbability)
        {
            int type = 0;
            SimulationManager instance = Singleton <SimulationManager> .instance;

            if (instance.m_randomizer.Int32(10000U) < doNothingProbability)
            {
                type = 0;
            }
            int num    = 2000;
            int factor = Singleton <BuildingManager> .instance.m_finalMonumentEffect[10].m_factor;

            if (factor != 0)
            {
                num = num * 100 / (100 + factor);
            }
            if (instance.m_randomizer.Int32(10000U) < num)
            {
                type = 1;
            }
            type = instance.m_randomizer.Int32(10000U) < 2500 ? 2 : 3;

            switch (type)
            {
            case 1:      // leaving reason
                return(TransferManager.TransferReason.None);

            case 2:
                return(GetShoppingReason());

            case 3:
                return(GetEntertainmentReason());

            default:
                return(TransferManager.TransferReason.None);
            }
        }
Example #18
0
    void Reset()
    {
        if (simManager == null)
        {
            simManager = FindObjectOfType <SimulationManager>();
        }

        if (fieldForceSlider == null)
        {
            fieldForceSlider = Utils.FindObjectInHierarchy <SimulatorSliderSetBoundingForce>().GetComponent <InteractionSlider>();
        }
        if (fieldRadiusSlider == null)
        {
            fieldRadiusSlider = Utils.FindObjectInHierarchy <SimulatorSliderSetBoundingRadius>().GetComponent <InteractionSlider>();
        }
        if (socialForceSlider == null)
        {
            socialForceSlider = Utils.FindObjectInHierarchy <SimulatorSliderSetMaxForce>().GetComponent <InteractionSlider>();
        }
        if (socialRadiusSlider == null)
        {
            socialRadiusSlider = Utils.FindObjectInHierarchy <SimulatorSliderSetMaxRange>().GetComponent <InteractionSlider>();
        }
        if (dragSlider == null)
        {
            dragSlider = Utils.FindObjectInHierarchy <SimulatorSliderSetDrag>().GetComponent <InteractionSlider>();
        }
        if (particleCountSlider == null)
        {
            particleCountSlider = Utils.FindObjectInHierarchy <SimulatorSliderSetParticleCount>().GetComponent <InteractionSlider>();
        }

        if (zoomController == null)
        {
            zoomController = Utils.FindObjectInHierarchy <SimulationZoomController>();
        }
    }
Example #19
0
        public override void OnAfterSimulationTick()
        {
            if (!V10Bulldoze.active || c++ < V10Bulldoze.ui.data.interval)
            {
                return;
            }
            c = 0;

            if (!V10Bulldoze.ui.data.abandoned && !V10Bulldoze.ui.data.burned)
            {
                return;
            }

            if (simulationManager == null)
            {
                simulationManager = SimulationManager.instance;
                bulldozeTool      = GameObject.FindObjectOfType <BulldozeTool> ();
                method            = bulldozeTool.GetType().GetMethod("DeleteBuilding", BindingFlags.NonPublic | BindingFlags.Instance);
            }

            if (V10Bulldoze.ui.data.abandoned)
            {
                checkBuildings(SkylinesOverwatch.Data.Instance.BuildingsAbandoned);
            }
            if (V10Bulldoze.ui.data.burned && c2 <= V10Bulldoze.ui.data.max)
            {
                ushort [] toCheck = SkylinesOverwatch.Data.Instance.BuildingsBurnedDown;
                if (V10Bulldoze.ui.data.service)
                {
                    toCheck = toCheck.Except(SkylinesOverwatch.Data.Instance.PlayerBuildings).ToArray();
                }
                checkBuildings(toCheck);
            }

            c2 = 0;
        }
Example #20
0
        public RedirectToRouteResult PurchaseSingleItem(int id)
        {
            SimulationManager mgr = new SimulationManager();

            var item = db.StoreItems.Find(id);

            var userProfile = db.UserProfiles.Local.SingleOrDefault(u => u.UserName == User.Identity.Name)
                              ?? db.UserProfiles.SingleOrDefault(u => u.UserName == User.Identity.Name);

            var student = db.Students.Find(userProfile.UserId);

            var accounts = db.Accounts.Where(x => x.StudentID == student.UserId);

            var account = accounts.FirstOrDefault();

            var accountSavings = accounts.Single(x => x.AccountName == "Savings");

            var purchase = mgr.PurchaseSingleItem(item, student, account, accountSavings);

            db.Purchases.Add(purchase);
            db.SaveChanges();

            return(RedirectToAction("Index", "Student"));
        }
        public static ushort StartTransfer(ushort buildingID, ref Building data, TransferManager.TransferReason reason, TransferManager.TransferOffer offer, string prefabName)
        {
            SimulationManager instance1  = Singleton <SimulationManager> .instance;
            VehicleManager    instance2  = Singleton <VehicleManager> .instance;
            ushort            vehicle    = 0;
            DepotAI           buildingAi = Singleton <BuildingManager> .instance.m_buildings.m_buffer[(int)buildingID].Info.m_buildingAI as DepotAI;

            if (reason == buildingAi.m_transportInfo.m_vehicleReason)
            {
                VehicleInfo vehicleInfo = VehicleManagerMod.GetVehicleInfo(ref instance1.m_randomizer, buildingAi.m_info.m_class, offer.TransportLine, prefabName);
                if ((Object)vehicleInfo != (Object)null)
                {
                    Vector3 position;
                    Vector3 target;
                    buildingAi.CalculateSpawnPosition(buildingID, ref data, ref instance1.m_randomizer, vehicleInfo, out position, out target);
                    if (instance2.CreateVehicle(out vehicle, ref instance1.m_randomizer, vehicleInfo, position, reason, false, true))
                    {
                        vehicleInfo.m_vehicleAI.SetSource(vehicle, ref instance2.m_vehicles.m_buffer[(int)vehicle], buildingID);
                        vehicleInfo.m_vehicleAI.StartTransfer(vehicle, ref instance2.m_vehicles.m_buffer[(int)vehicle], reason, offer);
                    }
                }
            }
            return(vehicle);
        }
        private bool findRandomTargetEverywhere(out Vector3 target, out float angle)
        {
            GameAreaManager   gam = Singleton <GameAreaManager> .instance;
            SimulationManager sm  = Singleton <SimulationManager> .instance;
            int   i = sm.m_randomizer.Int32(0, 4);
            int   j = sm.m_randomizer.Int32(0, 4);
            float minX;
            float minZ;
            float maxX;
            float maxZ;

            gam.GetAreaBounds(i, j, out minX, out minZ, out maxX, out maxZ);

            float randX = (float)sm.m_randomizer.Int32(0, 10000) * 0.0001f;
            float randZ = (float)sm.m_randomizer.Int32(0, 10000) * 0.0001f;

            target.x = minX + (maxX - minX) * randX;
            target.y = 0f;
            target.z = minZ + (maxZ - minZ) * randZ;
            target.y = Singleton <TerrainManager> .instance.SampleRawHeightSmoothWithWater(target, false, 0f);

            angle = (float)sm.m_randomizer.Int32(0, 10000) * 0.0006283185f;
            return(true);
        }
Example #23
0
        private static ushort FindLeisure(ref ResidentAI thisAI, uint citizenID, ref Citizen person, ushort buildingID)
        {
            ushort foundLeisure = 0;

            if ((person.m_instance != 0 || NewResidentAI.DoRandomMove(thisAI)))
            {
                BuildingManager   _buildingManager   = Singleton <BuildingManager> .instance;
                SimulationManager _simulationManager = Singleton <SimulationManager> .instance;
                Building          _currentBuilding   = _buildingManager.m_buildings.m_buffer[buildingID];

                foundLeisure = _buildingManager.FindBuilding(_currentBuilding.m_position, 1000f, ItemClass.Service.Commercial, ItemClass.SubService.CommercialLeisure, Building.Flags.Created | Building.Flags.Active, Building.Flags.Deleted);

                if (foundLeisure != 0)
                {
                    if (_simulationManager.m_randomizer.Int32(0, 10) > 2)
                    {
                        thisAI.StartMoving(citizenID, ref person, buildingID, foundLeisure);
                        person.SetVisitplace(citizenID, foundLeisure, 0U);
                        person.m_visitBuilding = foundLeisure;
                        LoggingWrapper.Log("Citizen " + citizenID + " found leisure.");
                    }
                    else
                    {
                        LoggingWrapper.Log("Citizen " + citizenID + " found leisure, but chose not to bother.");
                        NewResidentAI.FindVisitPlace(thisAI, citizenID, buildingID, NewResidentAI.GetEntertainmentReason(thisAI));
                    }
                }
                else
                {
                    LoggingWrapper.Log("Citizen " + citizenID + " couldn't find leisure.");
                    NewResidentAI.FindVisitPlace(thisAI, citizenID, buildingID, NewResidentAI.GetEntertainmentReason(thisAI));
                }
            }

            return(foundLeisure);
        }
    //-----------------------------------------------------------------------------------
    public void Update()
    {
      if ( SimulationManager.ReadSimulationBufferUniqueUnsafe( BroadcastStart, UpdateBody, UpdateCorpuscles ) )
      {
        statistics_           = SimulationManager.simStatistics_;
        listJointGroupsInfo_  = SimulationManager.listJgInfo_;
        listExplosionInfo_    = SimulationManager.listExplosionInfo_;
        listContactEventInfo_ = SimulationManager.listContactEventInfo_;
   
        UpdateListsBodyGORequested      = true;
        UpdateListJointsRequested       = true;
        UpdateClothCollidersRequested   = true;

        InternalEditorUtility.RepaintAllViews();
      }

      if ( UpdateListsBodyGORequested )
      {
        CreateBodyBoxes();
      }

      if ( UpdateListJointsRequested )
      {
        CreateJointPivotBoxes();
      }

      if ( UpdateClothCollidersRequested )
      {
        CreateClothSpheres();
      }

      if (nCorpuscles_ > 0)
      {
        RebindCorpuscleRenderersShaderAttributes();
      }
    }
Example #25
0
    public float[] layerSample; // Sample to show in the inspector

    // Use this for initialization
    void Start()
    {
        basicLayer           = new float[4 + 1, 11];
        mass                 = GetComponent <Rigidbody2D>().mass;
        gravity              = GetComponent <Rigidbody2D>().gravityScale;
        canJump              = false;
        travelDist           = 0;
        travelPlat           = 0;
        timeStayedOnPlatform = 0;
        fitnessScore         = 0;
        jumpForceOutputs     = new float[9];
        simManager           = FindObjectOfType <SimulationManager>();

        jumpForces = new float[9];
        for (int i = 0; i < jumpForces.Length; i++)
        {
            jumpForces[i] = baseJumpForce * (i + 1);
        }

        inputs = new float[4];

        GeneticCrossOver();
        GeneticMutation();
    }
        public override void ProcessPacket(Guid sourcePlayerId, Packet packet, IProcessorContext context)
        {
            TimeScaleUpdatePacket  timeScaleUpdatePacket = (TimeScaleUpdatePacket)packet;
            ServerProcessorContext processorContext      = (ServerProcessorContext)context;
            SimulationManager      simulationManager     = processorContext.Server.SimulationManager;
            TimeManager            timeManager           = processorContext.Server.TimeManager;

            Player?simulationOwner = simulationManager.GetSimulationOwner();

            if (simulationOwner == null || sourcePlayerId != simulationOwner.Value.Id)
            {
                //Deny request if client isn't the simulation owner
                return;
            }

            if (timeManager.IsTimeLocked())
            {
                // The server is holding onto the current timescale
                // Inform the client, maybe?
                return;
            }

            timeManager.SetTimescale(timeScaleUpdatePacket.TimeScale, timeScaleUpdatePacket.IsPaused);
        }
Example #27
0
 public EndPlanningPeriodEvent(double timeIn, SimulationManager managerIn)
     : base(timeIn, managerIn)
 {
 }
Example #28
0
        public override Event GetEvent(SimulationManager managerIn)
        {
            StationList processCells = managerIn.LayoutManager.Layout.Stations;

            return(new ProcessorBreakdownEvent(this.Time, managerIn, processCells[this.cell].Processors[this.processor]));
        }
 public static void Register()
 {
     instance = new SubscriptionManager();
     SimulationManager.RegisterSimulationManager(instance);
 }
 private void ProcessLoadingExtensions(SimulationManager.UpdateMode mode, string methodName, Func<ILoadingExtension, SimulationManager.UpdateMode, bool> callback)
 {
     var loadingExtensions = (List<ILoadingExtension>)(typeof(LoadingWrapper).
         GetField("m_LoadingExtensions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this));
     var exceptions = new List<Exception>();
     foreach (var loadingExtension in loadingExtensions)
     {
         try
         {
             callback(loadingExtension, mode);
         }
         catch (Exception ex)
         {
             UnityEngine.Debug.LogException(ex);
             exceptions.Add(ex);
         }
     }
     if (exceptions.Count <= 0)
     {
         return;
     }
     var mergedTraces = "";
     var i = 0;
     exceptions.ForEach((e) =>
     {
         if (e == null)
         {
             mergedTraces += String.Format("\n---------------------------\n[{0}]: <null exception>", i);
         }
         else
         {
             mergedTraces += String.Format("\n---------------------------\n[{0}]: {1}\n{2}", i, e.Message, e.StackTrace);
         }
         ++i;
     });
     UIView.ForwardException(new ModException(String.Format("{0} - Some mods caused errors:", mode),
         new Exception(mergedTraces)));
 }
        public void UpdateData(SimulationManager.UpdateMode mode)
        {
            var g = GameAreaManager.instance;
            if (mode == SimulationManager.UpdateMode.NewGame || mode == SimulationManager.UpdateMode.NewAsset || mode == SimulationManager.UpdateMode.LoadAsset)
            {
                g.m_areaCount = 0;
                int num = (int)g.GetType().GetField("m_startTile", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(g);
                for (int index1 = 0; index1 < GRID; ++index1)
                {
                    for (int index2 = 0; index2 < GRID; ++index2)
                    {
                        int index3 = index1 * GRID + index2;
                        areaGrid[index3] = index3 != num ? 0 : ++g.m_areaCount;
                    }
                }
            }
            int x1;
            int z1;
            g.GetStartTile(out x1, out z1);
            if (mode != SimulationManager.UpdateMode.LoadGame || (float)g.GetType().GetField("m_buildableArea0", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(g) < 0.0)
            {
                float m_buildableArea0 = 0.0f;
                float m_buildableArea1 = 0.0f;
                float m_buildableArea2 = 0.0f;
                float m_buildableArea3 = 0.0f;
                float num1 = 0.0f;
                float num2 = 0.0f;
                float num3 = 0.0f;
                float num4 = 0.0f;
                for (int tileZ = 0; tileZ < GRID; tileZ += 1)
                {
                    for (int tileX = 0; tileX < GRID; tileX += 1)
                    {
                        switch (Mathf.Abs(tileX - x1) + Mathf.Abs(tileZ - z1))
                        {
                            case 0:
                                m_buildableArea0 += CalculateBuildableArea(tileX, tileZ);
                                ++num1;
                                break;

                            case 1:
                                m_buildableArea1 += CalculateBuildableArea(tileX, tileZ);
                                ++num2;
                                break;

                            case 2:
                                m_buildableArea2 += CalculateBuildableArea(tileX, tileZ);
                                ++num3;
                                break;

                            case 3:
                                m_buildableArea3 += CalculateBuildableArea(tileX, tileZ);
                                ++num4;
                                break;
                        }
                    }
                }
                if ((double)num1 != 0.0)
                    m_buildableArea0 /= num1;
                if ((double)num2 != 0.0)
                    m_buildableArea1 /= num2;
                if ((double)num3 != 0.0)
                    m_buildableArea2 /= num3;
                if ((double)num4 != 0.0)
                    m_buildableArea3 /= num4;

                g.GetType().GetField("m_buildableArea0", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(g, m_buildableArea0);
                g.GetType().GetField("m_buildableArea1", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(g, m_buildableArea1);
                g.GetType().GetField("m_buildableArea2", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(g, m_buildableArea2);
                g.GetType().GetField("m_buildableArea3", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(g, m_buildableArea3);
            }

            for (int z2 = 0; z2 < GRID; ++z2)
            {
                for (int x2 = 0; x2 < GRID; ++x2)
                {
                    if (g.GetArea(x2, z2) > 0)
                    {
                        Singleton<TerrainManager>.instance.SetDetailedPatch(x2, z2);

                        float minX = (float)(((double)x2 - 4.5f) * 1920.0);
                        float maxX = (float)(((double)(x2 + 1) - 4.5f) * 1920.0);
                        float minZ = (float)(((double)z2 - 4.5f) * 1920.0);
                        float maxZ = (float)(((double)(z2 + 1) - 4.5f) * 1920.0);
                        Singleton<ZoneManager>.instance.UpdateBlocks(minX, minZ, maxX, maxZ);
                    }
                }
            }
            if (mode == SimulationManager.UpdateMode.NewGame || g.m_areaNotUnlocked == null)
                g.m_areaNotUnlocked = new GenericGuide();
        }
Example #32
0
 public void NullNoneMatchingConstraints()
 {
     var s = Moksy.Common.SimulationFactory.When.I.Post().ToImdb("/Pet").With.Constraint(new LengthEquals("TheProperty", 4));
     SimulationManager mgr = new SimulationManager();
     mgr.Add(s.Simulation);
     var result = mgr.FindMatchingConstraints(s.Simulation, null, null, null);
     Assert.AreEqual(0, result.Count());
 }
Example #33
0
        public void Initialize(SimulationManager.UpdateMode _updateMode)
        {
            updateMode = _updateMode;

            if (!loggingInitialized)
            {
                Application.logMessageReceived += (condition, trace, type) =>
                {
                    if (!logExceptionsToConsole)
                    {
                        return;
                    }

                    if (Instance.console != null)
                    {
                        Instance.console.AddMessage(String.Format("{0} ({1})", condition, trace), type, true);
                        return;
                    }

                    if (type == LogType.Error || type == LogType.Exception || type == LogType.Assert)
                    {
                        Log.Error(condition);
                    }
                    else if (type == LogType.Warning)
                    {
                        Log.Warning(condition);
                    }
                    else
                    {
                        Log.Message(condition);
                    }
                };

                loggingInitialized = true;
            }

            sceneExplorer = gameObject.AddComponent<SceneExplorer>();
            watches = gameObject.AddComponent<Watches>();
            colorPicker = gameObject.AddComponent<ColorPicker>();

            sceneExplorerColorConfig = gameObject.AddComponent<SceneExplorerColorConfig>();

            LoadConfig();

            if (extendGamePanels && (updateMode == SimulationManager.UpdateMode.NewGame || updateMode == SimulationManager.UpdateMode.LoadGame))
            {
                panelExtender = gameObject.AddComponent<GamePanelExtender>();
            }

            if (useModToolsConsole)
            {
                console = gameObject.AddComponent<Console>();
            }

            if (config.hookUnityLogging)
            {
                UnityLoggingHook.EnableHook();
            }

            if (updateMode == SimulationManager.UpdateMode.Undefined && config.improvedWorkshopIntegration)
            {
                ImprovedWorkshopIntegration.Bootstrap();
            }
        }
Example #34
0
 public void UpdateData(SimulationManager.UpdateMode mode)
 {
 }
 private void Initialize()
 {
     this._buildingManager = Singleton<BuildingManager>.instance;
     this._simulationManager = Singleton<SimulationManager>.instance;
     this._effectManager = Singleton<EffectManager>.instance;
     this._economyManager = Singleton<EconomyManager>.instance;
     this._coverageManager = Singleton<CoverageManager>.instance;
     this._nullAudioGroup = new AudioGroup(0, new SavedFloat("NOTEXISTINGELEMENT", Settings.gameSettingsFile, 0f, false));
 }
 private void OnLevelLoaded(SimulationManager.UpdateMode mode)
 {
     this.ResetUndoBuffer();
 }
Example #37
0
        /// <summary>
        /// Like OnLevelLoaded, but executed earlier.
        /// </summary>
        /// <param name="mode"></param>
        public void OnUpdateData(SimulationManager.UpdateMode mode)
        {
            if (mode != SimulationManager.UpdateMode.LoadMap && mode != SimulationManager.UpdateMode.NewMap
                && mode != SimulationManager.UpdateMode.LoadGame && mode != SimulationManager.UpdateMode.NewGame) return;

            // no trees
            _availableTrees.Add(null);

            for (uint i = 0; i < PrefabCollection<TreeInfo>.LoadedCount(); i++)
            {
                var prefab = PrefabCollection<TreeInfo>.GetLoaded(i);

                if (prefab == null) continue;

                _availableTrees.Add(prefab);
            }

            // no street lights
            _availableStreetLights.Add(null);

            for (uint i = 0; i < PrefabCollection<PropInfo>.LoadedCount(); i++)
            {
                var prefab = PrefabCollection<PropInfo>.GetLoaded(i);

                if (prefab == null) continue;
                if (prefab.m_class.m_service == ItemClass.Service.Road ||
                    prefab.m_class.m_subService == ItemClass.SubService.PublicTransportPlane ||
                    prefab.name.Contains("StreetLamp"))
                {
                    if (prefab.m_effects != null && prefab.m_effects.Length > 0)
                    {
                        if (prefab.name.Contains("Taxiway")) continue;
                        if (prefab.name.Contains("Runway")) continue;

                        if (prefab.m_effects.Where(effect => effect.m_effect != null).Any(effect => effect.m_effect is LightEffect))
                        {
                            _availableStreetLights.Add(prefab);
                        }
                    }
                }
            }

            // compile list of data indices for fast check if a prefab is a street light:
            StreetLightPrefabDataIndices = _availableStreetLights.Where(prop => prop != null).Select(prop => prop.m_prefabDataIndex).ToArray();
        }
Example #38
0
 public void MatchesOneViolationsNoIndex()
 {
     var s = Moksy.Common.SimulationFactory.When.I.Post().ToImdb("/Pet").With.Constraint(new LengthEquals("TheProperty", 4));
     SimulationManager mgr = new SimulationManager();
     mgr.Add(s.Simulation);
     StringContent content = new StringContent(@"{""TheProperty"":""ABCD""}");
     var match = mgr.Match(HttpMethod.Post, content, "/Pet", null, new List<Header>(), false);
     Assert.IsNotNull(match);
     Assert.AreEqual(1, match.EvaluatedMatchingConstraints.Count);
 }
Example #39
0
        public static void SimulationStepActive(CommercialBuildingAI thisAI, ushort buildingID, ref Building buildingData, ref Building.Frame frameData)
        {
            //This is a mess because I pulled it directly from the decompiled code and patched it up slightly.
            //It works though, and that's all I'm bothered about for now.

            if (thisAI)
            {
                DistrictManager               instance1            = Singleton <DistrictManager> .instance;
                byte                          district             = instance1.GetDistrict(buildingData.m_position);
                DistrictPolicies.Services     policies             = instance1.m_districts.m_buffer[(int)district].m_servicePolicies;
                DistrictPolicies.Taxation     taxationPolicies     = instance1.m_districts.m_buffer[(int)district].m_taxationPolicies;
                DistrictPolicies.CityPlanning cityPlanningPolicies = instance1.m_districts.m_buffer[(int)district].m_cityPlanningPolicies;
                instance1.m_districts.m_buffer[(int)district].m_servicePoliciesEffect |= policies & (DistrictPolicies.Services.PowerSaving | DistrictPolicies.Services.WaterSaving | DistrictPolicies.Services.SmokeDetectors | DistrictPolicies.Services.Recycling | DistrictPolicies.Services.RecreationalUse | DistrictPolicies.Services.ExtraInsulation | DistrictPolicies.Services.NoElectricity | DistrictPolicies.Services.OnlyElectricity | DistrictPolicies.Services.RecyclePlastic);
                switch (thisAI.m_info.m_class.m_subService)
                {
                case ItemClass.SubService.CommercialLow:
                    if ((taxationPolicies & (DistrictPolicies.Taxation.TaxRaiseComLow | DistrictPolicies.Taxation.TaxLowerComLow)) != (DistrictPolicies.Taxation.TaxRaiseComLow | DistrictPolicies.Taxation.TaxLowerComLow))
                    {
                        instance1.m_districts.m_buffer[(int)district].m_taxationPoliciesEffect |= taxationPolicies & (DistrictPolicies.Taxation.TaxRaiseComLow | DistrictPolicies.Taxation.TaxLowerComLow);
                    }
                    instance1.m_districts.m_buffer[(int)district].m_cityPlanningPoliciesEffect |= cityPlanningPolicies & DistrictPolicies.CityPlanning.SmallBusiness;
                    break;

                case ItemClass.SubService.CommercialHigh:
                    if ((taxationPolicies & (DistrictPolicies.Taxation.TaxRaiseComHigh | DistrictPolicies.Taxation.TaxLowerComHigh)) != (DistrictPolicies.Taxation.TaxRaiseComHigh | DistrictPolicies.Taxation.TaxLowerComHigh))
                    {
                        instance1.m_districts.m_buffer[(int)district].m_taxationPoliciesEffect |= taxationPolicies & (DistrictPolicies.Taxation.TaxRaiseComHigh | DistrictPolicies.Taxation.TaxLowerComHigh);
                    }
                    instance1.m_districts.m_buffer[(int)district].m_cityPlanningPoliciesEffect |= cityPlanningPolicies & DistrictPolicies.CityPlanning.BigBusiness;
                    break;

                case ItemClass.SubService.CommercialLeisure:
                    instance1.m_districts.m_buffer[(int)district].m_taxationPoliciesEffect     |= taxationPolicies & DistrictPolicies.Taxation.DontTaxLeisure;
                    instance1.m_districts.m_buffer[(int)district].m_cityPlanningPoliciesEffect |= cityPlanningPolicies & DistrictPolicies.CityPlanning.NoLoudNoises;
                    break;

                case ItemClass.SubService.CommercialTourist:
                    instance1.m_districts.m_buffer[(int)district].m_cityPlanningPoliciesEffect |= cityPlanningPolicies & DistrictPolicies.CityPlanning.LightningRods;
                    break;

                case ItemClass.SubService.CommercialEco:
                    instance1.m_districts.m_buffer[(int)district].m_cityPlanningPoliciesEffect |= cityPlanningPolicies;
                    break;
                }
                Citizen.BehaviourData behaviour = new Citizen.BehaviourData();
                int aliveWorkerCount            = 0;
                int totalWorkerCount            = 0;
                int workPlaceCount = 0;
                int num1           = NewPrivateBuildingAI.HandleWorkers(thisAI, buildingID, ref buildingData, ref behaviour, ref aliveWorkerCount, ref totalWorkerCount, ref workPlaceCount);

                if ((buildingData.m_flags & Building.Flags.Evacuating) != Building.Flags.None)
                {
                    num1 = 0;
                }

                int width      = buildingData.Width;
                int length     = buildingData.Length;
                int num2       = MaxIncomingLoadSize(thisAI);
                int aliveCount = 0;
                int totalCount = 0;
                GetVisitBehaviour(thisAI, buildingID, ref buildingData, ref behaviour, ref aliveCount, ref totalCount);
                int visitCount = thisAI.CalculateVisitplaceCount(new Randomizer((int)buildingID), width, length);
                int num3       = Mathf.Max(0, visitCount - totalCount);
                int a1         = visitCount * 500;
                int num4       = Mathf.Max(a1, num2 * 4);
                TransferManager.TransferReason incomingTransferReason = GetIncomingTransferReason(thisAI);
                TransferManager.TransferReason outgoingTransferReason = GetOutgoingTransferReason(thisAI, buildingID);
                if (num1 != 0)
                {
                    int num5 = num4;
                    if (incomingTransferReason != TransferManager.TransferReason.None)
                    {
                        num5 = Mathf.Min(num5, (int)buildingData.m_customBuffer1);
                    }
                    if (outgoingTransferReason != TransferManager.TransferReason.None)
                    {
                        num5 = Mathf.Min(num5, num4 - (int)buildingData.m_customBuffer2);
                    }
                    int num6 = Mathf.Max(0, Mathf.Min(num1, (num5 * 200 + num4 - 1) / num4));
                    int a2   = (visitCount * num6 + 9) / 10;
                    if (Singleton <SimulationManager> .instance.m_isNightTime)
                    {
                        a2 = a2 + 1 >> 1;
                    }
                    int num7 = Mathf.Max(0, Mathf.Min(a2, num5));
                    if (incomingTransferReason != TransferManager.TransferReason.None)
                    {
                        buildingData.m_customBuffer1 -= (ushort)num7;
                    }
                    if (outgoingTransferReason != TransferManager.TransferReason.None)
                    {
                        buildingData.m_customBuffer2 += (ushort)num7;
                    }
                    num1 = (num7 + 9) / 10;
                }
                int electricityConsumption;
                int waterConsumption;
                int sewageAccumulation;
                int garbageAccumulation;
                int incomeAccumulation;
                thisAI.GetConsumptionRates(new Randomizer((int)buildingID), num1, out electricityConsumption, out waterConsumption, out sewageAccumulation, out garbageAccumulation, out incomeAccumulation);
                int heatingConsumption = 0;
                if (electricityConsumption != 0 && instance1.IsPolicyLoaded(DistrictPolicies.Policies.ExtraInsulation))
                {
                    if ((policies & DistrictPolicies.Services.ExtraInsulation) != DistrictPolicies.Services.None)
                    {
                        heatingConsumption = Mathf.Max(1, electricityConsumption * 3 + 8 >> 4);
                        incomeAccumulation = incomeAccumulation * 95 / 100;
                    }
                    else
                    {
                        heatingConsumption = Mathf.Max(1, electricityConsumption + 2 >> 2);
                    }
                }
                if (garbageAccumulation != 0 && (policies & DistrictPolicies.Services.Recycling) != DistrictPolicies.Services.None)
                {
                    garbageAccumulation = Mathf.Max(1, garbageAccumulation * 85 / 100);
                    incomeAccumulation  = incomeAccumulation * 95 / 100;
                }
                int taxRate;
                switch (thisAI.m_info.m_class.m_subService)
                {
                case ItemClass.SubService.CommercialLeisure:
                    taxRate = (buildingData.m_flags & Building.Flags.HighDensity) == Building.Flags.None ? Singleton <EconomyManager> .instance.GetTaxRate(ItemClass.Service.Commercial, ItemClass.SubService.CommercialLow, thisAI.m_info.m_class.m_level, taxationPolicies) : Singleton <EconomyManager> .instance.GetTaxRate(ItemClass.Service.Commercial, ItemClass.SubService.CommercialHigh, thisAI.m_info.m_class.m_level, taxationPolicies);

                    if ((taxationPolicies & DistrictPolicies.Taxation.DontTaxLeisure) != DistrictPolicies.Taxation.None)
                    {
                        taxRate = 0;
                    }
                    if ((cityPlanningPolicies & DistrictPolicies.CityPlanning.NoLoudNoises) != DistrictPolicies.CityPlanning.None && Singleton <SimulationManager> .instance.m_isNightTime)
                    {
                        electricityConsumption = electricityConsumption + 1 >> 1;
                        waterConsumption       = waterConsumption + 1 >> 1;
                        sewageAccumulation     = sewageAccumulation + 1 >> 1;
                        garbageAccumulation    = garbageAccumulation + 1 >> 1;
                        incomeAccumulation     = 0;
                        break;
                    }
                    break;

                case ItemClass.SubService.CommercialTourist:
                    taxRate = (buildingData.m_flags & Building.Flags.HighDensity) == Building.Flags.None ? Singleton <EconomyManager> .instance.GetTaxRate(ItemClass.Service.Commercial, ItemClass.SubService.CommercialLow, thisAI.m_info.m_class.m_level, taxationPolicies) : Singleton <EconomyManager> .instance.GetTaxRate(ItemClass.Service.Commercial, ItemClass.SubService.CommercialHigh, thisAI.m_info.m_class.m_level, taxationPolicies);

                    break;

                default:
                    taxRate = Singleton <EconomyManager> .instance.GetTaxRate(thisAI.m_info.m_class, taxationPolicies);

                    break;
                }
                if (num1 != 0)
                {
                    int num5 = HandleCommonConsumption(thisAI, buildingID, ref buildingData, ref frameData, ref electricityConsumption, ref heatingConsumption, ref waterConsumption, ref sewageAccumulation, ref garbageAccumulation, policies);
                    num1 = (num1 * num5 + 99) / 100;
                    if (num1 != 0)
                    {
                        int amount1 = incomeAccumulation;
                        if (amount1 != 0)
                        {
                            if (thisAI.m_info.m_class.m_subService == ItemClass.SubService.CommercialLow)
                            {
                                if ((cityPlanningPolicies & DistrictPolicies.CityPlanning.SmallBusiness) != DistrictPolicies.CityPlanning.None)
                                {
                                    Singleton <EconomyManager> .instance.FetchResource(EconomyManager.Resource.PolicyCost, 12, thisAI.m_info.m_class);

                                    amount1 *= 2;
                                }
                            }
                            else if ((cityPlanningPolicies & DistrictPolicies.CityPlanning.BigBusiness) != DistrictPolicies.CityPlanning.None)
                            {
                                Singleton <EconomyManager> .instance.FetchResource(EconomyManager.Resource.PolicyCost, 25, thisAI.m_info.m_class);

                                amount1 *= 3;
                            }
                            if ((policies & DistrictPolicies.Services.RecreationalUse) != DistrictPolicies.Services.None)
                            {
                                amount1 = (amount1 * 105 + 99) / 100;
                            }
                            int num6 = Singleton <EconomyManager> .instance.AddPrivateIncome(amount1, ItemClass.Service.Commercial, thisAI.m_info.m_class.m_subService, thisAI.m_info.m_class.m_level, taxRate);

                            int amount2 = (behaviour.m_touristCount * num6 + (aliveCount >> 1)) / Mathf.Max(1, aliveCount);
                            int amount3 = Mathf.Max(0, num6 - amount2);
                            if (amount3 != 0)
                            {
                                Singleton <EconomyManager> .instance.AddResource(EconomyManager.Resource.CitizenIncome, amount3, thisAI.m_info.m_class);
                            }
                            if (amount2 != 0)
                            {
                                Singleton <EconomyManager> .instance.AddResource(EconomyManager.Resource.TourismIncome, amount2, thisAI.m_info.m_class);
                            }
                        }
                        int groundPollution;
                        int noisePollution;
                        thisAI.GetPollutionRates(num1, cityPlanningPolicies, out groundPollution, out noisePollution);
                        if (groundPollution != 0 && Singleton <SimulationManager> .instance.m_randomizer.Int32(3U) == 0)
                        {
                            Singleton <NaturalResourceManager> .instance.TryDumpResource(NaturalResourceManager.Resource.Pollution, groundPollution, groundPollution, buildingData.m_position, 60f);
                        }
                        if (noisePollution != 0)
                        {
                            Singleton <ImmaterialResourceManager> .instance.AddResource(ImmaterialResourceManager.Resource.NoisePollution, noisePollution, buildingData.m_position, 60f);
                        }
                        if (num5 < 100)
                        {
                            buildingData.m_flags |= Building.Flags.RateReduced;
                        }
                        else
                        {
                            buildingData.m_flags &= ~Building.Flags.RateReduced;
                        }
                        buildingData.m_flags |= Building.Flags.Active;
                    }
                    else
                    {
                        buildingData.m_flags &= ~(Building.Flags.RateReduced | Building.Flags.Active);
                    }
                }
                else
                {
                    electricityConsumption  = 0;
                    heatingConsumption      = 0;
                    waterConsumption        = 0;
                    sewageAccumulation      = 0;
                    garbageAccumulation     = 0;
                    buildingData.m_problems = Notification.RemoveProblems(buildingData.m_problems, Notification.Problem.Electricity | Notification.Problem.Water | Notification.Problem.Sewage | Notification.Problem.Flood | Notification.Problem.Heating);
                    buildingData.m_flags   &= ~(Building.Flags.RateReduced | Building.Flags.Active);
                }
                int   health    = 0;
                int   wellbeing = 0;
                float radius    = (float)(buildingData.Width + buildingData.Length) * 2.5f;
                if (behaviour.m_healthAccumulation != 0)
                {
                    if (aliveWorkerCount + aliveCount != 0)
                    {
                        health = (behaviour.m_healthAccumulation + (aliveWorkerCount + aliveCount >> 1)) / (aliveWorkerCount + aliveCount);
                    }
                    Singleton <ImmaterialResourceManager> .instance.AddResource(ImmaterialResourceManager.Resource.Health, behaviour.m_healthAccumulation, buildingData.m_position, radius);
                }
                if (behaviour.m_wellbeingAccumulation != 0)
                {
                    if (aliveWorkerCount + aliveCount != 0)
                    {
                        wellbeing = (behaviour.m_wellbeingAccumulation + (aliveWorkerCount + aliveCount >> 1)) / (aliveWorkerCount + aliveCount);
                    }
                    Singleton <ImmaterialResourceManager> .instance.AddResource(ImmaterialResourceManager.Resource.Wellbeing, behaviour.m_wellbeingAccumulation, buildingData.m_position, radius);
                }
                int num8 = Citizen.GetHappiness(health, wellbeing) * 15 / 100;
                int a3   = aliveWorkerCount * 20 / workPlaceCount;
                if ((buildingData.m_problems & Notification.Problem.MajorProblem) == Notification.Problem.None)
                {
                    num8 += 20;
                }
                if (buildingData.m_problems == Notification.Problem.None)
                {
                    num8 += 25;
                }
                int num9  = num8 + Mathf.Min(a3, (int)buildingData.m_customBuffer1 * a3 / num4) + (a3 - Mathf.Min(a3, (int)buildingData.m_customBuffer2 * a3 / num4));
                int num10 = (int)(8 - thisAI.m_info.m_class.m_level);
                int num11 = (int)(11 - thisAI.m_info.m_class.m_level);
                if (thisAI.m_info.m_class.m_subService == ItemClass.SubService.CommercialHigh)
                {
                    ++num10;
                    ++num11;
                }
                if (taxRate < num10)
                {
                    num9 += num10 - taxRate;
                }
                if (taxRate > num11)
                {
                    num9 -= taxRate - num11;
                }
                if (taxRate >= num11 + 4)
                {
                    if ((int)buildingData.m_taxProblemTimer != 0 || Singleton <SimulationManager> .instance.m_randomizer.Int32(32U) == 0)
                    {
                        int num5 = taxRate - num11 >> 2;
                        buildingData.m_taxProblemTimer = (byte)Mathf.Min((int)byte.MaxValue, (int)buildingData.m_taxProblemTimer + num5);
                        if ((int)buildingData.m_taxProblemTimer >= 96)
                        {
                            buildingData.m_problems = Notification.AddProblems(buildingData.m_problems, Notification.Problem.TaxesTooHigh | Notification.Problem.MajorProblem);
                        }
                        else if ((int)buildingData.m_taxProblemTimer >= 32)
                        {
                            buildingData.m_problems = Notification.AddProblems(buildingData.m_problems, Notification.Problem.TaxesTooHigh);
                        }
                    }
                }
                else
                {
                    buildingData.m_taxProblemTimer = (byte)Mathf.Max(0, (int)buildingData.m_taxProblemTimer - 1);
                    buildingData.m_problems        = Notification.RemoveProblems(buildingData.m_problems, Notification.Problem.TaxesTooHigh);
                }
                int entertainment;
                int attractiveness;
                GetAccumulation(thisAI, new Randomizer((int)buildingID), num1, taxRate, cityPlanningPolicies, taxationPolicies, out entertainment, out attractiveness);
                if (entertainment != 0)
                {
                    Singleton <ImmaterialResourceManager> .instance.AddResource(ImmaterialResourceManager.Resource.Entertainment, entertainment, buildingData.m_position, radius);
                }
                if (attractiveness != 0)
                {
                    Singleton <ImmaterialResourceManager> .instance.AddResource(ImmaterialResourceManager.Resource.Attractiveness, attractiveness);
                }
                int happiness = Mathf.Clamp(num9, 0, 100);
                buildingData.m_health       = (byte)health;
                buildingData.m_happiness    = (byte)happiness;
                buildingData.m_citizenCount = (byte)(aliveWorkerCount + aliveCount);
                HandleDead(thisAI, buildingID, ref buildingData, ref behaviour, totalWorkerCount + totalCount);
                int crimeAccumulation = behaviour.m_crimeAccumulation / 10;
                if (thisAI.m_info.m_class.m_subService == ItemClass.SubService.CommercialLeisure)
                {
                    crimeAccumulation = crimeAccumulation * 5 + 3 >> 2;
                }
                if ((policies & DistrictPolicies.Services.RecreationalUse) != DistrictPolicies.Services.None)
                {
                    crimeAccumulation = crimeAccumulation * 3 + 3 >> 2;
                }
                HandleCrime(thisAI, buildingID, ref buildingData, crimeAccumulation, (int)buildingData.m_citizenCount);
                int num12 = (int)buildingData.m_crimeBuffer;
                if (aliveWorkerCount != 0)
                {
                    Singleton <ImmaterialResourceManager> .instance.AddResource(ImmaterialResourceManager.Resource.Density, aliveWorkerCount, buildingData.m_position, radius);

                    int num5 = (behaviour.m_educated0Count * 100 + behaviour.m_educated1Count * 50 + behaviour.m_educated2Count * 30) / aliveWorkerCount + 50;
                    buildingData.m_fireHazard = (byte)num5;
                }
                else
                {
                    buildingData.m_fireHazard = (byte)0;
                }
                int crimeRate = (int)buildingData.m_citizenCount == 0 ? 0 : (num12 + ((int)buildingData.m_citizenCount >> 1)) / (int)buildingData.m_citizenCount;
                int count     = 0;
                int cargo     = 0;
                int capacity  = 0;
                int outside   = 0;
                if (incomingTransferReason != TransferManager.TransferReason.None)
                {
                    CalculateGuestVehicles(thisAI, buildingID, ref buildingData, incomingTransferReason, ref count, ref cargo, ref capacity, ref outside);
                    buildingData.m_tempImport = (byte)Mathf.Clamp(outside, (int)buildingData.m_tempImport, (int)byte.MaxValue);
                }
                buildingData.m_tempExport = (byte)Mathf.Clamp(behaviour.m_touristCount, (int)buildingData.m_tempExport, (int)byte.MaxValue);
                SimulationManager _simulationManager = Singleton <SimulationManager> .instance;
                if ((long)((_simulationManager.m_currentFrameIndex & 3840U) >> 8) == (long)((int)buildingID & 15) && (thisAI.m_info.m_class.m_subService == ItemClass.SubService.CommercialLow || thisAI.m_info.m_class.m_subService == ItemClass.SubService.CommercialHigh) && ((int)Singleton <ZoneManager> .instance.m_lastBuildIndex == (int)_simulationManager.m_currentBuildIndex && (buildingData.m_flags & Building.Flags.Upgrading) == Building.Flags.None))
                {
                    CheckBuildingLevel(thisAI, buildingID, ref buildingData, ref frameData, ref behaviour, aliveCount);
                }
                if ((buildingData.m_flags & (Building.Flags.Completed | Building.Flags.Upgrading)) == Building.Flags.None)
                {
                    return;
                }
                Notification.Problem problems1 = Notification.RemoveProblems(buildingData.m_problems, Notification.Problem.NoCustomers | Notification.Problem.NoGoods);

                //Begin edited section

                if ((int)buildingData.m_customBuffer2 > num4 - (a1 >> 1) && aliveCount <= visitCount >> 1)
                {
                    if (_simulationManager.m_currentDayTimeHour > 19 && _simulationManager.m_currentDayTimeHour < 20)
                    {
                        buildingData.m_outgoingProblemTimer = (byte)Mathf.Min(byte.MaxValue, buildingData.m_outgoingProblemTimer + 1);

                        if (buildingData.m_outgoingProblemTimer >= 192)
                        {
                            problems1 = Notification.AddProblems(problems1, Notification.Problem.NoCustomers | Notification.Problem.MajorProblem);
                        }
                        else if (buildingData.m_outgoingProblemTimer >= 128)
                        {
                            problems1 = Notification.AddProblems(problems1, Notification.Problem.NoCustomers);
                        }
                    }
                    else
                    {
                        buildingData.m_outgoingProblemTimer = 0;
                    }
                }
                else
                {
                    buildingData.m_outgoingProblemTimer = (byte)0;
                }

                if (!CityEventManager.instance.EventStartsWithin(3D) && !CityEventManager.instance.EventTakingPlace() && !CityEventManager.instance.EventJustEnded())
                {
                    if ((int)buildingData.m_customBuffer1 == 0)
                    {
                        buildingData.m_incomingProblemTimer = (byte)Mathf.Min((int)byte.MaxValue, (int)buildingData.m_incomingProblemTimer + 1);
                        problems1 = (int)buildingData.m_incomingProblemTimer >= 64 ? Notification.AddProblems(problems1, Notification.Problem.NoGoods | Notification.Problem.MajorProblem) : Notification.AddProblems(problems1, Notification.Problem.NoGoods);
                    }
                    else
                    {
                        buildingData.m_incomingProblemTimer = (byte)0;
                    }

                    float currentHour = _simulationManager.m_currentDayTimeHour;

                    //Artifically shop at night to keep industry happy. Will give the effect of industry stocking up commercial over night.
                    //Note: ModifyMaterialBuffer is expensive, so if there's any performance impact with the mod now, it'll most likely be this.
                    if ((currentHour > 20f || currentHour < 4f))
                    {
                        if (_simulationManager.m_randomizer.Int32(80) < 2)
                        {
                            //Simulate 2 people buying things
                            int amount = -200;
                            thisAI.ModifyMaterialBuffer(buildingID, ref buildingData, TransferManager.TransferReason.Shopping, ref amount);
                        }
                    }
                    else if (Experiments.ExperimentsToggle.AllowActiveCommercialFix && _simulationManager.m_randomizer.Int32(40) < 5) //Added in as a potential fix to random inactive buildings. Lack of customers still shuts down commercial.
                    {
                        int amount = -50;
                        thisAI.ModifyMaterialBuffer(buildingID, ref buildingData, TransferManager.TransferReason.Shopping, ref amount);
                    }
                }
                else
                {
                    buildingData.m_incomingProblemTimer = 0;
                }

                //End edited section

                buildingData.m_problems = problems1;
                instance1.m_districts.m_buffer[(int)district].AddCommercialData(ref behaviour, health, happiness, crimeRate, workPlaceCount, aliveWorkerCount, Mathf.Max(0, workPlaceCount - totalWorkerCount), visitCount, aliveCount, num3, (int)thisAI.m_info.m_class.m_level, electricityConsumption, heatingConsumption, waterConsumption, sewageAccumulation, garbageAccumulation, incomeAccumulation, Mathf.Min(100, (int)buildingData.m_garbageBuffer / 50), (int)buildingData.m_waterPollution * 100 / (int)byte.MaxValue, (int)buildingData.m_finalImport, (int)buildingData.m_finalExport, thisAI.m_info.m_class.m_subService);
                if ((int)buildingData.m_fireIntensity == 0 && incomingTransferReason != TransferManager.TransferReason.None)
                {
                    int num5 = num4 - (int)buildingData.m_customBuffer1 - capacity - (num2 >> 1);
                    if (num5 >= 0)
                    {
                        Singleton <TransferManager> .instance.AddIncomingOffer(incomingTransferReason, new TransferManager.TransferOffer()
                        {
                            Priority = num5 * 8 / num2,
                            Building = buildingID,
                            Position = buildingData.m_position,
                            Amount   = 1,
                            Active   = false
                        });
                    }
                }
                if ((int)buildingData.m_fireIntensity == 0 && outgoingTransferReason != TransferManager.TransferReason.None)
                {
                    int num5 = (int)buildingData.m_customBuffer2 - aliveCount * 100;
                    if (num5 >= 100 && num3 > 0)
                    {
                        Singleton <TransferManager> .instance.AddOutgoingOffer(outgoingTransferReason, new TransferManager.TransferOffer()
                        {
                            Priority = Mathf.Max(1, num5 * 8 / num4),
                            Building = buildingID,
                            Position = buildingData.m_position,
                            Amount   = Mathf.Min(num5 / 100, num3),
                            Active   = false
                        });
                    }
                }

                PrivateBuildingAI baseAI = thisAI as PrivateBuildingAI; //Because we don't have access to base here.

                if (baseAI != null)
                {
                    NewPrivateBuildingAI.SimulationStepActive(baseAI, buildingID, ref buildingData, ref frameData);
                }

                HandleFire(thisAI, buildingID, ref buildingData, ref frameData, policies);
            }
            else
            {
                Debug.LogError("Commercial building " + buildingID + " has no AI! This could have been bad.");
            }
        }
        //Thread: Main
        public void OnCreated(IThreading threading)
        {
            Debug.Log("MyIThreadingExtension Created");

            simulationManager = Singleton<SimulationManager>.instance;

            this.stopWatch = new Stopwatch();
            this.stopWatch.Start();

            //SendEvent();

            Debug.Log("MyIThreadingExtension Created Complete");
        }
 private void OnLevelLoaded(SimulationManager.UpdateMode mode)
 {
     UnityEngine.Debug.Log("Lalala");
 }
Example #42
0
        public void MatchesJsonOneViolation()
        {
            var v = new LengthEquals("TheProperty", 4);
            var s = Moksy.Common.SimulationFactory.When.I.Post().ToImdb("/Pet").With.Constraint(v);
            SimulationManager mgr = new SimulationManager();
            mgr.Add(s.Simulation);

            var matches = mgr.FindMatchingConstraints(s.Simulation, new List<ConstraintBase>() { v }, @"{ ""TheProperty"":""ABCD"" }", null);
            Assert.AreEqual(1, matches.Count());
        }
        void LoadedGameCallback(SimulationManager.UpdateMode updateMode)
        {
            if (!loadingGuildGame)
            {
                Log.Debug("Loaded but was not a guild game");
                return;
            }

            loadingGuildGame = false;
            Singleton<LoadingManager>.instance.m_levelLoaded -= LoadedGameCallback;
            manager.OnStartedGuildGame(currentCityId);
        }
        public void UpdateData(SimulationManager.UpdateMode mode)
        {
            Singleton<LoadingManager>.instance.m_loadingProfilerSimulation.BeginLoading("ElectricityManager.UpdateData");

            if ((bool)m_refreshGrid.GetValue(ElectricityManager.instance))
            {
                UpdateGrid(-100000f, -100000f, 100000f, 100000f);
            }
            Singleton<LoadingManager>.instance.m_loadingProfilerSimulation.EndLoading();
        }
Example #45
0
        public void OnLevelLoaded(SimulationManager.UpdateMode mode)
        {
            InitModTools(mode);

            var loadingManager = LoadingManager.instance;
            var wrapper = loadingManager.m_LoadingWrapper;

            var loadingExtensions = Util.GetPrivate<List<ILoadingExtension>>(wrapper, "m_LoadingExtensions");

            try
            {
                for (int i = 0; i < loadingExtensions.Count; i++)
                {
                    loadingExtensions[i].OnLevelLoaded((LoadMode)mode);
                }
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                UIView.ForwardException(new ModException("A Mod caused an error", ex));
            }
        }
	void Awake() {
		sm = SimulationManager.sharedSimManager;
		sm.TimeScale = this;
	}
Example #47
0
        private static void InitModTools(SimulationManager.UpdateMode mode)
        {
            if (!IsModToolsActive())
            {
                return;
            }

            if (modToolsGameObject != null)
            {
                return;
            }

            modToolsGameObject = new GameObject("ModTools");
            modTools = modToolsGameObject.AddComponent<ModTools>();
            modTools.Initialize(mode);
        }
Example #48
0
 // Use this for initialization
 void Start()
 {
     this.simManager = (SimulationManager)GameObject.Find("OldNest").GetComponent("SimulationManager");
     this.ant = (AntManager) transform.GetComponent("AntManager");
     this.cont = (CharacterController)transform.GetComponent("CharacterController");
     this.lastTurn = transform.position;
     this.dir = Random.Range(0, 360);
     this.nextDirChange_time = Time.timeSinceLevelLoad + maxDirChange_time;
     this.rg = new RandomGenerator();
     this.pheromoneParent = GameObject.Find("Pheromones").transform;
     this.nextPheromoneCheck = Time.timeSinceLevelLoad;
     //passive ants laying in centre of nests makes ants gravitate towards nest centers to much
     if(!this.ant.passive && this.usePheromones)
         InvokeRepeating("LayPheromone", 0, pheromoneFrequency);
 }
Example #49
0
 public ProcessorBreakdownEvent(double timeIn, SimulationManager managerIn, Processor processorIn)
     : base(timeIn, managerIn)
 {
     this.processor = processorIn;
 }
	void Awake() {
		//check the current task.
		sm = SimulationManager.sharedSimManager;
	}
        public override void SimulationStep(ushort buildingID, ref Building buildingData, ref Building.Frame frameData)
        {
            base.SimulationStep(buildingID, ref buildingData, ref frameData);
            if (Singleton <SimulationManager> .instance.m_randomizer.Int32(10U) == 0)
            {
                DistrictManager instance = Singleton <DistrictManager> .instance;
                byte            district = instance.GetDistrict(buildingData.m_position);
                ushort          num      = instance.m_districts.m_buffer[(int)district].m_Style;
                if ((int)num > 0 && (int)num - 1 < instance.m_Styles.Length)
                {
                    DistrictStyle districtStyle = instance.m_Styles[(int)num - 1];
                    if (districtStyle != null && (UnityEngine.Object) this.m_info.m_class != (UnityEngine.Object)null && (districtStyle.AffectsService(this.m_info.GetService(), this.m_info.GetSubService(), this.m_info.m_class.m_level) && !districtStyle.Contains(this.m_info)) && (int)Singleton <ZoneManager> .instance.m_lastBuildIndex == (int)Singleton <SimulationManager> .instance.m_currentBuildIndex)
                    {
                        buildingData.m_flags |= Building.Flags.Demolishing;
                        ++Singleton <SimulationManager> .instance.m_currentBuildIndex;
                    }
                }
            }
            if ((buildingData.m_flags & Building.Flags.ZonesUpdated) != Building.Flags.None)
            {
                SimulationManager instance = Singleton <SimulationManager> .instance;
                if ((int)buildingData.m_fireIntensity != 0 || instance.m_randomizer.Int32(10U) != 0 || (int)Singleton <ZoneManager> .instance.m_lastBuildIndex != (int)instance.m_currentBuildIndex)
                {
                    return;
                }
                buildingData.m_flags &= ~Building.Flags.ZonesUpdated;
                if (buildingData.CheckZoning(this.m_info.m_class.GetZone(), this.m_info.m_class.GetSecondaryZone()))
                {
                    return;
                }
                buildingData.m_flags |= Building.Flags.Demolishing;
                PrivateBuildingAIDetour.CheckNearbyBuildingZones(buildingData.m_position);
                ++instance.m_currentBuildIndex;
            }
            else
            {
                if ((buildingData.m_flags & (Building.Flags.Abandoned | Building.Flags.Downgrading)) == Building.Flags.None || (int)buildingData.m_majorProblemTimer != (int)byte.MaxValue && (buildingData.m_flags & Building.Flags.Abandoned) != Building.Flags.None)
                {
                    return;
                }
                SimulationManager instance1 = Singleton <SimulationManager> .instance;
                ZoneManager       instance2 = Singleton <ZoneManager> .instance;
                int num1;
                switch (this.m_info.m_class.m_service)
                {
                case ItemClass.Service.Residential:
                    num1 = instance2.m_actualResidentialDemand;
                    break;

                case ItemClass.Service.Commercial:
                    num1 = instance2.m_actualCommercialDemand;
                    break;

                case ItemClass.Service.Industrial:
                    num1 = instance2.m_actualWorkplaceDemand;
                    break;

                case ItemClass.Service.Office:
                    num1 = instance2.m_actualWorkplaceDemand;
                    break;

                default:
                    num1 = 0;
                    break;
                }
                if (instance1.m_randomizer.Int32(100U) >= num1 || (int)instance2.m_lastBuildIndex != (int)instance1.m_currentBuildIndex || (double)Singleton <TerrainManager> .instance.WaterLevel(VectorUtils.XZ(buildingData.m_position)) > (double)buildingData.m_position.y)
                {
                    return;
                }
                ItemClass.SubService subService = this.m_info.m_class.m_subService;
                ItemClass.Level      level      = ItemClass.Level.Level1;
                int width = buildingData.Width;
                int num2  = buildingData.Length;
                if (this.m_info.m_class.m_service == ItemClass.Service.Industrial)
                {
                    ZoneBlock.GetIndustryType(buildingData.m_position, out subService, out level);
                }
                else if (this.m_info.m_class.m_service == ItemClass.Service.Commercial)
                {
                    ZoneBlock.GetCommercialType(buildingData.m_position, this.m_info.m_class.GetZone(), width, num2, out subService, out level);
                }
                DistrictManager instance3          = Singleton <DistrictManager> .instance;
                byte            district           = instance3.GetDistrict(buildingData.m_position);
                ushort          num3               = instance3.m_districts.m_buffer[(int)district].m_Style;
                BuildingInfo    randomBuildingInfo = Singleton <BuildingManager> .instance.GetRandomBuildingInfo(ref Singleton <SimulationManager> .instance.m_randomizer, this.m_info.m_class.m_service, subService, level, width, num2, this.m_info.m_zoningMode, (int)num3);

                if (randomBuildingInfo == null)
                {
                    return;
                }
                buildingData.m_flags |= Building.Flags.Demolishing;
                float num4 = buildingData.m_angle + 1.570796f;
                float num5;
                if (this.m_info.m_zoningMode == BuildingInfo.ZoningMode.CornerLeft && randomBuildingInfo.m_zoningMode == BuildingInfo.ZoningMode.CornerRight)
                {
                    num5 = num4 - 1.570796f;
                    num2 = width;
                }
                else if (this.m_info.m_zoningMode == BuildingInfo.ZoningMode.CornerRight && randomBuildingInfo.m_zoningMode == BuildingInfo.ZoningMode.CornerLeft)
                {
                    num5 = num4 + 1.570796f;
                    num2 = width;
                }
                ushort building;
                if (Singleton <BuildingManager> .instance.CreateBuilding(out building, ref Singleton <SimulationManager> .instance.m_randomizer, randomBuildingInfo, buildingData.m_position, buildingData.m_angle, num2, Singleton <SimulationManager> .instance.m_currentBuildIndex))
                {
                    ++Singleton <SimulationManager> .instance.m_currentBuildIndex;
                    switch (this.m_info.m_class.m_service)
                    {
                    case ItemClass.Service.Residential:
                        instance2.m_actualResidentialDemand = Mathf.Max(0, instance2.m_actualResidentialDemand - 5);
                        break;

                    case ItemClass.Service.Commercial:
                        instance2.m_actualCommercialDemand = Mathf.Max(0, instance2.m_actualCommercialDemand - 5);
                        break;

                    case ItemClass.Service.Industrial:
                        instance2.m_actualWorkplaceDemand = Mathf.Max(0, instance2.m_actualWorkplaceDemand - 5);
                        break;

                    case ItemClass.Service.Office:
                        instance2.m_actualWorkplaceDemand = Mathf.Max(0, instance2.m_actualWorkplaceDemand - 5);
                        break;
                    }
                }
                ++instance1.m_currentBuildIndex;
            }
        }
Example #52
0
 public void Setup()
 {
     Manager = new SimulationManager();
 }
        public static void StartSession(string mapName, string playerMap, SimulationManager.UpdateMode mode, SimulationMetaData ngs)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableStartSession))
                {
                    if (Mod.DEBUG_LOG_ON) { Helper.dbgLog("Start Session telemetry disabled."); }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("start_session", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("type", playerMap),
                    new Telemetry.Pair("start_flag", mode.ToString()),
                    new Telemetry.Pair("map_name", Path.GetFileName(mapName))
                });
                if (ngs != null)
                {
                    telemetry.AddEvent("start_session", new Telemetry.Pair[]
                    {
                        new Telemetry.Pair("environment", ngs.m_environment),
                        new Telemetry.Pair("invert_traffic", ngs.m_invertTraffic),
                        new Telemetry.Pair("guid", ngs.m_gameInstanceIdentifier)
                    });
                }
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase<LogChannel>.Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
        /// <summary>
        /// Like OnLevelLoaded, but executed earlier.
        /// </summary>
        /// <param name="mode"></param>
        public void OnUpdateData(SimulationManager.UpdateMode mode)
        {
            if (mode != SimulationManager.UpdateMode.LoadGame && mode != SimulationManager.UpdateMode.LoadMap) return;

            DeserializeSegmentDataMap();
            DeserializeActiveOptions();

            foreach (var segmentData in _usedSegmentData)
            {
                segmentData.UsedCount = SegmentToSegmentDataMap.Count(segmentData.Equals);
                segmentData.FindPrefabs(); // Find the prefabs for the loaded names
            }

            CleanupData();
        }
Example #55
0
 public override Event GetEvent(SimulationManager managerIn)
 {
     return(new EndPlanningPeriodEvent(this.Time, managerIn));
 }
Example #56
0
        public void UpdateData(SimulationManager.UpdateMode mode)
        {
            try
            {

                lightPropsDefParseErrors = new HashSet<string>();
                var checkedPaths = new List<string>();

                for (uint i = 0; i < PrefabCollection<PropInfo>.LoadedCount(); i++)
                {
                    var prefab = PrefabCollection<PropInfo>.GetLoaded(i);

                    if (prefab == null) continue;

                    // search for LightPropDefinition.xml
                    var asset = PackageManager.FindAssetByName(prefab.name);

                    var crpPath = asset?.package?.packagePath;
                    if (crpPath == null) continue;

                    var lightPropsDefPath = Path.Combine(Path.GetDirectoryName(crpPath) ?? "",
                        "LightPropsDefinition.xml");

                    // skip files which were already parsed
                    if (checkedPaths.Contains(lightPropsDefPath)) continue;
                    checkedPaths.Add(lightPropsDefPath);

                    if (!File.Exists(lightPropsDefPath)) continue;

                    LightPropsDefinition lightPropsDef = null;

                    var xmlSerializer = new XmlSerializer(typeof (LightPropsDefinition));
                    try
                    {
                        using (var streamReader = new System.IO.StreamReader(lightPropsDefPath))
                        {
                            lightPropsDef = xmlSerializer.Deserialize(streamReader) as LightPropsDefinition;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                        lightPropsDefParseErrors.Add(asset.package.packageName + " - " + e.Message);
                        continue;
                    }

                    if (lightPropsDef?.Props == null || lightPropsDef.Props.Count == 0)
                    {
                        lightPropsDefParseErrors.Add(asset.package.packageName + " - lightPropDef is null or empty.");
                        continue;
                    }

                    foreach (var propDef in lightPropsDef.Props)
                    {
                        if (propDef?.Name == null)
                        {
                            lightPropsDefParseErrors.Add(asset.package.packageName + " - Prop name missing.");
                            continue;
                        }

                        var propDefPrefab = FindProp(propDef.Name, asset.package.packageName);

                        if (propDefPrefab == null)
                        {
                            lightPropsDefParseErrors.Add(asset.package.packageName + " - Prop with name " + propDef.Name +
                                                         " not loaded.");
                            continue;
                        }

                        if (propDef.Effects == null || propDef.Effects.Count == 0)
                        {
                            lightPropsDefParseErrors.Add(asset.package.packageName + " - No effects specified for " +
                                                         propDef.Name + ".");
                            continue;
                        }

                        var effects = new List<PropInfo.Effect>();

                        foreach (var effectDef in propDef.Effects)
                        {
                            if (effectDef?.Name == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect name missing.");
                                continue;
                            }

                            var effectPrefab = EffectCollection.FindEffect(effectDef.Name);

                            if (effectPrefab == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect with name " + effectDef.Name +
                                                             " not loaded.");
                                continue;
                            }

                            if (effectDef.Position == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect position not set.");
                                continue;
                            }

                            if (effectDef.Direction == null)
                            {
                                lightPropsDefParseErrors.Add(propDef.Name + " - Effect direction not set.");
                                continue;
                            }

                            var effect = new PropInfo.Effect
                            {
                                m_effect = effectPrefab,
                                m_position = effectDef.Position.ToUnityVector(),
                                m_direction = effectDef.Direction.ToUnityVector().normalized
                            };

                            effects.Add(effect);
                        }

                        if (effects.Count == 0)
                        {
                            lightPropsDefParseErrors.Add("No effects specified for " + propDef.Name + ".");
                            continue;
                        }

                        propDefPrefab.m_effects = effects.ToArray();

                        // taken from PropInfo.InitializePrefab
                        if (propDefPrefab.m_effects != null)
                        {
                            propDefPrefab.m_hasEffects = (propDefPrefab.m_effects.Length != 0);
                            for (var j = 0; j < propDefPrefab.m_effects.Length; j++)
                            {
                                if (propDefPrefab.m_effects[j].m_effect == null) continue;

                                propDefPrefab.m_effects[j].m_effect.InitializeEffect();
                                var layer = propDefPrefab.m_effects[j].m_effect.GroupLayer();
                                if (layer != -1)
                                {
                                    propDefPrefab.m_effectLayer = layer;
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                Debug.LogException(e);
            }
        }
Example #57
0
        //?private Dictionary<int, BehaviourState> _stateHistory = new Dictionary<int, BehaviourState>();

        public AntDebugResults(SimulationManager simulation, string basePath)
            : base(simulation, Path.Combine(basePath, "ants_debug"))
        {
            WriteLine("Tick,AntId,PerceivedTicks");
        }
Example #58
0
        public override void OnAfterSimulationTick()
        {
            if (!V10Bulldoze.active || c++ < V10Bulldoze.ui.data.interval)
                return;
            c = 0;

            if (!V10Bulldoze.ui.data.abandoned && !V10Bulldoze.ui.data.burned)
                return;

            if (simulationManager == null) {
                simulationManager = SimulationManager.instance;
                bulldozeTool = GameObject.FindObjectOfType<BulldozeTool> ();
                method = bulldozeTool.GetType ().GetMethod ("DeleteBuilding", BindingFlags.NonPublic | BindingFlags.Instance);
            }

            if (V10Bulldoze.ui.data.abandoned)
                checkBuildings (SkylinesOverwatch.Data.Instance.BuildingsAbandoned);
            if (V10Bulldoze.ui.data.burned && c2 <= V10Bulldoze.ui.data.max) {
                ushort [] toCheck = SkylinesOverwatch.Data.Instance.BuildingsBurnedDown;
                if (V10Bulldoze.ui.data.service)
                    toCheck = toCheck.Except (SkylinesOverwatch.Data.Instance.PlayerBuildings).ToArray ();
                checkBuildings (toCheck);
            }

            c2 = 0;
        }
Example #59
0
 void GetSimulationManager()
 {
     simulationManager = this.gameObject.GetComponent <SimulationManager>();
 }
Example #60
0
 public void MatchesTwoViolationsOnlyOneIndex()
 {
     var s = Moksy.Common.SimulationFactory.When.I.Post().ToImdb("/Pet").With.NotExists("Kind").Constraint(new LengthEquals("TheProperty", 4)).Constraint(new IsNull("Other"));
     SimulationManager mgr = new SimulationManager();
     mgr.Add(s.Simulation);
     StringContent content = new StringContent(@"{""TheProperty"":""ABCD""}");
     var match = mgr.Match(HttpMethod.Post, content, "/Pet", "", new List<Header>(), false);
     Assert.IsNull(match);
 }