Beispiel #1
0
        public override void Update(double delta)
        {
            _position = new Vector3(
                (float)_playerAirplane.CurrentState.Position.Y,
                _playerAirplane.Altitude,
                (float)_playerAirplane.CurrentState.Position.X);

            Vector3 orientation = new Vector3((float)_playerAirplane.CurrentState.AngularPosition.X,
                                              (float)_playerAirplane.CurrentState.AngularPosition.Y,
                                              (float)_playerAirplane.CurrentState.AngularPosition.Z);
            // Create the rotation matrix from the yaw, pitch, and roll values (in radians).
            Matrix rotationMatrix = Matrix.RotationYawPitchRoll(orientation.X, orientation.Y, orientation.Z);

            // Get the direction that the camera is pointing to and the up direction
            Vector3 lookAt = Vector3.TransformCoordinate(Vector3.UnitZ, rotationMatrix);
            Vector3 up = Vector3.TransformCoordinate(Vector3.UnitY, rotationMatrix);

            Vector3 positionDisplacement = Vector3.TransformCoordinate(new Vector3(0, 10, -60), rotationMatrix);

            // Finally create the view matrix from the three updated vectors.
            _viewMatrix = Matrix.LookAtLH(_position + positionDisplacement, _position + positionDisplacement + lookAt, up);

            _uiMatrix = Matrix.LookAtLH(new Vector3(0, 0, -50), Vector3.UnitZ, Vector3.UnitY);

            _reflectionMatrix = Matrix.LookAtLH(new Vector3(_position.X, -_position.Y, _position.Z),
                new Vector3(_position.X + lookAt.X, -_position.Y /*- lookAt.Y*/, _position.Z + lookAt.Z), up);
        }
 public TimeSeriesLineVertex(Vector3 position, Vector3 normal, float time, uint color)
 {
     Position = position;
     Normal = normal;
     Tu = time;
     Tv = 0;
     this.color = color;
 }
Beispiel #3
0
 public Player(LabGame game)
 {
     this.game = game;
     type = GameObjectType.Player;
     myModel = game.assets.GetModel("player", CreatePlayerModel);
     pos = new SharpDX.Vector3(0, game.boundaryBottom + 0.5f, 0);
     GetParamsFromModel();
 }
Beispiel #4
0
 private bool checkStomp(Skeleton skeleton, float boxScale, Vector3 boxTranslation)
 {
     var foot = convert(skeleton.Joints[JointType.FootRight].Position);
     if ((foot.X < (boxTranslation.X + boxScale)) && (foot.X > (boxTranslation.X - boxScale)) &&
         (foot.Y < (boxTranslation.Y + boxScale)) && (foot.Y > (boxTranslation.Y - boxScale)) &&
         (-1 * foot.Z < (boxTranslation.Z + boxScale)) && (-1 * foot.Z > (boxTranslation.Z - boxScale))) return true;
     return false;
 }
Beispiel #5
0
        public KmlLabels()
        {
            texture = Texture11.FromBitmap( Resources.circle, 0);
            star = Texture11.FromBitmap(Resources.icon_rating_star_large_on, 0);

            center = new Vector3(10, 10, 0);
            positions = new List<Vector3>();
            names = new List<string>();
        }
        public Player(Game game)
            : base(game)
        {
            type = GameObjectType.Player;
            model = game.assets.GetModel("player", CreatePlayerModel);
            pos = new SharpDX.Vector3(0, game.boundaryBottom, 0);

            vel = Vector3.Zero;
        }
 public Player(LabGame game)
 {
     this.game = game;
     type = GameObjectType.Player;
     myModel = game.assets.GetModel("player", CreatePlayerModel);
     radius = 0.5f;
     frictionConstant = 0.4f;
     pos = new SharpDX.Vector3(0, 0, 0);
     GetParamsFromModel();
     effect = game.Content.Load<Effect>("Phong");
 }
Beispiel #8
0
 public System.Windows.Point CanvasPointFrom3DPoint(Point3D modelPoint3D)
 {
     Point3D worldPoint = ViewportImage.ModelToWorld.Transform(modelPoint3D);
     SharpDX.Vector3 worldPointSharpDX = new SharpDX.Vector3((float)worldPoint.X, (float)worldPoint.Y, (float)worldPoint.Z);
     float width = (float)ViewportImage.imageWidth;
     float height = (float)ViewportImage.imageHeight;
     SharpDX.Matrix trans = SharpDX.Matrix.Multiply(ViewportImage.View, ViewportImage.Projection);
     //Vector3 point2DSharpDX = Vector3.Project(worldPointSharpDX, 0, 0, ViewportImage.Width, ViewportImage.Height, 0.0f, 1.0f, trans);
     Vector3 point2DSharpDX = Vector3.Project(worldPointSharpDX, 0, 0, width, height, 0.0f, 1.0f, trans);
     return new System.Windows.Point((double)(point2DSharpDX.X), (double)(point2DSharpDX.Y));
 }
Beispiel #9
0
 public Player(LabGame game)
 {
     this.game = game;
     type = GameObjectType.Player;
     myModel = game.assets.GetModel("boat.png", CreatePlayerModel);
     pos = new SharpDX.Vector3(0, 0, -1);
     this.locallight.lightCol = new Vector4(0f,0.15f,0.5f,1f);
     this.locallight.lightPos = new Vector4(this.pos.X, this.pos.Y,this.pos.Z-2,1f);
     game.addLight(this.locallight);
     velocity = new Vector3(0, 0, 0);
     acceleration = new Vector3(0, 0, 0);
     hitpoints = (int)(100 / game.difficulty);
     armour = 1;
     maxspeed = 0.5f;
     maxaccel = 1.4f;
     GetParamsFromModel();
 }
Beispiel #10
0
        public CannonModel(Project1Game game)
        {
            model = game.Content.Load<Model>("Cannon");
            basicEffect = new BasicEffect(game.GraphicsDevice)
            {
                View = game.camera.View,
                Projection = game.camera.Projection,
                World = Matrix.Scaling(0.0003f) * Matrix.Translation(game.x0, game.y0 + 0.05f,game.z0),
                VertexColorEnabled = true
            };

            BasicEffect.EnableDefaultLighting(model,true);
            inputLayout = VertexInputLayout.FromBuffer(0, vertices);

            this.game = game;
            pos = new SharpDX.Vector3(-0.8f, 0f, 0.8f);
        }
Beispiel #11
0
        public Tree(Project1Game game)
        {
            model = game.Content.Load<Model>("tree1a_lod0");
            basicEffect = new BasicEffect(game.GraphicsDevice)
            {
                View = game.camera.View,
                Projection = game.camera.Projection,
                World = Matrix.Scaling(0.003f),
                VertexColorEnabled = true
            };

            BasicEffect.EnableDefaultLighting(model,true);
            inputLayout = VertexInputLayout.FromBuffer(0, vertices);

            this.game = game;
            pos = new SharpDX.Vector3(0, 0, 0);
        }
        public MazeLandscape(LabGame game,int dimension,int seed )
        {
            this.seed = seed;
            this.dimension = dimension;
            this.game = game;
            maze = new RandomMaze(dimension, seed);
            cube = new Cube();
            maze.GenerateMaze();
            maze.setStartPointAndDestPoint();

            while (maze.destPoint == null)
            {
                game.mazeSeed=game.random.Next();
                this.seed = game.mazeSeed;
                maze = new RandomMaze(dimension, this.seed);
                //cube = new Cube();
                maze.GenerateMaze();
                maze.setStartPointAndDestPoint();
            }

            //display path.

            /*
                            List<Node> pathFromSrcToDest = maze.astar.FindPath(maze.astar.Float2DtoInt(maze.maze)
                , RandomMaze.WALL, maze.startPoint.x, maze.startPoint.y, maze.destPoint.x, maze.destPoint.y);
            */
            //maze.updateMazeRoad(pathFromSrcToDest, Project.Cube.goal);

            type = GameObjectType.MazeLandscape;
            //if maze existed before just remove it from model
            game.assets.modelDict.Remove(mazeModelName);
            myModel = game.assets.GetModel(mazeModelName, CreateMazeLandscapeModel);
            //radius = 0.5f;
            //frictionConstant = 0.4f;
            pos = new SharpDX.Vector3(0, 0, 0);
            GetParamsFromModel();
            effect = game.Content.Load<Effect>("Phong");
            Debug.WriteLine("maze created");
            entranceX = maze.startPoint.x * CUBESCALE * 2;
            entranceZ = maze.startPoint.y * CUBESCALE * 2;
            normalMaze = myModel.shapeArray;
        }
 public void AddTriangle(Vector3 v1, Vector3 v2, Vector3 v3, Color color, Dates date)
 {
     trianglePoints.Add(v1);
     trianglePoints.Add(v2);
     trianglePoints.Add(v3);
     triangleColors.Add(color);
     triangleDates.Add(date);
     EmptyTriangleBuffer();
 }
 public void AddLine(Vector3 v1, Vector3 v2)
 {
     linePoints.Add(new Vector3d(v1));
     linePoints.Add(new Vector3d(v2));
     EmptyLineBuffer();
 }
Beispiel #15
0
        private static void PredictCastR(AIHeroClient target)
        {
            var inRange = SharpDX.Vector2.DistanceSquared(target.Position.ToVector2(), ObjectManager.Player.Position.ToVector2()) < R.Range * R.Range;
            PredictionOutput prediction;
            var     spellCasted = false;
            Vector3 pos1, pos2;

            var nearChamps  = (from champ in ObjectManager.Get <AIHeroClient>() where champ.IsValidTarget(maxRangeR) && target != champ select champ).ToList();
            var innerChamps = new List <AIHeroClient>();
            var outerChamps = new List <AIHeroClient>();

            foreach (var champ in nearChamps)
            {
                if (SharpDX.Vector2.DistanceSquared(champ.Position.ToVector2(), ObjectManager.Player.Position.ToVector2()) < R.Range * R.Range)
                {
                    innerChamps.Add(champ);
                }
                else
                {
                    outerChamps.Add(champ);
                }
            }

            var nearMinions  = GameObjects.GetMinions(ObjectManager.Player.Position, maxRangeR);
            var innerMinions = new List <AIBaseClient>();
            var outerMinions = new List <AIBaseClient>();

            foreach (var minion in nearMinions)
            {
                if (SharpDX.Vector2.DistanceSquared(minion.Position.ToVector2(), ObjectManager.Player.Position.ToVector2()) < R.Range * R.Range)
                {
                    innerMinions.Add(minion);
                }
                else
                {
                    outerMinions.Add(minion);
                }
            }

            if (inRange)
            {
                R.Speed    = speedR * 0.9f;
                R.From     = target.Position + (SharpDX.Vector3.Normalize(ObjectManager.Player.Position - target.Position) * (lengthR * 0.1f));
                prediction = R.GetPrediction(target);
                R.From     = ObjectManager.Player.Position;

                if (prediction.CastPosition.Distance(ObjectManager.Player.Position) < R.Range)
                {
                    pos1 = prediction.CastPosition;
                }
                else
                {
                    pos1    = target.Position;
                    R.Speed = speedR;
                }

                R.From           = pos1;
                R.RangeCheckFrom = pos1;
                R.Range          = lengthR;

                if (nearChamps.Count > 0)
                {
                    var closeToPrediction = new List <AIHeroClient>();
                    foreach (var enemy in nearChamps)
                    {
                        prediction = R.GetPrediction(enemy);

                        if (prediction.Hitchance >= HitChance.High && SharpDX.Vector2.DistanceSquared(pos1.ToVector2(), prediction.CastPosition.ToVector2()) < (R.Range * R.Range) * 0.8)
                        {
                            closeToPrediction.Add(enemy);
                        }
                    }

                    if (closeToPrediction.Count > 0)
                    {
                        if (closeToPrediction.Count > 1)
                        {
                            closeToPrediction.Sort((enemy1, enemy2) => enemy2.Health.CompareTo(enemy1.Health));
                        }

                        prediction = R.GetPrediction(closeToPrediction[0]);
                        pos2       = prediction.CastPosition;

                        CastR(pos1, pos2);
                        spellCasted = true;
                    }
                }

                if (!spellCasted)
                {
                    CastR(pos1, R.GetPrediction(target).CastPosition);
                }

                R.Speed          = speedR;
                R.Range          = rangeR;
                R.From           = ObjectManager.Player.Position;
                R.RangeCheckFrom = ObjectManager.Player.Position;
            }
            else
            {
                float startPointRadius = 150;

                SharpDX.Vector3 startPoint = ObjectManager.Player.Position + SharpDX.Vector3.Normalize(target.Position - ObjectManager.Player.Position) * rangeR;

                var targets = (from champ in nearChamps where SharpDX.Vector2.DistanceSquared(champ.Position.ToVector2(), startPoint.ToVector2()) < startPointRadius * startPointRadius && SharpDX.Vector2.DistanceSquared(ObjectManager.Player.Position.ToVector2(), champ.Position.ToVector2()) < rangeR * rangeR select champ).ToList();
                if (targets.Count > 0)
                {
                    if (targets.Count > 1)
                    {
                        targets.Sort((enemy1, enemy2) => enemy2.Health.CompareTo(enemy1.Health));
                    }

                    pos1 = targets[0].Position;
                }
                else
                {
                    var minionTargets = (from minion in nearMinions where SharpDX.Vector2.DistanceSquared(minion.Position.ToVector2(), startPoint.ToVector2()) < startPointRadius * startPointRadius && SharpDX.Vector2.DistanceSquared(ObjectManager.Player.Position.ToVector2(), minion.Position.ToVector2()) < rangeR * rangeR select minion).ToList();
                    if (minionTargets.Count > 0)
                    {
                        if (minionTargets.Count > 1)
                        {
                            minionTargets.Sort((enemy1, enemy2) => enemy2.Health.CompareTo(enemy1.Health));
                        }

                        pos1 = minionTargets[0].Position;
                    }
                    else
                    {
                        pos1 = startPoint;
                    }
                }

                R.From           = pos1;
                R.Range          = lengthR;
                R.RangeCheckFrom = pos1;
                prediction       = R.GetPrediction(target);

                if (prediction.Hitchance >= HitChance.High)
                {
                    CastR(pos1, prediction.CastPosition);
                }

                R.Range          = rangeR;
                R.From           = ObjectManager.Player.Position;
                R.RangeCheckFrom = ObjectManager.Player.Position;
            }
        }
Beispiel #16
0
 private void makeCubeg(Skeleton skeleton, float scale, Vector3 translation)
 {
     world = Matrix.Scaling(scale) * Matrix.Translation(translation);
     worldViewProj = world * view * proj;
     worldViewProj.Transpose();
     sDXdata.context.UpdateSubresource(ref worldViewProj, sDXdata.constantBuffer);
     sDXdata.textureView = GetTexture("green.jpg");
     sDXdata.context.PixelShader.SetShaderResource(0, sDXdata.textureView);
     sDXdata.context.Draw(36, 0);
 }
Beispiel #17
0
 public WallHopPosition(SharpDX.Vector3 pA, SharpDX.Vector3 pB)
 {
     this.pA = pA;
     this.pB = pB;
 }
Beispiel #18
0
        public SkyLabel(RenderContext11 renderContext, Vector3d point, string text, LabelSytle style)
        {
            Text = text;
            Style = style;

            if (texture == null)
            {
                texture = Texture11.FromBitmap(Resources.circle, 0);
            }

            pos = point;

            center = new Vector3(9, 9, 0);

            textBatch = new Text3dBatch(80);

            if (style == LabelSytle.Telrad)
            {
                // Telrad-style labels are always screen-aligned
                var t3 = new Text3d(new Vector3d(0, 0, 0.1), new Vector3d(0, 1, 0), text, 20, .01);
                t3.alignment = Text3d.Alignment.Left;
                textBatch.Add(t3);
            }
            else
            {
                // This will produce sky or orbit aligned text
                textBatch.Add(new Text3d(pos, new Vector3d(0,1,0), text, 20, .01));
            }
        }
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3 up = MathHelper.Convert(freelook.Up);
            sceneConstants.View = Matrix.LookAtLH(MathHelper.Convert(freelook.Eye), MathHelper.Convert(freelook.Target), up);
            sceneConstants.Projection = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane);
            sceneConstants.ViewInverse = Matrix.Invert(sceneConstants.View);

            Vector3 light = new Vector3(20, 30, 10);
            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Matrix lightView = Matrix.LookAtLH(light, Vector3.Zero, up);
            Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);
            sceneConstants.LightViewProjection = lightView * lightProjection;

            DataStream data;
            _immediateContext.MapSubresource(sceneConstantsBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data);
            Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
            _immediateContext.UnmapSubresource(sceneConstantsBuffer, 0);
            data.Dispose();

            effect2.GetVariableByName("InverseProjection").AsMatrix().SetMatrix(Matrix.Invert(sceneConstants.Projection));
            effect2.GetVariableByName("InverseView").AsMatrix().SetMatrix(sceneConstants.ViewInverse);
            effect2.GetVariableByName("LightInverseViewProjection").AsMatrix().SetMatrix(Matrix.Invert(sceneConstants.LightViewProjection));
            effect2.GetVariableByName("LightPosition").AsVector().Set(new Vector4(light, 1));
            effect2.GetVariableByName("EyePosition").AsVector().Set(new Vector4(MathHelper.Convert(freelook.Eye), 1));

            float tanHalfFOVY = (float)Math.Tan(FieldOfView * 0.5f);
            effect2.GetVariableByName("TanHalfFOVX").AsScalar().Set(tanHalfFOVY * AspectRatio);
            effect2.GetVariableByName("TanHalfFOVY").AsScalar().Set(tanHalfFOVY);
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;
            effect2.GetVariableByName("ProjectionA").AsScalar().Set(projectionA);
            effect2.GetVariableByName("ProjectionB").AsScalar().Set(projectionB);

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);
            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            effect2.GetVariableByName("OverlayViewProjection").AsMatrix().SetMatrix(overlayMatrix);
        }
Beispiel #20
0
 public FTransform(SharpDX.Vector4 rot, SharpDX.Vector3 translation, SharpDX.Vector3 scale)
 {
     Rotation    = rot;
     Translation = translation;
     Scale3D     = scale;
 }
Beispiel #21
0
 public VertexPositionColor(SharpDX.Vector3 position, SharpDX.Color4 color)
 {
     Position = position;
     Color    = color;
 }
 /// <summary>Function called when the size needs to be updated on the object.</summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="size">The new size.</param>
 protected override void OnSizeUpdate(GorgonPolySprite animObject, DX.Vector3 size)
 {
     // Not used.
 }
Beispiel #23
0
        /// <summary>
        /// Changes the camera distance.
        /// </summary>
        /// <param name="delta">The delta.</param>
        /// <param name="zoomAround">The zoom around point.</param>
        private bool ChangeCameraDistance(ref double delta, Point3D zoomAround)
        {
            // Handle the 'zoomAround' point
            var target           = this.Camera.CameraInternal.Position + this.Camera.CameraInternal.LookDirection;
            var relativeTarget   = zoomAround - target;
            var relativePosition = zoomAround - this.Camera.CameraInternal.Position;

            if (relativePosition.LengthSquared() < 1e-5)
            {
                if (delta > 0) //If Zoom out from very close distance, increase the initial relativePosition
                {
                    relativePosition.Normalize();
                    relativePosition /= 10;
                }
                else//If Zoom in too close, stop it.
                {
                    return(false);
                }
            }
            var f = Math.Pow(2.5, delta);
            var newRelativePosition = relativePosition * (float)f;
            var newRelativeTarget   = relativeTarget * (float)f;

            var newTarget   = zoomAround - newRelativeTarget;
            var newPosition = zoomAround - newRelativePosition;

            var newDistance = (newPosition - zoomAround).Length();
            var oldDistance = (this.Camera.CameraInternal.Position - zoomAround).Length();

            if (newDistance > this.Controller.ZoomDistanceLimitFar && (oldDistance < this.Controller.ZoomDistanceLimitFar || newDistance > oldDistance))
            {
                var ratio = (newDistance - this.Controller.ZoomDistanceLimitFar) / newDistance;
                f *= 1 - ratio;
                newRelativePosition = relativePosition * (float)f;
                newRelativeTarget   = relativeTarget * (float)f;

                newTarget   = zoomAround - newRelativeTarget;
                newPosition = zoomAround - newRelativePosition;
                delta       = Math.Log(f) / Math.Log(2.5);
            }

            if (newDistance < this.Controller.ZoomDistanceLimitNear && (oldDistance > this.Controller.ZoomDistanceLimitNear || newDistance < oldDistance))
            {
                var ratio = (this.Controller.ZoomDistanceLimitNear - newDistance) / newDistance;
                f *= (1 + ratio);
                newRelativePosition = relativePosition * (float)f;
                newRelativeTarget   = relativeTarget * (float)f;

                newTarget   = zoomAround - newRelativeTarget;
                newPosition = zoomAround - newRelativePosition;
                delta       = Math.Log(f) / Math.Log(2.5);
            }

            var newLookDirection = newTarget - newPosition;

            if (newLookDirection.LengthSquared() < 1e-5)
            {
                return(false);
            }
            this.Camera.LookDirection = newLookDirection;
            this.Camera.Position      = newPosition;
            return(true);
        }
Beispiel #24
0
        /// <summary>
        /// Function to build the meshes.
        /// </summary>
        private static void BuildMeshes()
        {
            var fnU = new DX.Vector3(0.5f, 1.0f, 0);
            var fnV = new DX.Vector3(1.0f, 1.0f, 0);

            DX.Vector3.Cross(ref fnU, ref fnV, out DX.Vector3 faceNormal);
            faceNormal.Normalize();

            _triangle = new Triangle(_graphics,
                                     new Vertex3D
            {
                Position = new DX.Vector4(-12.5f, -1.5f, 12.5f, 1),
                Normal   = faceNormal,
                UV       = new DX.Vector2(0, 1.0f)
            },
                                     new Vertex3D
            {
                Position = new DX.Vector4(0, 24.5f, 12.5f, 1),
                Normal   = faceNormal,
                UV       = new DX.Vector2(0.5f, 0.0f)
            },
                                     new Vertex3D
            {
                Position = new DX.Vector4(12.5f, -1.5f, 12.5f, 1),
                Normal   = faceNormal,
                UV       = new DX.Vector2(1.0f, 1.0f)
            })
            {
                Material =
                {
                    PixelShader  = "WaterShader",
                    VertexShader = "VertexShader",
                    Textures     =
                    {
                        [0] = "UV",
                        [1] = "Water_Normal",
                        [2] = "Water_Specular"
                    }
                },
                Position = new DX.Vector3(0, 0, 1.0f)
            };
            _renderer.Meshes.Add(_triangle);

            _plane = new Plane(_graphics, new DX.Vector2(25.0f, 25.0f), new RectangleF(0, 0, 1.0f, 1.0f), new DX.Vector3(90, 0, 0), 32, 32)
            {
                Position = new DX.Vector3(0, -1.5f, 1.0f),
                Material =
                {
                    PixelShader  = "WaterShader",
                    VertexShader = "VertexShader",
                    Textures     =
                    {
                        [0] = "UV",
                        [1] = "Water_Normal",
                        [2] = "Water_Specular"
                    }
                }
            };
            _renderer.Meshes.Add(_plane);

            _cube = new Cube(_graphics, new DX.Vector3(1, 1, 1), new RectangleF(0, 0, 1.0f, 1.0f), new DX.Vector3(45.0f, 0, 0))
            {
                Position = new DX.Vector3(0, 0, 1.5f),
                Material =
                {
                    SpecularPower =               0,
                    PixelShader   = "BumpMapShader",
                    VertexShader  = "VertexShader",
                    Textures      =
                    {
                        [0] = "UV",
                        [1] = "GorgonNormalMap"
                    }
                }
            };
            _renderer.Meshes.Add(_cube);

            _sphere = new Sphere(_graphics, 1.0f, new RectangleF(0.0f, 0.0f, 1.0f, 1.0f), DX.Vector3.Zero, 64, 64)
            {
                Position = new DX.Vector3(-2.0f, 1.0f, 0.75f),
                Material =
                {
                    PixelShader   = "PixelShader",
                    VertexShader  = "VertexShader",
                    SpecularPower =          0.75f,
                    Textures      =
                    {
                        [0] = "Earth"
                    }
                }
            };
            _renderer.Meshes.Add(_sphere);

            _icoSphere = new IcoSphere(_graphics, 5.0f, new DX.RectangleF(0, 0, 1, 1), DX.Vector3.Zero, 3)
            {
                Rotation = new DX.Vector3(0, -45.0f, 0),
                Position = new DX.Vector3(10, 2, 9.5f),
                Material =
                {
                    PixelShader  = "BumpMapShader",
                    VertexShader = "VertexShader",
                    Textures     =
                    {
                        [0] = "Earth",
                        [1] = "Earth_Normal",
                        [2] = "Earth_Specular"
                    }
                }
            };
            _renderer.Meshes.Add(_icoSphere);

            _clouds = new Sphere(_graphics, 5.125f, new RectangleF(0.0f, 0.0f, 1.0f, 1.0f), DX.Vector3.Zero, 16)
            {
                Position = new DX.Vector3(10, 2, 9.5f),
                Material =
                {
                    PixelShader  = "PixelShader",
                    VertexShader = "VertexShader",
                    BlendState   = GorgonBlendState.Additive,
                    Textures     =
                    {
                        [0] = "Clouds"
                    }
                }
            };
            _renderer.Meshes.Add(_clouds);
        }
Beispiel #25
0
        /// <summary>
        /// Function to process the keyboard commands.
        /// </summary>
        private static void ProcessKeys()
        {
            DX.Vector3 cameraDir = DX.Vector3.Zero;
            DX.Vector3 lookAt    = _camera.LookAt;
            lookAt.Normalize();

            if (_keyboard.KeyStates[Keys.Left] == GI.KeyState.Down)
            {
                _cameraRotation.Y -= 40.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.Right] == GI.KeyState.Down)
            {
                _cameraRotation.Y += 40.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.Up] == GI.KeyState.Down)
            {
                _cameraRotation.X -= 40.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.Down] == GI.KeyState.Down)
            {
                _cameraRotation.X += 40.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.PageUp] == GI.KeyState.Down)
            {
                _cameraRotation.Z -= 40.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.PageDown] == GI.KeyState.Down)
            {
                _cameraRotation.Z += 40.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.D] == GI.KeyState.Down)
            {
                cameraDir.X = 2.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.A] == GI.KeyState.Down)
            {
                cameraDir.X = -2.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.W] == GI.KeyState.Down)
            {
                cameraDir.Z = 2.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.S] == GI.KeyState.Down)
            {
                cameraDir.Z = -2.0f * GorgonTiming.Delta;
            }
            if (_keyboard.KeyStates[Keys.Q] == GI.KeyState.Down)
            {
                cameraDir.Y = 2.0f * GorgonTiming.Delta;
            }
            else if (_keyboard.KeyStates[Keys.E] == GI.KeyState.Down)
            {
                cameraDir.Y = -2.0f * GorgonTiming.Delta;
            }

            if (_lock)
            {
                _camera.Target(_sphere.Position);
            }

            _camera.Rotation = _cameraRotation;
            _camera.Move(ref cameraDir);
        }
Beispiel #26
0
        public MainViewModel()
        {
            EffectsManager = new DefaultEffectsManager();
            // ----------------------------------------------
            // titles
            this.Title    = "Lighting Demo";
            this.SubTitle = "WPF & SharpDX";

            // ----------------------------------------------
            // camera setup
            this.Camera = new PerspectiveCamera {
                Position = new Point3D(100, 100, 100), LookDirection = new Vector3D(-100, -100, -100), UpDirection = new Vector3D(0, 1, 0)
            };
            // ----------------------------------------------
            // setup scene
            this.AmbientLightColor = Colors.DimGray;
            this.Light1Color       = Colors.LightGray;


            this.Light1Direction = new Vector3D(-100, -100, -100);
            SetupCameraBindings(Camera);
            // ----------------------------------------------
            // ----------------------------------------------
            // scene model3d
            this.ModelMaterial = PhongMaterials.Silver;

            // ----------------------------------------------
            // floor model3d
            var b2 = new MeshBuilder(true, true, true);

            b2.AddBox(new Vector3(0.0f, 0, 0.0f), 150, 1, 150, BoxFaces.All);
            b2.AddBox(new Vector3(0, 25, 70), 150, 50, 20);
            b2.AddBox(new Vector3(0, 25, -70), 150, 50, 20);
            this.Floor                    = b2.ToMeshGeometry3D();
            this.FloorMaterial            = PhongMaterials.Bisque;
            this.FloorMaterial.DiffuseMap = TextureModel.Create(new System.Uri(@"TextureCheckerboard2.jpg", System.UriKind.RelativeOrAbsolute).ToString());
            this.FloorMaterial.NormalMap  = TextureModel.Create(new System.Uri(@"TextureCheckerboard2_dot3.jpg", System.UriKind.RelativeOrAbsolute).ToString());

            var caritems = Load3ds("leone.3DBuilder.obj").Select(x => x.Geometry as MeshGeometry3D).ToArray();
            var scale    = new Vector3(1f);

            foreach (var item in caritems)
            {
                for (int i = 0; i < item.Positions.Count; ++i)
                {
                    item.Positions[i] = item.Positions[i] * scale;
                }
            }
            Model = MeshGeometry3D.Merge(caritems);

            ModelTransform = new Media3D.RotateTransform3D()
            {
                Rotation = new Media3D.AxisAngleRotation3D(new Vector3D(1, 0, 0), -90)
            };

            Instances = new Matrix[6];
            for (int i = 0; i < Instances.Length; ++i)
            {
                Instances[i] = Matrix.Translation(new Vector3(15 * i - 30, 15 * (i % 2) - 30, 0));
            }

            OutlineInstances = new Matrix[6];
            for (int i = 0; i < Instances.Length; ++i)
            {
                OutlineInstances[i] = Matrix.Translation(new Vector3(15 * i - 30, 15 * (i % 2), 0));
            }

            var blendDesc = new BlendStateDescription();

            blendDesc.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled        = true,
                BlendOperation        = BlendOperation.Add,
                AlphaBlendOperation   = BlendOperation.Add,
                SourceBlend           = BlendOption.One,
                DestinationBlend      = BlendOption.One,
                SourceAlphaBlend      = BlendOption.Zero,
                DestinationAlphaBlend = BlendOption.One,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };
            BlendDescription        = blendDesc;
            DepthStencilDescription = new DepthStencilStateDescription()
            {
                IsDepthEnabled  = true,
                DepthComparison = Comparison.LessEqual,
                DepthWriteMask  = DepthWriteMask.Zero
            };
        }
Beispiel #27
0
        bool desktopDuplicationEnabled = true;  // Properties.Settings.Default.DesktopDuplicationEnabled;

        void RenderLoop()
        {
            while (true)
            {
                lock (renderLock)
                {
                    var deviceContext = device.ImmediateContext;

                    // render user view
                    deviceContext.ClearRenderTargetView(userViewRenderTargetView, Color4.Black);
                    deviceContext.ClearDepthStencilView(userViewDepthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                    SharpDX.Vector3 headPosition = new SharpDX.Vector3(0f, 1.1f, -1.4f);  // may need to change this default

                    if (localHeadTrackingEnabled)
                    {
                        float distanceSquared = 0;
                        lock (headCameraSpacePointLock)
                        {
                            headPosition = new SharpDX.Vector3(headCameraSpacePoint.X, headCameraSpacePoint.Y, headCameraSpacePoint.Z);

                            float dx = handLeftCameraSpacePoint.X - handRightCameraSpacePoint.X;
                            float dy = handLeftCameraSpacePoint.Y - handRightCameraSpacePoint.Y;
                            float dz = handLeftCameraSpacePoint.Z - handRightCameraSpacePoint.Z;
                            distanceSquared = dx * dx + dy * dy + dz * dz;
                        }
                        var transform = SharpDX.Matrix.RotationY((float)Math.PI) * SharpDX.Matrix.Translation(0, 0.45f, 0);
                        //headPosition = SharpDX.Vector3.TransformCoordinate(headPosition, transform);

                        if (trackingValid && (distanceSquared < 0.02f) && (alpha > 1))
                        {
                            alpha = 0;
                        }
                        //Console.WriteLine(distanceSquared);
                    }

                    var userView = SharpDX.Matrix.Translation(headPosition);// GraphicsTransforms.LookAt(headPosition, headPosition + SharpDX.Vector3.UnitZ, SharpDX.Vector3.UnitY);
                    userView.Transpose();


                    //Console.WriteLine("headPosition = " + headPosition);


                    float aspect         = (float)userViewTextureWidth / (float)userViewTextureHeight;
                    var   userProjection = GraphicsTransforms.PerspectiveFov(20.0f / 180.0f * (float)Math.PI, aspect, 0.001f, 1000.0f);
                    userProjection.Transpose();

                    // smooth depth images
                    foreach (var camera in ensemble.cameras)
                    {
                        var cameraDeviceResource = cameraDeviceResources[camera];
                        if (cameraDeviceResource.depthImageChanged)
                        {
                            fromUIntPS.Render(deviceContext, cameraDeviceResource.depthImageTextureRV, cameraDeviceResource.floatDepthImageRenderTargetView);
                            for (int i = 0; i < 1; i++)
                            {
                                bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.floatDepthImageRenderTargetView2);
                                bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV2, cameraDeviceResource.floatDepthImageRenderTargetView);
                            }
                            cameraDeviceResource.depthImageChanged = false;
                        }
                    }

                    // wobble effect
                    if (wobbleEffectEnabled)
                    {
                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    world[i, j] = (float)camera.pose[i, j];
                                }
                            }
                            world.Transpose();

                            // view and projection matrix are post-multiply
                            var userWorldViewProjection = world * userView * userProjection;

                            depthAndColorShader.SetConstants(deviceContext, camera.calibration, userWorldViewProjection);
                            depthAndColorShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.colorImageTextureRV, cameraDeviceResource.vertexBuffer, userViewRenderTargetView, userViewDepthStencilView, userViewViewport);
                        }
                    }

                    // 3d object
                    if (threeDObjectEnabled)
                    {
                        var world = SharpDX.Matrix.Scaling(1.0f) * SharpDX.Matrix.RotationY(90.0f / 180.0f * (float)Math.PI) *
                                    SharpDX.Matrix.RotationX(-40.0f / 180.0f * (float)Math.PI) * SharpDX.Matrix.Translation(0, 0.7f, 0.0f);

                        var pointLight = new PointLight();
                        pointLight.position = new Vector3(0, 2, 0);
                        pointLight.Ia       = new Vector3(0.1f, 0.1f, 0.1f);
                        meshShader.SetVertexShaderConstants(deviceContext, world, userView * userProjection, pointLight.position);
                        meshShader.Render(deviceContext, meshDeviceResources, pointLight, userViewRenderTargetView, userViewDepthStencilView, userViewViewport);
                    }

                    // wobble effect
                    if (wobbleEffectEnabled)
                    {
                        alpha += 0.05f;
                        if (alpha > 1)
                        {
                            radialWobbleShader.SetConstants(deviceContext, 0);
                        }
                        else
                        {
                            radialWobbleShader.SetConstants(deviceContext, alpha);
                        }
                        radialWobbleShader.Render(deviceContext, userViewSRV, filteredUserViewRenderTargetView);
                    }

                    // desktop duplication
                    if (desktopDuplicationEnabled)
                    {
                        // update the desktop texture; this will block until there is some change
                        var outputDuplicateFrameInformation = default(OutputDuplicateFrameInformation);
                        SharpDX.DXGI.Resource resource      = null;
                        outputDuplication.AcquireNextFrame(5000, out outputDuplicateFrameInformation, out resource);
                        var texture = resource.QueryInterface <Texture2D>();

                        // pick up the window under the cursor
                        var cursorPos = new POINT();
                        GetCursorPos(out cursorPos);
                        var hwnd = WindowFromPoint(cursorPos);
                        var rect = new RECT();
                        GetWindowRect(hwnd, out rect);

                        // adjust bounds so falls within source texture
                        if (rect.Left < 0)
                        {
                            rect.Left = 0;
                        }
                        if (rect.Top < 0)
                        {
                            rect.Top = 0;
                        }
                        if (rect.Right > texture.Description.Width - 1)
                        {
                            rect.Right = texture.Description.Width;
                        }
                        if (rect.Bottom > texture.Description.Height - 1)
                        {
                            rect.Bottom = texture.Description.Height;
                        }

                        int width  = rect.Right - rect.Left;
                        int height = rect.Bottom - rect.Top;

                        // resize our texture if necessary
                        if ((desktopTexture == null) || (desktopTexture.Description.Width != width) || (desktopTexture.Description.Height != height))
                        {
                            if (desktopTexture != null)
                            {
                                desktopTextureSRV.Dispose();
                                desktopTexture.Dispose();
                            }
                            var desktopTextureDesc = new Texture2DDescription()
                            {
                                Width             = width,
                                Height            = height,
                                MipLevels         = 1, // revisit this; we may benefit from mipmapping?
                                ArraySize         = 1,
                                Format            = SharpDX.DXGI.Format.B8G8R8A8_UNorm,
                                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                                Usage             = ResourceUsage.Default,
                                BindFlags         = BindFlags.ShaderResource,
                                CpuAccessFlags    = CpuAccessFlags.None,
                            };
                            desktopTexture    = new Texture2D(device, desktopTextureDesc);
                            desktopTextureSRV = new ShaderResourceView(device, desktopTexture);
                        }

                        // copy the winodw region into our texture
                        var sourceRegion = new ResourceRegion()
                        {
                            Left   = rect.Left,
                            Right  = rect.Right,
                            Top    = rect.Top,
                            Bottom = rect.Bottom,
                            Front  = 0,
                            Back   = 1,
                        };
                        deviceContext.CopySubresourceRegion(texture, 0, sourceRegion, desktopTexture, 0);
                        texture.Dispose();
                    }

                    // render user view to seperate form
                    passThroughShader.viewport = new Viewport(0, 0, userViewForm.videoPanel1.Width, userViewForm.videoPanel1.Height);

                    // TODO: clean this up by simply using a pointer to the userViewSRV
                    if (threeDObjectEnabled)
                    {
                        passThroughShader.Render(deviceContext, userViewSRV, userViewForm.renderTargetView);
                    }
                    if (wobbleEffectEnabled)
                    {
                        passThroughShader.Render(deviceContext, filteredUserViewSRV, userViewForm.renderTargetView);
                    }
                    if (desktopDuplicationEnabled)
                    {
                        passThroughShader.Render(deviceContext, desktopTextureSRV, userViewForm.renderTargetView);
                    }
                    userViewForm.swapChain.Present(0, PresentFlags.None);

                    // projection puts x and y in [-1,1]; adjust to obtain texture coordinates [0,1]
                    // TODO: put this in SetContants?
                    userProjection[0, 0] /= 2;
                    userProjection[1, 1] /= -2; // y points down
                    userProjection[2, 0] += 0.5f;
                    userProjection[2, 1] += 0.5f;

                    // projection mapping for each projector
                    foreach (var form in projectorForms)
                    {
                        deviceContext.ClearRenderTargetView(form.renderTargetView, Color4.Black);
                        deviceContext.ClearDepthStencilView(form.depthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                            {
                                for (int j = 0; j < 4; j++)
                                {
                                    world[i, j] = (float)camera.pose[i, j];
                                }
                            }
                            world.Transpose();

                            var projectorWorldViewProjection = world * form.view * form.projection;
                            var userWorldViewProjection      = world * userView * userProjection;

                            projectiveTexturingShader.SetConstants(deviceContext, userWorldViewProjection, projectorWorldViewProjection);

                            // TODO: clean this up by simply using a pointer to the userViewSRV
                            if (wobbleEffectEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, filteredUserViewSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                            if (threeDObjectEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, userViewSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                            if (desktopDuplicationEnabled)
                            {
                                projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, desktopTextureSRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                            }
                        }

                        form.swapChain.Present(1, PresentFlags.None);
                    }


                    if (desktopDuplicationEnabled)
                    {
                        outputDuplication.ReleaseFrame();
                    }


                    //Console.WriteLine(stopwatch.ElapsedMilliseconds);
                    stopwatch.Restart();
                }
            }
        }
Beispiel #28
0
        private void SDXThread(object sender)
        {
            while (true)
            {
                Thread.Sleep(15);
                Console.Clear();
                device.BeginDraw();
                device.Clear(null);
                if (AMK.Hile == true)
                {
                    int EntityCount = AMK.Mem.Read <int>(AMK.ULevel + 0xA8);
                    Console.WriteLine($"EntityCount:{EntityCount}");
                    if (EntityCount < 1 || EntityCount > 10000)
                    {
                        continue;
                    }
                    SharpDX.Vector3 LocalPlayerPosition = AMK.Mem.Read <SharpDX.Vector3>(AMK.LocalPlayer + Offsets.LLocation);
                    //if (LocalPlayerPosition == null) continue;
                    IntPtr aactorPtr = AMK.Mem.Read <IntPtr>(AMK.ULevel + Offsets.ActorPtr);
                    for (int i = 0; i < EntityCount; i++)
                    {
                        IntPtr curActor = AMK.Mem.Read <IntPtr>(aactorPtr + (i * IntPtr.Size));
                        //if (curActor == null) continue;

                        int PlayerID = AMK.Mem.Read <int>(curActor + Offsets.ActorID);
                        if (!AMK.tGnames.ContainsKey(PlayerID))
                        {
                            continue;
                        }

                        if (AMK.tGnames[PlayerID] != "" && !ArabaTH)
                        {
                            continue;
                        }

                        float hp = AMK.Mem.Read <float>(curActor + Offsets.ActorHP);
                        if (AMK.tGnames[PlayerID] == "" && hp < 1 && AMK.Mem.Read <float>(curActor + Offsets.GroggyH) < 1)
                        {
                            continue;
                        }

                        IntPtr rootCmpPtr = AMK.Mem.Read <IntPtr>(curActor + Offsets.RootComponent);

                        SharpDX.Vector3 actorLocation = AMK.Mem.Read <SharpDX.Vector3>(rootCmpPtr + Offsets.ActorLoc);

                        var lDeltaInMeters = (LocalPlayerPosition - actorLocation).Length() / 100;
                        if (lDeltaInMeters > 800 || lDeltaInMeters < 3)
                        {
                            continue;
                        }
                        AMK.CameraManager = (AMK.Mem.Read <IntPtr>(AMK.LocalPlayerControl + Offsets.CameraManager));
                        Matriks.WorldToScreen2(actorLocation, AMK.CameraManager, out SharpDX.Vector2 GelBakem);
                        if (AMK.tGnames[PlayerID] == "" && lDeltaInMeters < 100 && AMK.Bone == true)
                        {
                            IntPtr     mesh             = AMK.Mem.Read <IntPtr>(curActor + 0x400);
                            IntPtr     bonearray        = AMK.Mem.Read <IntPtr>(mesh + 0x790);
                            FTransform ComponentToWorld = AMK.Mem.Read <FTransform>(mesh + 0x190);
                            foreach (Bone[] part in skeleton)
                            {
                                SharpDX.Vector2 previousBone = new SharpDX.Vector2();
                                foreach (Bone b in part)
                                {
                                    FTransform      bone        = AMK.Mem.Read <FTransform>(bonearray + ((int)b * 0x30));
                                    Matrix          Matrix      = bone.ToMatrixWithScale() * ComponentToWorld.ToMatrixWithScale();
                                    SharpDX.Vector3 currentBone = new SharpDX.Vector3(Matrix.M41, Matrix.M42, Matrix.M43);
                                    Matriks.WorldToScreen2(currentBone, AMK.CameraManager, out SharpDX.Vector2 cr);
                                    if (previousBone.X == 0)
                                    {
                                        previousBone = cr;
                                        continue;
                                    }
                                    else
                                    {
                                        //if (b == Bone.forehead) Ekranabas(cr, "O", System.Drawing.Color.Red, font);
                                        device.DrawLine(previousBone, cr, (new SolidColorBrush(device, RawColorFromColor(System.Drawing.Color.DarkRed))));
                                        previousBone = cr;
                                    }
                                }
                            }
                        }
                        if (AMK.tGnames[PlayerID] == "" && hp < 1)
                        {
                            Ekranabas(GelBakem, $"[{lDeltaInMeters.ToString("N2")}]", System.Drawing.Color.Purple, fontSmall);
                        }
                        else if (lDeltaInMeters > 150)
                        {
                            Ekranabas(GelBakem, $"{AMK.tGnames[PlayerID]}[{lDeltaInMeters.ToString("N2")}]", System.Drawing.Color.Green, fontSmall);
                        }
                        else
                        {
                            Ekranabas(GelBakem, $"{AMK.tGnames[PlayerID]}[{lDeltaInMeters.ToString("N2")}]", System.Drawing.Color.Red, font);
                        }
                    }
                }
                device.TryEndDraw(out long w, out w);
            }
        }
Beispiel #29
0
        internal void ItemClick(Vector3 searchPoint, float distance)
        {
            if (LabelItemClicked == null)
            {
                return;
            }

            if (lastHoverIndex > -1)
            {
                LabelItemClicked.Invoke(lastHoverIndex);
            }

            searchPoint = -searchPoint;
            Vector3 dist;

            var closestItem = -1;
            var index = 0;
            foreach (var point in positions)
            {
                dist = searchPoint - point;
                if (dist.Length() < distance)
                {
                    distance = dist.Length();
                    closestItem = index;
                }
                index++;
            }
            if (closestItem == -1)
            {
                return ;
            }

            LabelItemClicked.Invoke(closestItem);
        }
Beispiel #30
0
        private void ProcessLeftMouse(EButtonEvent buttonEvent)
        {
            if (buttonEvent == EButtonEvent.Pressed && m_controlledTransform != null)
            {
                if (IsHovered)
                {
                    Plane axisPlane;
                    if (m_activeAxisList.Count > 1)
                    {
                        Vector3 planeNormal = Vector3.Cross(m_activeAxisList[0], m_activeAxisList[1]);
                        axisPlane = new Plane(m_gizmoLocation, planeNormal);
                    }
                    else
                    {
                        Vector3 planeNormal;
                        if (Mode == EGizmoMode.Rotation)
                        {
                            // Rotation
                            planeNormal = m_activeAxisList[0];
                        }
                        else
                        {
                            //Translation / Scale
                            Vector3 toCamera     = m_frameViewInfo.ViewLocation - m_gizmoLocation;
                            Vector3 planeTangent = Vector3.Cross(m_activeAxisList[0], toCamera);
                            planeNormal = Vector3.Cross(m_activeAxisList[0], planeTangent);
                        }

                        axisPlane = new Plane(m_gizmoLocation, planeNormal);
                    }

                    World.ViewManager.GetViewInfo(out SSceneViewInfo viewInfo);
                    Ray ray = CreateMouseRay(viewInfo);

                    if (ray.Intersects(ref axisPlane, out Vector3 intersectionPoint))
                    {
                        m_startLocation = intersectionPoint;

                        switch (Mode)
                        {
                        case EGizmoMode.Translation:
                            m_clickOffset      = intersectionPoint - m_gizmoLocation;
                            m_originalPosition = m_controlledTransform.WorldPosition;
                            break;

                        case EGizmoMode.Rotation:
                            Vector3 toStart = m_startLocation - m_gizmoLocation;
                            m_rotationDragAxis = Vector3.Cross(toStart, m_activeAxisList[0]);
                            m_rotationDragAxis.Normalize();
                            m_originalRotation = m_controlledTransform.WorldRotation;
                            break;

                        case EGizmoMode.Scale:
                            m_originalScale = m_controlledTransform.WorldScale;
                            m_scaleAxis     = Vector3.Zero;
                            foreach (Vector3 axis in m_activeAxisList)
                            {
                                m_scaleAxis += Vector3.Transform(axis, Quaternion.Invert(m_controlledTransform.WorldRotation));
                            }

                            m_scaleAxis.Normalize();
                            m_scaleSizeFactor = m_originalScale.Length();
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }

                        IsClicked = true;
                    }
                }
            }
            else if (m_controlledTransform != null)
            {
                if (IsClicked)
                {
                    switch (Mode)
                    {
                    case EGizmoMode.Translation:
                        Vector3 newPosition = m_controlledTransform.WorldPosition;
                        if (newPosition != m_originalPosition)
                        {
                            OnTranslationChanged?.Invoke(m_controlledTransform, m_originalPosition, newPosition);
                        }
                        break;

                    case EGizmoMode.Rotation:
                        Quaternion newRotation = m_controlledTransform.WorldRotation;
                        if (newRotation != m_originalRotation)
                        {
                            OnRotationChanged?.Invoke(m_controlledTransform, m_originalRotation, newRotation);
                        }
                        break;

                    case EGizmoMode.Scale:
                        Vector3 newScale = m_controlledTransform.WorldScale;
                        if (newScale != m_originalScale)
                        {
                            OnScaleChanged?.Invoke(m_controlledTransform, m_originalScale, newScale);
                        }
                        break;
                    }
                }

                IsClicked         = false;
                m_totalAngleDelta = 0.0f;
                m_totalScaleDelta = 0.0f;
            }
        }
Beispiel #31
0
        public static async Task<bool> MoveToPosWithNavMeshAsync(SharpDX.Vector3 vecDest, int NearDistance = 50)
        {
            if (Nav.D3.Navmesh.Current == null)
                Nav.D3.Navmesh.Create(Enigma.D3.Engine.Current, new Nav.ExploreEngine.Nearest());

            var localAcd = ActorCommonDataHelper.GetLocalAcd();
            var distance = vecDest.Distance(); // (Math.Pow(localAcd.x0D0_WorldPosX - vecDest.X, 2) + Math.Pow(localAcd.x0D4_WorldPosY - vecDest.Y, 2));

            var minDistanceReached = distance;
            var dtDistanceReached = DateTime.Now;

            DateTime dtTimeout = DateTime.Now;
            while (distance > NearDistance)
            {
                if (DateTime.Now > dtTimeout.AddSeconds(30) || DateTime.Now > dtDistanceReached.AddSeconds(10))
                    return false;

                SharpDX.Vector2 curVector = localAcd.ToSharpDXVector2(); // new SharpDX.Vector2(localAcd.x0D0_WorldPosX, localAcd.x0D4_WorldPosY);
                SharpDX.Vector2 destVector = new SharpDX.Vector2(vecDest.X, vecDest.Y);

                // Update current player position.
                Nav.D3.Navmesh.Current.Navigator.CurrentPos = localAcd.ToNavVec3(); // new Nav.Vec3(localAcd.x0D0_WorldPosX, localAcd.x0D4_WorldPosY, localAcd.x0D8_WorldPosZ);

                // Update destination. You can keep setting the same value there is internal check if destination has actually changed. 
                // This destination overrides any internal destinations (including exploration). When You just want to explore You do 
                // not need to set any destination. It will be set automatically.
                Nav.D3.Navmesh.Current.Navigator.Destination = new Nav.Vec3(vecDest.X, vecDest.Y, vecDest.Z);

                // Get current destination.
                Nav.Vec3 goToPosition = Nav.D3.Navmesh.Current.Navigator.GoToPosition;
                while (goToPosition.IsEmpty)
                    await Task.Delay(10);

                SharpDX.Vector3 goToPositionVector = new SharpDX.Vector3(goToPosition.X, goToPosition.Y, goToPosition.Z);
                await MoveToPosAsync(goToPositionVector);



            }

            return true;
        }
Beispiel #32
0
        private void ProcessTranslationDrag()
        {
            if (m_activeAxis == EGizmoAxis.None)
            {
                return;
            }

            if (m_activeAxisList.Count <= 0)
            {
                return;
            }

            Ray pickRay = CreateMouseRay(in m_frameViewInfo);

            if (m_activeAxisList.Count > 1)
            {
                Vector3 planeNormal       = Vector3.Cross(m_activeAxisList[0], m_activeAxisList[1]);
                Plane   intersectionPlane = new Plane(m_startLocation, planeNormal);

                if (intersectionPlane.Intersects(ref pickRay, out Vector3 intersection))
                {
                    m_controlledTransform.SetWorldPosition(intersection - m_clickOffset);
                }
            }
            else
            {
                Vector3 planeTangent      = Vector3.Cross(m_activeAxisList[0], m_frameViewInfo.ViewLocation - m_gizmoLocation);
                Vector3 planeNormal       = Vector3.Cross(m_activeAxisList[0], planeTangent);
                Plane   intersectionPlane = new Plane(m_startLocation, planeNormal);

                if (intersectionPlane.Intersects(ref pickRay, out Vector3 intersection))
                {
                    intersection -= m_originalPosition + m_clickOffset;
                    m_controlledTransform.SetWorldPosition(m_originalPosition + m_activeAxisList[0] * Vector3.Dot(intersection, m_activeAxisList[0]));
                }
            }
        }
Beispiel #33
0
        public static void changeDirection1()
        {
            ObjectManager.Player.IssueOrder(GameObjectOrder.HoldPosition, ObjectManager.Player.ServerPosition);
            Packet.C2S.Move.Encoded(new Packet.C2S.Move.Struct(startPoint.X + directionVector.X / rotateMultiplier, startPoint.Y + directionVector.Y / rotateMultiplier)).Send();

            directionPos = new SharpDX.Vector3(startPoint.X, startPoint.Y, startPoint.Z);
            directionPos.X = startPoint.X + directionVector.X / rotateMultiplier;
            directionPos.Y = startPoint.Y + directionVector.Y / rotateMultiplier;
            directionPos.Z = startPoint.Z + directionVector.Z / rotateMultiplier;
            Utility.DelayAction.Add(60, delegate { changeDirection2(); });
        }
 /// <summary>
 /// The stop animations.
 /// </summary>
 private void StopAnimations()
 {
     this.rotationSpeed = new Vector2();
     this.panSpeed      = new Vector3D();
     this.zoomSpeed     = 0;
 }
        public void UpdateMesh()
        {
            Vector3 point = new Vector3();

            //Updates Terrainmesh

            for (int x = 0; x < TerrainSize; x++)
            {
                for (int z = 0; z < TerrainSize; z++)
                {
                    point   = terrainMesh.Positions[z + (x * TerrainSize)];
                    point.Y = (TerrainHeights[z + x * TerrainSize] * HeightMultiplicator);
                    terrainMesh.Positions[z + x * TerrainSize] = point;
                }
            }
            TerrainMeshMainGeometry3D = terrainMesh.ToMeshGeometry3D();

            for (int x = 1; x < TerrainSize - 1; x++)
            {
                for (int z = 1; z < TerrainSize - 1; z++)
                {
                    Vector3 neighbour0 = terrainMesh.Positions[z + (x * TerrainSize) - 1];
                    Vector3 neighbour1 = terrainMesh.Positions[z + (x * TerrainSize) + 1];
                    Vector3 neighbour2 = terrainMesh.Positions[z + (x * TerrainSize) - TerrainSize];
                    Vector3 neighbour3 = terrainMesh.Positions[z + (x * TerrainSize) + TerrainSize];
                    Vector3 vec0       = neighbour0 - neighbour1;
                    Vector3 vec1       = neighbour2 - neighbour3;
                    terrainMesh.Normals[z + x * TerrainSize] = Vector3.Cross(vec0, vec1);
                }
            }

            //Updates Bordermesh
            for (int z = 0; z < TerrainSize; z++)
            {
                point   = borderMesh.Positions[(z * 2) + 1];
                point.Y = (TerrainHeights[z] * HeightMultiplicator);
                borderMesh.Positions[(z * 2) + 1] = point;
            }

            for (int x = 0; x < TerrainSize; x++)
            {
                point   = borderMesh.Positions[(x * 2) + 1 + (2 * TerrainSize)];
                point.Y = (TerrainHeights[x * TerrainSize + TerrainSize - 1] * HeightMultiplicator);
                borderMesh.Positions[(x * 2) + 1 + (2 * TerrainSize)] = point;
            }

            for (int z = TerrainSize; z > 0; z--)
            {
                point   = borderMesh.Positions[(z * 2) - 1 + (4 * TerrainSize)];
                point.Y = (TerrainHeights[(TerrainSize * TerrainSize) - z] * HeightMultiplicator);
                borderMesh.Positions[(z * 2) - 1 + (4 * TerrainSize)] = point;
            }

            for (int x = TerrainSize; x > 0; x--)
            {
                point   = borderMesh.Positions[(x * 2) - 1 + (6 * TerrainSize)];
                point.Y = (TerrainHeights[(TerrainSize - x) * TerrainSize] * HeightMultiplicator);
                borderMesh.Positions[(x * 2) - 1 + (6 * TerrainSize)] = point;
            }
            TerrainMeshBorderGeometry3D = borderMesh.ToMeshGeometry3D();
        }
        void RenderLoop()
        {
            while (true)
            {
                lock (renderLock)
                {
                    var deviceContext = device.ImmediateContext;

                    // render user view
                    deviceContext.ClearDepthStencilView(userViewDepthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                    SharpDX.Vector3 headPosition =  new SharpDX.Vector3(0f, 1.1f, -1.4f); // may need to change this default

                    var userView = GraphicsTransforms.LookAt(headPosition, headPosition + SharpDX.Vector3.UnitZ, SharpDX.Vector3.UnitY);
                    userView.Transpose();

                    float aspect = (float)userViewTextureWidth / (float)userViewTextureHeight;
                    var userProjection = GraphicsTransforms.PerspectiveFov(55.0f / 180.0f * (float)Math.PI, aspect, 0.001f, 1000.0f);
                    userProjection.Transpose();

                    // smooth depth images
                    foreach (var camera in ensemble.cameras)
                    {
                        var cameraDeviceResource = cameraDeviceResources[camera];
                        if (cameraDeviceResource.depthImageChanged)
                        {
                            fromUIntPS.Render(deviceContext, cameraDeviceResource.depthImageTextureRV, cameraDeviceResource.floatDepthImageRenderTargetView);
                            bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.floatDepthImageRenderTargetView2);
                            bilateralFilter.Render(deviceContext, cameraDeviceResource.floatDepthImageRV2, cameraDeviceResource.floatDepthImageRenderTargetView);
                            cameraDeviceResource.depthImageChanged = false;
                        }
                    }

                    // projection puts x and y in [-1,1]; adjust to obtain texture coordinates [0,1]
                    // TODO: put this in SetContants?
                    userProjection[0, 0] /= 2;
                    userProjection[1, 1] /= -2; // y points down
                    userProjection[2, 0] += 0.5f;
                    userProjection[2, 1] += 0.5f;

                    // projection mapping for each projector
                    foreach (var form in projectorForms)
                    {
                        deviceContext.ClearRenderTargetView(form.renderTargetView, Color4.Black);
                        deviceContext.ClearDepthStencilView(form.depthStencilView, DepthStencilClearFlags.Depth, 1, 0);

                        foreach (var camera in ensemble.cameras)
                        {
                            var cameraDeviceResource = cameraDeviceResources[camera];

                            // Copy camera pose
                            var world = new SharpDX.Matrix();
                            for (int i = 0; i < 4; i++)
                                for (int j = 0; j < 4; j++)
                                    world[i, j] = (float)camera.pose[i, j];
                            world.Transpose();

                            var projectorWorldViewProjection = world * form.view * form.projection;
                            var userWorldViewProjection = world * userView * userProjection;

                            projectiveTexturingShader.SetConstants(deviceContext, userWorldViewProjection, projectorWorldViewProjection, clock.Elapsed);
                            projectiveTexturingShader.Render(deviceContext, cameraDeviceResource.floatDepthImageRV, cameraDeviceResource.vertexBuffer, form.renderTargetView, form.depthStencilView, form.viewport);
                        }

                        form.swapChain.Present(1, PresentFlags.None);
                    }

                    //Console.WriteLine(stopwatch.ElapsedMilliseconds);
                    stopwatch.Restart();
                }
            }
        }
Beispiel #37
0
    /// <summary>
    /// Converts screen coordinates to in-world coordinates via raycasting.
    /// </summary>
    /// <param name="screenPos">Screen coordinates.</param>
    /// <param name="worldPos">Converted coordinates.</param>
    /// <param name="rayDistance">How far to search for a collision.</param>
    /// <returns>True if successful. On false, worldPos's contents are undefined.</returns>
    public bool ScreenToWorld(Vector2 screenPos, out Vector3 worldPos, float rayDistance = 100000.0f)
    {
        // The game is only visible in the main viewport, so if the cursor is outside
        // of the game window, do not bother calculating anything
        var windowPos  = ImGuiHelpers.MainViewport.Pos;
        var windowSize = ImGuiHelpers.MainViewport.Size;

        if (screenPos.X < windowPos.X || screenPos.X > windowPos.X + windowSize.X ||
            screenPos.Y < windowPos.Y || screenPos.Y > windowPos.Y + windowSize.Y)
        {
            worldPos = default;
            return(false);
        }

        // Get base object with matrices
        var matrixSingleton = this.getMatrixSingleton();

        // Read current ViewProjectionMatrix plus game window size
        var   viewProjectionMatrix = default(SharpDX.Matrix);
        float width, height;

        unsafe
        {
            var rawMatrix = (float *)(matrixSingleton + 0x1b4).ToPointer();

            for (var i = 0; i < 16; i++, rawMatrix++)
            {
                viewProjectionMatrix[i] = *rawMatrix;
            }

            width  = *rawMatrix;
            height = *(rawMatrix + 1);
        }

        viewProjectionMatrix.Invert();

        var localScreenPos = new SharpDX.Vector2(screenPos.X - windowPos.X, screenPos.Y - windowPos.Y);
        var screenPos3D    = new SharpDX.Vector3
        {
            X = (localScreenPos.X / width * 2.0f) - 1.0f,
            Y = -((localScreenPos.Y / height * 2.0f) - 1.0f),
            Z = 0,
        };

        SharpDX.Vector3.TransformCoordinate(ref screenPos3D, ref viewProjectionMatrix, out var camPos);

        screenPos3D.Z = 1;
        SharpDX.Vector3.TransformCoordinate(ref screenPos3D, ref viewProjectionMatrix, out var camPosOne);

        var clipPos = camPosOne - camPos;

        clipPos.Normalize();

        bool isSuccess;

        unsafe
        {
            var camPosArray  = camPos.ToArray();
            var clipPosArray = clipPos.ToArray();

            // This array is larger than necessary because it contains more info than we currently use
            var worldPosArray = stackalloc float[32];

            // Theory: this is some kind of flag on what type of things the ray collides with
            var unknown = stackalloc int[3]
            {
                0x4000,
                0x4000,
                0x0,
            };

            fixed(float *pCamPos = camPosArray)
            {
                fixed(float *pClipPos = clipPosArray)
                {
                    isSuccess = this.screenToWorldNative(pCamPos, pClipPos, rayDistance, worldPosArray, unknown);
                }
            }

            worldPos = new Vector3
            {
                X = worldPosArray[0],
                Y = worldPosArray[1],
                Z = worldPosArray[2],
            };
        }

        return(isSuccess);
    }
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3 up = MathHelper.Convert(freelook.Up);
            sceneConstants.View = Matrix.LookAtLH(MathHelper.Convert(freelook.Eye), MathHelper.Convert(freelook.Target), up);
            sceneConstants.Projection = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane);
            sceneConstants.ViewInverse = Matrix.Invert(sceneConstants.View);

            Vector3 light = new Vector3(20, 30, 10);
            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Matrix lightView = Matrix.LookAtLH(light, Vector3.Zero, up);
            Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);
            sceneConstants.LightViewProjection = lightView * lightProjection;

            using (var data = sceneConstantsBuffer.Map(MapMode.WriteDiscard))
            {
                Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
                sceneConstantsBuffer.Unmap();
            }

            inverseProjectionVar.SetMatrix(Matrix.Invert(sceneConstants.Projection));
            inverseViewVar.SetMatrix(sceneConstants.ViewInverse);
            lightInverseViewProjectionVar.SetMatrix(Matrix.Invert(sceneConstants.LightViewProjection));
            lightPositionVar.Set(new Vector4(light, 1));
            eyePositionVar.Set(new Vector4(MathHelper.Convert(freelook.Eye), 1));
            eyeZAxisVar.Set(new Vector4(Vector3.Normalize(MathHelper.Convert(freelook.Target - freelook.Eye)), 1));

            float tanHalfFOVY = (float)Math.Tan(FieldOfView * 0.5f);
            tanHalfFOVXVar.Set(tanHalfFOVY * AspectRatio);
            tanHalfFOVYVar.Set(tanHalfFOVY);
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;
            projectionAVar.Set(projectionA);
            projectionBVar.Set(projectionB);

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);
            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            overlayViewProjectionVar.SetMatrix(overlayMatrix);
        }
Beispiel #39
0
        public override void Update(float elapsed)
        {
            T -= Animate ? elapsed * Speed : 0;


            Lines.Clear();



            ////see Anthony Lander's work on zeta symmetry
            //var piot = Math.PI / T; ////beware of 0 T!
            //var twopiot = piot * 2.0;
            //var tau = 0.5 * ((1.0 / (Math.Exp(piot) - 1.0)) + (1.0 / (1.0 - Math.Exp(-piot)))); ////unfortunate name
            //var kap = 0.5 * ((1.0 / Math.Sqrt(Math.Exp(twopiot) - 1.0)) + (1.0 / Math.Sqrt(1.0 - Math.Exp(-twopiot))));
            var tau = T / Math.PI;          ////seems equivalent to above? not exactly the same though - is this more accurate?
            var kap = Math.Sqrt(tau * 0.5); ////dexyguess


            var x = -Sr;
            var s = Complex.Zero;

            StartLine(Vector3.Zero, Color.White);
            for (var b = 1.0; b <= N; b++)
            {
                //// standard reimann zeta function representation
                var v = Complex.Pow(new Complex(b, 0), new Complex(x, T));
                s += v;

                //// expanded version
                //var c = Math.Pow(b, x);
                //var ylogb = y * Math.Log(b);
                //var cos = c * Math.Cos(ylogb);
                //var sin = c * Math.Sin(ylogb);
                //var v = new Complex(cos, sin);
                //s += v;

                var colour = (b < kap) ? Colour1 : (b < tau) ? Colour2 : Colour3;

                var p = new Vector3((float)s.Real, (float)s.Imaginary, 0.0f); //main step graph output
                //var p = new Vector3((float)v.Real, (float)v.Imaginary, 0.0f); //step delta output
                ContinueLine(p, colour);
            }

            //s = Complex.Zero;
            //StartLine(Vector3.Zero, Color.White);
            //for (var b = 1.0; b <= N; b++)
            //{
            //    //// standard reimann zeta function representation, negative side
            //    var v = Complex.Pow(new Complex(b, 0), new Complex(x, -T));
            //    s += v;
            //    var colour = (b < kap) ? Colour1 : (b < tau) ? Colour2 : Colour3;
            //    var p = new Vector3((float)s.Real, (float)s.Imaginary, 0.0f); //main step graph output
            //    //var p = new Vector3((float)v.Real, (float)v.Imaginary, 0.0f); //step delta output
            //    ContinueLine(p, colour);
            //}



            var subdiv   = 0.5;
            var subdivrt = Math.Sqrt(subdiv);

            s = Complex.Zero;
            StartLine(Vector3.Zero, Color.White);
            for (int i = 1; i <= N; i++)
            {
                var b = i * subdiv;

                var c     = Math.Pow(b, x);
                var logb  = Math.Log(b);
                var ylogb = T * logb;
                var cos   = c * Math.Cos(ylogb);
                var sin   = c * Math.Sin(ylogb);
                var v     = new Complex(cos, sin) * subdivrt;

                //var dcos = sin / logb;
                //var dsin = cos / logb;
                //var v = new Complex(dcos, dsin);
                s += v;

                var colour = (b < kap) ? Colour1 : (b < tau) ? Colour2 : Colour3;

                var p = new Vector3((float)s.Real, (float)s.Imaginary, 0.0f); //main graph output
                //var p = new Vector3((float)v.Real, (float)v.Imaginary, 0.0f); //smooth step delta output
                //ContinueLine(p, colour);
            }
        }
Beispiel #40
0
        /// <summary>
        /// Function to calculate tangent information for bump mapping.
        /// </summary>
        /// <param name="vertexData">Buffer holding the vertices.</param>
        /// <param name="indexData">Buffer holding the indices.</param>
        protected void CalculateTangents(GorgonNativeBuffer <Vertex3D> vertexData, GorgonNativeBuffer <int> indexData)
        {
            var biTanData   = new DX.Vector3[VertexCount];
            var tanData     = new DX.Vector3[VertexCount];
            int indexOffset = 0;

            for (int i = 0; i < TriangleCount; ++i)
            {
                int index1 = indexData[indexOffset++];

                // If we hit a strip-restart index, then skip to the next index.
                if ((PrimitiveType == PrimitiveType.TriangleStrip) &&
                    (index1 < 0))
                {
                    index1 = indexData[indexOffset++];
                }

                int index2 = indexData[indexOffset++];
                int index3 = indexData[indexOffset++];

                Vertex3D vertex1 = vertexData[index1];
                Vertex3D vertex2 = vertexData[index2];
                Vertex3D vertex3 = vertexData[index3];

                DX.Vector4.Subtract(ref vertex2.Position, ref vertex1.Position, out DX.Vector4 deltaPos1);

                DX.Vector4.Subtract(ref vertex3.Position, ref vertex1.Position, out DX.Vector4 deltaPos2);

                DX.Vector2.Subtract(ref vertex2.UV, ref vertex1.UV, out DX.Vector2 deltaUV1);
                DX.Vector2.Subtract(ref vertex3.UV, ref vertex1.UV, out DX.Vector2 deltaUV2);

                float denom = ((deltaUV1.X * deltaUV2.Y) - (deltaUV1.Y * deltaUV2.X));
                float r     = 0.0f;

                if (!denom.EqualsEpsilon(0))
                {
                    r = 1.0f / denom;
                }

                var tangent = new DX.Vector3(((deltaUV2.Y * deltaPos1.X) - (deltaUV1.Y * deltaPos2.X)) * r,
                                             ((deltaUV2.Y * deltaPos1.Y) - (deltaUV1.Y * deltaPos2.Y)) * r,
                                             ((deltaUV2.Y * deltaPos1.Z) - (deltaUV1.Y * deltaPos2.Z)) * r);

                var biTangent = new DX.Vector3(((deltaUV1.X * deltaPos2.X) - (deltaUV2.X * deltaPos1.X)) * r,
                                               ((deltaUV1.X * deltaPos2.Y) - (deltaUV2.X * deltaPos1.Y)) * r,
                                               ((deltaUV1.X * deltaPos2.Z) - (deltaUV2.X * deltaPos1.Z)) * r);

                DX.Vector3.Add(ref tanData[index1], ref tangent, out tanData[index1]);
                DX.Vector3.Add(ref tanData[index2], ref tangent, out tanData[index2]);
                DX.Vector3.Add(ref tanData[index3], ref tangent, out tanData[index3]);

                DX.Vector3.Add(ref biTanData[index1], ref biTangent, out biTanData[index1]);
                DX.Vector3.Add(ref biTanData[index2], ref biTangent, out biTanData[index2]);
                DX.Vector3.Add(ref biTanData[index3], ref biTangent, out biTanData[index3]);
            }

            for (int i = 0; i < VertexCount; ++i)
            {
                Vertex3D vertex = vertexData[i];


                DX.Vector3.Dot(ref vertex.Normal, ref tanData[i], out float dot);
                DX.Vector3.Multiply(ref vertex.Normal, dot, out DX.Vector3 tangent);
                DX.Vector3.Subtract(ref tanData[i], ref tangent, out tangent);
                DX.Vector3.Normalize(ref tangent, out tangent);

                DX.Vector3.Cross(ref vertex.Normal, ref tanData[i], out DX.Vector3 cross);
                DX.Vector3.Dot(ref cross, ref biTanData[i], out dot);

                vertexData[i] = new Vertex3D
                {
                    Position = vertex.Position,
                    Normal   = vertex.Normal,
                    UV       = vertex.UV,
                    Tangent  = new DX.Vector4(tangent, dot < 0.0f ? -1.0f : 1.0f)
                };
            }
        }
 public TimeSeriesPointVertex(Vector3 position, float size, float time, uint color)
 {
     Position = position;
     PointSize = size;
     Tu = time;
     Tv = 0;
     this.color = color;
 }
 /// <summary>
 /// Function called when the angle of rotation needs to be updated on the object.
 /// </summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="rotation">The new angle of rotation, in degrees, on the x, y and z axes.</param>
 protected override void OnRotationUpdate(GorgonSprite animObject, DX.Vector3 rotation) => animObject.Angle = rotation.Z;
Beispiel #43
0
 /// <summary>
 /// Bone's World to Screen Function
 /// </summary>
 /// <param name="viewMatrix"></param>
 /// <param name="pos"></param>
 /// <param name="screen"></param>
 /// <param name="windowWidth"></param>
 /// <param name="windowHeight"></param>
 /// <returns></returns>
 public static bool WorldToScreenBone(D3DMatrix viewMatrix, ShpVector3 pos, out ShpVector2 screen, out int distance, int windowWidth, int windowHeight)
 => WorldToScreenItem(viewMatrix, pos, out screen, out distance, windowWidth, windowHeight);
 /// <summary>
 /// Function called when a scale needs to be updated on the object.
 /// </summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="scale">The new scale.</param>
 protected override void OnScaleUpdate(GorgonSprite animObject, DX.Vector3 scale) => animObject.Scale = (DX.Vector2)scale;
        public static Matrix RotationMatrixFromRotationVector(Matrix rotationVector)
        {
            double angle = rotationVector.Norm();
            var axis = new SharpDX.Vector3((float)(rotationVector[0] / angle), (float)(rotationVector[1] / angle), (float)(rotationVector[2] / angle));

            // Why the negative sign? SharpDX returns a post-multiply matrix. Instead of transposing to get the pre-multiply matrix we just invert the input rotation.
            var sR = SharpDX.Matrix.RotationAxis(axis, -(float)angle);

            var R = new Matrix(3, 3);
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    R[i, j] = sR[i, j];
            return R;
        }
 /// <summary>
 /// Function called when a position needs to be updated on the object.
 /// </summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="position">The new position.</param>
 protected override void OnPositionUpdate(GorgonSprite animObject, DX.Vector3 position)
 {
     animObject.Position = (DX.Vector2)position;
     animObject.Depth    = position.Z;
 }
Beispiel #47
0
        public IPlace HoverCheck(Vector3 searchPoint, IPlace defaultPlace, float distance)
        {
            searchPoint = -searchPoint;
            Vector3 dist;
            if (defaultPlace != null)
            {
                var testPoint = Coordinates.RADecTo3d(defaultPlace.RA, -defaultPlace.Dec, -1.0).Vector311;
                dist = searchPoint - testPoint;
                distance = dist.Length();
            }

            var closestItem = -1;
            var index = 0;
            foreach (var point in positions)
            {
                dist = searchPoint - point;
                if (dist.Length() < distance)
                {
                    distance = dist.Length();
                    closestItem = index;
                }
                index++;
            }

            lastHoverIndex = closestItem;

            if (closestItem == -1)
            {
                return defaultPlace;
            }

            var pnt = Coordinates.CartesianToSpherical(positions[closestItem]);
            var name = names[closestItem];
            if (String.IsNullOrEmpty(name))
            {
                name = string.Format("RA={0}, Dec={1}", Coordinates.FormatHMS(pnt.RA), Coordinates.FormatDMS(pnt.Dec));
            }
            var place = new TourPlace(name, pnt.Dec, pnt.RA, Classification.Unidentified, "", ImageSetType.Sky, -1);
            return place;
        }
        public MainViewModel()
        {
            EffectsManager  = new DefaultEffectsManager();
            RenderTechnique = EffectsManager[DefaultRenderTechniqueNames.Blinn];
            // ----------------------------------------------
            // titles
            this.Title    = "Lighting Demo";
            this.SubTitle = "WPF & SharpDX";

            // ----------------------------------------------
            // camera setup
            this.Camera = new PerspectiveCamera {
                Position = new Point3D(0, 0, 0), UpDirection = new Vector3D(0, 1, 0)
            };

            camLookDir = new Vector3D(0, 0, -1);
            //Camera.ZoomExtents()
            // ----------------------------------------------
            // setup scene
            this.AmbientLightColor = Colors.DimGray;
            this.Light1Color       = Colors.LightGray;


            this.Light1Direction = new Vector3D(-100, -100, -100);
            SetupCameraBindings(Camera);

            // ----------------------------------------------
            // ----------------------------------------------
            // scene model3d
            this.HeartMaterial            = PhongMaterials.Silver;
            this.HeartMaterial.DiffuseMap = LoadFileToMemory(new System.Uri(@"Heart_CM_TEXTURE.jpg", System.UriKind.RelativeOrAbsolute).ToString());
            this.HeartMaterial.NormalMap  = LoadFileToMemory(new System.Uri(@"Heart_NM_TEXTURE.jpg", System.UriKind.RelativeOrAbsolute).ToString());

            this.HumanMaterial            = PhongMaterials.Bisque;
            this.HumanMaterial.DiffuseMap = LoadFileToMemory(new System.Uri(@"RUST_3d_Low1_Difuse.jpg", System.UriKind.RelativeOrAbsolute).ToString());
            this.HumanMaterial.NormalMap  = LoadFileToMemory(new System.Uri(@"RUST_3d_Low1_Normal.jpg", System.UriKind.RelativeOrAbsolute).ToString());


            var scale = new Vector3(1f);

            var humanitems = Load3ds("RUST_3d_Low1.obj").Select(x => x.Geometry as MeshGeometry3D).ToArray();

            foreach (var item in humanitems)
            {
                for (int i = 0; i < item.Positions.Count; ++i)
                {
                    item.Positions[i] = item.Positions[i] * scale;
                }
            }
            HumanModel = MeshGeometry3D.Merge(humanitems);


            var caritems = Load3ds("Heart.obj").Select(x => x.Geometry as MeshGeometry3D).ToArray();

            var heartScale = new Vector3(70f);

            foreach (var item in caritems)
            {
                for (int i = 0; i < item.Positions.Count; ++i)
                {
                    item.Positions[i] = item.Positions[i] * heartScale;
                }
            }
            HeartModel = MeshGeometry3D.Merge(caritems);

            HeartInstances    = new Matrix[1];
            HeartInstances[0] = Matrix.Translation(new Vector3(10, 125, 3));

            var builder = new MeshBuilder(true, false, false);

            builder.AddBox(new Vector3(), 200, 0.5, 200);
            Plane1Model = builder.ToMeshGeometry3D();

            builder = new MeshBuilder(true, false, false);
            builder.AddBox(new Vector3(), 0.1, 40, 40);
            Plane2Model = builder.ToMeshGeometry3D();

            PlaneMaterial = new PhongMaterial()
            {
                DiffuseColor = new Color4(0.1f, 0.8f, 0.1f, 0.5f)
            };

            Plane1Transform = new TranslateTransform3D(new Vector3D(0, 15, 0));
        }
Beispiel #49
0
        public SkyLabel(RenderContext11 renderContext, double ra, double dec, string text, LabelSytle style, double distance)
        {
            RA = ra;
            Dec = dec;
            Text = text;
            Style = style;

            Distance = distance;

            if (texture == null)
            {
                texture = Texture11.FromBitmap(Resources.circle, 0);
            }

            var up = new Vector3d();
            var textPos = new Vector3d();
            if (Earth3d.MainWindow.SolarSystemMode)
            {
                pos = Coordinates.RADecTo3d(ra, -dec, distance);
                up = Coordinates.RADecTo3d(ra, -dec + 90, distance);

                pos.RotateX(Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI);
                pos.Add(Planets.GetPlanet3dLocation(SolarSystemObjects.Earth));

                up.RotateX(Coordinates.MeanObliquityOfEcliptic(SpaceTimeController.JNow) / 180.0 * Math.PI);
                up.Add(Planets.GetPlanet3dLocation(SolarSystemObjects.Earth));
               }
            else
            {
                pos = Coordinates.RADecTo3d(ra+12, dec, distance);
                textPos = Coordinates.RADecTo3d(ra + 12, dec + 2, distance);
                up = Coordinates.RADecTo3d(ra+12, dec + 92, distance);

            }
            center = new Vector3(9, 9, 0);

            textBatch = new Text3dBatch(24);
            if (style == LabelSytle.Telrad)
            {
                // Telrad-style labels are always screen-aligned
                var t3 = new Text3d(new Vector3d(0, 0, 0.1), new Vector3d(0, 1, 0), text, 20, .01);
                t3.alignment = Text3d.Alignment.Left;
                textBatch.Add(t3);
            }
            else
            {
                up.Normalize();
                textPos.Normalize();
                textBatch.Add(new Text3d(textPos, up, text, 20, .0005));
            }
        }
Beispiel #50
0
 /// <summary>
 /// Calculate the screen position of a 3D point.
 /// </summary>
 /// <param name="p">
 /// The 3D point.
 /// </param>
 /// <returns>
 /// The 2D point.
 /// </returns>
 protected Point Project(Point3D p)
 {
     return(this.Controller.Viewport.Project(p).ToPoint());
 }
Beispiel #51
0
        public void Draw(RenderContext11 renderContext, bool space3d)
        {
            var cam = Vector3d.TransformCoordinate(Earth3d.MainWindow.RenderContext11.CameraPosition, Matrix3d.Invert(Earth3d.WorldMatrix));

            if (!space3d)
            {
                if (Vector3d.Dot(cam, pos) < 0)
                {
                    return;
                }
            }
            var temp = pos;

            if (Earth3d.MainWindow.SolarSystemMode)
            {
                temp.Add( Earth3d.MainWindow.viewCamera.ViewTarget);
            }

            var wvp = renderContext.World * renderContext.View * renderContext.Projection;

            var screenPos = Vector3.Project(temp.Vector311, renderContext.ViewPort.TopLeftX, renderContext.ViewPort.TopLeftY,renderContext.ViewPort.Width,renderContext.ViewPort.Height, 0, 1, wvp.Matrix11);

            // Get the w component of the transformed object position; if it's negative the
            // object is behind the viewer.
            var w = wvp.M14 * temp.X + wvp.M24 * temp.Y + wvp.M34 * temp.Z + wvp.M44;
            if (w < 0.0 && Earth3d.MainWindow.SolarSystemMode)
            {
                // Don't show labels that are behind the viewer
                return;
            }

            screenPos = new Vector3((int)screenPos.X, (int)screenPos.Y, 1);

            Sprite2d.Draw2D(renderContext, texture, new SizeF(20, 20), new PointF(0, 0), 0, new PointF(screenPos.X, screenPos.Y), Color.White);

            if (Earth3d.MainWindow.SolarSystemMode || Style == LabelSytle.Telrad)
            {
                var worldMatrix = renderContext.World;
                var viewMatrix = renderContext.View;
                var projectionMatrix = renderContext.Projection;

                var labelScale = Earth3d.MainWindow.SolarSystemMode ? 8.0 : 30.0;
                renderContext.World =
                    Matrix3d.Scaling(labelScale, labelScale, 1.0) *
                    Matrix3d.Translation(screenPos.X + 10.0, -screenPos.Y, 0.0) *
                    Matrix3d.Translation(-renderContext.ViewPort.Width / 2, renderContext.ViewPort.Height / 2, 0);
                renderContext.View = Matrix3d.Identity;
                renderContext.Projection = Matrix3d.OrthoLH(renderContext.ViewPort.Width, renderContext.ViewPort.Height, 1, -1);

                renderContext.BlendMode = BlendMode.PremultipliedAlpha;
                textBatch.Draw(renderContext, 1, Color.White);

                renderContext.World = worldMatrix;
                renderContext.View = viewMatrix;
                renderContext.Projection = projectionMatrix;
            }
            else
            {
                renderContext.BlendMode = BlendMode.PremultipliedAlpha;
                textBatch.Draw(renderContext, 1, Color.White);
            }

            //todo11 Implement this
            //sprite.Begin(SpriteFlags.AlphaBlend | SpriteFlags.SortTexture);

            //sprite.Draw(texture, rect, center, screenPos, Color.White);
            //Rectangle recttext = new Rectangle((int)(screenPos.X + 15), (int)(screenPos.Y - 8), 0, 0);
            //Earth3d.MainWindow.labelFont.DrawText(sprite, Text, recttext,
            //DrawTextFormat.NoClip, System.Drawing.Color.White);

            //sprite.End();
        }
Beispiel #52
0
 public static bool UnderTower(SharpDX.Vector3 pos)
 {
     return
         (ObjectManager.Get <AITurretClient>()
          .Any(i => i.IsEnemy && !i.IsDead && (i.Distance(pos) < 850 + ObjectManager.Player.BoundingRadius)) || GameObjects.EnemySpawnPoints.Any(i => i.Position.Distance(pos) < 850 + ObjectManager.Player.BoundingRadius));
 }
Beispiel #53
0
 /// <summary>
 /// Calculate the screen position of a 3D point.
 /// </summary>
 /// <param name="p">
 /// The 3D point.
 /// </param>
 /// <returns>
 /// The 2D point.
 /// </returns>
 protected Point Project(Point3D p)
 {
     return(this.CameraController.Viewport.Project(p));
 }
 /// <summary>
 /// Stops the panning.
 /// </summary>
 public void StopPanning()
 {
     this.panSpeed = Vector3.Zero;
 }
Beispiel #55
0
        private static void Wallhopper_OnGameUpdate(EventArgs args)
        {
            if (!busy && Config.Item("WallJump").GetValue<KeyBind>().Active && Buffmanager.qStacks == 2)
            {
                var closest = minRange + 1f;
                foreach (WallHopPosition pos in jumpPositions)
                {
                    if (ObjectManager.Player.Distance(pos.pA) < closest || ObjectManager.Player.Distance(pos.pB) < closest)
                    {
                        busy = true;
                        if (ObjectManager.Player.Distance(pos.pA) < ObjectManager.Player.Distance(pos.pB))
                        {
                            closest = ObjectManager.Player.Distance(pos.pA);
                            startPoint = pos.pA;
                            endPoint = pos.pB;
                        }
                        else
                        {
                            closest = ObjectManager.Player.Distance(pos.pB);
                            startPoint = pos.pB;
                            endPoint = pos.pA;
                        }
                    }

                }
                if (busy)
                {
                    directionVector.X = startPoint.X - endPoint.X;
                    directionVector.Y = startPoint.Y - endPoint.Y;
                    ObjectManager.Player.IssueOrder(GameObjectOrder.HoldPosition, ObjectManager.Player.ServerPosition);
                    Packet.C2S.Move.Encoded(new Packet.C2S.Move.Struct(startPoint.X, startPoint.Y)).Send();
                    Utility.DelayAction.Add(180, delegate { changeDirection1(); });
                }
            }
        }
        /// <summary>
        /// The on time step.
        /// </summary>
        /// <param name="ticks">
        /// The time.
        /// </param>
        public void OnTimeStep(long ticks)
        {
            if (lastTick == 0)
            {
                lastTick = ticks;
            }
            var time = (float)(ticks - this.lastTick) / Stopwatch.Frequency;
            time = time == 0 ? 0.016f : time;
            // should be independent of time
            var factor = Viewport.IsInertiaEnabled ? (float)Clamp(Math.Pow(Viewport.CameraInertiaFactor, time / 0.02f), 0.1f, 1) : 0;
            bool needUpdate = false;

            if (this.rotationSpeed.LengthSquared() > 0.1)
            {
                this.rotateHandler.Rotate(
                    this.rotationPosition.ToVector2(), rotationPosition.ToVector2() + (rotationSpeed * time), this.rotationPoint3D, false);
                this.rotationSpeed *= factor;
                needUpdate = true;
                this.spinningSpeed = VectorZero;
            }
            else
            {
                this.rotationSpeed = VectorZero;
                if (this.isSpinning && this.spinningSpeed.LengthSquared() > 0.1)
                {
                    this.rotateHandler.Rotate(
                        this.spinningPosition.ToVector2(), spinningPosition.ToVector2() + (spinningSpeed * time), this.spinningPoint3D, false);
                    if (!Viewport.InfiniteSpin)
                    {
                        this.spinningSpeed *= factor;
                    }
                    needUpdate = true;
                }
                else
                {
                    this.spinningSpeed = VectorZero;
                }
            }

            if (this.panSpeed.LengthSquared() > 0.0001)
            {
                this.panHandler.Pan(this.panSpeed * time, false);
                this.panSpeed *= factor;
                needUpdate = true;
            }
            else
            {
                this.panSpeed = Vector3DZero;
            }

            if (this.moveSpeed.LengthSquared() > 0.0001)
            {
                this.zoomHandler.MoveCameraPosition(this.moveSpeed * time, false);
                this.moveSpeed *= factor;
                needUpdate = true;
            }
            else
            {
                this.moveSpeed = Vector3DZero;
            }

            if (Math.Abs(this.zoomSpeed) > 0.001)
            {
                this.zoomHandler.Zoom(this.zoomSpeed * time, this.zoomPoint3D, false, false);
                this.zoomSpeed *= factor;
                needUpdate = true;
            }
            else
            {
                zoomSpeed = 0;
            }

            if (ActualCamera != null && ActualCamera.OnTimeStep())
            {
                needUpdate = true;
            }
            if (needUpdate)
            {
                lastTick = ticks;
                Viewport.InvalidateRender();
            }
            else
            {
                lastTick = 0;
            }
        }
 /// <summary>Function called when the size needs to be updated on the object.</summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="size">The new size.</param>
 protected override void OnSizeUpdate(GorgonSprite animObject, DX.Vector3 size) => animObject.Size = new DX.Size2F(size.X, size.Y);
Beispiel #58
0
        private bool isTouchingBox(Skeleton skeleton, float boxScale, Vector3 boxTranslation)
        {
            var hand1 = convert(skeleton.Joints[JointType.HandRight].Position);
            var hand2 = convert(skeleton.Joints[JointType.HandLeft].Position);

            if ((hand1.X < (boxTranslation.X + boxScale)) && (hand1.X > (boxTranslation.X - boxScale)) &&
                (hand1.Y < (boxTranslation.Y + boxScale)) && (hand1.Y > (boxTranslation.Y - boxScale)) &&
                (-1 * hand1.Z < (boxTranslation.Z + boxScale)) && (-1 * hand1.Z > (boxTranslation.Z - boxScale))) return true;
            if ((hand2.X < (boxTranslation.X + boxScale)) && (hand2.X > (boxTranslation.X - boxScale)) &&
                (hand2.Y < (boxTranslation.Y + boxScale)) && (hand2.Y > (boxTranslation.Y - boxScale)) &&
                (-1 * hand2.Z < (boxTranslation.Z + boxScale)) && (-1 * hand2.Z > (boxTranslation.Z - boxScale))) return true;

            return false;
        }
Beispiel #59
0
 /// <summary>
 /// Un-projects a point from the screen (2D) to a point on plane (3D)
 /// </summary>
 /// <param name="p">
 /// The 2D point.
 /// </param>
 /// <param name="position">
 /// plane position
 /// </param>
 /// <param name="normal">
 /// plane normal
 /// </param>
 /// <returns>
 /// A 3D point.
 /// </returns>
 public Point3D?UnProject(Point p, Point3D position, Vector3D normal)
 {
     return(UnProject(p.ToVector2(), position, normal));
 }
Beispiel #60
0
 /// <summary>Function called when the size needs to be updated on the object.</summary>
 /// <param name="animObject">The object being animated.</param>
 /// <param name="size">The new size.</param>
 protected override void OnSizeUpdate(GorgonTextSprite animObject, DX.Vector3 size)
 {
     // NOT USED.
 }