コード例 #1
0
ファイル: SimulationRunner.cs プロジェクト: britg/ptq
 void Awake()
 {
     QualitySettings.vSyncCount = 0;
     Application.targetFrameRate = 60;
     sim = new Simulation();
     sim.Setup();
 }
コード例 #2
0
ファイル: SimulationView.cs プロジェクト: GabrielSibley/games
    public void Display(Simulation sim)
    {
        Simulation = sim;
        pipeEditor.Simulation = sim; //TODO: axe
        inputManager.ProcessInput();
        if (ActivePanel == UIPanel.Machines)
        {
            shopView.gameObject.SetActive(true);
            shopView.Display(sim.MachineShop);
        }
        else
        {
            shopView.gameObject.SetActive(false);
        }

        if (ActivePanel == UIPanel.Contracts)
        {
            contractsPanel.SetActive(true);
            supplyView.Display(sim.SupplyShop);
            deliverView.Display(sim.DeliveryShop);
        }
        else
        {
            contractsPanel.SetActive(false);
        }

        carriedMachineDisplay.Display(CarriedMachine);

        DisplayFloorMachines(sim);
        DisplayContractSlots();

        Simulation = null;
    }
コード例 #3
0
ファイル: SimulationTest.cs プロジェクト: Zolniu/DigitalRune
        public void EmptySimulation()
        {
            Simulation simulation = new Simulation();
              Assert.IsNotNull(simulation.CollisionDomain);
              Assert.IsEmpty(simulation.CollisionDomain.CollisionObjects);
              Assert.IsNotNull(simulation.Constraints);
              Assert.IsEmpty(simulation.Constraints);
              Assert.IsNotNull(simulation.ContactConstraints);
              Assert.IsEmpty(simulation.ContactConstraints);
              Assert.IsNotNull(simulation.ForceEffects);
              Assert.IsEmpty(simulation.ForceEffects);
              Assert.IsNotNull(simulation.IslandManager);
              Assert.IsEmpty(simulation.IslandManager.Islands);
              Assert.IsNotNull(simulation.RigidBodies);
              Assert.IsEmpty(simulation.RigidBodies);
              Assert.IsNotNull(simulation.Settings);
              Assert.IsNotNull(simulation.World);

              simulation.Update(0);
              simulation.Update(1);

              Assert.IsEmpty(simulation.CollisionDomain.CollisionObjects);
              Assert.IsEmpty(simulation.Constraints);
              Assert.IsEmpty(simulation.ContactConstraints);
              Assert.IsEmpty(simulation.ForceEffects);
              Assert.IsEmpty(simulation.IslandManager.Islands);
              Assert.IsEmpty(simulation.RigidBodies);
        }
コード例 #4
0
        public override void Apply(Simulation Sim)
        {
            var cell = Sim.World.CellAt(Location);

            if (Onto.PresentActor != null)
            {
                Result = MutationResult.Failure;
                return;
            }

            var stepIndex = cell.Links.FindIndex(l => Object.ReferenceEquals(l.Neighbor, Onto));
            if (stepIndex < 0 || stepIndex >= cell.Links.Count)
            {
                Result = MutationResult.Failure;
                return;
            }

            cell.PresentActor = null;
            Onto.PresentActor = Actor;

            //Actor.CurrentAction = new MoveAction(cell, cell.Links[stepIndex].Direction);
            Actor.FacingDirection = cell.Links[stepIndex].Direction;

            Actor.Location = Onto.Location;

            Result = MutationResult.Success;
        }
コード例 #5
0
 public void TestNetwork3()
 {
     NewRandom originalRand = new NewRandom(10);
     Simulation network = new Simulation(originalRand);
     network.ChangeNetworkState();
     Assert.AreEqual(network.ShowState(4), "is healthy.");
 }
コード例 #6
0
ファイル: Mine.cs プロジェクト: Blecki/GnomeColony
        public override void ExecuteTask(Simulation Sim)
        {
            switch (State)
            {
                case States.Mining:
                    AssignedGnome.FacingDirection = CellLink.DirectionFromAToB(AssignedGnome.Location, Location);

                    Progress -= 0.1f;//Game.ElapsedSeconds;
                    if (Progress <= 0.0f)
                    {
                        MineMutation = new WorldMutations.RemoveBlockMutation(Location, AssignedGnome);
                        Sim.AddWorldMutation(MineMutation);
                        State = States.Finalizing;
                    }

                    return;
                case States.Finalizing:
                    if (MineMutation.Result == MutationResult.Failure)
                        State = States.Mining;
                    else
                    {
                        State = States.Done;
                        Sim.AddTask(new RemoveExcessResource(Location));
                    }
                    return;
                case States.Done:
                    throw new InvalidProgramException("Task should have been deemed completed.");
            }
        }
コード例 #7
0
ファイル: LocalGame.cs プロジェクト: hvp/Gemgine
        public void Begin()
        {
            guiModule = new GuiModule(Main.GraphicsDevice, Main.Input);
            inputModule = new InputModule(Main.Input);

            simulation = new Simulation(Main.Content, new MISP.GenericScriptObject(
                "episode-name", "main-menu", "server", null));
            simulation.debugOutput += (s) => { Main.Write(s); };
            simulation.Content.FrontLoadTextures();
            Main.Write("Started menu simulation\n");
            Main.ScriptEngine.PrepareEnvironment(simulation.scriptEngine);
            Main.ScriptEngine.AddEnvironment("menu", simulation.scriptEngine, simulation.scriptContext);

            renderModule = new RenderModule(Main.GraphicsDevice, simulation.Content);
            simulation.modules.Add(renderModule);
            octTreeModule = new OctTreeModule(new BoundingBox(new Vector3(-100, -100, -100), new Vector3(100, 100, 100)), 5.0f);
            simulation.modules.Add(octTreeModule);
            simulation.modules.Add(inputModule);
            simulation.modules.Add(guiModule);

            simulation.beginSimulation();

            //var labelString = "Jemgine";

            //var label = new UIItem(Layout.CenterItem(new Rectangle(0, 0, 10 * labelString.Length, 16),
            //    Main.GraphicsDevice.Viewport.Bounds));
            //label.settings = new MISP.GenericScriptObject(
            //    "bg-color", new Vector3(0, 0, 0),
            //    "text-color", new Vector3(1,1,1),
            //    "label", labelString);
            //guiModule.uiRoot.AddChild(label);
        }
コード例 #8
0
        public ActionResult Simulation(VGeneralProperties model)
        {
            ViewBag.Title = "Input | Wake Simulation II | Offwind";
            lock (_model)
            {
                model.WindFarm = _model.WindFarm;
                ObjectMapperManager.DefaultInstance.GetMapper<VGeneralProperties, VGeneralProperties>().Map(model, _model);
            }
            var dWindFarm = _ctx.DWindFarms.First(e => _model.WindFarm == e.Name);
            _model.NTurbines = dWindFarm.DWindFarmTurbines.Count();

            var input = new Simulation()
            {
                Tstart = (double)_model.StartTime,
                Tend = (double)_model.StopTime,
                DT = (double)_model.TimeStep,
                NTurbines = _model.NTurbines,
                RatedPower = 5,
                EnablePowerDistribution = true,
                EnableTurbineDynamics = true,
                PowerRefInterpolation = true,
                Pdemand = 3 * 5e6,
                PRefSampleTime = 5
            };

            input.LoadNREL5MW_MatFile(WebConfigurationManager.AppSettings["WakeFarmControlNREL5MW"]);
            input.LoadWind_MatFile(WebConfigurationManager.AppSettings["WakeFarmControlWind"]);

            _simulation = FarmControl2.Simulation(input);
            return RedirectToAction("Results");
        }
コード例 #9
0
ファイル: PlayerMethods.cs プロジェクト: MartyIX/SoTh
        /// <summary>
        /// Prepares everything needed for start of given round
        /// </summary>
        public void InitializeRound()
        {
            DebugP("InitializeRound");
            form.KeyboardInitialize();
            //form.resetTimeAndSteps();

            profile.userCanPressArrows = false;

            gameDesk.Clear();
            gameDesk.logList.Clear();

            // creates model for this player
            model = new Simulation(form, this);

            if (this.ToString() == "PlayerTwo")
            {
                model.calendar.IsEnabledAddingEvents = false; // default for second player
            }

            //form.IsGraphicsChangeEnabled = false;
            //XmlRounds xmlRounds = gameDesk.LoadRoundFromXML(form.actLeagueXml, this.round);
            //form.IsGraphicsChangeEnabled = true;

            //this.roundsNo = xmlRounds.Count;

            this.gameState = GameState.BeforeFirstMove;

            gameDesk.HookRedrawing();
        }
コード例 #10
0
        public void Init()
        {
            motionSimulation = new ThreadSimulationProxy(new Simulation());

            //var npc = new NPC() { ID = "Villain" };
            //motionSimulation.Insert(npc);
            //unit1 = new ThreadUnitProxy(new Unit { ID = "Unit1" }, motionSimulation);
            var us = new Simulation().CreateUnit();
            ((Unit)us).ID = "Unit1";

            unit1 = motionSimulation.CreateUnit(us);
            unit1.IntersectsUnit += new EventHandler<IObjectArgs<IUnit>>(unit1_IntersectsUnit);
            //unit1.IntersectsUnit -= new EventHandler<IObjectArgs<IUnit>>(unit1_IntersectsUnit);
            //unit1.IntersectsUnit += (sender, unit) =>
            //{
            //    DebugOutput("UNITS INTERSECTED");
            //};
            //unit1.IntersectsUnit -= (sender, unit) =>
            //{
            //    DebugOutput("UNITS INTERSECTED");
            //};
            motionSimulation.Insert(unit1);

            //var projectile = new Projectile();
            //projectile.HitsObject += new Action<Object>((o) =>
            //{
            //    DebugOutput("Projectile hit " + ((Unit)o).ID);
            //});
            //motionSimulation.Insert(projectile);
        }
コード例 #11
0
ファイル: Mine.cs プロジェクト: Blecki/GnomeColony
 public override void Apply(Simulation Sim, WorldSceneNode WorldNode)
 {
     if (Sim.World.Check(WorldNode.HoverBlock))
     {
         Sim.AddTask(new Tasks.Mine(WorldNode.HoverBlock));
     }
 }
コード例 #12
0
        public override void Apply(Simulation Sim)
        {
            var cell = Sim.World.CellAt(Location);

            if (cell.Block == null)
            {
                Result = MutationResult.Failure;
                return;
            }

            if (cell.PresentActor != null || (!Task.NoGnomesInArea(Sim, Location)))
            {
                Result = MutationResult.Failure;
                return;
            }

            if (cell.Resources.Count != 0)
            {
                Result = MutationResult.Failure;
                return;
            }

            if (cell.Block.MineResources != null) cell.Resources = new List<String>(cell.Block.MineResources);
            cell.Block = null;

            if (cell.Resources.Count > 0)
            {
                Gnome.CarriedResource = cell.Resources[0];
                cell.Resources.RemoveAt(0);
            }

            Sim.SetUpdateFlag(Location);

            Result = MutationResult.Success;
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: felix11/MSP-Workshops
        private void buttonStartSimulation_Click(object sender, EventArgs e)
        {
            if (buttonStartSimulation.Text.StartsWith("Stop"))
            {
                buttonStartSimulation.Text = "Start Simulation";
                timer1.Stop();
            }
            else
            {
                buttonStartSimulation.Text = "Stop Simulation";

                Series s1 = chart1.Series.First(); // time
                Series s2 = chart2.Series.First(); // data
                Series s3 = chart3.Series.First(); // loader

                s1.Points.Clear();
                s2.Points.Clear();
                s3.Points.Clear();

                starttime = DateTime.Now;
                labelTime.Text = "0 msec";
                timer1.Tick += new EventHandler(timer1_Tick);
                timer1.Start();
                textBoxOutput.Text = "";

                Simulation sim = new Simulation();
                sim.start(Convert.ToInt32(numericUpDownStudentCount.Value), s1.Points, s2.Points, loaders);
            }
        }
コード例 #14
0
        public static bool ScreenPositionToWorldPositionRaycast(Vector2 screenPos, CameraComponent camera, Simulation simulation)
        {
            var invViewProj = Matrix.Invert(camera.ViewProjectionMatrix);

            Vector3 sPos;
            sPos.X = screenPos.X * 2f - 1f;
            sPos.Y = 1f - screenPos.Y * 2f;

            sPos.Z = 0f;
            var vectorNear = Vector3.Transform(sPos, invViewProj);
            vectorNear /= vectorNear.W;

            sPos.Z = 1f;
            var vectorFar = Vector3.Transform(sPos, invViewProj);
            vectorFar /= vectorFar.W;

            var result = simulation.RaycastPenetrating(vectorNear.XYZ(), vectorFar.XYZ());
            foreach (var hitResult in result)
            {
                if (hitResult.Succeeded)
                {
                    return true;
                }
            }

            return false;
        }
コード例 #15
0
ファイル: Feeder.cs プロジェクト: ProCP-Fontys/Simulation
    public Feeder(int feederID, Crossing crossing, Simulation simulation)
    {
        this.simulation = simulation;
        this.FeederID = feederID;
        this.crossing = crossing;
        random = new Random();

        CarsComingIn = new Car[5];
        CarsGoingOut = new Car[5];

        StopPointsComingIn = new List<Point>();
        StopPointsGoingOut = new List<Point>();

        switch (this.FeederID)
        {
            case 1:
                for (int i = 4; i > -1; i--)
                {
                    this.StopPointsGoingOut.Add(new Point(Convert.ToInt16(i + "7"), 112));
                }

                for (int i = 12; i < 53; i += 10)
                {
                    this.StopPointsComingIn.Add(new Point(i, 82));
                }
                break;
            case 2:
                for (int i = 4; i > -1; i--)
                {
                    this.StopPointsGoingOut.Add(new Point(82, Convert.ToInt16(i + "7")));
                }
                for (int i = 12; i < 53; i += 10)
                {
                    this.StopPointsComingIn.Add(new Point(112, Convert.ToInt16(i)));
                }
                break;
            case 3:
                for (int i = 146; i < 187; i += 10)
                {
                    this.StopPointsGoingOut.Add(new Point(i, 82));
                }
                for (int i = 186; i > 145; i -= 10)
                {
                    this.StopPointsComingIn.Add(new Point(i, 112));
                }
                break;
            case 4:
                for (int i = 146; i < 187; i += 10)
                {
                    this.StopPointsGoingOut.Add(new Point(112, i));
                }

                for (int i = 192; i > 151; i -= 10)
                {
                    this.StopPointsComingIn.Add(new Point(82, i));
                }
                break;
        }
    }
コード例 #16
0
ファイル: ServerModule.cs プロジェクト: Blecki/GemgineCore
        void IModule.BeginSimulation(Simulation sim)
        {
            this.sim = sim;
            sim.sendMessageHandler += (bytes) => { pendingMessages.Add(bytes); };

            try
            {
                netSession = new Network.ServerSession(port, sim.debug);

                netSession.onClientJoined += (client) =>
                {
                    var welcomeDatagram = new Network.WriteOnlyDatagram();
                    welcomeDatagram.WriteUInt(0, 8);
                    welcomeDatagram.WriteString(sim.Content.Module.Name);
                    welcomeDatagram.WriteUInt((uint)sim.Content.Module.Version, 32);
                    netSession.sendCriticalDatagram(client, welcomeDatagram.BufferAsArray, () =>
                    {
                        sim.EnqueueEvent("on-new-client", new MISP.ScriptList(client));
                    });
                };

                netSession.onDatagramReceived += (client, bytes) =>
                    {
                        var gram = new Network.ReadOnlyDatagram(bytes);
                        while (gram.More)
                        {
                            uint messageCode = 0;
                            gram.ReadUInt(out messageCode, 8);

                            switch (messageCode)
                            {
                                case 0:
                                    //Should never receive this message.
                                    break;
                                case 1:
                                    //Should never receive this message.
                                    break;
                                case 2:
                                    {
                                        UInt32 length;
                                        gram.ReadUInt(out length, 32);
                                        byte[] message = new byte[length];
                                        gram.ReadBytes(message, length);
                                        string messageID = null;
                                        MISP.ScriptList messageData = null;
                                        ScriptMessage.DecodeMessage(message, out messageID, out messageData);
                                        sim.EnqueueEvent(messageID, messageData);
                                    }
                                    break;
                            }
                        }
                    };
            }
            catch (Exception e)
            {
                System.Console.WriteLine("While trying to create a server module, " + e.Message);
                throw e;
            }
        }
コード例 #17
0
ファイル: Bus.cs プロジェクト: npk48/DeSimulator
 public Bus(Simulation Sim, int Id = 0, int Max = 999)
     : base(Sim)
 {
     Identity = Id;
     MaxPassengers = Max;
     Passengers = new Dictionary<string, Queue<Passenger>>();
     Destination = new List<string>();
 }
コード例 #18
0
ファイル: Mine.cs プロジェクト: Blecki/GnomeColony
        public override Task Prerequisite(Simulation Sim)
        {
            if (State != States.Mining) return null;

            if (AssignedGnome.CarryingResource) return new Deposit();
            if (Sim.World.CellAt(Location).Resources.Count != 0) return new RemoveExcessResource(this.Location);
            return null;
        }
コード例 #19
0
ファイル: Simulator.cs プロジェクト: ProCP-Fontys/Simulation
 public Simulator(Simulation simulation)
 {
     this.simulation = simulation;
     simulation.gridGroupBox.Enabled = false;//disable so you cannot drag crossing until creating the grid
     grid = new Grid();
     cars = new List<Car>();
     pictureBoxCrossing = new List<PictureBox>();
 }
コード例 #20
0
        public GameSessionClient(string peerName, string token)
        {
            _name = peerName;
            _token = token;

            _simulation = new Simulation();
            _simulation.Boid.CanAttack = true;
        }
コード例 #21
0
 public override TaskStatus QueryStatus(Simulation Sim)
 {
     if (!Sim.World.Check(Location)) return TaskStatus.Impossible;
     var cell = Sim.World.CellAt(Location);
     var requiredResources = Task.FindUnfilledResourceRequirments(cell, ParentTask);
     if (requiredResources.Count == 0) return TaskStatus.Complete;
     else return TaskStatus.NotComplete;
 }
コード例 #22
0
 public BufferingForm(Simulation Sim, bool StartFromBeginning, long NumberGenerations, MetroFramework.MetroThemeStyle Theme, MetroFramework.MetroColorStyle ColorStyle)
 {
     InitializeComponent();
     this.Sim = Sim;
     this.StartFromBeginning = StartFromBeginning;
     this.NumberGenerations = NumberGenerations;
     this.BSim = new SimpleBufferedSimulation((int)NumberGenerations);
     this.SetThemeStyle(Theme, ColorStyle);
 }
コード例 #23
0
ファイル: Passenger.cs プロジェクト: npk48/DeSimulator
 public Passenger(Simulation Sim, string From = "", string To = "")
     : base(Sim)
 {
     Id = Counter++;
     Start = From;
     Destination = To;
     OnOffTime = 1;
     State = PassengerState.Waiting;
 }
コード例 #24
0
ファイル: MarkStorehouse.cs プロジェクト: Blecki/GnomeColony
 public override void Apply(Simulation Sim, WorldSceneNode WorldNode)
 {
     if (Sim.World.Check(WorldNode.HoverBlock))
     {
         var cell = Sim.World.CellAt(WorldNode.HoverBlock);
         cell.SetFlag(CellFlags.Storehouse, true);
         Sim.SetUpdateFlag(WorldNode.HoverBlock);
     }
 }
コード例 #25
0
ファイル: Ragdoll_Avatars.cs プロジェクト: Zolniu/DigitalRune
        /// <overloads>
        /// <summary>
        /// Creates a <see cref="Ragdoll"/> for an Xbox LIVE Avatar. (Only available on Xbox 360.)
        /// </summary>
        /// </overloads>
        /// 
        /// <summary>
        /// Creates a <see cref="Ragdoll"/> for an Xbox LIVE Avatar. (Only available on Xbox 360.)
        /// </summary>
        /// <param name="avatarPose">The avatar pose.</param>
        /// <param name="simulation">The simulation.</param>
        /// <returns>The avatar ragdoll.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="avatarPose"/> or <paramref name="simulation"/> is <see langword="null"/>.
        /// </exception>
        /// <remarks>
        /// This method is available only in the Xbox 360 build of the 
        /// DigitalRune.Physics.Specialized.dll.
        /// </remarks>
        public static Ragdoll CreateAvatarRagdoll(AvatarPose avatarPose, Simulation simulation)
        {
            if (avatarPose == null)
            throw new ArgumentNullException("avatarPose");
              if (simulation == null)
            throw new ArgumentNullException("simulation");

              return CreateAvatarRagdoll(avatarPose.SkeletonPose.Skeleton, simulation);
        }
コード例 #26
0
        private float _slopeLimit = ConstantsF.PiOver4; // = 45°

        #endregion Fields

        #region Constructors

        //--------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="KinematicCharacterController"/> class.
        /// </summary>
        /// <param name="simulation">The simulation.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="simulation" /> is <see langword="null"/>.
        /// </exception>
        public DynamicCharacterController(Simulation simulation)
        {
            if (simulation == null)
            throw new ArgumentNullException("simulation");

              Simulation = simulation;

              CapsuleShape shape = new CapsuleShape(0.4f, 1.8f);
              MassFrame mass = new MassFrame { Mass = 80 };  // Push strength is proportional to the mass!
              UniformMaterial material = new UniformMaterial
              {
            // The body should be frictionless, so that it can be easily pushed by the simulation to
            // valid positions. And it does not slow down when sliding along walls.
            StaticFriction = 0.0f,
            DynamicFriction = 0.0f,

            // The body should not bounce when being hit or pushed.
            Restitution = 0
              };

              Body = new RigidBody(shape, mass, material)
              {
            // We set the mass explicitly and it should not automatically change when the
            // shape is changed; e.g. a ducked character has a smaller shape, but still the same mass.
            AutoUpdateMass = false,

            // This body is under our control and should never be deactivated by the simulation.
            CanSleep = false,
            CcdEnabled = true,

            // The capsule does not rotate in any direction.
            LockRotationX = true,
            LockRotationY = true,
            LockRotationZ = true,

            Name = "CharacterController",

            Pose = new Pose(new Vector3F(0, shape.Height / 2, 0)),
              };

              // Create a ray that senses the space below the capsule. The ray starts in the capsule
              // center (to detect penetrations) and extends 0.4 units below the capsule bottom.
              RayShape rayShape = new RayShape(Vector3F.Zero, -Vector3F.UnitY, shape.Height / 2 + 0.4f)
              {
            StopsAtFirstHit = true,
              };
              GeometricObject rayGeometry = new GeometricObject(rayShape, Body.Pose);
              _ray = new CollisionObject(rayGeometry);

              // Whenever the Body moves, the ray moves with it.
              Body.PoseChanged += (s, e) => rayGeometry.Pose = Body.Pose;

              // Enable the character controller. (Adds body to simulation.)
              Enabled = true;
        }
コード例 #27
0
    // Searches for an ConstraintVehicleHandler instance in the Simulation.ForceEffects.
    private static ConstraintVehicleHandler GetHandler(Simulation simulation)
    {
      foreach (var forceEffect in simulation.ForceEffects)
      {
        ConstraintVehicleHandler handler = forceEffect as ConstraintVehicleHandler;
        if (handler != null)
          return handler;
      }

      return null;
    }
コード例 #28
0
ファイル: WindowManager.cs プロジェクト: Foda/MarioClone
        public WindowManager()
        {
            //Init main window shit
            window = new RenderWindow(new VideoMode(640, 480), "Super cool window title!");
            window.SetVerticalSyncEnabled(true);
            window.SetActive(true);
            window.Closed += window_Closed;

            // Open gl
            Gl.glEnable(Gl.GL_TEXTURE_2D);
            Gl.glLoadIdentity();
            Gl.glOrtho(0, 640, 480, 0, 0, 1);
            Gl.glMatrixMode(Gl.GL_MODELVIEW);

            Gl.glDisable(Gl.GL_DEPTH_TEST);

            Gl.glLoadIdentity();
            Gl.glTranslatef(0.375f, 0.375f, 0);

            particles = new CircleShape[pcount];
            for (int i = 0; i < pcount; i++)
            {
                particles[i] = new CircleShape(4f);
                particles[i].FillColor = Color.White;
                particles[i].Position = new Vector2f(0, 0);
                particles[i].Radius = 4;
            }

            circletest = new CircleShape();
            circletest.Position = new Vector2f(100, 100);
            circletest.OutlineColor = Color.Red;
            circletest.OutlineThickness = 1;
            circletest.FillColor = Color.Black;
            circletest.Radius = 100;

            circletest2 = new CircleShape();
            circletest2.Position = new Vector2f(200, 300);
            circletest2.OutlineColor = Color.Red;
            circletest2.OutlineThickness = 1;
            circletest2.FillColor = Color.Black;
            circletest2.Radius = 100;

            mytext = new Text("test", new Font("arial.ttf"), 16);
            mytext.Position = new Vector2f(4, 4);
            mytext.Color = Color.White;
            mytext.Style = Text.Styles.Bold;

            mytextShadow = new Text("test", new Font("arial.ttf"), 16);
            mytextShadow.Position = new Vector2f(6, 6);
            mytextShadow.Color = Color.Black;

            sim = new Simulation();
            sim.InitSimulation(pcount);
        }
コード例 #29
0
ファイル: Crossing.cs プロジェクト: ProCP-Fontys/Simulation
    public Crossing(int crossingID, Simulation simulation)
    {
        this.simulation = simulation;
        this.CrossingID = crossingID;
        Feeders = new List<Feeder>();
        neighbors = new Neighbours();

        for (int i = 1; i < 5; i++)
        {
            Feeders.Add(new Feeder(i,this,simulation));
        }
    }
コード例 #30
0
ファイル: Tests.cs プロジェクト: xilec/LifeSimulation
        public void Extinction()
        {
            var simulation = new Simulation();

            for (int i = 0; i <400; i++)
            {
                simulation.Simulate();
            }

            Assert.IsTrue(simulation.Landscape.Agents.Any(x => x != null), "After simulation should be alived agents");
            Assert.IsTrue(simulation.Landscape.Plants.Any(x => x != null), "After simulation should be alived plants");
        }
コード例 #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExportNodeCommand"/> class.
 /// </summary>
 /// <param name="explorerPresenter">The explorer presenter</param>
 /// <param name="simulation">The simulation to document</param>
 public WriteDebugDoc(ExplorerPresenter explorerPresenter, Simulation simulation)
 {
     this.explorerPresenter = explorerPresenter;
     this.simulation        = simulation;
 }
コード例 #32
0
 /// <summary>
 /// Performs any required initialization logic after the Simulation instance has been constructed.
 /// </summary>
 /// <param name="simulation">Simulation that owns these callbacks.</param>
 public void Initialize(Simulation simulation)
 {
     //Often, the callbacks type is created before the simulation instance is fully constructed, so the simulation will call this function when it's ready.
     //Any logic which depends on the simulation existing can be put here.
 }
コード例 #33
0
ファイル: SimulationHistory.cs プロジェクト: knexer/Apophis
 public SimulationHistory(Simulation currentTimeSim)
 {
     CurrentTimeSim      = currentTimeSim;
     ResourcesAtEachTime = new List <ResourceCollection>();
     ResourcesAtEachTime.Add(new ResourceCollection(CurrentTimeSim.resources));
 }
コード例 #34
0
        protected List <Export> GenerateExports(ParameterCollection parameterCollection, Simulation simulation, ICircuitContext context)
        {
            if (parameterCollection.Count == 0)
            {
                return(CreateExportsForAllVoltageAndCurrents(simulation, context));
            }

            List <Export> result = new List <Export>();

            foreach (Parameter parameter in parameterCollection)
            {
                if (parameter is BracketParameter || parameter is ReferenceParameter)
                {
                    result.Add(GenerateExport(parameter, context, simulation));
                }
                else
                {
                    string expressionName  = parameter.Image;
                    var    expressionNames = context.Evaluator.GetExpressionNames();

                    if (expressionNames.Contains(expressionName))
                    {
                        var export = new ExpressionExport(
                            simulation.Name,
                            expressionName,
                            context.Evaluator.GetEvaluationContext(simulation));

                        result.Add(export);
                    }
                }
            }

            return(result);
        }
コード例 #35
0
        public static bool ScreenPositionToWorldPositionRaycast(Vector2 screenPos, CameraComponent camera, Simulation simulation)
        {
            var invViewProj = Matrix.Invert(camera.ViewProjectionMatrix);

            Vector3 sPos;

            sPos.X = screenPos.X * 2f - 1f;
            sPos.Y = 1f - screenPos.Y * 2f;

            sPos.Z = 0f;
            var vectorNear = Vector3.Transform(sPos, invViewProj);

            vectorNear /= vectorNear.W;

            sPos.Z = 1f;
            var vectorFar = Vector3.Transform(sPos, invViewProj);

            vectorFar /= vectorFar.W;

            var result = new FastList <HitResult>();

            simulation.RaycastPenetrating(vectorNear.XYZ(), vectorFar.XYZ(), result);
            foreach (var hitResult in result)
            {
                if (hitResult.Succeeded)
                {
                    return(true);
                }
            }

            return(false);
        }
コード例 #36
0
        public void TestEditOption()
        {
            string[] changes = new string[]
            {
                "[Clock].StartDate = 2019-1-20",
                ".Simulations.Sim1.Clock.EndDate = 3/20/2019",
                ".Simulations.Sim2.Enabled = false",
                ".Simulations.Sim1.Field.Soil.Thickness[1] = 500",
                ".Simulations.Sim1.Field.Soil.Thickness[2] = 2500",
                ".Simulations.Sim2.Name = SimulationVariant35",
            };
            string configFileName = Path.GetTempFileName();

            File.WriteAllLines(configFileName, changes);

            string apsimxFileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");
            string text           = ReflectionUtilities.GetResourceAsString("UnitTests.BasicFile.apsimx");

            // Check property values at this point.
            Simulations sims = FileFormat.ReadFromString <Simulations>(text, out List <Exception> errors);

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            Clock      clock = Apsim.Find(sims, typeof(Clock)) as Clock;
            Simulation sim1  = Apsim.Find(sims, typeof(Simulation)) as Simulation;
            Simulation sim2  = Apsim.Find(sims, "Sim2") as Simulation;
            Soil       soil  = Apsim.Get(sims, ".Simulations.Sim1.Field.Soil") as Soil;

            // Check property values - they should be unchanged at this point.
            DateTime start = new DateTime(2003, 11, 15);

            Assert.AreEqual(start.Year, clock.StartDate.Year);
            Assert.AreEqual(start.DayOfYear, clock.StartDate.DayOfYear);

            Assert.AreEqual(sim1.Name, "Sim1");
            Assert.AreEqual(sim2.Enabled, true);
            Assert.AreEqual(soil.Thickness[0], 150);
            Assert.AreEqual(soil.Thickness[1], 150);

            // Run Models.exe with /Edit command.
            sims.Write(apsimxFileName);
            Utilities.RunModels($"{apsimxFileName} /Edit {configFileName}");
            sims = FileFormat.ReadFromFile <Simulations>(apsimxFileName, out errors);
            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            // Get references to the changed models.
            clock = Apsim.Find(sims, typeof(Clock)) as Clock;
            Clock clock2 = Apsim.Get(sims, ".Simulations.SimulationVariant35.Clock") as Clock;

            // Sims should have at least 3 children - data store and the 2 sims.
            Assert.That(sims.Children.Count > 2);
            sim1 = sims.Children.OfType <Simulation>().First();
            sim2 = sims.Children.OfType <Simulation>().Last();
            soil = Apsim.Get(sims, ".Simulations.Sim1.Field.Soil") as Soil;

            start = new DateTime(2019, 1, 20);
            DateTime end = new DateTime(2019, 3, 20);

            // Check clock.
            Assert.AreEqual(clock.StartDate.Year, start.Year);
            Assert.AreEqual(clock.StartDate.DayOfYear, start.DayOfYear);
            Assert.AreEqual(clock.EndDate.Year, end.Year);
            Assert.AreEqual(clock.EndDate.DayOfYear, end.DayOfYear);

            // These changes should not affect the clock in simulation 2.
            start = new DateTime(2003, 11, 15);
            end   = new DateTime(2003, 11, 15);
            Assert.AreEqual(clock2.StartDate.Year, start.Year);
            Assert.AreEqual(clock2.StartDate.DayOfYear, start.DayOfYear);
            Assert.AreEqual(clock2.EndDate.Year, end.Year);
            Assert.AreEqual(clock2.EndDate.DayOfYear, end.DayOfYear);

            // Sim2 should have been renamed to SimulationVariant35
            Assert.AreEqual(sim2.Name, "SimulationVariant35");

            // Sim1's name should be unchanged.
            Assert.AreEqual(sim1.Name, "Sim1");

            // Sim2 should have been disabled. This should not affect sim1.
            Assert.That(sim1.Enabled);
            Assert.That(!sim2.Enabled);

            // First 2 soil thicknesses have been changed to 500 and 2500 respectively.
            Assert.AreEqual(soil.Thickness[0], 500, 1e-8);
            Assert.AreEqual(soil.Thickness[1], 2500, 1e-8);
        }
コード例 #37
0
 /// <summary>
 /// called each tick of the simulation for the component
 /// </summary>
 /// <param name="entity">The entity who owns the component</param>
 /// <param name="simulation">The simulation that the entity own</param>
 public virtual void Update(SimulationEntity entity, Simulation simulation)
 {
 }
コード例 #38
0
ファイル: RaycastingScript.cs プロジェクト: Ethereal77/stride
 public override void Start()
 {
     camera     = Entity.Get <CameraComponent>();
     simulation = this.GetSimulation();
 }
コード例 #39
0
        public static IMenuBarButton WithUpdateCommandFor <TBuildingBlock>(this IMenuBarButton menuBarItem, Simulation simulation, TBuildingBlock templateBuildingBlock, UsedBuildingBlock usedBuildingBlock)
            where TBuildingBlock : class, IPKSimBuildingBlock
        {
            var command = IoC.Resolve <UpdateBuildingBlockInSimulationUICommand <TBuildingBlock> >();

            command.TemplateBuildingBlock = templateBuildingBlock;
            command.Simulation            = simulation;
            command.UsedBuildingBlock     = usedBuildingBlock;
            return(menuBarItem.WithCommand(command));
        }
コード例 #40
0
 /// <summary>
 /// Computes the swivel and pitch angles required to aim in a given direction based on the tank's current pose.
 /// </summary>
 /// <param name="simulation">Simulation containing the tank.</param>
 /// <param name="aimDirection">Direction to aim in.</param>
 /// <returns>Swivel and pitch angles to point in the given direction.</returns>
 public (float targetSwivelAngle, float targetPitchAngle) ComputeTurretAngles(Simulation simulation, in Vector3 aimDirection)
コード例 #41
0
        public void TestTablesModified()
        {
            IModel sim1 = new Simulation()
            {
                Name     = "sim1",
                Children = new List <IModel>()
                {
                    new Report()
                    {
                        Name          = "Report1",
                        VariableNames = new[] { "[Clock].Today" },
                        EventNames    = new[] { "[Clock].DoReport" },
                    },
                    new MockSummary(),
                    new Clock()
                    {
                        StartDate = new DateTime(2020, 1, 1),
                        EndDate   = new DateTime(2020, 1, 2),
                    },
                }
            };

            IModel sim2 = Apsim.Clone(sim1);

            sim2.Name             = "sim2";
            sim2.Children[0].Name = "Report2";

            TestPostSim testPostSim = new TestPostSim();

            sim1.Children.Add(testPostSim);

            Simulations sims = Simulations.Create(new[] { sim1, sim2, new DataStore() });

            Utilities.InitialiseModel(sims);

            Runner           runner = new Runner(sims, simulationNamesToRun: new[] { "sim1" });
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            List <string> tablesMod = new List <string>()
            {
                "_Factors",
                "Report1",
                "_Simulations",
                "_Checkpoints",
            };

            Assert.AreEqual(tablesMod.OrderBy(x => x), testPostSim.TablesModified.OrderBy(x => x));

            runner = new Runner(sims, simulationNamesToRun: new[] { "sim2" });
            errors = runner.Run();
            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            tablesMod = new List <string>()
            {
                "_Factors",
                "Report2",
                "_Simulations",
                "_Checkpoints",
            };
            Assert.AreEqual(tablesMod.OrderBy(x => x), testPostSim.TablesModified.OrderBy(x => x));

            // Now run both sims
            runner = new Runner(sims);
            errors = runner.Run();
            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            tablesMod = new List <string>()
            {
                "_Factors",
                "Report2",
                "Report1",
                "_Simulations",
                "_Checkpoints",
            };
            Assert.AreEqual(tablesMod.OrderBy(x => x), testPostSim.TablesModified.OrderBy(x => x));
        }
コード例 #42
0
ファイル: Entity.cs プロジェクト: jerdsouz/SpiceSharp
        /// <summary>
        /// Creates behaviors of the specified types. The type order is important.
        /// </summary>
        /// <remarks>
        /// The order typically indicates hierarchy. The entity will create the behaviors in reverse order, allowing
        /// the most specific child class to be used that is necessary. For example, the <see cref="OP"/> simulation needs
        /// <see cref="ITemperatureBehavior"/> and an <see cref="IBiasingBehavior"/>. The entity will first look for behaviors
        /// of type <see cref="IBiasingBehavior"/>, and then for the behaviors of type <see cref="ITemperatureBehavior"/>. However,
        /// if the behavior that was created for <see cref="IBiasingBehavior"/> also implements <see cref="ITemperatureBehavior"/>,
        /// then then entity will not create a new instance of the behavior.
        /// </remarks>
        /// <param name="types">The types of behaviors that the simulation wants, in the order that they will be called.</param>
        /// <param name="simulation">The simulation requesting the behaviors.</param>
        /// <param name="entities">The entities being processed, used by the entity to find linked entities.</param>
        public virtual void CreateBehaviors(Type[] types, Simulation simulation, EntityCollection entities)
        {
            types.ThrowIfNull(nameof(types));
            simulation.ThrowIfNull(nameof(simulation));
            entities.ThrowIfNull(nameof(entities));

            // Skip creating behaviors if the entity is already defined in the pool
            var pool = simulation.EntityBehaviors;

            if (pool.ContainsKey(Name))
            {
                return;
            }

            // Get the behavior factories for this entity
            BehaviorFactoryDictionary factories;

            Lock.EnterReadLock();
            try
            {
                if (!BehaviorFactories.TryGetValue(GetType(), out factories))
                {
                    return;
                }
            }
            finally
            {
                Lock.ExitReadLock();
            }

            // By default, go through the types in reverse order (to account for inheritance) and create
            // the behaviors
            EntityBehaviorDictionary ebd = null;
            var newBehaviors             = new List <IBehavior>(types.Length);

            for (var i = types.Length - 1; i >= 0; i--)
            {
                // Skip creating behaviors that aren't needed
                if (ebd != null && ebd.ContainsKey(types[i]))
                {
                    continue;
                }
                Lock.EnterReadLock();
                try
                {
                    if (factories.TryGetValue(types[i], out var factory))
                    {
                        // Create the behavior
                        var behavior = factory(this);
                        pool.Add(behavior);
                        newBehaviors.Add(behavior);

                        // Get the dictionary if necessary
                        if (ebd == null)
                        {
                            ebd = pool[Name];
                        }
                    }
                }
                finally
                {
                    Lock.ExitReadLock();
                }
            }

            // Now set them up in the order they appear
            for (var i = newBehaviors.Count - 1; i >= 0; i--)
            {
                BindBehavior(newBehaviors[i], simulation);
            }
        }
コード例 #43
0
 public LotOutObserver(Simulation mySimulation, string name) : base(mySimulation, name)
 {
 }
コード例 #44
0
 public SponsorNewt(Simulation simulation, TypedIndex shape, float height, in Vector2 arenaMin, in Vector2 arenaMax, Random random, int sponsorIndex) : this()
コード例 #45
0
 public virtual bool OnEntityCollision(Simulation simulation, SimulationEntity primaryEntity, SimulationEntity secondaryEntity)
 {
     return(true);
 }
コード例 #46
0
        public void NestedComputationTest()
        {
            int numRCS = 0;


            SimulationRun run = new SimulationRun(
                new BaseDB.ConfigContainer()
            {
                extent = new Int3(3), r = 1f / 8, m = 1f / 16
            },
                new ShardID(Int3.One, 0));

            Vec3 outlierCoords = Simulation.MySpace.Min;

            var    crossingLogic  = new MovingLogic(new Vec3(-1, 0, 0));
            Entity crosser        = new Entity(new EntityID(Guid.NewGuid(), Simulation.MySpace.Min), Vec3.Zero, crossingLogic, null);
            Vec3   crossingTarget = crosser.ID.Position + crossingLogic.Motion;

            foreach (var n in Simulation.Neighbors)
            {
                n.OnPutRCS = (decoded, gen) =>
                {
                    numRCS++;

                    Assert.AreEqual(gen, 1);


                    //RCS decoded = new RCS(rcs);

                    Assert.IsTrue(decoded.IsFullyConsistent);
                    //RCS.GenID id = new RCS.GenID(rcs.NumericID,0);
                    //Link lnk = Simulation.Neighbors.Find(id.ID.ToShard);
                    //Assert.IsNotNull(lnk);

                    if (n.WorldSpace.Grow(Simulation.Ranges.Transmission).Contains(outlierCoords))
                    {
                        Assert.IsFalse(decoded.CS.IsEmpty);
                    }
                    else
                    {
                        Assert.IsTrue(decoded.CS.IsEmpty);
                    }

                    if (n.WorldSpace.Contains(crossingTarget))
                    {
                        Assert.IsNotNull(decoded.CS.FindMotionOf(crosser.ID.Guid));
                    }
                }
            }
            ;


            run.FeedEntities(
                new Entity[]
            {
                new Entity(
                    new EntityID(Guid.NewGuid(), Simulation.MySpace.Center),
                    Vec3.Zero,
                    new ExceedingMovementLogic(),
                    //new EntityTest.FaultLogic.State(),
                    null),

                new Entity(
                    new EntityID(Guid.NewGuid(), outlierCoords),
                    Vec3.Zero,
                    new StationaryLogic(),
                    //new EntityTest.FaultLogic.State(),
                    null),
                crosser
            }
                );



            var inter = run.BeginAdvanceTLG(true);

            foreach (var p in inter.Intermediate.localChangeSet.NamedSets)
            {
                int expected = p.Key == "motions" || p.Key == "advertisements" ? 3 : 0;
                Assert.AreEqual(expected, p.Value.Size);
            }

            Assert.AreEqual(inter.Generation, 1);
            Assert.AreEqual(Simulation.NeighborCount, numRCS);
            //comp.

            {
                Link inbound = Simulation.Neighbors.Find(new Int3(0, 1, 1));
                RCS  inRCS   = new RCS(new EntityChangeSet(), new InconsistencyCoverage(inbound.ICExportRegion.Size));
                Simulation.FetchNeighborUpdate(run.tlgEntry, inbound, inRCS.Export());
            }

            var rs = run.CompleteAdvanceTLG(false);

            //check if most outer cells are 1 (one full-edge incoming RCS):
            var core     = rs.SDS.IC.Sub(Int3.One, rs.SDS.IC.Size - 2);
            int edgeSize = InconsistencyCoverage.CommonResolution - 2;

            Assert.AreEqual(rs.SDS.IC.OneCount, rs.SDS.IC.Size.Product - core.Size.Product - edgeSize * edgeSize, edgeSize.ToString());
            Assert.IsTrue(rs.SDS.IC.OneCount > 0);
            Assert.IsTrue(core.OneCount == 0);


            Assert.AreEqual(rs.Generation, 1);
            Assert.AreEqual(rs.SDS.FinalEntities.Length, 2);
            Assert.IsFalse(rs.SDS.HasEntity(crosser.ID.Guid));

            var check = Simulation.CheckMissingRCS(rs);

            Assert.IsFalse(check.AllThere);
            Assert.IsFalse(check.AnyAvailableFromNeighbors);
            Assert.AreEqual(check.missingRCS, numRCS - 1);
            Assert.IsTrue(check.predecessorIsConsistent);
            Assert.AreEqual(check.rcsAvailableFromNeighbor, 0);
            Assert.AreEqual(check.rcsRestoredFromDB, 0);
        }
コード例 #47
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sim"></param>
 public SolutesController(Simulation sim) : base(sim)
 {
 }
コード例 #48
0
        public unsafe override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(-20f, 13, -20f);
            camera.Yaw      = MathHelper.Pi * 3f / 4;
            camera.Pitch    = MathHelper.Pi * 0.1f;
            Simulation      = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            var shape = new Sphere(0.5f);

            shape.ComputeInertia(1, out var sphereInertia);
            var       shapeIndex        = Simulation.Shapes.Add(shape);
            const int width             = 64;
            const int height            = 64;
            const int length            = 64;
            var       spacing           = new Vector3(1.01f);
            var       halfSpacing       = spacing / 2;
            float     randomization     = 0.9f;
            var       randomizationSpan = (spacing - new Vector3(1)) * randomization;
            var       randomizationBase = randomizationSpan * -0.5f;
            var       random            = new Random(5);

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        var r        = new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                        var location = spacing * (new Vector3(i, j, k) + new Vector3(-width, 1, -length)) + randomizationBase + r * randomizationSpan;
                        if ((i + j + k) % 2 == 1)
                        {
                            var bodyDescription = new BodyDescription
                            {
                                Activity = new BodyActivityDescription {
                                    MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.1f
                                },
                                Pose = new RigidPose
                                {
                                    Orientation = BepuUtilities.Quaternion.Identity,
                                    Position    = location
                                },
                                Collidable = new CollidableDescription
                                {
                                    Continuity = new ContinuousDetectionSettings {
                                        Mode = ContinuousDetectionMode.Discrete
                                    },
                                    SpeculativeMargin = 0.1f,
                                    Shape             = shapeIndex
                                },
                                LocalInertia = sphereInertia
                            };
                            Simulation.Bodies.Add(bodyDescription);
                        }
                        else
                        {
                            var staticDescription = new StaticDescription
                            {
                                Pose = new RigidPose
                                {
                                    Orientation = BepuUtilities.Quaternion.Identity,
                                    Position    = location
                                },
                                Collidable = new CollidableDescription
                                {
                                    Continuity = new ContinuousDetectionSettings {
                                        Mode = ContinuousDetectionMode.Discrete
                                    },
                                    SpeculativeMargin = 0.1f,
                                    Shape             = shapeIndex
                                }
                            };
                            Simulation.Statics.Add(staticDescription);
                        }
                    }
                }
            }
            refineTimes = new TimingsRingBuffer(sampleCount, BufferPool);
            testTimes   = new TimingsRingBuffer(sampleCount, BufferPool);
        }
コード例 #49
0
ファイル: Modifier.cs プロジェクト: rafaelkuffner/DynaVis
 public abstract void drawGUI(Simulation boss, RectTransform mypos, Texture2D whiteTile, GUIStyle boxStyle2, GUIStyle labStyle2, float sx, float sy);
コード例 #50
0
 public virtual void OnSimulationRemove(Simulation simulation, SimulationEntity entity, EntityRemovalReason?reason)
 {
 }
コード例 #51
0
 /// <summary>
 /// Generates a new export.
 /// </summary>
 protected Export GenerateExport(Parameter parameter, ICircuitContext context, Simulation simulation)
 {
     return(ExportFactory.Create(parameter, context, simulation, Mapper));
 }
コード例 #52
0
 public static void constructor(Particle p, Simulation sim)
 {
     p.timer = 1;
 }
コード例 #53
0
        //List<DebugStep> debugSteps;
        public override void Initialize(ContentArchive content, Camera camera)
        {
            camera.Position = new Vector3(0, -2.5f, 10);
            camera.Yaw      = 0;
            camera.Pitch    = 0;

            Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0)));

            const int pointCount = 16;

            points = new QuickList <Vector3>(pointCount * 2, BufferPool);
            //points.Allocate(BufferPool) = new Vector3(0, 0, 0);
            //points.Allocate(BufferPool) = new Vector3(0, 0, 1);
            //points.Allocate(BufferPool) = new Vector3(0, 1, 0);
            //points.Allocate(BufferPool) = new Vector3(0, 1, 1);
            //points.Allocate(BufferPool) = new Vector3(1, 0, 0);
            //points.Allocate(BufferPool) = new Vector3(1, 0, 1);
            //points.Allocate(BufferPool) = new Vector3(1, 1, 0);
            //points.Allocate(BufferPool) = new Vector3(1, 1, 1);
            var random = new Random(5);

            for (int i = 0; i < pointCount; ++i)
            {
                points.AllocateUnsafely() = new Vector3(3 * (float)random.NextDouble(), 1 * (float)random.NextDouble(), 3 * (float)random.NextDouble());
                //points.AllocateUnsafely() = new Vector3(0, 1, 0) + Vector3.Normalize(new Vector3((float)random.NextDouble() * 2 - 1, (float)random.NextDouble() * 2 - 1, (float)random.NextDouble() * 2 - 1)) * (float)random.NextDouble();
            }

            var pointsBuffer = points.Span.Slice(points.Count);

            CreateShape(pointsBuffer, BufferPool, out _, out var hullShape);
            const int iterationCount = 100;
            var       start          = Stopwatch.GetTimestamp();

            for (int i = 0; i < iterationCount; ++i)
            {
                CreateShape(pointsBuffer, BufferPool, out _, out var perfTestShape);
                perfTestShape.Dispose(BufferPool);
            }
            var end = Stopwatch.GetTimestamp();

            Console.WriteLine($"Hull computation time (us): {(end - start) * 1e6 / (iterationCount * Stopwatch.Frequency)}");

            var hullShapeIndex = Simulation.Shapes.Add(hullShape);

            hullShape.ComputeInertia(1, out var inertia);

            Simulation.Bodies.Add(BodyDescription.CreateDynamic(new Vector3(0, 0, 0), inertia, new CollidableDescription(hullShapeIndex, 10.1f), new BodyActivityDescription(0.01f)));

            Simulation.Statics.Add(new StaticDescription(new Vector3(-25, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Sphere(2)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-20, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Capsule(0.5f, 2)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-15, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2f, 2f, 2f)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-10, -5, 5), new CollidableDescription(Simulation.Shapes.Add(new Triangle {
                A = new Vector3(0, 0, -10), B = new Vector3(5, 0, -10), C = new Vector3(0, 0, -5)
            }), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-5, -5, 0), new CollidableDescription(Simulation.Shapes.Add(new Cylinder(1, 1)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(-5, -5, 5), new CollidableDescription(Simulation.Shapes.Add(new Cylinder(1, 1)), 0.1f)));
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -5, 0), new CollidableDescription(hullShapeIndex, 0.1f)));

            var spacing = new Vector3(3f, 3f, 3);
            int width   = 16;
            int height  = 16;
            int length  = 16;
            var origin  = -0.5f * spacing * new Vector3(width, 0, length) + new Vector3(40, 0.2f, -40);

            for (int i = 0; i < width; ++i)
            {
                for (int j = 0; j < height; ++j)
                {
                    for (int k = 0; k < length; ++k)
                    {
                        Simulation.Bodies.Add(BodyDescription.CreateDynamic(
                                                  new RigidPose(origin + spacing * new Vector3(i, j, k), BepuUtilities.Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), MathHelper.Pi * 0.05f)),
                                                  inertia, new CollidableDescription(hullShapeIndex, 1f), new BodyActivityDescription(0.01f)));
                    }
                }
            }
            Simulation.Statics.Add(new StaticDescription(new Vector3(0, -10, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(1000, 1, 1000)), 0.1f)));
        }
コード例 #54
0
 public virtual bool OnWorldBoundaryCollision(Simulation simulation, SimulationEntity entity, CollisionSide side)
 {
     return(true);
 }
コード例 #55
0
ファイル: Program.cs プロジェクト: hdiedam/OSPSuite.SimModel
 protected void Context()
 {
     sut = new Simulation();
     //         sut.Options.KeepXMLNodeAsString = true;
 }
コード例 #56
0
 public virtual bool OnTileCollision(Simulation simulation, SimulationEntity entity, TileCollision tc)
 {
     return(true);
 }
コード例 #57
0
 protected override void Context()
 {
     base.Context();
     _simulationToLoad = A.Fake <Simulation>();
 }
コード例 #58
0
 public AgentCakarne(int id, Simulation mySim, Agent parent) :
     base(id, mySim, parent)
 {
     Init();
 }
コード例 #59
0
        private void Draw(Simulation simulation)
        {
            if (_surfaceImage.Source != null)
            {
                return;
            }

            var group = new DrawingGroup();

            using (DrawingContext context = group.Open())
            {
                var surfaceRect = new Rect(0, 0, ActualWidth, ActualHeight);

                context.PushClip(new RectangleGeometry(surfaceRect));

                context.DrawRectangle(
                    Brushes.White,
                    null,
                    surfaceRect);

                double xRatio = ActualWidth / simulation.Width;
                double yRatio = ActualHeight / simulation.Height;



                Pen pen = new Pen
                {
                    Brush = Brushes.Blue,

                    //Thickness = 2
                };

                foreach (Drop drop in simulation.Drops)
                {
                    double x = xRatio * drop.PositionX;
                    double y = ActualHeight - yRatio * drop.PositionY;

                    context.DrawLine(pen, new Point(x, y), new Point(x - ActualWidth * drop.VelocityX * drop.Volume, y - 5 * ActualHeight / 300 * drop.Volume));
                }

                for (int i = 0; i < simulation.Land.Regions.Count; ++i)
                {
                    LandRegion landRegion = simulation.Land.Regions[i];

                    double landRegionWidth  = xRatio;
                    double landRegionHeight = yRatio * landRegion.Height;

                    if (landRegionHeight > 0)
                    {
                        var landRegionRect = new Rect(
                            x: i * landRegionWidth,
                            y: ActualHeight - landRegionHeight,
                            width: landRegionWidth,
                            height: landRegionHeight);


                        context.DrawRectangle(Brushes.Black, null, landRegionRect);
                    }

                    double landRegionWaterHeight = yRatio * landRegion.Water;

                    var landRegionWaterRect = new Rect(
                        x: i * landRegionWidth,
                        y: ActualHeight - landRegionHeight - landRegionWaterHeight,
                        width: landRegionWidth,
                        height: landRegionWaterHeight);

                    context.DrawRectangle(Brushes.DarkBlue, null, landRegionWaterRect);
                }
            }
            group.Freeze();
            _surfaceImage.Source = new DrawingImage(group);
        }
コード例 #60
0
 public SimulationGradesCombinedModel(Simulation simulation, List <Grade> grades)
 {
     ID        = simulation.ID;
     TraineeID = simulation.TraineeID;
     Grades    = grades;
 }