Example #1
0
        private void toolStripRenderer_SelectedIndexChanged(object sender, EventArgs e)
        {
            RenderType   renderType   = this.toolStripRenderer.SelectedItem != null ? (RenderType)this.toolStripRenderer.SelectedItem : RenderType.RayTracer;
            StrategyType strategyType = this.toolStripStrategy.SelectedItem != null ? (StrategyType)this.toolStripStrategy.SelectedItem : StrategyType.Progressive;

            RenderStrategy strategy = new ProgressiveRenderStrategy();

            switch (strategyType)
            {
            case StrategyType.Scanline:
                strategy = new ScanlineRenderStrategy();
                break;

            case StrategyType.Progressive:
                strategy = new ProgressiveRenderStrategy();
                break;
            }
            switch (renderType)
            {
            case RenderType.RayTracer:
                this.tracer = new RayTracer(UnifiedScenesRepository.Scenes[this.TabText], strategy);
                break;

            case RenderType.PhotonTracer:
                this.tracer = new PhotonTracer(UnifiedScenesRepository.Scenes[this.TabText], strategy, 500000);
                break;

            case RenderType.DistributedRayTracer:
                this.tracer = new DistributedRayTracer(UnifiedScenesRepository.Scenes[this.TabText], strategy);
                break;
            }
        }
Example #2
0
 private void DocumentWindow_FormClosed(object sender, FormClosedEventArgs e)
 {
     this.tracer = null;
     UnifiedScenesRepository.Scenes.Remove(this.TabText);
     GC.Collect();
     GC.WaitForPendingFinalizers();
 }
Example #3
0
        public void Show()
        {
            ResetBuffor();

            double ray          = hero.direction - fov / 2;
            double rayEnd       = hero.direction + fov / 2;
            double rayAngle     = 0;
            double rayIncrement = (double)fov / (double)screenWidth;

            for (int screenPosition = 0; screenPosition < screenWidth; screenPosition++)
            {
                double radians = RayCasting.DecToRadCorrected(ray);
                int    endX    = (int)(hero.x + 50 * Math.Sin(radians));
                int    endY    = (int)(hero.y + 50 * Math.Cos(radians));

                double correction = 1.0;
                correction = Math.Cos(RayCasting.DecToRad((double)fov / 2 - rayAngle));

                int distance  = (int)CastRay(hero.x, hero.y, endX, endY);
                int distanceC = (int)(CastRay(hero.x, hero.y, endX, endY) * correction);
                DrawOnBuffor(distanceC, screenPosition, correction);

                rayAngle += rayIncrement;
                ray      += rayIncrement;
            }

            string screen = "╔";

            for (int x = 0; x < screenWidth; x++)
            {
                screen += '═';
            }
            screen += "╗\n";

            for (int y = 0; y < screenHeight; y++)
            {
                screen += "║";
                for (int x = 0; x < screenWidth; x++)
                {
                    screen += buffor[x, y];
                }
                screen += "║\n";
            }
            screen += "╚";
            for (int x = 0; x < screenWidth; x++)
            {
                screen += '═';
            }
            screen += "╝\n";

            string debug = "X: " + (int)hero.x + " Y: " + (int)hero.y + " Rotation: " + (int)hero.direction + " fov: " + fov + "    ";

            Console.SetCursorPosition(0, 0);
            Console.Write(screen + debug);
        }
    //GUI FUNCTION
    void OnGUI()
    {
        //Access InReach variable from raycasting script.
        GameObject Player     = GameObject.Find("Player");
        RayCasting raycasting = Player.GetComponent <RayCasting>();

        if (raycasting.InReach == true && raycasting.hitTag == "Door")
        {
            GUI.color = Color.white;
            GUI.Box(new Rect(20, 20, 200, 25), "Press 'E' to open/close");
        }
    }
    void OnGUI()
    {
        GameObject Player     = GameObject.Find("Player");
        RayCasting raycasting = Player.GetComponent <RayCasting>();

        if (raycasting.InReach == true && raycasting.hitTag == "PowerlineLeft")
        {
            GUI.color = Color.white;
            GUI.Box(new Rect(20, 20, 200, 55), "Powerline Voltage: " + voltage.ToString() +
                    "\nPowerline Frequency: " + frequency.ToString() + "\nPowerline Current: " + current.ToString());
        }
    }
Example #6
0
    // Use this for initialization
    void Start()
    {
        rcasting = new RayCasting();
        damageData = new DamageData(damage);

        if (burrelPoint == null)
        {
            Debug.LogError("Gun Burrel Point is not recognized");
            burrelPoint = this.gameObject.transform;
        }

        gunflame = burrelPoint.GetComponent<ParticleSystem>();
    }
        public override void AgentAction(float[] vectorAction, string textAction)
        {
            Debug.Log("Agent took action: " + textAction);
            int moveX = Mathf.FloorToInt(vectorAction[0]) - 1;
            int moveY = Mathf.FloorToInt(vectorAction[1]) - 1;

            _controlableEntityController.MoveEntity(new Vector2(moveX, moveY));

            Vector2    goalPos    = GameManager.Instance.WorldManager.GetGoalPosition();
            Vector2    agentPos   = _controlableEntityController.transform.position;
            Collider2D collider2D = RayCasting.CastRayToHit(agentPos, goalPos, true);
            bool       seeGoal    = collider2D.tag == "Goal";

            if (seeGoal)
            {
                Vector2 distanceVec      = (Vector2)_controlableEntityController.transform.position - goalPos;
                float   distanceToGoal   = distanceVec.magnitude;
                float   maxLevelDistance = GameManager.Instance.WorldManager.GetMaxLenOfLevel();

                if (distanceToGoal > maxLevelDistance)
                {
                    AddReward(0);
                }
                else if (minGoalDistance > distanceToGoal)
                {
                    minGoalDistance = distanceToGoal;
                    float distanceReward = 1.0f - distanceToGoal / maxLevelDistance;
                    distanceReward = Mathf.Pow(distanceReward, 4);
                    AddReward(distanceReward);
                }
            }


            // TODO(Rok Kos): Decrease reward the longer agent is alive
            AddReward(-1f / agentParameters.maxStep);


            if (_controlableEntityController.GetPlayerDead())
            {
                SetReward(-3);
                Done();
            }

            if (_controlableEntityController.GetPlayerWon())
            {
                SetReward(1);
                Done();
            }
        }
Example #8
0
        public void Triangle()
        {
            ReadOnlySpan <Point> shape = stackalloc[] {
                new Point(0d, 0d),
                new Point(20d, 0d),
                new Point(10d, 10d)
            };

            var rc = new RayCasting();

            Assert.True(rc.Contains(shape, new Point(10d, 5d)));
            Assert.False(rc.Contains(shape, new Point(0d, 5d)));
            Assert.False(rc.Contains(shape, new Point(20d, 5d)));
        }
    }
Example #9
0
        public void Rectangle()
        {
            // Note: stackalloc

            ReadOnlySpan <Point> shape = stackalloc[] {
                new Point(0d, 0d),
                new Point(20d, 0d),
                new Point(20d, 20d),
                new Point(0d, 20d)
            };

            var rc = new RayCasting();

            Assert.True(rc.Contains(shape, new Point(10d, 10d)));
            Assert.False(rc.Contains(shape, new Point(-10d, 10d)));
            Assert.False(rc.Contains(shape, new Point(10d, 30d)));
        }
Example #10
0
        public void Update(GameTime gameTime)
        {
            mMenu.CheckRegisteredEvents();

            mCameraHandler.Update(gameTime.ElapsedGameTime.Milliseconds);

            mCamera.mLocation.Y = mScene.mTerrain.GetHeight(mCamera.mLocation) + 1.5f;

            // We need to calculate the collision of the camera with the terrain
            var location = mCamera.mLocation - mCamera.mThirdPersonDistance * mCamera.Direction;

            var height         = mScene.mTerrain.GetHeight(location);
            var relativeHeight = height - mCamera.mLocation.Y + 1.0f;
            var terrainAngle   = Math.Sinh(relativeHeight / mCamera.mThirdPersonDistance);

            if (mCamera.mRotation.Y < terrainAngle)
            {
                mCamera.mRotation.Y        = (float)terrainAngle;
                mCameraHandler.mRotation.Y = (float)terrainAngle;
            }

            if (mCamera.mRotation.Y > Math.PI / 3.5f)
            {
                mCamera.mRotation.Y        = (float)Math.PI / 3.5f;
                mCameraHandler.mRotation.Y = (float)Math.PI / 3.5f;
            }

            mScene.Update(mCamera, gameTime);

            mSilverback.Update(mScene.mTerrain, mCamera, mCameraHandler, mScene, gameTime);

            mLabel.Text = gameTime.ElapsedGameTime.Milliseconds + "ms 1002 movable actors";

            if (InputManager.MouseRightButtonPressed())
            {
                var raycast = RayCasting.CalculateMouseRayTerrainIntersection(mViewport, mCamera, mScene.mTerrain);

                if (!raycast.mIntersected)
                {
                    return;
                }

                mSubApe.SetTarget(raycast.mLocation);
            }
        }
Example #11
0
        public override void CollectObservations()
        {
            Vector2 goalPos = GameManager.Instance.WorldManager.GetGoalPosition();

            AddVectorObs(goalPos);

            Vector2 agentPos = this.transform.position;

            AddVectorObs(agentPos);


            List <RayInfo> rays = RayCasting.CastRays(agentPos, 8, true);

            foreach (RayInfo ri in rays)
            {
                AddVectorObs(ri.rayLenght);
            }
        }
    void OnGUI()
    {
        GameObject Player     = GameObject.Find("Player");
        RayCasting raycasting = Player.GetComponent <RayCasting>();

        if (raycasting.InReach == true && raycasting.hitTag == "BreakerLeft")
        {
            GUI.color = Color.white;
            GUI.Box(new Rect(20, 20, 200, 55), "Breaker Voltage: " + voltage.ToString() + "\n" +
                    "Breaker Frequency: " + frequency.ToString() + "\nBreaker Current: " + current.ToString());
        }

        /*
         * GameObject pl = GameObject.Find ("Powerline");
         * PowerlineProperties powerline = pl.GetComponent<PowerlineProperties> ();
         * GUI.Label (new Rect(10, 10, 1000, 20), "Powerline Voltage: " + powerline.voltage.ToString());
         * GUI.Label (new Rect(10, 20, 1000, 20), "Breaker Voltage:   " + voltage.ToString());
         */
    }
        public override void CollectObservations()
        {
            Vector2 goalPos = GameManager.Instance.WorldManager.GetGoalPosition();

            AddVectorObs(goalPos);

            Vector2 agentPos = _controlableEntityController.transform.position;

            AddVectorObs(agentPos);


            List <RayInfo> rays = RayCasting.CastRays(agentPos, 8, true);

            foreach (RayInfo ri in rays)
            {
                AddVectorObs(ri.rayLenght);
            }

            AddVectorObs(GetStepCount() / (float)agentParameters.maxStep);
        }
Example #14
0
        /// <summary>
        /// Calculates latitude/longitude for given screen coordinate.
        /// Cast a ray to the terrain geometry (Patrick Murris - march 2007)
        /// </summary>
        public virtual void PickingRayIntersectionWithTerrain(
            int screenX,
            int screenY,
            out Angle latitude,
            out Angle longitude,
            World world)
        {
            // Get near and far points on the ray
            Vector3 v1 = new Vector3(screenX, screenY, viewPort.MinZ);

            v1.Unproject(viewPort, m_absoluteProjectionMatrix, m_absoluteViewMatrix, m_absoluteWorldMatrix);
            Vector3 v2 = new Vector3(screenX, screenY, viewPort.MaxZ);

            v2.Unproject(viewPort, m_absoluteProjectionMatrix, m_absoluteViewMatrix, m_absoluteWorldMatrix);
            Point3d p1 = new Point3d(v1.X, v1.Y, v1.Z);
            Point3d p2 = new Point3d(v2.X, v2.Y, v2.Z);

            // Find intersection
            RayCasting.RayIntersectionWithTerrain(p1, p2, 100, 1, out latitude, out longitude, world);
        }
Example #15
0
 void Awake()
 {
     currentCombatState = false;
     raycasting = new RayCasting();
 }
        public override void Render(RayCasting caster, IEnumerable <TiledBitmap.Tile> tiles)
        {
            #region Progressive Render from http://www.cc.gatech.edu/~phlosoft/photon/
            //float resX = caster.Scene.DefaultCamera.ResX; //g.VisibleClipBounds.Width;
            //float resY = caster.Scene.DefaultCamera.ResY; //g.VisibleClipBounds.Height;
            ManualResetEvent fineshedHandle         = new ManualResetEvent(false);
            IEnumerable <TiledBitmap.Tile> imgTiles = tiles as IList <TiledBitmap.Tile> ?? tiles.ToList();

            int numberOfWorkers = imgTiles.Count();
            foreach (var imgTile in imgTiles)
            {
                caster = caster.Clone();
                Tuple <RayCasting, TiledBitmap.Tile> casterTile = new Tuple <RayCasting, TiledBitmap.Tile>(caster, imgTile);
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        Tuple <RayCasting, TiledBitmap.Tile> localCasterAndTile = state as Tuple <RayCasting, TiledBitmap.Tile>;
                        TiledBitmap.Tile tile = localCasterAndTile.Item2;
                        RayCasting caster1    = localCasterAndTile.Item1;

                        tile.CompleteCycle(TiledBitmap.RenderCycleType.Start);

                        int iterations = 0;
                        int pCol       = 0, pRow = 0, pIteration = 1, pMax = 2;

                        float resTotal = tile.Width * tile.Height;
                        while (iterations < resTotal)
                        {
                            //Render Pixels Out of Order With Increasing Resolution: 2x2, 4x4, 16x16... 512x512
                            if (pCol >= pMax)
                            {
                                pRow++;
                                pCol = 0;
                                if (pRow >= pMax)
                                {
                                    pIteration++;
                                    pRow   = 0;
                                    pMax <<= 1; //Equals: pMax = (int)Math.Pow(2, pIteration);
                                }
                            }
                            bool pNeedsDrawing = (pIteration == 1 || (pRow % 2 != 0) || (pRow % 2 == 0 && (pCol % 2 != 0)));
                            float x            = pCol * (tile.Width / pMax) + tile.X;
                            float y            = pRow * (tile.Height / pMax) + tile.Y;
                            pCol++;
                            if (pNeedsDrawing)
                            {
                                iterations++;
                                Ray ray;
                                RGBColor finalColor = RGBColor.Black;
                                if (caster1.Scene.Sampler.NumberOfSamples > 1)
                                {
                                    foreach (Point2D sample in caster1.Scene.Sampler.GetSamplesFor(x, y))
                                    {
                                        //ray = this.scene.DefaultCamera.CreateRayFromScreen(x + sample.X, y + sample.Y);
                                        ray = caster1.Scene.DefaultCamera.CreateRayFromScreen(sample.X, sample.Y);
                                        ray.PrevRefractIndex = caster1.Scene.RefractIndex;
                                        finalColor          += caster1.Trace(ray, 0);
                                    }
                                    //brush.Color = (finalColor * (1f / this.scene.Sampler.NumberOfSamples)).ToColor();
                                    finalColor = (finalColor / caster1.Scene.Sampler.NumberOfSamples);


                                    //Graphics graphics = Graphics.FromImage(tile.Image);
                                    tile.Graphics.FillRectangle(new SolidBrush(finalColor.ToColor()), x - tile.X, y - tile.Y, (tile.Width / pMax), (tile.Height / pMax));
                                    //graphics.Flush();
                                    //graphics.Dispose();
                                }
                                else
                                {
                                    ray        = caster1.Scene.DefaultCamera.CreateRayFromScreen(x, y);
                                    finalColor = caster1.Trace(ray, 0);

                                    // Debug.WriteLine("Graphics: " + tile.Graphics.GetHashCode());

                                    tile.Graphics.FillRectangle(new SolidBrush(finalColor.ToColor()), x - tile.X, y - tile.Y, (tile.Width / pMax), (tile.Height / pMax));

                                    //tile.Graphics.Flush(FlushIntention.Sync);
                                }
                                tile.CompleteCycle(TiledBitmap.RenderCycleType.Partial);
                            }
                        }
                        tile.CompleteCycle(TiledBitmap.RenderCycleType.Finish);
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref numberOfWorkers) == 0)
                        {
                            fineshedHandle.Set();
                        }
                    }
                }, casterTile);
            }//);
            fineshedHandle.WaitOne();
            #endregion
        }
Example #17
0
        public override void Render(RayCasting caster, IEnumerable <TiledBitmap.Tile> tiles)
        {
            //float resX = caster.Scene.DefaultCamera.ResX; //g.VisibleClipBounds.Width;
            //float resY = caster.Scene.DefaultCamera.ResY; //g.VisibleClipBounds.Height;
            //Parallel.ForEach(tiles, tile => {
            ManualResetEvent fineshedHandle         = new ManualResetEvent(false);
            IEnumerable <TiledBitmap.Tile> imgTiles = tiles as IList <TiledBitmap.Tile> ?? tiles.ToList();

            numberOfWorkers = imgTiles.Count();
            foreach (var imgTile in imgTiles)
            {
                caster = caster.Clone();
                Tuple <RayCasting, TiledBitmap.Tile> casterTile = new Tuple <RayCasting, TiledBitmap.Tile>(caster, imgTile);
                //new Thread(state =>
                ThreadPool.QueueUserWorkItem(state =>
                {
                    try
                    {
                        Tuple <RayCasting, TiledBitmap.Tile> localCasterAndTile = state as Tuple <RayCasting, TiledBitmap.Tile>;
                        TiledBitmap.Tile tile = localCasterAndTile.Item2;
                        RayCasting caster1    = localCasterAndTile.Item1;
                        //Stopwatch timer = new Stopwatch();
                        //timer.Start();
                        //Console.WriteLine("Started@" + DateTime.Now.ToString("mm:ss.fff tt"));


                        float total   = tile.Width * tile.Height;
                        float partial = 0;
                        for (int y = tile.Y; y < tile.Y + tile.Height; y++)
                        {
                            if (cancelRender)
                            {
                                break;
                            }
                            for (int x = tile.X; x < tile.X + tile.Width; x++)
                            {
                                if (cancelRender)
                                {
                                    break;
                                }
                                Ray ray;
                                RGBColor finalColor = RGBColor.Black;
                                if (caster1.Scene.Sampler.NumberOfSamples > 1)
                                {
                                    foreach (Point2D sample in caster1.Scene.Sampler.GetSamplesFor(x, y))
                                    {
                                        ray = caster1.Scene.DefaultCamera.CreateRayFromScreen(sample.X, sample.Y);
                                        ray.PrevRefractIndex = caster1.Scene.RefractIndex;
                                        finalColor          += caster1.Trace(ray, 0);
                                    }
                                    finalColor = (finalColor * 1f / caster1.Scene.Sampler.NumberOfSamples);
                                }
                                else
                                {
                                    ray        = caster1.Scene.DefaultCamera.CreateRayFromScreen(x, y);
                                    finalColor = caster1.Trace(ray, 0);
                                }

                                tile.Image.SetPixel(x - tile.X, y - tile.Y, finalColor.ToColor());
                                //unsafe
                                //{
                                //    Bitmap img = tile.Image;
                                //    BitmapData imgData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, img.PixelFormat);
                                //    byte bitsPerPixel = Texture.GetBitsPerPixel(imgData.PixelFormat);
                                //    byte* scan0 = (byte*)imgData.Scan0.ToPointer();
                                //    byte* data = scan0 + (x - tile.X) * imgData.Stride + (y - tile.Y) * bitsPerPixel / 8;

                                //    data[0] = (byte)(finalColor.R * 255);
                                //    data[1] = (byte)(finalColor.G * 255);
                                //    data[2] = (byte)(finalColor.B * 255);
                                //    img.UnlockBits(imgData);
                                //}
                            }
                            partial += tile.Height;
                            if (((partial / total) * 100) >= 20)
                            {
                                partial = 0;
                                tile.CompleteCycle(TiledBitmap.RenderCycleType.Partial);
                            }
                        }
                        tile.CompleteCycle(TiledBitmap.RenderCycleType.Finish);

                        //timer.Stop();
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref numberOfWorkers) == 0)
                        {
                            fineshedHandle.Set();
                            cancelHandle.Set();
                            cancelRender = false;
                        }
                    }
                }, casterTile);
                //}){IsBackground = false}.Start(casterTile);
            }//);
            cancelHandle.Set();
            fineshedHandle.WaitOne();
        }
Example #18
0
 public abstract void Render(RayCasting rayCasting, IEnumerable <TiledBitmap.Tile> tiles);
Example #19
0
        public void Update(GameTime time)
        {
            if (IsVisible && !mWasVisible)
            {
                mWasVisible = true;
                mGameScreen.mCameraHandler.Unlock();
            }

            if (mGameScreen.IsVisible)
            {
                IsVisible = true;
            }

            if (mHudStartTime == 0)
            {
                mHudStartTime = time.TotalGameTime.TotalMilliseconds;
            }

            var hudTime  = time.TotalGameTime.TotalMilliseconds - mHudStartTime;
            var timeSpan = TimeSpan.FromMilliseconds(hudTime);

            mTimeLabel.Text = "Time: " + timeSpan.Minutes + ":" + timeSpan.Seconds;

            if (mGameScreen.mLevel.mLevelStory != null)
            {
                mContinueLabel.mTextColor = Color.White *
                                            (float)(Math.Sin(time.TotalGameTime.TotalMilliseconds / 200.0f) * 0.5f +
                                                    0.5f);
            }

            if (mGameScreen.mLevel.mSilverback != null)
            {
                mHPLabel.Text = "HP: " + mGameScreen.mLevel.mSilverback.HP.ToString() + " / " + mGameScreen.mLevel.mSilverback.mMaxHP.ToString();
            }

            DisableUnusedApeSelectorButtons();

            // Iterate over all Menu elements
            foreach (var menu in mMenuList)
            {
                if (!menu.mIsVisible)
                {
                    continue;
                }
                menu.CheckRegisteredEvents();
            }

            if (mActorBatch != null && InputManager.MouseRightButtonPressed())
            {
                var raycast = RayCasting.CalculateMouseRayTerrainIntersection(mGameScreen.mViewport, mGameScreen.mCamera, mGameScreen.mLevel.mTerrain);

                if (!raycast.mIntersected)
                {
                    return;
                }

                foreach (var actor in mActorBatch.mActors)
                {
                    var movable = (IMoveable)actor.IActor;
                    movable.SetTarget(raycast.mLocation);
                }
            }

            if (mGameScreen.mLevel.mSilverback.HP <= 0)
            {
                ScreenManager.Remove(this);
                ScreenManager.Add(mLoseScreen);
                Statistic.Lost++;
            }

            if (mGameScreen.mLevel.mHuts.Count == 0)
            {
                ScreenManager.Remove(this);
                ScreenManager.Add(mWinScreen);
                Statistic.Win++;
            }
        }
Example #20
0
        public void Update(GameTime gameTime)
        {
            if (mSelectedMesh != null && mSelectedActor == null && !mSelectMode)
            {
                mSelectedActor       = new Actor(mSelectedMesh);
                mSelectedActor.Color = new Vector3(.3f, 0.3f, 0.3f);
                mLevel.Add(mSelectedActor);
            }

            SoundManager.Update(gameTime, mLevel, mCamera);

            mCameraHandler.Update(gameTime.ElapsedGameTime.Milliseconds);

            var state = Keyboard.GetState();

            // if (state.IsKeyDown(Keys.LeftShift))
            if (InputManager.AllKeysDown(Keys.LeftShift))
            {
                mShiftDown = true;
            }

            // if (state.IsKeyUp(Keys.LeftShift) && mShiftDown)
            if (InputManager.AllKeysUp(Keys.LeftShift) && mShiftDown)
            {
                if (mSelectMode)
                {
                    if (mLevel.mActorBatches.Count > 1)
                    {
                        mSelectedMesh = mLevel.mActorBatches[0].mMesh == mLevel.mTerrain.Actor.mMesh ? mLevel.mActorBatches[1].mMesh : mLevel.mActorBatches[0].mMesh;
                    }
                    mSelectMode = false;
                }
                else
                {
                    mSelectMode = true;
                    mLevel.Remove(mSelectedActor);
                    mSelectedActor = null;
                    mSelectedMesh  = null;
                }

                mShiftDown = false;
            }

            // if (state.IsKeyDown(Keys.Left))
            if (InputManager.AllKeysDown(Keys.Left))
            {
                mActorYRotation -= 0.005f * gameTime.ElapsedGameTime.Milliseconds;
            }

            // if (state.IsKeyDown(Keys.Right))
            if (InputManager.AllKeysDown(Keys.Right))
            {
                mActorYRotation += 0.005f * gameTime.ElapsedGameTime.Milliseconds;
            }

            // if (state.IsKeyDown(Keys.Up))
            if (InputManager.AllKeysDown(Keys.Up))
            {
                mActorYOffset += 0.005f * gameTime.ElapsedGameTime.Milliseconds;
            }

            // if (state.IsKeyDown(Keys.Down))
            if (InputManager.AllKeysDown(Keys.Down))
            {
                mActorYOffset -= 0.005f * gameTime.ElapsedGameTime.Milliseconds;
            }

            // if (state.IsKeyDown(Keys.Delete) && mSelectMode && mSelectedActor != null)
            if (InputManager.AllKeysDown(Keys.Delete) && mSelectMode && mSelectedActor != null)
            {
                mDeleteDown = true;
            }

            // if (state.IsKeyUp(Keys.Delete) && mDeleteDown)
            if (InputManager.AllKeysUp(Keys.Delete) && mDeleteDown)
            {
                if (mSelectedActor != null)
                {
                    mLevel.Remove(mSelectedActor);
                }
                mSelectedActor = null;
            }

            var mouseState = Mouse.GetState();

            if (!mSelectMode)
            {
                var intersection =
                    RayCasting.CalculateMouseRayTerrainIntersection(mViewport, mCamera, mLevel.mTerrain);

                if (intersection.mIntersected && mSelectedActor != null)
                {
                    intersection.mLocation.Y += mActorYOffset;
                    var matrix = Matrix.CreateRotationY(mActorYRotation) *
                                 Matrix.CreateTranslation(intersection.mLocation);
                    mSelectedActor.ModelMatrix = matrix;

                    // if (mouseState.RightButton == ButtonState.Pressed)
                    if (InputManager.MouseRightButtonPressed())
                    {
                        mRightMouseButtonDown = true;
                    }

                    // if (mouseState.RightButton != ButtonState.Pressed && mRightMouseButtonDown)
                    if (InputManager.MouseRightButtonReleased() && mRightMouseButtonDown)
                    {
                        mSelectedActor.Color  = new Vector3(1.0f);
                        mSelectedActor        = null;
                        mRightMouseButtonDown = false;
                        if (mSetOnce)
                        {
                            mSetOnce      = false;
                            mSelectMode   = true;
                            mSelectedMesh = null;
                        }
                    }
                }
            }
            else
            {
                // if (mouseState.RightButton == ButtonState.Pressed && mSelectedActor == null && !mDeleteDown)
                if (InputManager.MouseRightButtonPressed() && mSelectedActor == null && !mDeleteDown)
                {
                    var intersection =
                        RayCasting.CalculateMouseRayIntersection(mViewport, mCamera, mLevel, mLevel.mTerrain);

                    if (intersection.mIntersected && !intersection.mIsTerrainIntersection)
                    {
                        mSelectedActor       = intersection.mActor;
                        mSelectedActor.Color = new Vector3(0.3f);
                        mActorYRotation      = 0.0f;
                        mActorYOffset        = 0.0f;
                        mSelectedMesh        = mSelectedActor.mMesh;
                    }
                }

                // We need to check if the button is still pressed
                if (Mouse.GetState().RightButton == ButtonState.Pressed && mSelectedActor != null)
                {
                    var intersection =
                        RayCasting.CalculateMouseRayTerrainIntersection(mViewport, mCamera, mLevel.mTerrain);

                    if (intersection.mIntersected)
                    {
                        intersection.mLocation.Y  += mActorYOffset;
                        mSelectedActor.ModelMatrix = Matrix.CreateRotationY(mActorYRotation) * Matrix.CreateTranslation(intersection.mLocation);
                    }
                }

                // if (mouseState.RightButton == ButtonState.Released)
                if (InputManager.MouseRightButtonReleased())
                {
                    if (mSelectedActor != null)
                    {
                        mSelectedActor.Color = new Vector3(1.0f);
                    }
                    mSelectedActor = null;
                    mDeleteDown    = false;
                }
            }

            mLevel.Update(mCamera, mCameraHandler, gameTime);
        }
Example #21
0
 // Use this for initialization
 void Start()
 {
     _raycasting = new RayCasting(mainCamera, ray_distance);
 }