Exemplo n.º 1
0
        public SharpDX.Matrix ToMatrix(Vector3 origin = default(Vector3))
        {
            float radPitch = (float)(this.Pitch * Math.PI / 180f);
            float radYaw   = (float)(this.Yaw * Math.PI / 180f);
            float radRoll  = (float)(this.Roll * Math.PI / 180f);

            float SP = (float)Math.Sin(radPitch);
            float CP = (float)Math.Cos(radPitch);
            float SY = (float)Math.Sin(radYaw);
            float CY = (float)Math.Cos(radYaw);
            float SR = (float)Math.Sin(radRoll);
            float CR = (float)Math.Cos(radRoll);

            SharpDX.Matrix m = new SharpDX.Matrix();
            m[0, 0] = CP * CY;
            m[0, 1] = CP * SY;
            m[0, 2] = SP;
            m[0, 3] = 0f;

            m[1, 0] = SR * SP * CY - CR * SY;
            m[1, 1] = SR * SP * SY + CR * CY;
            m[1, 2] = -SR * CP;
            m[1, 3] = 0f;

            m[2, 0] = -(CR * SP * CY + SR * SY);
            m[2, 1] = CY * SR - CR * SP * SY;
            m[2, 2] = CR * CP;
            m[2, 3] = 0f;

            m[3, 0] = origin.X;
            m[3, 1] = origin.Y;
            m[3, 2] = origin.Z;
            m[3, 3] = 1f;
            return(m);
        }
 public static void Translation(float x, float y, float z, out Matrix result)
 {
     result     = Matrix.Identity;
     result.M41 = x;
     result.M42 = y;
     result.M43 = z;
 }
Exemplo n.º 3
0
        public MainWindow()
        {
            _dxgiDevice = AvaloniaLocator.Current.GetService <SharpDX.DXGI.Device>();
            _d3dDevice  = _dxgiDevice.QueryInterface <SharpDX.Direct3D11.Device>();
            _d2dDevice  = AvaloniaLocator.Current.GetService <SharpDX.Direct2D1.Device>();
            DataContext = _model = new MainWindowViewModel();
            _desc       = new SwapChainDescription()
            {
                BufferCount     = 1,
                ModeDescription =
                    new ModeDescription((int)ClientSize.Width, (int)ClientSize.Height,
                                        new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = PlatformImpl?.Handle.Handle ?? IntPtr.Zero,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            _swapChain = new SwapChain(new Factory1(), _d3dDevice, _desc);

            _d2dContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, DeviceContextOptions.None)
            {
                DotsPerInch = new Size2F(96, 96)
            };

            CreateMesh();
            _view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            this.GetObservable(ClientSizeProperty).Subscribe(Resize);
            Resize(ClientSize);
            AvaloniaXamlLoader.Load(this);
            Background = Avalonia.Media.Brushes.Transparent;
        }
Exemplo n.º 4
0
        public void BuildMatrices(SharpDX.Direct3D11.Device pID3DDevice)
        {
            matView = Camera.GetViewMatrix();

            pID3DDevice.Transform.View = matView;

            if (dynamic_znear)
            {
                Camera.GetDynamicZRange(zfar_ratio, out RenderZnear, out RenderZfar);
            }
            else
            {
                RenderZnear = znear;
                RenderZfar  = zfar;
            }

            float aspect = ((float)width) / ((float)height);

#if false
            SharpDX.Matrix matrix = SharpDX.Matrix.PerspectiveFovLH(Camera.Angle, aspect, RenderZnear, RenderZfar);
#else
            float          ang    = Camera.Angle;
            SharpDX.Matrix matrix = SharpDX.Matrix.OrthoLH(2 * ang * aspect, 2 * ang, -100, 100);
#endif
            pID3DDevice.Transform.Projection = matrix;
            matProj              = matrix;
            Viewport.X           = 0;
            Viewport.Y           = 0;
            Viewport.MinZ        = 0;
            Viewport.MaxZ        = 1;
            Viewport.Width       = width;
            Viewport.Height      = height;
            pID3DDevice.Viewport = Viewport;
        }
Exemplo n.º 5
0
        protected override void Draw()
        {
            // Ensure transforms are updated and clear; otherwise leave to Model3D tree
            GraphicsDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, new Color4(1.0f, 1.0f, 1.0f, 1.0f), 1.0f, 0);
            GraphicsDevice.BeginScene();
            float aspect = (float)GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height;

            switch (this.ViewPort3D.ProjectionType)
            {
            case ProjectionType.Perspective:
                projection = Matrix.PerspectiveFovRH(fov, aspect, 0.01f, 10000f);
                break;

            case ProjectionType.Orthogonal:
                float width  = (float)this.Models.Select(m => m.Bounds.Maximum.X).Max() * aspect;
                float height = (float)this.Models.Select(m => m.Bounds.Maximum.Y).Max();
                projection = Matrix.OrthoRH(width / this.Scale, height / this.Scale, 1, 100);
                break;
            }

            view  = Matrix.LookAtRH(CameraPosition, CameraTarget, CameraUpVector);
            world = Matrix.Identity;
            // ENDTODO
            GraphicsDevice.SetTransform(TransformState.Projection, ref projection);
            GraphicsDevice.SetTransform(TransformState.View, ref view);
            GraphicsDevice.SetTransform(TransformState.World, ref world);

            foreach (Model3D model in this.Models)
            {
                model.Draw();
            }
            GraphicsDevice.EndScene();
            GraphicsDevice.Present();
        }
Exemplo n.º 6
0
        public static Matrix rotationMatrix(Quaternion q)
        {
            SharpDX.Matrix matrix = new SharpDX.Matrix();
            // This is the arithmetical formula optimized to work with unit quaternions.
            // |1-2y²-2z²        2xy-2zw         2xz+2yw       0|
            // | 2xy+2zw        1-2x²-2z²        2yz-2xw       0|
            // | 2xz-2yw         2yz+2xw        1-2x²-2y²      0|
            // |    0               0               0          1|

            // And this is the code.
            // First Column
            matrix[0] = 1 - 2 * (q.Y * q.Y + q.Z * q.Z);
            matrix[1] = 2 * (q.X * q.Y + q.Z * q.W);
            matrix[2] = 2 * (q.X * q.Z - q.Y * q.W);
            matrix[3] = 0;

            // Second Column
            matrix[4] = 2 * (q.X * q.Y - q.Z * q.W);
            matrix[5] = 1 - 2 * (q.X * q.X + q.Z * q.Z);
            matrix[6] = 2 * (q.Y * q.Z + q.X * q.W);
            matrix[7] = 0;

            // Third Column
            matrix[8] = 2 * (q.X * q.Z + q.Y * q.W);
            matrix[9] = 2 * (q.Y * q.Z - q.X * q.W);
            matrix[10] = 1 - 2 * (q.X * q.X + q.Y * q.Y);
            matrix[11] = 0;

            // Fourth Column
            matrix[12] = 0;
            matrix[13] = 0;
            matrix[14] = 0;
            matrix[15] = 1;
            return matrix;
        }
Exemplo n.º 7
0
        protected void trackball_TrackBallMoved(Object sender, EventArgs e)
        {
            System.Windows.Media.Media3D.Quaternion delta = ((Trackball)sender).Delta;
            Vector3 deltaAxis = new Vector3();

            deltaAxis.X = (float)delta.Axis.X;
            deltaAxis.Y = (float)delta.Axis.Y;
            deltaAxis.Z = (float)delta.Axis.Z;
            deltaAxis.Normalize();
            Vector3 cameraLookDirection = viewport3DImage.CameraTarget - viewport3DImage.CameraPosition;
            Vector3 cameraUpDirection   = viewport3DImage.CameraUpVector;

            cameraLookDirection.Normalize();
            // Subtract any component of cameraUpDirection along cameraLookDirection
            cameraUpDirection = cameraUpDirection - Vector3.Multiply(cameraLookDirection, Vector3.Dot(cameraUpDirection, cameraLookDirection));
            cameraUpDirection.Normalize();
            Vector3 cameraX = Vector3.Cross(cameraLookDirection, cameraUpDirection);
            // Get axis of rotation in the camera coordinates
            Vector3 deltaAxisWorld = Vector3.Multiply(cameraX, deltaAxis.X) +
                                     Vector3.Multiply(cameraUpDirection, deltaAxis.Y) +
                                     Vector3.Multiply(cameraLookDirection, -deltaAxis.Z);

            SharpDX.Matrix cameraTransform = SharpDX.Matrix.RotationAxis(deltaAxisWorld, (float)(delta.Angle * Math.PI / 180.0));
            viewport3DImage.CameraTarget   = Vector3.Transform(viewport3DImage.CameraTarget, cameraTransform).ToVector3();
            viewport3DImage.CameraPosition = Vector3.Transform(viewport3DImage.CameraPosition, cameraTransform).ToVector3();
            viewport3DImage.CameraUpVector = Vector3.Transform(viewport3DImage.CameraUpVector, cameraTransform).ToVector3();
            double newPhi = FindPhi();

            if (newPhi != lastPhi)
            {
                lastPhi = newPhi;
                axes.UpdateOpenSides(newPhi);
            }
        }
Exemplo n.º 8
0
        public static void WorldToScreen2(Vector3 WorldLocation, IntPtr CameraManager, out Vector2 Screenlocation)
        {
            //Initialize screen location
            Screenlocation = new Vector2(0, 0);

            POVInfo POV = AMK.Mem.Read <POVInfo>((CameraManager + Offsets.CameraCache) + Offsets.POV); // CameraManager + 0x410 + 0x10; 0x03B8

            SharpDX.Vector3 Rotation = POV.Rotation;                                                   //AMK.Mem.Read<Vector3>(POV + 0x00C);
            // AMK.Mem.Read<Vector3>(POV);
            //Console.WriteLine($"POV:{Rotation.Pitch},{Rotation.Yaw},{Rotation.Roll} - Loc: {Location.ToString()}");
            Vector3 vAxisX, vAxisY, vAxisZ;

            SharpDX.Matrix m = ToMatrix(Rotation.X, Rotation.Y, Rotation.Z);

            vAxisX = new Vector3(m.M11, m.M12, m.M13);
            vAxisY = new Vector3(m.M21, m.M22, m.M23);
            vAxisZ = new Vector3(m.M31, m.M32, m.M33);

            Vector3 vDelta       = new Vector3(WorldLocation.X - POV.Location.X, WorldLocation.Y - POV.Location.Y, WorldLocation.Z - POV.Location.Z);
            Vector3 vTransformed = new Vector3(Vector3.Dot(vDelta, vAxisY), Vector3.Dot(vDelta, vAxisZ), Vector3.Dot(vDelta, vAxisX));

            if (vTransformed.Z < 1f)
            {
                vTransformed.Z = 1f;
            }

            float FovAngle      = POV.FOV;// AMK.Mem.Read<float>(POV + 0x018); ;
            float ScreenCenterX = 1920 / 2;
            float ScreenCenterY = 1080 / 2;

            Screenlocation.X = ScreenCenterX + vTransformed.X * (ScreenCenterX / (float)Math.Tan(FovAngle * (float)Math.PI / 360)) / vTransformed.Z;
            Screenlocation.Y = ScreenCenterY - vTransformed.Y * (ScreenCenterX / (float)Math.Tan(FovAngle * (float)Math.PI / 360)) / vTransformed.Z;
        }
Exemplo n.º 9
0
        public void SetUniform(string name, Matrix4 m)
        {
            this.Use();
            int uid = this.GetUniform(name);

            Graphics.SetShaderUniform(uid, m);
        }
Exemplo n.º 10
0
        private void ControlOnCustomRender()
        {
            var info = new DrawInfo();

            for (int i = 0; i < 3; i++)
            {
                info.World = Matrix.RotationY((float)(DateTime.Now - start).TotalSeconds * 0.2f) *
                             Matrix.Translation(i * 3 - 3, 0, 0);
                info.Projection     = camera.Projection;
                info.View           = camera.View;
                info.DiffuseMap     = texture[i];
                info.NormalMap      = normalmap[i];
                info.MetallicMap    = metallicmap[i];
                info.RoughnessMap   = roughnessmap[i];
                info.CameraPosition = camera.Position;
                info.CubeMap        = cubemap;

                Renderer.Current.DrawModel3D(model, info);
            }
            info.World        = Matrix.Scaling(10) * Matrix.Translation(0, -1.7f, 0);
            info.DiffuseMap   = texture[3];
            info.NormalMap    = normalmap[3];
            info.MetallicMap  = metallicmap[3];
            info.RoughnessMap = roughnessmap[3];
            Renderer.Current.DrawModel3D(floor, info);
        }
Exemplo n.º 11
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // cache location etc for when we come out of fullscreen
            windowedLocation = Location;
            windowedSize     = Size;

            // pick up view and projection for projector
            view = new SharpDX.Matrix();
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    view[i, j] = (float)projector.pose[i, j];
                }
            }
            view.Invert();
            view.Transpose();

            var   cameraMatrix = projector.cameraMatrix;
            float fx           = (float)cameraMatrix[0, 0];
            float fy           = (float)cameraMatrix[1, 1];
            float cx           = (float)cameraMatrix[0, 2];
            float cy           = (float)cameraMatrix[1, 2];

            float near = 0.1f;
            float far  = 100.0f;

            float w = projector.width;
            float h = projector.height;

            projection = GraphicsTransforms.ProjectionMatrixFromCameraMatrix(fx, fy, cx, cy, w, h, near, far);
            projection.Transpose();
        }
Exemplo n.º 12
0
        public static DX.Matrix MakeD3DMatrix(Matrix4 matrix)
        {
            // Transpose matrix
            // D3D9 uses row vectors i.e. V*M
            // Ogre, OpenGL and everything else uses column vectors i.e. M*V

            var dxMat = new DX.Matrix();

            // set it to a transposed matrix since DX uses row vectors
            dxMat.M11 = matrix.m00;
            dxMat.M12 = matrix.m10;
            dxMat.M13 = matrix.m20;
            dxMat.M14 = matrix.m30;
            dxMat.M21 = matrix.m01;
            dxMat.M22 = matrix.m11;
            dxMat.M23 = matrix.m21;
            dxMat.M24 = matrix.m31;
            dxMat.M31 = matrix.m02;
            dxMat.M32 = matrix.m12;
            dxMat.M33 = matrix.m22;
            dxMat.M34 = matrix.m32;
            dxMat.M41 = matrix.m03;
            dxMat.M42 = matrix.m13;
            dxMat.M43 = matrix.m23;
            dxMat.M44 = matrix.m33;

            return(dxMat);
        }
        //https://csharp.hotexamples.com/examples/SharpDX/Matrix/-/php-matrix-class-examples.html
        public static Matrix rotationMatrix(Quaternion q)
        {
            SharpDX.Matrix matrix = new SharpDX.Matrix();
            // This is the arithmetical formula optimized to work with unit quaternions.
            // |1-2y²-2z²        2xy-2zw         2xz+2yw       0|
            // | 2xy+2zw        1-2x²-2z²        2yz-2xw       0|
            // | 2xz-2yw         2yz+2xw        1-2x²-2y²      0|
            // |    0               0               0          1|

            // And this is the code.
            // First Column
            matrix[0] = 1 - 2 * (q.Y * q.Y + q.Z * q.Z);
            matrix[1] = 2 * (q.X * q.Y + q.Z * q.W);
            matrix[2] = 2 * (q.X * q.Z - q.Y * q.W);
            matrix[3] = 0;

            // Second Column
            matrix[4] = 2 * (q.X * q.Y - q.Z * q.W);
            matrix[5] = 1 - 2 * (q.X * q.X + q.Z * q.Z);
            matrix[6] = 2 * (q.Y * q.Z + q.X * q.W);
            matrix[7] = 0;

            // Third Column
            matrix[8]  = 2 * (q.X * q.Z + q.Y * q.W);
            matrix[9]  = 2 * (q.Y * q.Z - q.X * q.W);
            matrix[10] = 1 - 2 * (q.X * q.X + q.Y * q.Y);
            matrix[11] = 0;

            // Fourth Column
            matrix[12] = 0;
            matrix[13] = 0;
            matrix[14] = 0;
            matrix[15] = 1;
            return(matrix);
        }
Exemplo n.º 14
0
        protected override void HandlePaint(Rect rect)
        {
            var viewProj = Matrix.Multiply(_view, _proj);
            var context  = Direct2D1Platform.Direct3D11Device.ImmediateContext;

            // Clear views
            context.ClearDepthStencilView(_depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
            context.ClearRenderTargetView(_renderView, Color.White);

            // Update WorldViewProj Matrix
            var worldViewProj = Matrix.RotationX((float)_model.RotationX) * Matrix.RotationY((float)_model.RotationY)
                                * Matrix.RotationZ((float)_model.RotationZ)
                                * Matrix.Scaling((float)_model.Zoom)
                                * viewProj;

            worldViewProj.Transpose();
            context.UpdateSubresource(ref worldViewProj, _contantBuffer);

            // Draw the cube
            context.Draw(36, 0);
            base.HandlePaint(rect);

            // Present!
            _swapChain.Present(0, PresentFlags.None);
        }
Exemplo n.º 15
0
        public static Matrix4 ConvertD3DMatrix(ref DX.Matrix d3DMat)
        {
            var mat = Matrix4.Zero;

            mat.m00 = d3DMat.M11;
            mat.m10 = d3DMat.M12;
            mat.m20 = d3DMat.M13;
            mat.m30 = d3DMat.M14;

            mat.m01 = d3DMat.M21;
            mat.m11 = d3DMat.M22;
            mat.m21 = d3DMat.M23;
            mat.m31 = d3DMat.M24;

            mat.m02 = d3DMat.M31;
            mat.m12 = d3DMat.M32;
            mat.m22 = d3DMat.M33;
            mat.m32 = d3DMat.M34;

            mat.m03 = d3DMat.M41;
            mat.m13 = d3DMat.M42;
            mat.m23 = d3DMat.M43;
            mat.m33 = d3DMat.M44;

            return(mat);
        }
Exemplo n.º 16
0
        public void Draw(Mesh mesh)
        {
            if (mesh != null && mesh.Fragment != null && mesh.VertexBuffer != null && mesh.IndexBuffer != null)
            {
                WP.View = mesh.Projection == Mesh.ProjectionType.Unit ? UnitView : PixelView;

                System.Windows.Media.Matrix world = System.Windows.Media.Matrix.Multiply(mesh.LocalTransform, mesh.WorldTransform);
                WP.World = Utils.Convert(world);

                SharpDX.Matrix vw   = SharpDX.Matrix.Multiply(WP.World, WP.View);
                Vector4        posA = Vector2.Transform(new Vector2((float)mesh.AABB.Left, (float)mesh.AABB.Bottom), vw);
                Vector4        posB = Vector2.Transform(new Vector2((float)mesh.AABB.Right, (float)mesh.AABB.Top), vw);

                float minX = Math.Min(posA.X, posB.X);
                float maxX = Math.Max(posA.X, posB.X);

                if (maxX < -1f || minX > 1f)
                {
                    return;
                }


                PrimitiveTopology topology = mesh.Geometry == Mesh.GeometryType.Polygons ? PrimitiveTopology.TriangleList : PrimitiveTopology.LineList;
                int indexCount             = (mesh.Geometry == Mesh.GeometryType.Polygons ? 3 : 2) * mesh.PrimitiveCount;

                SetAlphaBlend(mesh.UseAlpha);
                Setup(mesh.Fragment, mesh.VertexBufferBinding, mesh.IndexBuffer, topology);
                RenderDevice.ImmediateContext.DrawIndexed(indexCount, 0, 0);
                SetAlphaBlend(false);

                Statistics.Add(mesh.PrimitiveCount);
            }
        }
        public unsafe void SetConstants(DeviceContext deviceContext,
                                        SharpDX.Matrix userWorldViewProjection,
                                        SharpDX.Matrix projectorWorldViewProjection,
                                        TimeSpan elapsedTime)
        {
            Constants constants = new Constants();

            for (int i = 0, col = 0; col < 4; col++)
            {
                for (int row = 0; row < 4; row++)
                {
                    constants.userWorldViewProjection[i]      = userWorldViewProjection[row, col];
                    constants.projectorWorldViewProjection[i] = projectorWorldViewProjection[row, col];
                    i++;
                }
            }

            constants.globalTime = (float)elapsedTime.TotalSeconds;

            DataStream dataStream;

            deviceContext.MapSubresource(constantBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out dataStream);
            dataStream.Write <Constants>(constants);
            deviceContext.UnmapSubresource(constantBuffer, 0);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Function to assign a projection matrix for the layer.
        /// </summary>
        /// <param name="view">The projection (camera) matrix to assign.</param>
        /// <param name="aspect">The aspect ratio.</param>
        /// <remarks>
        /// <para>
        /// This is necessary so we can project our 3D data into 2D space. We will be using the 2D renderer camera for this, so the matrix will be orthogonal. This can lead to some... er...
        /// "interesting" issues.  But since we're not making a complex scene here, just set it as-is.
        /// </para>
        /// </remarks>
        private void SetProjection(ref DX.Matrix projection)
        {
            _projectionMatrix = projection;
            DX.Matrix.Multiply(ref _viewMatrix, ref _projectionMatrix, out _viewProjection);

            _viewProjectionBuffer?.Buffer.SetData(ref _viewProjection);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Function to return an interpolated point from the spline.
        /// </summary>
        /// <param name="startPointIndex">Index in the point list to start from.</param>
        /// <param name="delta">Delta value to interpolate.</param>
        /// <returns>The interpolated value at <paramref name="delta"/>.</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="startPointIndex"/> parameter is less than 0, or greater than/equal to the number of points in the spline minus 1.</exception>
        /// <remarks>
        /// <para>
        /// The <paramref name="delta"/> parameter is a unit value where 0 is the first point in the spline (relative to <paramref name="startPointIndex"/>) and 1 is the next point from the <paramref name="startPointIndex"/> in the spline.
        /// </para>
        /// <para>
        /// If the <paramref name="delta"/> is less than 0, or greater than 1, the value will be wrapped to fit within the 0..1 range.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentOutOfRangeException"><c>[Debug only]</c> Thrown when the <paramref name="startPointIndex"/> is less than 0, or greater than/equal to the number of points - 1 in the <see cref="IGorgonSpline.Points"/> parameter.</exception>
        public DX.Vector4 GetInterpolatedValue(int startPointIndex, float delta)
        {
            DX.Matrix calculations = DX.Matrix.Identity;

            startPointIndex.ValidateRange(nameof(startPointIndex), 0, Points.Count - 1);

            if (delta.EqualsEpsilon(0.0f))
            {
                return(Points[startPointIndex]);
            }

            if (delta.EqualsEpsilon(1.0f))
            {
                return(Points[startPointIndex + 1]);
            }

            var deltaCubeSquare = new DX.Vector4(delta * delta * delta, delta * delta, delta * delta, 1.0f);

            DX.Vector4 startPoint     = Points[startPointIndex];
            DX.Vector4 startPointNext = Points[startPointIndex + 1];
            DX.Vector4 tangent        = _tangents[startPointIndex];
            DX.Vector4 tangentNext    = _tangents[startPointIndex + 1];

            calculations.Row1 = startPoint;
            calculations.Row2 = startPointNext;
            calculations.Row3 = tangent;
            calculations.Row4 = tangentNext;

            DX.Matrix.Multiply(ref _coefficients, ref calculations, out DX.Matrix calcResult);
            DX.Vector4.Transform(ref deltaCubeSquare, ref calcResult, out DX.Vector4 result);

            return(result);
        }
Exemplo n.º 20
0
        public static void Draw(RenderContext11 renderContext, PositionColoredTextured[] points, int count, Texture11 texture, SharpDX.Direct3D.PrimitiveTopology primitiveType, float opacity = 1.0f)
        {
            if (VertexBuffer == null)
            {
                VertexBuffer        = new Buffer(renderContext.Device, System.Runtime.InteropServices.Marshal.SizeOf(points[0]) * 2500, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, System.Runtime.InteropServices.Marshal.SizeOf(points[0]));
                VertexBufferBinding = new VertexBufferBinding(VertexBuffer, System.Runtime.InteropServices.Marshal.SizeOf((points[0])), 0);
            }
            renderContext.devContext.InputAssembler.PrimitiveTopology = primitiveType;
            renderContext.BlendMode = BlendMode.Alpha;
            renderContext.setRasterizerState(TriangleCullMode.Off);
            SharpDX.Matrix mat = (renderContext.World * renderContext.View * renderContext.Projection).Matrix11;
            mat.Transpose();

            WarpOutputShader.MatWVP = mat;
            WarpOutputShader.Use(renderContext.devContext, texture != null, opacity);

            renderContext.SetVertexBuffer(VertexBufferBinding);

            DataBox box = renderContext.devContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);

            Utilities.Write(box.DataPointer, points, 0, count);

            renderContext.devContext.UnmapSubresource(VertexBuffer, 0);
            if (texture != null)
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, texture.ResourceView);
            }
            else
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, null);
            }
            renderContext.devContext.Draw(count, 0);
        }
Exemplo n.º 21
0
        public MainWindow()
        {
            InitializeComponent();

            Loaded += (sender, args) =>
                      Catch(() =>
            {
                _manager = new DxManager(SharpDxElement);
                Prepare();
            });


            SharpDxElement.OnResized +=
                (source, e) =>
                Catch(
                    () =>
                    _proj =
                        Matrix.PerspectiveFovLH(
                            (float)Math.PI / 4.0f,
                            (float)SharpDxElement.ActualWidth / (float)SharpDxElement.ActualHeight,
                            0.1f,
                            100.0f)
                    );


            new DispatcherTimer
            {
                Interval  = TimeSpan.FromMilliseconds(15),
                IsEnabled = true,
            }.Tick += (sender, args) => Draw();

            Closing += (sender, args) => Utilities.Dispose(ref _manager);
        }
Exemplo n.º 22
0
        RawMatrix Map(SharpDX.Matrix from)
        {
            RawMatrix matIdentity = new RawMatrix();// Matrix.Identity;

            matIdentity.M11 = from.M11;
            matIdentity.M12 = from.M12;
            matIdentity.M13 = from.M13;
            matIdentity.M14 = from.M14;

            matIdentity.M21 = from.M21;
            matIdentity.M22 = from.M22;
            matIdentity.M23 = from.M23;
            matIdentity.M24 = from.M24;

            matIdentity.M31 = from.M31;
            matIdentity.M32 = from.M32;
            matIdentity.M33 = from.M33;
            matIdentity.M34 = from.M34;

            matIdentity.M41 = from.M41;
            matIdentity.M42 = from.M42;
            matIdentity.M43 = from.M43;
            matIdentity.M44 = from.M44;
            return(matIdentity);
        }
Exemplo n.º 23
0
        public unsafe void SetVertexShaderConstants(DeviceContext deviceContext, SharpDX.Matrix world, SharpDX.Matrix viewProjection, Vector3 lightPosition)
        {
            // hlsl matrices are default column order
            var constants = new VSConstantBuffer();

            for (int i = 0, col = 0; col < 4; col++)
            {
                for (int row = 0; row < 4; row++)
                {
                    constants.world[i]          = world[row, col];
                    constants.viewProjection[i] = viewProjection[row, col];
                    i++;
                }
            }

            for (int i = 0; i < 3; i++)
            {
                constants.lightPosition[i] = lightPosition[i];
            }

            DataStream dataStream;

            deviceContext.MapSubresource(vertexShaderConstantBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out dataStream);
            dataStream.Write <VSConstantBuffer>(constants);
            deviceContext.UnmapSubresource(vertexShaderConstantBuffer, 0);
        }
Exemplo n.º 24
0
        // could be method on Projector:
        void SetViewProjectionFromProjector(ProjectorCameraEnsemble.Projector projector)
        {
            // pick up view and projection for a given projector
            view = new SharpDX.Matrix();
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    view[i, j] = (float)projector.pose[i, j];
                }
            }
            view.Invert();
            view.Transpose();

            var   cameraMatrix = projector.cameraMatrix;
            float fx           = (float)cameraMatrix[0, 0];
            float fy           = (float)cameraMatrix[1, 1];
            float cx           = (float)cameraMatrix[0, 2];
            float cy           = (float)cameraMatrix[1, 2];

            float near = 0.1f;
            float far  = 100.0f;

            float w = projector.width;
            float h = projector.height;

            projection = ProjectionMatrixFromCameraMatrix(fx, fy, cx, cy, w, h, near, far);
            projection.Transpose();
        }
Exemplo n.º 25
0
        private void Draw()
        {
            _manager.Clear(Color.Black);


            var context = _manager.Device.ImmediateContext;

            var time     = (float)_clock.Elapsed.TotalSeconds;
            var viewProj = Matrix.Multiply(_view, _proj);

            var world =
                Matrix.RotationX(time) *
                Matrix.RotationY(time * 1.5f) *
                Matrix.RotationZ(time * .9f) *
                Matrix.Translation(0, 0, 0);

            var worldViewProj = world * viewProj;

            Vector3 lightDirection = new Vector3(-0.3f, 0.3f, +1);

            lightDirection.Normalize();

            _cbuf.WorldViewProj = worldViewProj;
            _cbuf.World         = world;
            _cbuf.LightDir      = new Vector4(lightDirection, 1);
            _cbuf.Light         = (CheckBoxLight.IsChecked ?? false) ? 1 : 0;

            context.UpdateSubresource(ref _cbuf, _constantBuffer);

            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_sphereVertBuffer, Utilities.SizeOf <Vector4>() * 3, 0));
            context.InputAssembler.SetIndexBuffer(_sphereIndBuffer, SharpDX.DXGI.Format.R16_UInt, 0);
            context.DrawIndexed(_sphere.Indices.Length, 0, 0);

            _manager.Present();
        }
Exemplo n.º 26
0
        protected static void OnCameraChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            ViewportImage viewportImage = ((ViewportImage)obj);

            viewportImage.RequestRender();
            viewportImage.view = Matrix.LookAtRH(viewportImage.CameraPosition, viewportImage.CameraTarget, viewportImage.CameraUpVector);
        }
Exemplo n.º 27
0
        private void UpdateViewProjectionMatrix(RenderingContext renderingContext)
        {
            var camera = renderingContext.UsedCamera;

            var leftRightHandedCoordinateSystem = camera as ILeftRightHandedCoordinateSystem;

            if (leftRightHandedCoordinateSystem != null)
            {
                leftRightHandedCoordinateSystem.IsRightHandedCoordinateSystem = false;
            }

            // We also need to force the update of the camera - this will recalculate the matrices
            camera.Update(forceMatrixUpdate: true);


            // Now we can get the viewProjection matrix from the DXViewportView's camera
            _viewProjectionMatrix = camera.GetViewProjection();

            // If the matrices in the shaders are written in default format, then we need to transpose them.
            // To remove the need for transpose we can define the matrices in HLSL as row_major (this is used in DXEngine's shaders, but here the original shader from SharpDX is preserved).
            _viewProjectionMatrix.Transpose();


            // Set IsRightHandedCoordinateSystem back to standard DXEngine's settings
            if (leftRightHandedCoordinateSystem != null)
            {
                leftRightHandedCoordinateSystem.IsRightHandedCoordinateSystem = true;
            }

            camera.Update(forceMatrixUpdate: true);

            // Save frame number so we will not update _viewProjectionMatrix in this frame any more
            _viewProjectionMatrixFrameNumber = renderingContext.FrameNumber;
        }
Exemplo n.º 28
0
        protected override void setupShader(RenderContext11 renderContext, Texture11 texture, float opacity)
        {
            SharpDX.Matrix mvp = (renderContext.World * renderContext.View * renderContext.Projection).Matrix11;
            mvp.Transpose();

            float aspectRatio = renderContext.ViewPort.Width / renderContext.ViewPort.Height;

            Color4 color = new Color4(TintColor.Red, TintColor.Green, TintColor.Blue, TintColor.Alpha * opacity);

            // Set up the shader
            if (renderStrategy == RenderStrategy.GeometryShader)
            {
                PointSpriteShader11.WVPMatrix         = mvp;
                PointSpriteShader11.Color             = color;
                PointSpriteShader11.ViewportScale     = new SharpDX.Vector2(1.0f, aspectRatio) * 0.001f;
                PointSpriteShader11.MinPointSize      = MinPointSize;
                PointSpriteShader11.PointScaleFactors = PointScaleFactors;
                PointSpriteShader11.Use(renderContext.Device.ImmediateContext);
            }
            else
            {
                CompatibilityPointSpriteShader.WVPMatrix         = mvp;
                CompatibilityPointSpriteShader.Color             = color;
                CompatibilityPointSpriteShader.ViewportScale     = new SharpDX.Vector2(1.0f, aspectRatio) * 0.001f;
                CompatibilityPointSpriteShader.PointScaleFactors = PointScaleFactors;
                CompatibilityPointSpriteShader.MinPointSize      = MinPointSize;
                bool useInstancing = renderStrategy == RenderStrategy.Instanced;
                CompatibilityPointSpriteShader.Use(renderContext.Device.ImmediateContext, useInstancing);
            }

            // Set shader resources
            renderContext.Device.ImmediateContext.PixelShader.SetShaderResource(0, texture == null ? null : texture.ResourceView);
        }
        public static Matrix Scaling(float scale)
        {
            Matrix result = Matrix.Identity;

            result.M11 = result.M22 = result.M33 = scale;
            return(result);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Transforms the absolute position to a position relative to transport object the player is on
        /// </summary>
        /// <param name="loc">The location</param>
        /// <returns>The location relative to the transport the player is on</returns>
        public static Location GetRelativeToPlayerTransport(this Location loc)
        {
            var player    = ObjectManager.Instance.Player;
            var transport = player?.CurrentTransport;

            if (transport == null)
            {
                return(null);
            }

            Matrix inverse;

            var transportMatrix = transport.TransportMatrix;

            Matrix.Invert(ref transportMatrix, out inverse);

            var x = inverse.M31 * loc.Z +
                    inverse.M11 * loc.X +
                    inverse.M21 * loc.Y +
                    inverse.M41;

            var y = inverse.M32 * loc.Z +
                    inverse.M12 * loc.X +
                    inverse.M22 * loc.Y +
                    inverse.M42;

            var z = inverse.M33 * loc.Z +
                    inverse.M13 * loc.X +
                    inverse.M23 * loc.Y +
                    inverse.M43;

            return(new Location(x, y, z));
        }
Exemplo n.º 31
0
        /// <summary>
        /// Gets screen coordinates for an enemy based on yours and their position
        /// </summary>
        /// <param name="localRotation"></param>
        /// <param name="enemy"></param>
        /// <param name="screen"></param>
        /// <returns></returns>
        public static bool WorldToScreen(SharpDX.Matrix localRotation, Vector3 enemy, out Vector3 screen)
        {
            screen = new Vector3(0, 0, 0);

            var transposedRotation = Matrix.Transpose(localRotation);

            var translationVector = new Vector3(transposedRotation.M41, transposedRotation.M42, transposedRotation.M43);

            var up = new Vector3(transposedRotation.M21, transposedRotation.M22, transposedRotation.M23);

            var right = new Vector3(transposedRotation.M11, transposedRotation.M12, transposedRotation.M13);

            var w = D3DxVec3Dot(translationVector, enemy) + transposedRotation.M44;

            if (w < 0.098f)
            {
                return(false);
            }

            var y = D3DxVec3Dot(up, enemy) + transposedRotation.M24;
            var x = D3DxVec3Dot(right, enemy) + transposedRotation.M14;

            screen.X = ((ScreenWidth) * (1f + x / w) / 2);
            screen.Y = ((ScreenHeight) * (1f - y / w) / 2);
            screen.Z = w;

            return(true);
        }
Exemplo n.º 32
0
        public static Matrix RotationVectorFromRotationMatrix(Matrix R)
        {
            var sR = new SharpDX.Matrix();
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                    sR[i, j] = (float)R[i, j];
            var q = SharpDX.Quaternion.RotationMatrix(sR);

            // Why the negative sign? SharpDX assumes a post-multiply rotation matrix. Instead of transposing the input we invert the output quaternion.
            var sRotationVector = -q.Angle * q.Axis;

            var rotationVector = new Matrix(3, 1);
            for (int i = 0; i < 3; i++)
                rotationVector[i] = sRotationVector[i];
            return rotationVector;
        }
Exemplo n.º 33
0
 private void Reset(Size size)
 {
     lastColor = Color.Black;
     var xScale = (size.Width > 0) ? 2.0f / size.Width : 0.0f;
     var yScale = (size.Height > 0) ? 2.0f / size.Height : 0.0f;
     var viewportTransform = new Matrix
     {
         M11 = xScale,
         M22 = -yScale,
         M33 = 1.0f,
         M44 = 1.0f,
         M41 = -1.0f,
         M42 = 1.0f
     };
     drawShader.WorldViewProjection = viewportTransform;
 }
Exemplo n.º 34
0
        public override void Update(float timeTotal, float timeDelta)
        {
            //timeDelta; // Unused parameter.
            int width = (int)_renderTargetSize.Width;
            int height = (int)_renderTargetSize.Height;

            _view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            _proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, width / (float)height, 0.1f, 100.0f);
            _viewProj = Matrix.Multiply(_view, _proj);

            _worldViewProj = Matrix.Scaling(1.0f) * Matrix.RotationX(timeTotal) * Matrix.RotationY(timeTotal * 2.0f) * Matrix.RotationZ(timeTotal * .7f) * _viewProj;
            _worldViewProj.Transpose();
        }
Exemplo n.º 35
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // cache location etc for when we come out of fullscreen
            windowedLocation = Location;
            windowedSize = Size;

            // pick up view and projection for projector
            view = new SharpDX.Matrix();
            for (int i = 0; i < 4; i++)
                for (int j = 0; j < 4; j++)
                    view[i, j] = (float)projector.pose[i, j];
            view.Invert();
            view.Transpose();

            var cameraMatrix = projector.cameraMatrix;
            float fx = (float)cameraMatrix[0, 0];
            float fy = (float)cameraMatrix[1, 1];
            float cx = (float)cameraMatrix[0, 2];
            float cy = (float)cameraMatrix[1, 2];

            float near = 0.1f;
            float far = 100.0f;

            float w = projector.width;
            float h = projector.height;

            projection = GraphicsTransforms.ProjectionMatrixFromCameraMatrix(fx, fy, cx, cy, w, h, near, far);
            projection.Transpose();
        }
Exemplo n.º 36
0
 /* INITIALIZATION PROCEDURES */
 /// <summary>
 /// Create a projection matrix based on the current window size.
 /// </summary>
 /// <param name="gameEngine">An instance of the <see cref="Tesseract"/> game engine.</param>
 public void CreateProjection(Tesseract gameEngine)
 {
     Size windowSize = gameEngine.WindowManager.Window.ClientSize;
     Projection = Matrix.PerspectiveFovRH((float)Math.PI / 3F, windowSize.Width / (float)windowSize.Height, 0.5F, 1000F);
 }
Exemplo n.º 37
0
        void Update(float dt)
        {
            // translation
            float step = TranslationSpeed * dt;

            // Z
            if (KeyDown('W'))
                Translate(Vector3.UnitZ, step);
            else if (KeyDown('S'))
                Translate(-Vector3.UnitZ, step);

            // X
            if (KeyDown('A'))
                Translate(Vector3.UnitX, step);
            else if (KeyDown('D'))
                Translate(-Vector3.UnitX, step);

            // Y
            if (KeyDown('E'))
                Translate(Vector3.UnitY, step);
            else if (KeyDown('C'))
                Translate(-Vector3.UnitY, step);

            if (KeyDown('R'))
                View = OriginalView;

            if (mouseWheel != 0)
            {
                Translate(-Vector3.UnitZ, mouseWheel * MouseWheelStep);
                mouseWheel = 0;
            }

            bool mouseDown = (Control.MouseButtons & MouseButtons.Left) != 0;
            bool ctrlDown = KeyDown(0x11);
            bool shiftDown = KeyDown(0x10);

            if (mouseDown && (mousePosition != lastMousePosition))
            {
                if (shiftDown) // translate
                {
                    if (!translating)
                    {
                        translating = true;
                        startPosition = position;
                        startMousePosition = lastMousePosition;
                    }

                    var centerRay = Viewport.Unproject(new Vector3((float)Viewport.Width / 2f, (float)Viewport.Height / 2f, 0), Projection, orientation, SharpDX.Matrix.Identity);
                    centerRay.Normalize();

                    var startRay = Viewport.Unproject(new Vector3(startMousePosition.X, startMousePosition.Y, 0), Projection, orientation, SharpDX.Matrix.Identity);
                    startRay.Normalize();

                    var endRay = Viewport.Unproject(new Vector3(mousePosition.X, mousePosition.Y, 0), Projection, orientation, SharpDX.Matrix.Identity);
                    endRay.Normalize();

                    float startScale = ShiftTranslationSpeed / Vector3.Dot(centerRay, startRay);
                    float endScale = ShiftTranslationSpeed / Vector3.Dot(centerRay, endRay);

                    var translation = endScale * endRay - startScale * startRay;

                    position = startPosition - translation;
                    UpdateViewMatrix();
                }
                else // rotate
                {
                    if (!rotating)
                    {
                        rotating = true;
                        rotateXY = !ctrlDown;
                        startOrientation = orientation;
                        startMousePosition = lastMousePosition;
                    }

                    SharpDX.Matrix dR;

                    if (rotateXY)
                    {
                        var startRay = Viewport.Unproject(new Vector3(startMousePosition.X, startMousePosition.Y, 0), Projection, startOrientation, SharpDX.Matrix.Identity);
                        startRay.Normalize();

                        var endRay = Viewport.Unproject(new Vector3(mousePosition.X, mousePosition.Y, 0), Projection, startOrientation, SharpDX.Matrix.Identity);
                        endRay.Normalize();

                        float angle = (float)Math.Acos(Vector3.Dot(startRay, endRay));
                        var axis = Vector3.Cross(startRay, endRay);
                        axis.Normalize();
                        dR = SharpDX.Matrix.RotationAxis(axis, angle);
                    }
                    else // rotate around Z
                    {
                        var center = new Vector2((float)control.ClientSize.Width / 2f, (float)control.ClientSize.Height / 2f);

                        var startRay2D = new Vector2(startMousePosition.X, startMousePosition.Y);
                        var endRay = new Vector2(mousePosition.X, mousePosition.Y);
                        startRay2D -= center;
                        endRay -= center;

                        startRay2D.Normalize();
                        endRay.Normalize();

                        float angle = (float)Math.Atan2(endRay.Y, endRay.X) - (float)Math.Atan2(startRay2D.Y, startRay2D.X);
                        var axis = Viewport.Unproject(new Vector3(center.X, center.Y, 0), Projection, startOrientation, SharpDX.Matrix.Identity);
                        axis.Normalize();
                        dR = SharpDX.Matrix.RotationAxis(axis, angle);
                    }

                    orientation = dR * startOrientation;
                    orientation.Orthonormalize();

                    UpdateViewMatrix();
                }
            }
            else if (!mouseDown)
            {
                translating = false;
                rotating = false;
            }
        }
Exemplo n.º 38
0
        protected override void Draw()
        {
            // Ensure transforms are updated and clear; otherwise leave to Model3D tree
            GraphicsDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, new Color4(1.0f, 1.0f, 1.0f, 1.0f), 1.0f, 0);
            GraphicsDevice.BeginScene();
            float aspect = (float)GraphicsDevice.Viewport.Width / (float)GraphicsDevice.Viewport.Height;

            switch (this.ViewPort3D.ProjectionType)
            {
                case ProjectionType.Perspective:
                    projection = Matrix.PerspectiveFovRH(fov, aspect, 0.01f, 10000f);
                    break;
                case ProjectionType.Orthogonal:
                    float width = (float)this.Models.Select(m => m.Bounds.Maximum.X).Max() * aspect;
                    float height = (float)this.Models.Select(m => m.Bounds.Maximum.Y).Max();
                    projection = Matrix.OrthoRH(width / this.Scale, height / this.Scale, 1, 100);
                    break;
            }
            
            view = Matrix.LookAtRH(CameraPosition, CameraTarget, CameraUpVector);
            world = Matrix.Identity;
            // ENDTODO
            GraphicsDevice.SetTransform(TransformState.Projection, ref projection);
            GraphicsDevice.SetTransform(TransformState.View, ref view);
            GraphicsDevice.SetTransform(TransformState.World, ref world);
            
            foreach (Model3D model in this.Models)
            {
                model.Draw();
            }
            GraphicsDevice.EndScene();
            GraphicsDevice.Present();
        }
Exemplo n.º 39
0
		public static DX.Matrix MakeD3DMatrix( Matrix4 matrix )
		{
			// Transpose matrix
			// D3D9 uses row vectors i.e. V*M
			// Ogre, OpenGL and everything else uses column vectors i.e. M*V

			var dxMat = new DX.Matrix();

			// set it to a transposed matrix since DX uses row vectors
			dxMat.M11 = matrix.m00;
			dxMat.M12 = matrix.m10;
			dxMat.M13 = matrix.m20;
			dxMat.M14 = matrix.m30;
			dxMat.M21 = matrix.m01;
			dxMat.M22 = matrix.m11;
			dxMat.M23 = matrix.m21;
			dxMat.M24 = matrix.m31;
			dxMat.M31 = matrix.m02;
			dxMat.M32 = matrix.m12;
			dxMat.M33 = matrix.m22;
			dxMat.M34 = matrix.m32;
			dxMat.M41 = matrix.m03;
			dxMat.M42 = matrix.m13;
			dxMat.M43 = matrix.m23;
			dxMat.M44 = matrix.m33;

			return dxMat;
		}
Exemplo n.º 40
0
        public void Render(Device device, Mesh mesh, Matrix transformMatrix)
        {
            m_device = device;

            Parallel.For(0, mesh.Faces.Length, faceIndex =>
            {
                var face = mesh.Faces[faceIndex];
                var pointA = m_device.Project(mesh.Vertices[face.A], transformMatrix);
                var pointB = m_device.Project(mesh.Vertices[face.B], transformMatrix);
                var pointC = m_device.Project(mesh.Vertices[face.C], transformMatrix);

                var color = 0.25f + (faceIndex % mesh.Faces.Length) * 0.75f / mesh.Faces.Length;
                DrawTriangle(pointA, pointB, pointC, new Color4(color, color, color, 1));
            });
        }
        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();
                }
            }
        }
Exemplo n.º 42
0
 protected override void Initialize()
 {
     SetValue(ModelsProperty, new Model3DCollection(this));
     cameraTransform = Matrix.Identity;
     world = Matrix.Identity;
 }
Exemplo n.º 43
0
        public void Render(Device device, Mesh mesh, Matrix transformMatrix)
        {
            foreach ( var vertex in mesh.Vertices)
            {
                var pointA = device.Project( vertex, transformMatrix);

                device.DrawPoint(pointA, new Color4(1,0,0,1));
            }
        }
Exemplo n.º 44
0
        public static Vector3 GetCornerPointToAxis(CameraPosition cameraPosition, Quaternion axis, Direction direction)
        {
            // Orientation in Viewing direction
            var a1 = cameraPosition.Width / 2;
            var a2 = cameraPosition.Height / 2;
            var a3 = (double)cameraPosition.FocalLength;

            var angleY = Math.Atan(a1 / a3);
            var angleX = Math.Atan(a2 / a3);

            // Set sign for corner
            switch (direction)
            {
                default:
                case Direction.TopLeft:
                    break;
                case Direction.TopRight:
                    angleX = -angleX;
                    break;
                case Direction.BottomLeft:
                    angleY = -angleY;
                    break;
                case Direction.BottomRight:
                    angleX = -angleX;
                    angleY = -angleY;
                    break;
            }

            // Rotation matrices
            var xm = new SharpDX.Matrix
            {
                M11 = 1,
                M22 = (float)Math.Cos(angleX),
                M32 = (float)Math.Sin(angleX),
                M23 = (float)-Math.Sin(angleX),
                M33 = (float)Math.Cos(angleX)
            };

            var ym = new SharpDX.Matrix
            {
                M11 = (float)Math.Cos(angleY),
                M31 = (float)-Math.Sin(angleY),
                M22 = 1,
                M13 = (float)Math.Sin(angleY),
                M33 = (float)Math.Cos(angleY)
            };

            // Rotate the point by multiplying with quaternion and conjugate of quaternion
            var rot = Quaternion.RotationMatrix(xm) * Quaternion.RotationMatrix(ym) * axis;

            return Rotate(rot, new Vector3(0, 0, 1));
        }
Exemplo n.º 45
0
 public void Render(Device device, Mesh mesh, Matrix transformMatrix)
 {
     foreach (var render in renderList)
     {
         render.Render(device,mesh,transformMatrix);
     }
 }