Example #1
0
        //============================================================
        public void Update()
        {
            Vector3 position = new Vector3(_position.X, _position.Y, _position.Z);
            Vector3 target   = new Vector3(_target.X, _target.Y, _target.Z);

            _matrix.AssignNative(DxMatrix.LookAtLH(position, target, Vector3.UnitY));
        }
Example #2
0
        public override void DrawModel(DirectXModel model)
        {
            if (model.Mesh == null)
            {
                return;
            }
            Matrix oldWorldTransform = WorldTransform;

            ExtendedMaterial[] materials = model.Mesh.GetMaterials();
            MultiplyWorldTransform(model.ModifierMatrix);
            for (int i = 0; i < materials.Length; i++)
            {
                Material    material   = materials[i].MaterialD3D;
                BaseTexture oldTexture = null;
                Texture     texture;
                if (model.Textures.TryGetValue(i, out texture) && texture != null)
                {
                    oldTexture = _device.GetTexture(0);
                    _device.SetTexture(0, texture);
                }
                _device.Material = material;
                model.Mesh.DrawSubset(i);
                if (texture != null)
                {
                    _device.SetTexture(0, oldTexture);
                }
            }
            WorldTransform = oldWorldTransform;
        }
Example #3
0
        public void RenderNode(ModelNode node, SlimDX.Matrix transform, VisibilityNode visibilityNode, bool isTransparent)
        {
            if (visibilityNode != null && !visibilityNode.Visible)
            {
                return;
            }

            SlimDX.Matrix localTransform = transform * node.Transform;

            foreach (int subMeshIndex in node.SubMeshIndices)
            {
                SubMesh  subMesh  = SubMeshes[subMeshIndex];
                Mesh     mesh     = Meshes[subMesh.MeshIndex];
                Material material = Materials[subMesh.MaterialIndex];
                //if (material.Visible)
                //{
                if ((material.BlendMode == 0 && !isTransparent) || (material.BlendMode != 0 && isTransparent))
                {
                    mesh.ApplyMaterial(material);
                    mesh.ApplyTransform(localTransform);
                    mesh.ApplyBuffers();
                    mesh.Render(subMesh.indexCount, subMesh.startIndexLocation, subMesh.baseVertexLocation);
                }
                //}
            }

            int n = 0;

            foreach (ModelNode child in node.Nodes)
            {
                RenderNode(child, localTransform, visibilityNode?.Nodes[n], isTransparent);
                n++;
            }
        }
        private void updateFrame()
        {
            if (_device == null)
            {
                return;
            }


            d3dimage.Lock();
            _device.Clear(ClearFlags.Target, _backgroundColor, 0.0f, 0);

            //if (_tileCount > 0)
            //{
            //    //reset pre-alignment in case of plotting displacements
            //    //_device.SetTransform(TransformState.World, SlimDX.Matrix.Identity);
            //}


            if (_device.BeginScene().IsSuccess)
            {
                Result res;
                //Draw particles
                _device.SetTexture(0, _texture);
                res = _device.SetStreamSource(0, _vertexBufferTexture, 0, Marshal.SizeOf(typeof(vertex)));
                _device.VertexFormat = VertexFormat.Position | VertexFormat.Texture1;
                res = _device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);

                SlimDX.Matrix transSave = _device.GetTransform(TransformState.World);

                if (_tileCount > 0)
                {
                    _device.SetTexture(0, null);
                    //draw grid on reference image without shifts
                    _device.SetTransform(TransformState.World, SlimDX.Matrix.Identity);

                    _device.SetStreamSource(0, _vertexBufferTileGrid, 0, 16);
                    _device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;
                    _device.DrawPrimitives(PrimitiveType.LineList, 0, _tileCount + 2);
                    _device.SetTransform(TransformState.World, transSave);
                }

                if (_tileCount > 0 && _vertexBufferFlow != null)
                {
                    _device.SetTexture(0, null);
                    //draw grid on reference image without shifts
                    _device.SetTransform(TransformState.World, SlimDX.Matrix.Identity);

                    _device.SetStreamSource(0, _vertexBufferFlow, 0, 16);
                    _device.VertexFormat = VertexFormat.Position | VertexFormat.Diffuse;
                    _device.DrawPrimitives(PrimitiveType.LineList, 0, _tileCount);
                    _device.SetTransform(TransformState.World, transSave);
                }

                _device.EndScene();
            }
            //display
            _swapChain.Present(Present.None);
            d3dimage.AddDirtyRect(new Int32Rect(0, 0, d3dimage.PixelWidth, d3dimage.PixelHeight));
            d3dimage.Unlock();
        }
Example #5
0
        public void RenderNode(Node node, SlimDX.Matrix transform)
        {
            //node.Visible = false;
            if (node.Visible == false)
            {
                return;
            }

            SlimDX.Matrix localTransform = transform * node.Transform;

            foreach (int subMeshIndex in node.SubMeshIndices)
            {
                SubMesh  subMesh  = SubMeshes[subMeshIndex];
                Mesh     mesh     = Meshes[subMesh.MeshIndex];
                Material material = Materials[subMesh.MaterialIndex];
                mesh.ApplyMaterial(material);
                mesh.ApplyTransform(localTransform);
                mesh.ApplyBuffers();
                mesh.Render(subMesh.indexCount, subMesh.startIndexLocation, subMesh.baseVertexLocation);
            }

            foreach (Node child in node.Nodes)
            {
                RenderNode(child, localTransform);
            }
        }
        void view1_OnRender(object sender, EventArgs e)
        {
            if (!MainPlayer.Controller.LockCameraView)
            {
                Point windowPnt     = new Point(this.Left, this.Top);
                Point relativePoint = view1.TransformToAncestor(this).Transform(new Point(0, 0));
                Point p             = new Point(windowPnt.X + relativePoint.X + view1.ActualWidth / 2, windowPnt.Y + relativePoint.Y + view1.ActualHeight / 2);
                WeatherGame.RenderLoop.NativeMethods.SetCursorPos((int)p.X, (int)p.Y);
                Mouse.SetCursor(Cursors.None);

                MainPlayer.Update();
            }

            if (Global.GlobalSettings.RenderGrid)
            {
                SlimDX.Matrix mGridWorld = WorldSpace.GetRealWorldMatrixGrid(Rendering.Grid.Position, GlobalSettings.CurrentCell);
                Rendering.Grid.Draw(mGridWorld);

                SlimDX.Matrix mWorld = WorldSpace.GetRealWorldMatrix(Vector3.Zero, GlobalSettings.CurrentCell);
                Gizmo.DrawOrigin(mWorld);
            }

            if (GlobalSettings.RenderLights && GlobalSettings.RenderVolumes && GlobalSettings.CurrentObjRef != null && GlobalSettings.CurrentObjRef.BaseGameObject is Light)
            {
                Light l = GlobalSettings.CurrentObjRef.BaseGameObject as Light;
                l.RenderDebugLightVolume(GlobalSettings.CurrentObjRef, GlobalSettings.CurrentObjRef.CellContainer, Global.GlobalSettings.GridColor);
            }


            App.Tick();
        }
        void RenderModel(Graphics.Content.Model10 model, SlimDX.Matrix entityWorld, Effect effect)
        {
            throw new NotImplementedException();
            //if (model == null || !model.Visible || model.Mesh == null) return;

            Matrix world = model.World * entityWorld;

            world.M41 = (float)((int)world.M41);
            world.M42 = (float)((int)world.M42);
            world    *= Matrix.Scaling(2f / (float)view.Viewport.Width, 2f / (float)view.Viewport.Height, 1) * Matrix.Translation(-1, -1, 0) * Matrix.Scaling(1, -1, 1);
            world.M43 = 0.5f;

            effect.GetVariableByName("World").AsMatrix().SetMatrix(world);
            effect.GetVariableByName("Texture").AsResource().SetResource(model.TextureShaderView);

            effect.GetTechniqueByName("Render").GetPassByIndex(0).Apply();
            if (model.Mesh != null)
            {
                model.Mesh.Setup(view.Device10, view.Content.Acquire <InputLayout>(
                                     new Content.VertexStreamLayoutFromEffect
                {
                    Signature10 = effect.GetTechniqueByIndex(0).GetPassByIndex(0).Description.Signature,
                    Layout      = model.Mesh.VertexStreamLayout
                }));

                model.Mesh.Draw(device);
            }
        }
Example #8
0
        public TopViewCamera(Frame3D loc, double aspectRatio) : base(aspectRatio)
        {
            Vector3 vec = loc.ToDirectXVector();

            _topViewTransform = Matrix.LookAtLH(new Vector3(0, 0, vec.Z),
                                                new Vector3(), Vector3.UnitY);
        }
        void RenderModelWithEffect(Graphics.Content.Model9 model, SlimDX.Matrix world, Matrix viewProjection, Matrix halfPixelOffset,
                                   Graphics.Content.MetaResource <Graphics.Content.Model9, Graphics.Content.Model10> metaResource)
        {
            if (model == null)
            {
                return;
            }

            interfaceRenderer9Effect.SetTexture(EHTexture, model.Texture);
            //StateManager.SetTexture(0, model.Texture);

            //Device.SetSamplerState(4, SamplerState.MagFilter, TextureFilter.Anisotropic);
            //e.Scale = new Vector3((int)e.Scale.X, (int)e.Scale.Y, (int)e.Scale.Z);

            var g = metaResource as Graphics.Content.Graphic;

            if (g != null)
            {
                world = Matrix.Translation(g.Position) * world;
                //world = world * halfPixelOffset;
                world.M41 = (float)((int)world.M41) - 0.5f;
                world.M42 = (float)((int)world.M42) - 0.5f;
                StateManager.SetSamplerState(0, SamplerState.AddressU, g.TextureAdressMode);
                StateManager.SetSamplerState(0, SamplerState.AddressV, g.TextureAdressMode);
                interfaceRenderer9Effect.SetValue(EHOpacity, g.Alpha);
            }
            else
            {
                world = ((Graphics.Content.MetaModel)metaResource).World * world;

                StateManager.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Clamp);
                StateManager.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Clamp);

                interfaceRenderer9Effect.SetValue(EHOpacity, 1);
            }
            //Forces

            if (model.XMesh != null)
            {
                interfaceRenderer9Effect.SetValue(EHWorldViewProjection,
                                                  world * Scene.Camera.View * Matrix.PerspectiveFovLH(((LookatCamera)Scene.Camera).FOV, ((LookatCamera)Scene.Camera).AspectRatio, 1, 50));
            }
            else
            {
                interfaceRenderer9Effect.SetValue(EHWorldViewProjection, world * viewProjection);
            }
            interfaceRenderer9Effect.CommitChanges();
            //device.SetTransform(TransformState.World, world);
            if (model.Mesh != null)
            {
                model.Mesh.Draw(device);
                intermediateTrianglesPerFrame += model.Mesh.NFaces;
            }
            else if (model.XMesh != null)
            {
                model.XMesh.DrawSubset(0);
                intermediateTrianglesPerFrame += model.XMesh.FaceCount;
            }
        }
        public static void TransformXY(ref Vector2 vector, Matrix m)
        {
            float w1 = vector.X * m.M11 + vector.Y * m.M21;
            float h1 = vector.X * m.M12 + vector.Y * m.M22;

            vector.X = w1;
            vector.Y = h1;
        }
Example #11
0
 /// <summary>
 /// Создает камеру с видом от первого лица
 /// </summary>
 /// <param name="source">Тело, к которому привязана камера</param>
 /// <param name="offset">Смещение камеры относительно Location тела</param>
 /// <param name="viewAngle"> </param>
 /// <param name="aspectRatio"> </param>
 public FirstPersonCamera(Body source, Frame3D offset,
                          Angle viewAngle, double aspectRatio) : base(aspectRatio)
 {
     _source             = source;
     _offset             = offset;
     ViewAngle           = viewAngle;
     _defaultWorldMatrix = Matrix.LookAtLH(Vector3.Zero, new Vector3(-1, 0, 0), UpVector);
 }
Example #12
0
        public void Render(float pos_x, float pos_y, float scale_x, float scale_y)
        {
            // Modelview matrix corrects D3D half-texel offset (*2 here, as NDC space is from -1 to +1)
            SlimDX.Matrix mat = SlimDX.Matrix.Identity;
            mat.M41 = pos_x - texelSize;
            mat.M42 = pos_y + texelSize;
            mat.M11 = scale_x;
            mat.M22 = scale_y;

            effect.SetValue(m1h, mat);

            foreach (TextureBank bank in texBanks)
            {
                effect.SetTexture(t1h, bank.t1.tex);
                if (bank.t2 != null)
                {
                    effect.SetTexture(t2h, bank.t2.tex);
                }
                else
                {
                    effect.SetTexture(t2h, bank.t1.tex);
                }
                if (bank.t3 != null)
                {
                    effect.SetTexture(t3h, bank.t3.tex);
                }
                else
                {
                    effect.SetTexture(t3h, bank.t1.tex);
                }
                if (bank.t4 != null)
                {
                    effect.SetTexture(t4h, bank.t4.tex);
                }
                else
                {
                    effect.SetTexture(t4h, bank.t1.tex);
                }

                effect.CommitChanges();
                DXMain.device.SetStreamSource(2, bank.wBuffer, 0, TextureBank.WeightVertex.Stride);
                DXMain.device.BeginScene();
                effect.Begin(FX.None);
                effect.BeginPass(0);
                DXMain.device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 4225, 0, 8444);
                effect.EndPass();
                effect.End();
                DXMain.device.EndScene();
            }

            DXMain.device.BeginScene();
            effect.Begin(FX.None);
            effect.BeginPass(2);
            DXMain.device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 4225, 0, 8444);
            effect.EndPass();
            effect.End();
            DXMain.device.EndScene();
        }
Example #13
0
        private void SetupMatrices(int width, int height)
        {
            SlimDX.Matrix matOrtho    = SlimDX.Matrix.OrthoOffCenterLH(0, width, height, 0, 0.0f, 1.0f);
            SlimDX.Matrix matIdentity = SlimDX.Matrix.Identity;

            this.device.SetTransform(TransformState.Projection, matOrtho);
            this.device.SetTransform(TransformState.World, matIdentity);
            this.device.SetTransform(TransformState.View, matIdentity);
        }
        public void SetPreAlignment(float preShiftX, float preShiftY, float preRotationRad)
        {
            float maxDim = Math.Max(_realImageWidth, _realImageHeight);

            SlimDX.Matrix shift    = SlimDX.Matrix.Translation(preShiftX / maxDim, preShiftY / maxDim, 0);
            SlimDX.Matrix rotation = SlimDX.Matrix.RotationZ(-preRotationRad);

            SlimDX.Matrix world = rotation * shift;

            _device.SetTransform(TransformState.World, world);
        }
Example #15
0
        private IEnumerable <TrackComplexModelEntry> LoadModels()
        {
            var directory = Path.GetDirectoryName(_modelsIniFilename) ?? "";

            return(from section in new IniFile(_modelsIniFilename).GetSections("MODEL")
                   let rot = section.GetSlimVector3("ROTATION")
                             select new TrackComplexModelEntry {
                Kn5 = Kn5.FromFile(Path.Combine(directory, section.GetNonEmpty("FILE") ?? "")),
                Matrix = Matrix.Translation(section.GetSlimVector3("POSITION")) * Matrix.RotationYawPitchRoll(rot.X, rot.Y, rot.Z),
            });
        }
Example #16
0
 public Camera()
 {
     theta=	MathExt.toRadians(270f);
     phi=	MathExt.toRadians(45f);
     radius=	5f;
     nearView=	1f;
     farView=	48000f;
     fov=	MathExt.toRadians(90f);
     world=	DX.Matrix.Identity;
     view=	DX.Matrix.Identity;
     proj=	DX.Matrix.Identity;
 }
Example #17
0
        /// <summary> Draw outlined box.</summary>
        /// <remarks> Nesox, 2013-12-28.</remarks>
        /// <param name="center"> The min. </param>
        /// <param name="length"> The length. </param>
        /// <param name="width">  The width. </param>
        /// <param name="height"> The height. </param>
        /// <param name="color">  The color. </param>
        public static void DrawOutlinedBox(Vector3 center, float length, float width, float height, Color color)
        {
            float w = width / 2;
            float h = height / 2;
            float d = length / 2;

            Matrix mat = Matrix.Identity * Matrix.Scaling(w, d, h) * Matrix.Translation(center);

            Device.SetTransform(TransformState.World, mat);

            var min = new Vector3(-1, -1, 0);
            var max = new Vector3(1, 1, 1);

            var vtx = new[]
            {
                new ColoredVertex(new Vector3(min.X, max.Y, max.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(max.X, max.Y, max.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(min.X, min.Y, max.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(max.X, min.Y, max.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(min.X, min.Y, min.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(max.X, min.Y, min.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(min.X, max.Y, min.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(max.X, max.Y, min.Z), color.ToArgb())
            };

            var ind = new short[]
            {
                //Top           [_]
                0, 1, 1, 3,
                3, 2, 2, 0,
                //Bottom        [_]
                6, 7, 7, 5,
                5, 4, 4, 6,
                // Back         | |
                0, 6, 1, 7,
                // Front        | |
                2, 4, 3, 5,
                // Left         | |
                0, 6, 2, 4,
                // Right        | |
                1, 7, 3, 5
            };

            var oldDecl = Device.VertexDeclaration;

            using (var newDecl = ColoredVertex.GetDecl(Device))
            {
                Device.VertexDeclaration = newDecl;
                Device.DrawIndexedUserPrimitives(PrimitiveType.LineList, 0, 8, 12, ind, Format.Index16, vtx, 16);
                Device.VertexDeclaration = oldDecl;
            }
        }
Example #18
0
        /// <summary>
        /// Создает камеру, которую можно крутить движением мышки
        /// </summary>
        /// <param name="eventSource">Control,с которого обрабатываются события </param>
        /// <param name="cameraLocation">Исходное положение камеры</param>
        public TrackballCamera(Control eventSource, Frame3D cameraLocation)
            : base(eventSource.ClientSize.Width / (double)eventSource.ClientSize.Height)
        {
            EventSource = eventSource;
            Vector3 tempLoc = cameraLocation.ToDirectXVector();

            _cameraLocation = new Vector3(Math.Abs(tempLoc.X), 0, tempLoc.Z);
            Angle ang = Geometry.Atan2(tempLoc.Y, tempLoc.X);

            _rotationMatrix = Matrix.RotationZ(-(float)ang.Radian);
            _radius         = _cameraLocation.Length();
            Scale           = 1;
        }
Example #19
0
        // Updates the camera
        public void update()
        {
            // Variables
            float	x=	radius*(float)(Math.Sin(phi))*(float)(Math.Cos(theta));
            float	y=	radius*(float)(Math.Sin(phi))*(float)(Math.Sin(theta));
            float	z=	radius*(float)(Math.Cos(phi));

            view=	DX.Matrix.LookAtLH(
                new DX.Vector3(x, y, z),
                new DX.Vector3(0f),
                new DX.Vector3(0f, 1f, 0f)
            );
        }
Example #20
0
        public System.Windows.Point CanvasPointFrom3DPoint(Point3D modelPoint3D)
        {
            Point3D worldPoint = ViewportImage.ModelToWorld.Transform(modelPoint3D);

            SlimDX.Vector3 worldPointSlimDX = new SlimDX.Vector3((float)worldPoint.X, (float)worldPoint.Y, (float)worldPoint.Z);
            float          width            = (float)ViewportImage.imageWidth;
            float          height           = (float)ViewportImage.imageHeight;

            SlimDX.Matrix trans = SlimDX.Matrix.Multiply(ViewportImage.View, ViewportImage.Projection);
            //Vector3 point2DSlimDX = Vector3.Project(worldPointSlimDX, 0, 0, ViewportImage.Width, ViewportImage.Height, 0.0f, 1.0f, trans);
            Vector3 point2DSlimDX = Vector3.Project(worldPointSlimDX, 0, 0, width, height, 0.0f, 1.0f, trans);

            return(new System.Windows.Point((double)(point2DSlimDX.X), (double)(point2DSlimDX.Y)));
        }
Example #21
0
        /// <summary>
        /// Возвращает матрицу в системе координат DirectX
        /// </summary>
        /// <param name="frame">Фрейм</param>
        /// <returns></returns>
        public static Matrix ToDirectXMatrix(this Frame3D frame)
        {
            //Если нет кватерниона - поворачиваем исходя из Pitch, yaw, roll - иначе через кватернион.
            if (!frame.Orientation.HasValue)
            {
                return(Matrix.RotationYawPitchRoll((float)frame.Pitch.Radian,
                                                   (float)frame.Roll.Radian, -(float)frame.Yaw.Radian) *
                       Matrix.Translation(-(float)frame.X, (float)frame.Y, (float)frame.Z));
            }
            Quat quat = frame.Orientation.Value;
            var  q    = new Quaternion((float)quat.X, (float)quat.Y, (float)quat.Z, (float)quat.W);

            return(Matrix.RotationQuaternion(q) *
                   Matrix.Translation(-(float)frame.X, (float)frame.Y, (float)frame.Z));
        }
Example #22
0
 public override sealed void Initialize()
 {
     for (int i = 0; i < _lights.Count; i++)
     {
         _device.SetLight(i, _lights[i]);
         _device.EnableLight(i, true);
     }
     SetCommonRenderStates();
     foreach (Light light in _lights)
     {
         ShadowMatrices[light] = Matrix.Shadow(new Vector4(light.Direction, 1),
                                               new Plane(new Frame3D(0, 0, -1).ToDirectXVector(), 0.05f));
     }
     NormalMode();
 }
Example #23
0
        protected virtual void OnResetDevice()
        {
            Info.OnResetDevice();

            Matrix projection = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, NearPlane, FarPlane);

            Device.SetTransform(TransformState.Projection, projection);
            UpdateView();

            Device.SetRenderState(RenderState.Ambient, Ambient);

            Device.SetLight(0, light);
            Device.EnableLight(0, true);

            _meshFactory.OnResetDevice();
        }
        /// <summary>
        /// Create our BasicEffect
        /// </summary>
        /// <param name="Device">The device which will be used to perform all the rendering</param>
        public BasicEffect(Device Device)
        {
            this.Device      = Device;
            ImmediateContext = Device.ImmediateContext;

            //
            // Compile shader
            //
            string compileErrors;
            var    compiledShader = SlimDX.D3DCompiler.ShaderBytecode.CompileFromFile
                                    (
                "../../Effects/BasicEffect/BasicEffect.fx",
                null,
                "fx_5_0",
                SlimDX.D3DCompiler.ShaderFlags.Debug | SlimDX.D3DCompiler.ShaderFlags.SkipOptimization,
                SlimDX.D3DCompiler.EffectFlags.None,
                null,
                null,
                out compileErrors
                                    );

            if (compileErrors != null && compileErrors != "")
            {
                throw new EffectBuildException(compileErrors);
            }

            Effect          = new Effect(Device, compiledShader);
            EffectTechnique = Effect.GetTechniqueByName("BasicTechnique");

            //
            // Setup input description
            //
            var vertexDesc = new[]
            {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0)
            };

            WorldViewProj      = SlimDX.Matrix.Identity;
            CPO_WorldViewProj  = Effect.GetVariableByName("gWorldViewProj").AsMatrix();
            CPO_SelectionColor = Effect.GetVariableByName("gSelectionColor").AsVector();
            SRV_BasicTexture   = Effect.GetVariableByName("gBasicTexture").AsResource();

            InputLayout = new InputLayout(Device, EffectTechnique.GetPassByIndex(0).Description.Signature, vertexDesc);

            Util.ReleaseCom(ref compiledShader);
        }
Example #25
0
        /// <summary> Draw box. </summary>
        /// <remarks> Nesox, 2013-06-14. </remarks>
        /// <param name="center"> The min. </param>
        /// <param name="length"> The length. </param>
        /// <param name="width">  The width. </param>
        /// <param name="height"> The height. </param>
        /// <param name="color">  The color. </param>
        public static void DrawBox(Vector3 center, float length, float width, float height, Color color)
        {
            length /= 2f;
            width  /= 2f;
            height /= 2f;
            var extents = new Vector3(width, length, height);

            Device.SetTransform(TransformState.World, Matrix.Translation(center.X, center.Y, center.Z));

            var vtx = new[]
            {
                new ColoredVertex(new Vector3(-extents.X, extents.Y, extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(extents.X, extents.Y, extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(extents.X, -extents.Y, extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(-extents.X, -extents.Y, extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(-extents.X, extents.Y, -extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(extents.X, extents.Y, -extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(extents.X, -extents.Y, -extents.Z), color.ToArgb()),
                new ColoredVertex(new Vector3(-extents.X, -extents.Y, -extents.Z), color.ToArgb())
            };

            var ind = new short[]
            {
                // front
                0, 1, 2, 2, 3, 0,
                // right
                1, 5, 6, 6, 2, 1,
                // back
                5, 4, 7, 7, 6, 5,
                // left
                4, 0, 3, 3, 7, 4,
                // top
                4, 5, 1, 1, 0, 4,
                // bottom
                3, 2, 6, 6, 7, 3
            };

            var oldDecl = Device.VertexDeclaration;

            using (var newDecl = ColoredVertex.GetDecl(Device))
            {
                Device.VertexDeclaration = newDecl;
                Device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, 8, 12, ind, Format.Index16, vtx, 16);
                Device.VertexDeclaration = oldDecl;
            }
        }
        void RenderModel(Graphics.Content.Model9 model, SlimDX.Matrix world, Matrix halfPixelOffset,
                         Graphics.Content.MetaResource <Graphics.Content.Model9, Graphics.Content.Model10> metaResource)
        {
            if (model == null)
            {
                return;
            }

            var device = Scene.View.Device9;

            StateManager.SetTexture(0, model.Texture);

            //Device.SetSamplerState(4, SamplerState.MagFilter, TextureFilter.Anisotropic);
            //e.Scale = new Vector3((int)e.Scale.X, (int)e.Scale.Y, (int)e.Scale.Z);

            var g = metaResource as Graphics.Content.Graphic;

            if (g != null)
            {
                world = Matrix.Translation(g.Position) * world;
                //world = world * halfPixelOffset;
                world.M41 = (float)((int)world.M41) - 0.5f;
                world.M42 = (float)((int)world.M42) - 0.5f;
                StateManager.SetSamplerState(0, SamplerState.AddressU, g.TextureAdressMode);
                StateManager.SetSamplerState(0, SamplerState.AddressV, g.TextureAdressMode);
            }
            else
            {
                world = ((Graphics.Content.MetaModel)metaResource).World * world;

                StateManager.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Clamp);
                StateManager.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Clamp);
            }
            device.SetTransform(TransformState.World, world);
            if (model.Mesh != null)
            {
                model.Mesh.Draw(device);
                intermediateTrianglesPerFrame += model.Mesh.NFaces;
            }
            else if (model.XMesh != null)
            {
                model.XMesh.DrawSubset(0);
                intermediateTrianglesPerFrame += model.XMesh.FaceCount;
            }
        }
Example #27
0
        /// <summary>
        /// По перемещению мышки вычисляет перемешение камеры:
        /// матрицу для поворота и перемещение по вертикальной оси
        /// </summary>
        /// <param name="currentPosition">Положение мышки</param>
        protected virtual void Track(Point currentPosition)
        {
            Vector3 currentPosition3D = ProjectToTrackball(
                _eventSource.ClientRectangle.Width,
                _eventSource.ClientRectangle.Height, currentPosition);
            Vector3 diff = currentPosition3D - _previousPosition3D;

            _rotationMatrix *= Matrix.RotationZ(diff.X);
            float tempz = _cameraLocation.Z + diff.Y * 100;
            var   tempx = (float)Math.Sqrt(_radius * _radius - tempz * tempz);

            if (tempx > 1 && tempz > 0)
            {
                _cameraLocation.X = tempx;
                _cameraLocation.Z = tempz;
            }
            _previousPosition3D = currentPosition3D;
        }
Example #28
0
        public override void DrawScene(DirectXScene scene)
        {
            _device.BeginScene();
            Matrix oldWorld = WorldTransform;

            if (SceneConfig.EnableShadows)
            {
                FloorMode();
                scene.UpdateModelsBase(scene.Floor, null);
                ShadowMode();
                MultiplyWorldTransform(ShadowMatrices[_lights[0]]);
                scene.UpdateModelsBase(scene.RootBody, scene.Floor);
            }
            NormalMode();
            WorldTransform = oldWorld;
            scene.UpdateModelsBase(scene.RootBody, scene.Floor);
            _device.EndScene();
        }
        private Point GetWorlCoordinateFromMouseCoordinate(Point mouseCoordinate)
        {
            Point ret = new Point();

            SlimDX.Matrix projection = _device.GetTransform(TransformState.Projection);
            SlimDX.Matrix view       = _device.GetTransform(TransformState.View);

            SlimDX.Matrix transform = view * projection;
            transform.Invert();

            SlimDX.Vector3 vecMouse = new Vector3((float)((mouseCoordinate.X / ActualWidthDpi) - 0.5f) * 2.0f, (float)-((mouseCoordinate.Y / ActualHeightDpi) - 0.5f) * 2.0f, 0);
            SlimDX.Vector4 vecWorld = Vector3.Transform(vecMouse, transform);

            ret.X = vecWorld.X;
            ret.Y = vecWorld.Y;

            return(ret);
        }
Example #30
0
        //============================================================
        // <T>向上/向下旋转</T>
        //
        // @param angle 角度
        //============================================================
        public void DoPitch(float angle)
        {
            SFloatVector3 axis   = new SFloatVector3();
            SFloatVector3 axisUp = new SFloatVector3(0, 1, 0);

            axisUp.Cross(_direction, axis);
            DxMatrix      dxMatrix  = DxMatrix.RotationAxis(new Vector3(axis.X, axis.Y, axis.Z), angle);
            SFloatVector3 direction = new SFloatVector3();
            // 旋转Y轴
            SDxMatrix matrix = new SDxMatrix();

            matrix.AssignNative(dxMatrix);
            matrix.UpdateData();
            matrix.Transform3x3Vector3(direction, _direction);
            // 旋转方向
            direction.Normalize();
            _direction.Assign(direction);
            UpdateTarget();
        }
Example #31
0
        public void RenderNormalMap(float pos_x, float pos_y, float scale_x, float scale_y)
        {
            SlimDX.Matrix mat = SlimDX.Matrix.Identity;
            mat.M41 = pos_x;
            mat.M42 = pos_y;
            mat.M11 = scale_x;
            mat.M22 = scale_y;

            effect.SetValue(m1h, mat);

            effect.CommitChanges();
            DXMain.device.BeginScene();
            effect.Begin(FX.None);
            effect.BeginPass(1);
            DXMain.device.DrawIndexedPrimitives(PrimitiveType.TriangleStrip, 0, 0, 4225, 0, 8444);
            effect.EndPass();
            effect.End();
            DXMain.device.EndScene();
        }
Example #32
0
        public void Read(out SlimDX.Matrix data)
        {
            int length = Marshal.SizeOf(typeof(SlimDX.Matrix));

            if (CurPtr() + length > mSize)
            {
                data = SlimDX.Matrix.Identity;
                OnReadError();
                return;
            }
            unsafe
            {
                fixed(SlimDX.Matrix *pValue = &data)
                {
                    Marshal.Copy(mHandle, CurPtr(), (IntPtr)pValue, length);
                }
            }
            mPos += length;
        }
Example #33
0
		public override void MultiplyWorldTransform(Matrix matrix)
		{
			_device.MultiplyTransform(TransformState.World, matrix);
		}
Example #34
0
 // Resets the projection
 public void resetProjection(float aspectRatio)
 {
     proj=	DX.Matrix.PerspectiveFovLH(fov, aspectRatio, nearView, farView);
 }
Example #35
0
        /// <summary>
        /// Creates the matrices.
        /// </summary>
        private void CreateMatrices()
        {
            Contract.Ensures(camera != null, "Camera must be instantiated by this function.");
            Contract.Ensures(world != null, "World must be instantiated by this function.");
            Contract.Ensures(ortho != null, "Ortho must be instantiated by this function.");

            float screenNear = 0.1f;
            float screenDepth = 100f;
            camera = new Camera(dx.D3DDevice, dx.WindowWidth, dx.WindowHeight);
            camera.Position = new SlimDX.Vector3(0, 0.5f, -2.2f);
            world = SlimDX.Matrix.Identity;
            ortho = SlimDX.Matrix.OrthoLH(dx.WindowWidth, dx.WindowHeight, screenNear, screenDepth);
        }
Example #36
0
        /// <summary>
        /// Renders the specified time step.
        /// </summary>
        /// <param name="timeStep">The time step.</param>
        public void Render(double timeStep)
        {
            Contract.Requires<ArgumentException>(timeStep > 0, "Parameter timeStep must be greater than 0");
            dx.SetupRender(new Color4(1,0.8f,0.8f,0.8f));

            //Process controls
            foreach (System.Windows.Forms.Keys key in input.Pressed.Keys)
            {
                switch(key)
                {
                    case System.Windows.Forms.Keys.W:
                        MoveUp((float)(15 * timeStep));
                        break;
                    case System.Windows.Forms.Keys.S:
                        MoveUp((float)(-15 * timeStep));
                        break;
                    case System.Windows.Forms.Keys.A:
                        MoveRight((float)(-15 * timeStep));
                        break;
                    case System.Windows.Forms.Keys.D:
                        MoveRight((float)(15 * timeStep));
                        break;
                }
            }

            MoveForward((float)(15 * timeStep * input.MouseWheelDelta));
            if (OnTick != null)
            {
                OnTick(0d);
            }

            //set the shader
            fogShader.SetupShader(dx.Context);
            world = SlimDX.Matrix.Multiply(world, SlimDX.Matrix.RotationY(0.01f));

            //set the world, view and projection matrices
            fogShader.SetWVPMatrices(dx.Context, world, camera.ViewMatrix, camera.ProjectionMatrix);
            //bumpShader.SetCameraParameters(dx.Context, camera);
            //bumpShader.SetLightParameters(dx.Context, light);
            fogShader.SetFogParameters(dx.Context, 0, 2, new Color3(0.5f, 0.5f, 0.5f));
            //render the meshes
            foreach (Mesh<VertexPosTexNormTanBinorm> mesh in meshes)
            {
                fogShader.SetTextures(dx.Context, mesh.Textures);
                mesh.Draw(dx.Context);
            }
            //Render the 2D assets
            dx.DepthEnabled = false;
            colourTextureShader.SetupShader(dx.Context);
            colourTextureShader.SetTexture(dx.Context, fontEngine.Texture);
            colourTextureShader.SetWVPMatrices(dx.Context, SlimDX.Matrix.Identity, camera.ViewMatrix, ortho);
            //fontEngine.DrawIndexed(dx.Context);
            dx.DepthEnabled = true;

            dx.FinishRender();
        }
Example #37
0
 public void SetMatrices(Matrix objectTransform, ICamera camera) {
     _effect.FxWorldViewProj.SetMatrix(objectTransform * camera.ViewProj);
 }
 public static void TransformXY(ref Vector2 vector, Matrix m)
 {
   float w1 = vector.X * m.M11 + vector.Y * m.M21;
   float h1 = vector.X * m.M12 + vector.Y * m.M22;
   vector.X = w1;
   vector.Y = h1;
 }
Example #39
0
 public void SetMatrices(Matrix objectTransform, ICamera camera) { }