예제 #1
0
        /// <summary>
        /// Renders the mesh with the specified transformation
        /// </summary>
        /// <param name="modelTransform"></param>
        public void Render(Matrix4x4F modelTransform)
        {
            rDescription.FillMode = wireFrame ? FillMode.Wireframe : FillMode.Solid;
            // setup rasterization
            using (RasterizerState rState = this.manager.device.CreateRasterizerState(rDescription))
            {
                this.manager.device.RS.State = rState;
                this.manager.brightnessVariable.AsSingle = this.lightIntensity;

                if (rootParts != null)
                {
                    Matrix3D transform = modelTransform.ToMatrix3D();

                    foreach (Part part in rootParts)
                    {
                        RenderPart(part, transform, null);
                    }
                }

                // Note: see comment regarding input layout in RenderPart()
                // method; the same thing applies to the render state of the
                // rasterizer stage of the pipeline.
                this.manager.device.RS.State = null;
            }
        }
예제 #2
0
        private void Initialize3DTransformations(uint nWidth, uint nHeight)
        {
            worldVariable      = shader.GetVariableByName("World").AsMatrix;
            viewVariable       = shader.GetVariableByName("View").AsMatrix;
            projectionVariable = shader.GetVariableByName("Projection").AsMatrix;
            diffuseVariable    = shader.GetVariableByName("txDiffuse").AsShaderResource;

            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix.
            Vector3F eye = new Vector3F(0.0f, 2.0f, -6.0f);
            Vector3F at  = new Vector3F(0.0f, 0.0f, 0.0f);
            Vector3F up  = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix          = Camera.MatrixLookAtLH(eye, at, up);
            viewVariable.Matrix = viewMatrix;

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float)Math.PI * 0.24f,  // fovy
                nWidth / (float)nHeight, // aspect
                0.1f,                    // zn
                100.0f                   // zf
                );
            projectionVariable.Matrix = projectionMatrix;
        }
예제 #3
0
        /// <summary>
        /// Really draw the tool on the view
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        private void DrawTool(double x, double y, double z)
        {
            CamBamUI ui = CamBamUI.MainUI;

            // setup tool translation

            Matrix4x4F matrix4x4F = new Matrix4x4F();

            // move the identity matrix to our delta? positions

            matrix4x4F.Translate(x - _lastX, y - _lastY, z - _lastZ);

            _lastX = x;
            _lastY = y;
            _lastZ = z;

            // tell the tool
            _tool.ApplyTransformation(matrix4x4F);

            // hijack the current EditMode
            _orgEditMode = _ActiveView.CurrentEditMode;
            _ActiveView.CurrentEditMode = this;

            // trigger OnPaint
            _ActiveView.RepaintEditMode();

            _ActiveView.CurrentEditMode = _orgEditMode;

            _orgEditMode = null;
        }
예제 #4
0
        public static Matrix3D ToMatrix3D(this Matrix4x4F source)
        {
            Matrix3D destination = new Matrix3D( );

            destination.M11 = (float)source.M11;
            destination.M12 = (float)source.M12;
            destination.M13 = (float)source.M13;
            destination.M14 = (float)source.M14;

            destination.M21 = (float)source.M21;
            destination.M22 = (float)source.M22;
            destination.M23 = (float)source.M23;
            destination.M24 = (float)source.M24;

            destination.M31 = (float)source.M31;
            destination.M32 = (float)source.M32;
            destination.M33 = (float)source.M33;
            destination.M34 = (float)source.M34;

            destination.OffsetX = (float)source.M41;
            destination.OffsetY = (float)source.M42;
            destination.OffsetZ = (float)source.M43;
            destination.M44     = (float)source.M44;

            return(destination);
        }
예제 #5
0
파일: mop.cs 프로젝트: robgrz/matmill
        public override List <Polyline> GetOutlines()
        {
            List <Polyline> outlines = new List <Polyline>();

            foreach (Toolpath path in _toolpaths)
            {
                foreach (Sliced_path_item p in path.Trajectory)
                {
                    if (p.Item_type != Sliced_path_item_type.SLICE && p.Item_type != Sliced_path_item_type.SPIRAL)
                    {
                        continue;
                    }

                    Matrix4x4F mx = new Matrix4x4F();
                    mx.Translate(0.0, 0.0, path.Bottom);
                    if (Transform.Cached != null)
                    {
                        mx *= Transform.Cached;
                    }

                    Polyline poly = (Polyline)p.Clone();
                    poly.ApplyTransformation(mx);
                    outlines.Add(poly);
                }
            }

            return(outlines);
        }
예제 #6
0
 /// <summary>
 /// Do the desired translation
 /// </summary>
 /// <param name="xm"></param>
 public virtual void ApplyTransformation(Matrix4x4F xm)
 {
     if (_tool != null)
     {
         _tool.ApplyTransformation(xm);
     }
 }
예제 #7
0
        /// <summary>
        /// Renders the mesh with the specified transformation
        /// </summary>
        /// <param name="modelTransform"></param>
        public void Render(Matrix4x4F modelTransform)
        {
            rDescription.FillMode = wireFrame ? FillMode.Wireframe : FillMode.Solid;
            // setup rasterization
            using (RasterizerState rState = this.manager.device.CreateRasterizerState(rDescription))
            {
                this.manager.device.RS.State             = rState;
                this.manager.brightnessVariable.AsSingle = this.lightIntensity;

                if (rootParts != null)
                {
                    Matrix3D transform = modelTransform.ToMatrix3D();

                    foreach (Part part in rootParts)
                    {
                        RenderPart(part, transform, null);
                    }
                }

                // Note: see comment regarding input layout in RenderPart()
                // method; the same thing applies to the render state of the
                // rasterizer stage of the pipeline.
                this.manager.device.RS.State = null;
            }
        }
예제 #8
0
        public static Matrix4x4F ToMatrix4x4F(Matrix3D matrix)
        {
            Matrix4x4F matrix2 = new Matrix4x4F();

            matrix2.M11 = (float)matrix.M11;
            matrix2.M12 = (float)matrix.M12;
            matrix2.M13 = (float)matrix.M13;
            matrix2.M14 = (float)matrix.M14;

            matrix2.M21 = (float)matrix.M21;
            matrix2.M22 = (float)matrix.M22;
            matrix2.M23 = (float)matrix.M23;
            matrix2.M24 = (float)matrix.M24;

            matrix2.M31 = (float)matrix.M31;
            matrix2.M32 = (float)matrix.M32;
            matrix2.M33 = (float)matrix.M33;
            matrix2.M34 = (float)matrix.M34;

            matrix2.M41 = (float)matrix.OffsetX;
            matrix2.M42 = (float)matrix.OffsetY;
            matrix2.M43 = (float)matrix.OffsetZ;
            matrix2.M44 = (float)matrix.M44;

            return(matrix2);
        }
예제 #9
0
 public static Vector4F VectorMultiply(Matrix4x4F a, Vector4F b)
 {
     return new Vector4F(
         a.M11 * b.X + a.M21 * b.Y + a.M31 * b.Z + a.M41 * b.W,
         a.M12 * b.X + a.M22 * b.Y + a.M32 * b.Z + a.M42 * b.W,
         a.M13 * b.X + a.M23 * b.Y + a.M33 * b.Z + a.M43 * b.W,
         a.M14 * b.X + a.M24 * b.Y + a.M34 * b.Z + a.M44 * b.W
         );
 }
예제 #10
0
 public static Vector4F VectorMultiply(Matrix4x4F a, Vector4F b)
 {
     return(new Vector4F(
                a.M11 * b.X + a.M21 * b.Y + a.M31 * b.Z + a.M41 * b.W,
                a.M12 * b.X + a.M22 * b.Y + a.M32 * b.Z + a.M42 * b.W,
                a.M13 * b.X + a.M23 * b.Y + a.M33 * b.Z + a.M43 * b.W,
                a.M14 * b.X + a.M24 * b.Y + a.M34 * b.Z + a.M44 * b.W
                ));
 }
예제 #11
0
파일: mop.cs 프로젝트: robgrz/matmill
        private void paint_toolpath(ICADView iv, Display3D d3d, Color arccolor, Color linecolor, Toolpath path)
        {
            Polyline leadin = path.Leadin;

            Color chord_color = Color.FromArgb(128, CamBamConfig.Defaults.ToolpathRapidColor);

            if (leadin != null)
            {
                Matrix4x4F mx = new Matrix4x4F();
                mx.Translate(0.0, 0.0, path.Bottom);
                if (Transform.Cached != null)
                {
                    mx *= Transform.Cached;
                }

                d3d.ModelTransform = mx;
                d3d.LineWidth      = 1F;
                leadin.Paint(d3d, arccolor, linecolor);
                base.PaintDirectionVector(iv, leadin, d3d, mx);
            }

            foreach (Sliced_path_item p in path.Trajectory)
            {
                Color acol = arccolor;
                Color lcol = linecolor;

                if (p.Item_type == Sliced_path_item_type.CHORD || p.Item_type == Sliced_path_item_type.SMOOTH_CHORD || p.Item_type == Sliced_path_item_type.SLICE_SHORTCUT)
                {
                    if (!_should_draw_chords)
                    {
                        continue;
                    }
                    acol = chord_color;
                    lcol = chord_color;
                }

                if (p.Item_type == Sliced_path_item_type.DEBUG_MEDIAL_AXIS)
                {
                    acol = Color.Cyan;
                    lcol = Color.Cyan;
                }

                Matrix4x4F mx = new Matrix4x4F();
                mx.Translate(0.0, 0.0, path.Bottom);
                if (Transform.Cached != null)
                {
                    mx *= Transform.Cached;
                }

                d3d.ModelTransform = mx;
                d3d.LineWidth      = 1F;

                p.Paint(d3d, acol, lcol);
                base.PaintDirectionVector(iv, p, d3d, mx);
            }
        }
예제 #12
0
 private void directControl_MouseMove(object sender, MouseEventArgs e)
 {
     if (isDrag)
     {
         worldMatrix     *= MatrixMath.MatrixRotationX(0.01f * (lastLocation.Y - e.Y));
         worldMatrix     *= MatrixMath.MatrixRotationY(0.01f * (lastLocation.X - e.X));
         lastLocation     = e.Location;
         cbRotate.Checked = false;
     }
 }
예제 #13
0
        private void ScaleCameraDistance(float scale)
        {
            Vector4F   eye4      = new Vector4F(Eye.X, Eye.Y, Eye.Z, 0);
            Matrix4x4F transform = MatrixMath.MatrixScale(scale, scale, scale);

            eye4 = MatrixMath.VectorMultiply(transform, eye4);
            Eye  = new Vector3F(eye4.X, eye4.Y, eye4.Z);

            effects.ViewMatrix = DXUtil.Camera.MatrixLookAtLH(Eye, At, Up);
        }
예제 #14
0
        void RenderScene()
        {
            lock (syncObject)
            {
                if (device == null)
                {
                    CreateDeviceResources();
                }

                if (!pause)
                {
                    if (lastSavedDelta != 0)
                    {
                        startTime      = Environment.TickCount - lastSavedDelta;
                        lastSavedDelta = 0;
                    }
                    currentTimeVariation = (Environment.TickCount - startTime) / 6000.0f;
                    worldMatrix          = MatrixMath.MatrixTranslate(0, 0, currentTimeVariation);
                    textBrush.Transform  = Matrix3x2F.Translation(0, (4096f / 16f) * currentTimeVariation);
                }

                device.ClearDepthStencilView(
                    depthStencilView,
                    ClearOptions.Depth,
                    1,
                    0
                    );

                // Clear the back buffer
                device.ClearRenderTargetView(renderTargetView, backColor);

                diffuseVariable.Resource = null;

                technique.GetPassByIndex(0).Apply();

                // Draw the D2D content into our D3D surface
                RenderD2DContentIntoSurface();

                diffuseVariable.Resource = textureResourceView;

                // Update variables
                worldMatrixVariable.Matrix = worldMatrix;

                // Set index buffer
                device.IA.IndexBuffer = new IndexBuffer(facesIndexBuffer, Format.R16UInt, 0);

                // Draw the scene
                technique.GetPassByIndex(0).Apply();

                device.DrawIndexed((uint)Marshal.SizeOf(VertexArray.VerticesInstance), 0, 0);

                swapChain.Present(0, Microsoft.WindowsAPICodePack.DirectX.Graphics.PresentOptions.None);
            }
        }
예제 #15
0
 public static Matrix4x4F MatrixPerspectiveFovLH(float fovy, float aspect, float zn, float zf)
 {
     Matrix4x4F ret = new Matrix4x4F();
     ret.M11 = 1.0f / (aspect * (float)Math.Tan(fovy / 2));
     ret.M22 = 1.0f / (float)Math.Tan(fovy / 2);
     ret.M33 = zf / (zf - zn);
     ret.M34 = 1;
     ret.M43 = (zf * zn) / (zn - zf);
     ret.M44 = 0;
     return ret;
 }
예제 #16
0
        public static Matrix4x4F MatrixPerspectiveFovLH(float fovy, float aspect, float zn, float zf)
        {
            Matrix4x4F ret = new Matrix4x4F();

            ret.M11 = 1.0f / (aspect * (float)Math.Tan(fovy / 2));
            ret.M22 = 1.0f / (float)Math.Tan(fovy / 2);
            ret.M33 = zf / (zf - zn);
            ret.M34 = 1;
            ret.M43 = (zf * zn) / (zn - zf);
            ret.M44 = 0;
            return(ret);
        }
예제 #17
0
        void host_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            lock (syncObject)
            {
                if (device != null)
                {
                    uint nWidth  = (uint)host.ActualWidth;
                    uint nHeight = (uint)host.ActualHeight;

                    backBufferRenderTarget.Dispose();
                    device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null }, null);

                    //need to remove the reference to the swapchain's backbuffer to enable ResizeBuffers() call
                    renderTargetView.Dispose();
                    depthStencilView.Dispose();
                    depthStencil.Dispose();

                    device.RS.Viewports = null;

                    SwapChainDescription sd = swapChain.Description;
                    //Change the swap chain's back buffer size, format, and number of buffers
                    swapChain.ResizeBuffers(
                        sd.BufferCount,
                        nWidth,
                        nHeight,
                        sd.BufferDescription.Format,
                        sd.Options);

                    using (Texture2D pBuffer = swapChain.GetBuffer <Texture2D>(0))
                    {
                        renderTargetView = device.CreateRenderTargetView(pBuffer);
                    }

                    InitializeDepthStencil(nWidth, nHeight);

                    // bind the views to the device
                    device.OM.RenderTargets = new OutputMergerRenderTargets(new[] { renderTargetView }, depthStencilView);

                    SetViewport(nWidth, nHeight);

                    CreateBackBufferD2DRenderTarget();

                    // update the aspect ratio
                    projectionMatrix = Camera.MatrixPerspectiveFovLH(
                        (float)Math.PI * 0.24f,  // fovy
                        nWidth / (float)nHeight, // aspect
                        0.1f,                    // zn
                        100.0f                   // zf
                        );
                    projectionVariable.Matrix = projectionMatrix;
                }
            }
        }
예제 #18
0
파일: mop.cs 프로젝트: robgrz/matmill
        private void emit_toolpath(MachineOpToGCode gcg, Toolpath path)
        {
            // first item is the spiral by convention
            if (path.Trajectory[0].Item_type != Sliced_path_item_type.SPIRAL)
            {
                throw new Exception("no spiral in sliced path");
            }

            CBValue <double> normal_feedrate = base.CutFeedrate;
            CBValue <double> chord_feedrate  = _chord_feedrate != 0 ? new CBValue <double>(_chord_feedrate) : base.CutFeedrate;
            CBValue <double> spiral_feedrate = _spiral_feedrate != 0 ? new CBValue <double>(_spiral_feedrate) : base.CutFeedrate;
            CBValue <double> leadin_feedrate = _leadin.Cached != null && _leadin.Cached.LeadInFeedrate != 0 ? new CBValue <double>(_leadin.Cached.LeadInFeedrate) : base.CutFeedrate;

            if (path.Leadin != null)
            {
                base.CutFeedrate = leadin_feedrate;
                Polyline p = (Polyline)path.Leadin.Clone();
                p.ApplyTransformation(Matrix4x4F.Translation(0, 0, path.Bottom));
                gcg.AppendPolyLine(p, double.NaN);
            }

            foreach (Sliced_path_item item in path.Trajectory)
            {
                switch (item.Item_type)
                {
                case Sliced_path_item_type.SPIRAL:
                    base.CutFeedrate = spiral_feedrate;
                    break;

                case Sliced_path_item_type.SLICE:
                    base.CutFeedrate = normal_feedrate;
                    break;

                case Sliced_path_item_type.CHORD:
                case Sliced_path_item_type.SMOOTH_CHORD:
                case Sliced_path_item_type.SLICE_SHORTCUT:
                case Sliced_path_item_type.GUIDE:
                    base.CutFeedrate = chord_feedrate;
                    break;

                default:
                    throw new Exception("unknown item type in sliced trajectory");
                }

                Polyline p = (Polyline)item.Clone();
                p.ApplyTransformation(Matrix4x4F.Translation(0, 0, path.Bottom));
                gcg.AppendPolyLine(p, double.NaN);
            }

            base.CutFeedrate = normal_feedrate;
        }
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(sd.BufferCount, (uint)host.ActualWidth, (uint)host.ActualHeight, sd.BufferDescription.Format, sd.Options);
                SetViews();
                // Update the projection matrix
                projectionMatrix          = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)host.ActualWidth / (float)host.ActualHeight), 0.5f, 100.0f);
                projectionVariable.Matrix = projectionMatrix;
            }
            Matrix4x4F worldMatrix;

            currentTime = (Environment.TickCount - startTime) / 1000.0f;

            //WPF transforms used here use degrees as opposed to D3DX which uses radians in the native tutorial
            //360 degrees == 2 * Math.PI
            //world matrix rotates the first cube by t degrees
            RotateTransform3D rotateTransform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), currentTime * 30));

            worldMatrix = rotateTransform.Value.ToMatrix4x4F();

            // Modify the color
            meshColor.X = ((float)Math.Sin(currentTime * 1.0f) + 1.0f) * 0.5f;
            meshColor.Y = ((float)Math.Cos(currentTime * 3.0f) + 1.0f) * 0.5f;
            meshColor.Z = ((float)Math.Sin(currentTime * 5.0f) + 1.0f) * 0.5f;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            //
            // Update variables that change once per frame
            //
            worldVariable.Matrix          = worldMatrix;
            meshColorVariable.FloatVector = meshColor;

            //
            // Render the cube
            //
            TechniqueDescription techDesc = technique.Description;

            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            swapChain.Present(0, PresentOptions.None);
        }
예제 #20
0
파일: mop.cs 프로젝트: robgrz/matmill
        private Surface polyline_to_surface(Polyline p, double z)
        {
            if (base.Transform.Cached != null && !Transform.Cached.IsIdentity())
            {
                p = (Polyline)p.Clone();
                p.ApplyTransformation(Transform.Cached);
            }

            PolylineToMesh mesh    = new PolylineToMesh(p);
            Surface        surface = mesh.ToWideLine(base.ToolDiameter.Cached);

            surface.ApplyTransformation(Matrix4x4F.Translation(0.0, 0.0, z - 0.001));
            return(surface);
        }
예제 #21
0
 protected override void OnSizeChanged(EventArgs e)
 {
     if (active)
     {
         renderTargetView.Dispose();
         SwapChainDescription sd = swapChain.Description;
         swapChain.ResizeBuffers(sd.BufferCount, (uint)ClientSize.Width, (uint)ClientSize.Height, sd.BufferDescription.Format, sd.Options);
         SetViews();
         // Update the projection matrix
         projectionMatrix          = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)ClientSize.Width / (float)ClientSize.Height), 0.5f, 100.0f);
         projectionVariable.Matrix = projectionMatrix;
     }
     base.OnSizeChanged(e);
 }
        private void InitMatrices()
        {
            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 3.0f, -6.0f);
            Vector3F At  = new Vector3F(0.0f, 0.0f, 0.0f);
            Vector3F Up  = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Microsoft.WindowsAPICodePack.DirectX.DirectXUtilities.Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)host.ActualWidth / (float)host.ActualHeight), 0.5f, 100.0f);

            // Update Variables that never change
            viewVariable.Matrix       = viewMatrix;
            projectionVariable.Matrix = projectionMatrix;
        }
예제 #23
0
        private void InitMatrices()
        {
            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 3.0f, -6.0f);
            Vector3F At  = new Vector3F(0.0f, 0.0f, 0.0f);
            Vector3F Up  = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = DXUtil.Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)this.ClientSize.Width / (float)this.ClientSize.Height), 0.5f, 100.0f);

            // Update Variables that never change
            viewVariable.Matrix       = viewMatrix;
            projectionVariable.Matrix = projectionMatrix;
        }
예제 #24
0
 protected override void OnMouseWheel(MouseEventArgs e)
 {
     base.OnMouseWheel(e);
     if (e.Delta != 0)
     {
         float scale;
         if (e.Delta > 0)
         {
             scale = (0.01f * e.Delta);
         }
         else
         {
             scale = -100f / e.Delta;
         }
         worldMatrix *= MatrixMath.MatrixScale(scale, scale, scale);
     }
 }
        //
        // ICADView
        //

        /// <summary>
        /// Extension to ZoomToFit
        ///
        /// Original does not take Toolpaths into account
        /// </summary>
        /// <param name="icadview"></param>
        public static void ZoomToFitEx(this ICADView icadview)
        {
            if (icadview.CADFile == null || icadview.ViewProjection == null)
            {
                return;
            }

            PointF     empty  = PointF.Empty;
            PointF     point  = PointF.Empty;
            Matrix4x4F matrix = new Matrix4x4F(icadview.ViewProjection.ViewMatrix4x4F);

            matrix.m[12] = 0;
            matrix.m[13] = 0;

            icadview.CADFile.GetScreenExtentsEx(ref empty, ref point, matrix);
            icadview.ViewProjection.ZoomToFitScreenPoints(empty, point);
            icadview.RefreshView();
        }
예제 #26
0
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(
                    sd.BufferCount,
                    (uint)directControl.ClientSize.Width,
                    (uint)directControl.ClientSize.Height,
                    sd.BufferDescription.Format,
                    sd.Options);
                SetViews();
                // Update the projection matrix
                InitMatrices();
            }
            int   dwCurrentTime = Environment.TickCount;
            float t             = (dwCurrentTime - dwLastTime) / 1000f;

            dwLastTime = dwCurrentTime;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            // Clear the depth buffer to 1.0 (max depth)
            device.ClearDepthStencilView(depthStencilView, ClearOptions.Depth, 1.0f, (byte)0);

            lock (meshLock)
            {
                if (mesh != null)
                {
                    if (cbRotate.Checked)
                    {
                        worldMatrix *= MatrixMath.MatrixRotationY(-t);
                    }
                    mesh.Render(worldMatrix);
                }
            }

            Microsoft.WindowsAPICodePack.DirectX.ErrorCode error;
            swapChain.TryPresent(1, PresentOptions.None, out error);
        }
예제 #27
0
        private void LoadMesh(string filename)
        {
            lock (meshLock)
            {
                if (mesh != null)
                {
                    mesh.Dispose();
                    mesh = null;
                }

                worldMatrix = Matrix4x4F.Identity;

                XMesh meshT = meshManager.Open(filename);

                meshT.ShowWireFrame = cbWireframe.Checked;

                mesh = meshT;
            };
        }
예제 #28
0
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(sd.BufferCount, (uint)directControl.ClientSize.Width, (uint)directControl.ClientSize.Height, sd.BufferDescription.Format, sd.Options);
                SetViews();
                // Update the projection matrix
                projectionMatrix          = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.5f, ((float)directControl.ClientSize.Width / (float)directControl.ClientSize.Height), 0.1f, 100.0f);
                projectionVariable.Matrix = projectionMatrix;
            }
            t = (Environment.TickCount - dwTimeStart) / 50;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            // Rotate the cube
            RotateTransform3D rt = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), t));

            worldMatrix = rt.Value.ToMatrix4x4F();

            //
            // Update variables that change once per frame
            //
            worldVariable.Matrix = worldMatrix;

            //
            // Render the cube
            //
            TechniqueDescription techDesc = technique.Description;

            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            swapChain.Present(0, PresentOptions.None);
        }
예제 #29
0
 public static Matrix4x4F Transpose(Matrix4x4F matrix)
 {
     Matrix4x4F matrix2;
     matrix2.M11 = matrix.M11;
     matrix2.M12 = matrix.M21;
     matrix2.M13 = matrix.M31;
     matrix2.M14 = matrix.M41;
     matrix2.M21 = matrix.M12;
     matrix2.M22 = matrix.M22;
     matrix2.M23 = matrix.M32;
     matrix2.M24 = matrix.M42;
     matrix2.M31 = matrix.M13;
     matrix2.M32 = matrix.M23;
     matrix2.M33 = matrix.M33;
     matrix2.M34 = matrix.M43;
     matrix2.M41 = matrix.M14;
     matrix2.M42 = matrix.M24;
     matrix2.M43 = matrix.M34;
     matrix2.M44 = matrix.M44;
     return matrix2;
 }
예제 #30
0
        public static Matrix4x4F Transpose(Matrix4x4F matrix)
        {
            Matrix4x4F matrix2;

            matrix2.M11 = matrix.M11;
            matrix2.M12 = matrix.M21;
            matrix2.M13 = matrix.M31;
            matrix2.M14 = matrix.M41;
            matrix2.M21 = matrix.M12;
            matrix2.M22 = matrix.M22;
            matrix2.M23 = matrix.M32;
            matrix2.M24 = matrix.M42;
            matrix2.M31 = matrix.M13;
            matrix2.M32 = matrix.M23;
            matrix2.M33 = matrix.M33;
            matrix2.M34 = matrix.M43;
            matrix2.M41 = matrix.M14;
            matrix2.M42 = matrix.M24;
            matrix2.M43 = matrix.M34;
            matrix2.M44 = matrix.M44;
            return(matrix2);
        }
예제 #31
0
 protected override void OnMouseWheel(MouseEventArgs e)
 {
     base.OnMouseWheel(e);
     if (e.Delta != 0)
     {
         float scale;
         if (e.Delta > 0)
             scale = (0.01f * e.Delta);
         else
             scale = -100f / e.Delta;
         worldMatrix *= MatrixMath.MatrixScale( scale, scale, scale );
     }
 }
예제 #32
0
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(sd.BufferCount, (uint)directControl.ClientSize.Width, (uint)directControl.ClientSize.Height, sd.BufferDescription.Format, sd.Flags);
                SetViews();
                // Update the projection matrix
                projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.5f, ((float)directControl.ClientSize.Width / (float)directControl.ClientSize.Height), 0.1f, 100.0f);
                projectionVariable.Matrix = projectionMatrix;
            }
            t = (Environment.TickCount - dwTimeStart) / 50;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            // Rotate the cube
            RotateTransform3D rt = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), t));
            worldMatrix = rt.Value.ToMatrix4x4F();

            //
            // Update variables that change once per frame
            //
            worldVariable.Matrix = worldMatrix;

            //
            // Render the cube
            //
            TechniqueDescription techDesc = technique.Description;

            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            swapChain.Present(0, PresentFlag.Default);
        } 
예제 #33
0
        private void LoadMesh(string filename)
        {
            lock (meshLock)
            {
                if (mesh != null)
                {
                    mesh.Dispose();
                    mesh = null;
                }

                worldMatrix = Matrix4x4F.Identity;

                XMesh meshT = meshManager.Open(filename);

                meshT.ShowWireFrame = cbWireframe.Checked;

                mesh = meshT;
            };
        }
예제 #34
0
 private void directControl_MouseMove(object sender, MouseEventArgs e)
 {
     if (isDrag)
     {
         worldMatrix *= MatrixMath.MatrixRotationX(0.01f * (lastLocation.Y - e.Y));
         worldMatrix *= MatrixMath.MatrixRotationY( 0.01f * (lastLocation.X - e.X) );
         lastLocation = e.Location;
         cbRotate.Checked = false;
     }
 }
예제 #35
0
        void RenderScene()
        {
            lock (syncObject)
            {
                //initialize D3D device and D2D render targets the first time we get here
                if (device == null)
                    CreateDeviceResources();

                //tick count is used to control animation and calculate FPS
                int currentTime = Environment.TickCount;
                if (!startTime.HasValue)
                {
                    startTime = currentTime;
                }

                currentTicks = currentTime - startTime.GetValueOrDefault();

                float a = (currentTicks * 360.0f) * ((float)Math.PI / 180.0f) * 0.0001f;
                worldMatrix = MatrixMath.MatrixRotationY(a);

                // Swap chain will tell us how big the back buffer is
                SwapChainDescription swapDesc = swapChain.Description;
                uint nWidth = swapDesc.BufferDescription.Width;
                uint nHeight = swapDesc.BufferDescription.Height;

                device.ClearDepthStencilView(
                    depthStencilView, ClearOptions.Depth,
                    1, 0
                    );

                // Draw a gradient background before we draw the cube
                if (backBufferRenderTarget != null)
                {
                    backBufferRenderTarget.BeginDraw();

                    backBufferGradientBrush.Transform =
                        Matrix3x2F.Scale(
                            backBufferRenderTarget.Size,
                            new Point2F(0.0f, 0.0f));

                    RectF rect = new RectF(
                        0.0f, 0.0f,
                        nWidth,
                        nHeight);

                    backBufferRenderTarget.FillRectangle(rect, backBufferGradientBrush);
                    backBufferRenderTarget.EndDraw();
                }

                diffuseVariable.Resource = null;
                technique.GetPassByIndex(0).Apply();

                // Draw the D2D content into a D3D surface.
                RenderD2DContentIntoTexture();

                // Pass the updated texture to the pixel shader
                diffuseVariable.Resource = textureResourceView;

                // Update variables that change once per frame.
                worldVariable.Matrix = worldMatrix;

                // Set the index buffer.
                device.IA.IndexBuffer = new IndexBuffer(facesIndexBuffer, Format.R16UInt, 0);

                // Render the scene
                technique.GetPassByIndex(0).Apply();

                device.DrawIndexed(vertexArray.s_FacesIndexArray.Length, 0, 0);

                // Update fps
                currentTime = Environment.TickCount; // Get the ticks again
                currentTicks = currentTime - startTime.GetValueOrDefault();
                if ((currentTime - lastTicks) > 250)
                {
                    fps = (swapChain.LastPresentCount) / (currentTicks / 1000f);
                    lastTicks = currentTime;
                }

                backBufferRenderTarget.BeginDraw();

                // Draw fps
                backBufferRenderTarget.DrawText(
                    String.Format("Average FPS: {0:F1}", fps),
                    textFormatFps,
                    new RectF(
                        10f,
                        nHeight - 32f,
                        nWidth,
                        nHeight
                        ),
                    backBufferTextBrush
                    );

                backBufferRenderTarget.EndDraw();

                swapChain.Present(0, Microsoft.WindowsAPICodePack.DirectX.Graphics.PresentOptions.None);
            }
        }
 public void SetViewAndProjection(Matrix4x4F view, Matrix4x4F projection)
 {
     viewVariable.Matrix       = view;
     projectionVariable.Matrix = projection;
 }
예제 #37
0
        void RenderScene()
        {
            lock (syncObject)
            {
                if (device == null)
                    CreateDeviceResources();

                if (!pause)
                {
                    if (lastSavedDelta != 0)
                    {
                        startTime = Environment.TickCount - lastSavedDelta;
                        lastSavedDelta = 0;
                    }
                    currentTimeVariation = (Environment.TickCount - startTime)/6000.0f;
                    worldMatrix = MatrixMath.MatrixTranslate(0, 0, currentTimeVariation);
                    textBrush.Transform = Matrix3x2F.Translation(0, (4096f/16f)*currentTimeVariation);
                }

                device.ClearDepthStencilView(
                    depthStencilView,
                    ClearFlag.Depth,
                    1,
                    0
                    );

                // Clear the back buffer
                device.ClearRenderTargetView(renderTargetView, backColor);

                diffuseVariable.SetResource(null);

                technique.GetPassByIndex(0).Apply();

                // Draw the D2D content into our D3D surface
                RenderD2DContentIntoSurface();

                diffuseVariable.SetResource(
                    textureResourceView
                    );

                // Update variables
                worldMatrixVariable.Matrix = worldMatrix;

                // Set index buffer
                device.IA.SetIndexBuffer(
                    facesIndexBuffer,
                    Format.R16_UINT,
                    0
                    );

                // Draw the scene
                technique.GetPassByIndex(0).Apply();

                device.DrawIndexed((uint) Marshal.SizeOf(VertexArray.VerticesInstance), 0, 0);

                swapChain.Present(0, PresentFlag.Default);
            }
        }
예제 #38
0
        private void Initialize3DTransformations(uint nWidth, uint nHeight)
        {
            worldVariable = shader.GetVariableByName("World").AsMatrix;
            viewVariable = shader.GetVariableByName("View").AsMatrix;
            projectionVariable = shader.GetVariableByName("Projection").AsMatrix;
            diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource;

            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix.
            Vector3F eye = new Vector3F(0.0f, 2.0f, -6.0f);
            Vector3F at = new Vector3F(0.0f, 0.0f, 0.0f);
            Vector3F up = new Vector3F(0.0f, 1.0f, 0.0f);
            viewMatrix = Camera.MatrixLookAtLH(eye, at, up);
            viewVariable.Matrix = viewMatrix;

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float)Math.PI * 0.24f, // fovy
                nWidth / (float)nHeight, // aspect
                0.1f, // zn
                100.0f // zf
                );
            projectionVariable.Matrix = projectionMatrix;
        }
예제 #39
0
        void host_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            lock (syncObject)
            {
                if (device == null)
                    return;
                uint nWidth = (uint)host.ActualWidth;
                uint nHeight = (uint)host.ActualHeight;

                device.OM.SetRenderTargets(new RenderTargetView[] { null }, null);
                //need to remove the reference to the swapchain's backbuffer to enable ResizeBuffers() call
                renderTargetView.Dispose();
                depthStencilView.Dispose();
                depthStencil.Dispose();

                device.RS.SetViewports(null);

                SwapChainDescription sd = swapChain.Description;
                //Change the swap chain's back buffer size, format, and number of buffers
                swapChain.ResizeBuffers(
                    sd.BufferCount,
                    nWidth,
                    nHeight,
                    sd.BufferDescription.Format,
                    sd.Flags);

                using (Texture2D pBuffer = swapChain.GetBuffer<Texture2D>(0))
                {
                    renderTargetView = device.CreateRenderTargetView(pBuffer);
                }

                InitializeDepthStencil(nWidth, nHeight);

                // bind the views to the device
                device.OM.SetRenderTargets(new[] { renderTargetView }, depthStencilView);

                SetViewport(nWidth, nHeight);

                // update the aspect ratio
                projectionMatrix = Camera.MatrixPerspectiveFovLH(
                    (float)Math.PI * 0.1f, // fovy
                    nWidth / (float)nHeight, // aspect
                    0.1f, // zn
                    100.0f // zf
                    );
                projectionMarixVariable.Matrix = projectionMatrix;
            }
        }
예제 #40
0
        void CreateDeviceResources()
        {
            uint width = (uint) host.ActualWidth;
            uint height = (uint) host.ActualHeight;

            // If we don't have a device, need to create one now and all
            // accompanying D3D resources.
            CreateDevice();

            DXGIFactory dxgiFactory = DXGIFactory.CreateFactory();

            SwapChainDescription swapDesc = new SwapChainDescription();
            swapDesc.BufferDescription.Width = width;
            swapDesc.BufferDescription.Height = height;
            swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM;
            swapDesc.BufferDescription.RefreshRate.Numerator = 60;
            swapDesc.BufferDescription.RefreshRate.Denominator = 1;
            swapDesc.SampleDescription.Count = 1;
            swapDesc.SampleDescription.Quality = 0;
            swapDesc.BufferUsage = UsageOption.RenderTargetOutput;
            swapDesc.BufferCount = 1;
            swapDesc.OutputWindowHandle = host.Handle;
            swapDesc.Windowed = true;

            swapChain = dxgiFactory.CreateSwapChain(
                device, swapDesc);

            // Create rasterizer state object
            RasterizerDescription rsDesc = new RasterizerDescription();
            rsDesc.AntialiasedLineEnable = false;
            rsDesc.CullMode = CullMode.None;
            rsDesc.DepthBias = 0;
            rsDesc.DepthBiasClamp = 0;
            rsDesc.DepthClipEnable = true;
            rsDesc.FillMode = D3D10.FillMode.Solid;
            rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9
            rsDesc.MultisampleEnable = false;
            rsDesc.ScissorEnable = false;
            rsDesc.SlopeScaledDepthBias = 0;

            rasterizerState = device.CreateRasterizerState(
                rsDesc);

            device.RS.SetState(
                rasterizerState
                );

            // If we don't have a D2D render target, need to create all of the resources
            // required to render to one here.
            // Ensure that nobody is holding onto one of the old resources
            device.OM.SetRenderTargets(new RenderTargetView[] {null});

            InitializeDepthStencil(width, height);

            // Create views on the RT buffers and set them on the device
            RenderTargetViewDescription renderDesc = new RenderTargetViewDescription();
            renderDesc.Format = Format.R8G8B8A8_UNORM;
            renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D;
            renderDesc.Texture2D.MipSlice = 0;

            using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0))
            {
                renderTargetView = device.CreateRenderTargetView(
                    spBackBufferResource,
                    renderDesc);
            }

            device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView);

            SetViewport(width, height);


            // Create a D2D render target which can draw into the surface in the swap chain
            RenderTargetProperties props =
                new RenderTargetProperties(
                    RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                    96, 96, RenderTargetUsage.None, FeatureLevel.Default);

            // Allocate a offscreen D3D surface for D2D to render our 2D content into
            Texture2DDescription tex2DDescription;
            tex2DDescription.ArraySize = 1;
            tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource;
            tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified;
            tex2DDescription.Format = Format.R8G8B8A8_UNORM;
            tex2DDescription.Height = 4096;
            tex2DDescription.Width = 512;
            tex2DDescription.MipLevels = 1;
            tex2DDescription.MiscFlags = 0;
            tex2DDescription.SampleDescription.Count = 1;
            tex2DDescription.SampleDescription.Quality = 0;
            tex2DDescription.Usage = Usage.Default;

            offscreenTexture = device.CreateTexture2D(tex2DDescription);

            using (Surface dxgiSurface = offscreenTexture.GetDXGISurface())
            {
                // Create a D2D render target which can draw into our offscreen D3D surface
                renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget(
                    dxgiSurface,
                    props);
            }

            PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied);

            opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None,
                                                                            alphaOnlyFormat);

            // Load pixel shader
            // Open precompiled vertex shader
            // This file was compiled using DirectX's SDK Shader compilation tool: 
            // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx
            shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo");

            // Obtain the technique
            technique = shader.GetTechniqueByName("Render");

            // Obtain the variables
            worldMatrixVariable = shader.GetVariableByName("World").AsMatrix();
            viewMatrixVariable = shader.GetVariableByName("View").AsMatrix();
            projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix();
            diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource();

            // Create the input layout
            PassDescription passDesc = new PassDescription();
            passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayoutDescriptions,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.SetInputLayout(
                vertexLayout
                );

            IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance));
            Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true);

            BufferDescription bd = new BufferDescription();
            bd.Usage = Usage.Default;
            bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance);
            bd.BindFlags = BindFlag.VertexBuffer;
            bd.CpuAccessFlags = CpuAccessFlag.Unspecified;
            bd.MiscFlags = ResourceMiscFlag.Undefined;

            SubresourceData InitData = new SubresourceData()
                                           {
                                               SysMem = verticesDataPtr
                                           };


            vertexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(verticesDataPtr);

            // Set vertex buffer
            uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0,
                new D3DBuffer[] {vertexBuffer},
                new uint[] {stride},
                new uint[] {offset}
                );

            IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance));
            Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true);

            bd.Usage = Usage.Default;
            bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance);
            bd.BindFlags = BindFlag.IndexBuffer;
            bd.CpuAccessFlags = 0;
            bd.MiscFlags = 0;

            InitData.SysMem = indicesDataPtr;

            facesIndexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(indicesDataPtr);

            // Set primitive topology
            device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList);

            // Convert the D2D texture into a Shader Resource View
            textureResourceView = device.CreateShaderResourceView(
                offscreenTexture);

            // Initialize the world matrices
            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f);
            Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f);
            Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float) Math.PI*0.1f,
                width/(float) height,
                0.1f,
                100.0f);

            // Update Variables that never change
            viewMatrixVariable.Matrix = viewMatrix;

            projectionMarixVariable.Matrix = projectionMatrix;

            GradientStop[] gradientStops =
                {
                    new GradientStop(0.0f, new ColorF(Colors.Yellow)),
                    new GradientStop(1.0f, new ColorF(Colors.Black))
                };

            GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection(
                gradientStops,
                Gamma.Gamma_22,
                ExtendMode.Clamp);

            // Create a linear gradient brush for text
            textBrush = renderTarget.CreateLinearGradientBrush(
                new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)),
                spGradientStopCollection
                );
        }
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(sd.BufferCount, (uint)directControl.ClientSize.Width, (uint)directControl.ClientSize.Height, sd.BufferDescription.Format, sd.Options);
                SetViews();
                // Update the projection matrix
                projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)directControl.ClientSize.Width / (float)directControl.ClientSize.Height), 0.1f, 100.0f);
                projectionVariable.Matrix = projectionMatrix;
            }
            Matrix4x4F worldMatrix1;
            Matrix4x4F worldMatrix2;

            t = (Environment.TickCount - dwTimeStart) / 50.0f;

            // 1st Cube: Rotate around the origin
            //WPF transforms used here use degrees as opposed to D3DX which uses radians in the native tutorial
            //360 degrees == 2 * Math.PI
            //world1 matrix rotates the first cube by t degrees
            RotateTransform3D rt1 = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), t));
            worldMatrix1 = rt1.Value.ToMatrix4x4F();

            // 2nd Cube:  Rotate around the 1st cube
            Transform3DGroup tg = new Transform3DGroup();
            //spin the cube
            tg.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 0, 1), -t)));
            //scale it down
            tg.Children.Add(new ScaleTransform3D(0.3, 0.3, 0.3));
            //translate it (move to orbit)
            tg.Children.Add(new TranslateTransform3D(-4, 0, 0));
            //orbit around the big cube
            tg.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), -2 * t)));
            worldMatrix2 = tg.Value.ToMatrix4x4F();

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            // Clear the depth buffer to 1.0 (max depth)
            device.ClearDepthStencilView(depthStencilView, ClearOptions.Depth, 1.0f, (byte)0);

            TechniqueDescription techDesc = technique.Description;

            //
            // Update variables that change once per frame
            //
            worldVariable.Matrix = worldMatrix1;

            //
            // Render the 1st cube
            //
            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            //
            // Render the 2nd cube
            //
            worldVariable.Matrix = worldMatrix2;
            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            swapChain.Present(0, PresentOptions.None);
        } 
예제 #42
0
        void RenderScene()
        {
            lock (syncObject)
            {
                //initialize D3D device and D2D render targets the first time we get here
                if (device == null)
                {
                    CreateDeviceResources();
                }

                //tick count is used to control animation and calculate FPS
                int currentTime = Environment.TickCount;
                if (!startTime.HasValue)
                {
                    startTime = currentTime;
                }

                currentTicks = currentTime - startTime.GetValueOrDefault();

                float a = (currentTicks * 360.0f) * ((float)Math.PI / 180.0f) * 0.0001f;
                worldMatrix = MatrixMath.MatrixRotationY(a);

                // Swap chain will tell us how big the back buffer is
                SwapChainDescription swapDesc = swapChain.Description;
                uint nWidth  = swapDesc.BufferDescription.Width;
                uint nHeight = swapDesc.BufferDescription.Height;

                device.ClearDepthStencilView(
                    depthStencilView, ClearOptions.Depth,
                    1, 0
                    );

                // Draw a gradient background before we draw the cube
                if (backBufferRenderTarget != null)
                {
                    backBufferRenderTarget.BeginDraw();

                    backBufferGradientBrush.Transform =
                        Matrix3x2F.Scale(
                            backBufferRenderTarget.Size,
                            new Point2F(0.0f, 0.0f));

                    RectF rect = new RectF(
                        0.0f, 0.0f,
                        nWidth,
                        nHeight);

                    backBufferRenderTarget.FillRectangle(rect, backBufferGradientBrush);
                    backBufferRenderTarget.EndDraw();
                }

                diffuseVariable.Resource = null;
                technique.GetPassByIndex(0).Apply();

                // Draw the D2D content into a D3D surface.
                RenderD2DContentIntoTexture();

                // Pass the updated texture to the pixel shader
                diffuseVariable.Resource = textureResourceView;

                // Update variables that change once per frame.
                worldVariable.Matrix = worldMatrix;

                // Set the index buffer.
                device.IA.IndexBuffer = new IndexBuffer(facesIndexBuffer, Format.R16UInt, 0);

                // Render the scene
                technique.GetPassByIndex(0).Apply();

                device.DrawIndexed(vertexArray.s_FacesIndexArray.Length, 0, 0);

                // Update fps
                currentTime  = Environment.TickCount; // Get the ticks again
                currentTicks = currentTime - startTime.GetValueOrDefault();
                if ((currentTime - lastTicks) > 250)
                {
                    fps       = (swapChain.LastPresentCount) / (currentTicks / 1000f);
                    lastTicks = currentTime;
                }

                backBufferRenderTarget.BeginDraw();

                // Draw fps
                backBufferRenderTarget.DrawText(
                    String.Format("Average FPS: {0:F1}", fps),
                    textFormatFps,
                    new RectF(
                        10f,
                        nHeight - 32f,
                        nWidth,
                        nHeight
                        ),
                    backBufferTextBrush
                    );

                backBufferRenderTarget.EndDraw();

                swapChain.Present(0, Microsoft.WindowsAPICodePack.DirectX.Graphics.PresentOptions.None);
            }
        }
예제 #43
0
        private void InitMatrices()
        {
            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 3.0f, -6.0f);
            Vector3F At = new Vector3F(0.0f, 0.0f, 0.0f);
            Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Microsoft.WindowsAPICodePack.DirectX.DirectXUtilities.Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)host.ActualWidth / (float)host.ActualHeight), 0.5f, 100.0f);

            // Update Variables that never change
            viewVariable.Matrix = viewMatrix;
            projectionVariable.Matrix = projectionMatrix;
        }
예제 #44
0
        private void PlayButton_Click(object sender, EventArgs e)
        {
            if (!CheckState())
            {
                return;
            }

            if (GRBLMachinePlugin.Props.ToolChangeProcess == IgnoreProcessPassOn.Process)
            {
                string post = CamBamUI.MainUI.ActiveView.CADFile.MachiningOptions.PostProcessor;

                if (!string.IsNullOrEmpty(post) && post != "GRBLMachine")
                {
                    switch (MessageBox.Show("The Post Processor in Machining Options is not 'GRBLMachine'.\r\n\r\nSet Post Processor to 'GRBLMachine' and regenerate GCODE ?", "GRBLMachine - Play", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question))
                    {
                    case DialogResult.Yes:
                        CamBamUI.MainUI.ActiveView.CADFile.MachiningOptions.PostProcessor = "GRBLMachine";
                        CAMUtils.GenerateGCodeOutput(CamBamUI.MainUI.ActiveView);
                        break;

                    case DialogResult.Cancel:
                        return;

                    case DialogResult.No:
                        break;
                    }
                }
            }

            if (GRBLMachinePlugin.Props.TrackMachine == EnabledDisabled.Enabled)
            {
                CamBamUI ui = CamBamUI.MainUI;

                // turn toolpaths et al on
                ui.ActiveView.CADFile.ShowToolpaths       = true;
                ui.ActiveView.CADFile.ShowRapids          = true;
                ui.ActiveView.CADFile.ShowDirectionVector = true;
                ui.ViewContextMenus.RefreshCheckedMenus();

                // runs in background, so just start it, we'll do something else in the meanwhile
                CAMUtils.GenerateToolpaths(ui.ActiveView);

                // fit current drawing and current perspective to fit view
                ui.ActiveView.ZoomToFitEx();

                // setup ISO-like perspective ( inspired from ViewToolbarAddins (y) )
                ViewProjection vp = ui.ActiveView.ViewProjection;
                Matrix4x4F     mx = Matrix4x4F.Identity;

                mx.Scale(vp.ViewMatrix4x4F.GetScale());
                mx.RotZ(-Math.PI / 4f);                 // 90 degrees
                mx.RotX(-Math.PI / (4f * (60f / 90f))); // 60 degrees
                mx.Translate(vp.ViewMatrix4x4F.m[12], vp.ViewMatrix4x4F.m[13], vp.ViewMatrix4x4F.m[14]);

                vp.ViewMatrix4x4F = mx;

                // re-zoom, since drawing may now be outside the view
                ui.ActiveView.ZoomToFitEx();

                // wait until GenerateToolpaths is ready
                while (ui.ActiveView.IsThinking)
                {
                    Application.DoEvents();
                }

                // re-zoom, since toolpaths may be outside the view
                ui.ActiveView.ZoomToFitEx();
            }

            _sendingFileName          = FileName.Text;
            _writeThread              = new Thread(WriteThread);
            _writeThread.Name         = "GCODE-SenderThread";
            _writeThread.IsBackground = true;

            PauseButton.Checked = false;

            EnableButtons();

            FileName.Enabled     = false;
            BrowseButton.Enabled = false;
            LinesSent.Text       = LinesTotal.Text = "-";

            _pauseEvent.Set();
            _fileData.Clear();

            _writeThread.Start();
        }
예제 #45
0
 protected override void OnSizeChanged(EventArgs e)
 {
     if (active)
     {
         renderTargetView.Dispose();
         SwapChainDescription sd = swapChain.Description;
         swapChain.ResizeBuffers(sd.BufferCount, (uint)ClientSize.Width, (uint)ClientSize.Height, sd.BufferDescription.Format, sd.Flags);
         SetViews();
         // Update the projection matrix
         projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)ClientSize.Width / (float)ClientSize.Height), 0.5f, 100.0f);
         projectionVariable.Matrix = projectionMatrix;
     }
     base.OnSizeChanged(e);
 }
예제 #46
0
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(sd.BufferCount, (uint)directControl.ClientSize.Width, (uint)directControl.ClientSize.Height, sd.BufferDescription.Format, sd.Flags);
                SetViews();
                // Update the projection matrix
                projectionMatrix = Microsoft.WindowsAPICodePack.DirectX.DirectXUtilities.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)directControl.ClientSize.Width / (float)directControl.ClientSize.Height), 0.5f, 100.0f);
                projectionVariable.Matrix = projectionMatrix;
            }
            Matrix4x4F worldMatrix;

            t = (Environment.TickCount - dwTimeStart) / 50.0f;

            //WPF transforms used here use degrees as opposed to D3DX which uses radians in the native tutorial
            //360 degrees == 2 * Math.PI
            //world matrix rotates the first cube by t degrees
            RotateTransform3D rt1 = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), t));
            worldMatrix = rt1.Value.ToMatrix4x4F();

            //Setup our lighting parameters
            Vector4F[] vLightDirs =
            {
                new Vector4F( -0.577f, 0.577f, -0.577f, 1.0f ),
                new Vector4F( 0.0f, 0.0f, -1.0f, 1.0f )
            };
            Vector4F[] vLightColors = 
            {
                new Vector4F ( 0.5f, 0.5f, 0.5f, 1.0f ),
                new Vector4F ( 0.5f, 0.0f, 0.0f, 1.0f )
            };

            //rotate the second light around the origin
            //create a rotation matrix
            RotateTransform3D rt2 = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 2, 0), -t));
            //rotate vLightDirs[1] vector using the rotation matrix
            Vector3D vDir = new Vector3D(vLightDirs[1].X, vLightDirs[1].Y, vLightDirs[1].Z);
            vDir = rt2.Transform(vDir);
            vLightDirs[1].X = (float)vDir.X;
            vLightDirs[1].Y = (float)vDir.Y;
            vLightDirs[1].Z = (float)vDir.Z;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            // Clear the depth buffer to 1.0 (max depth)
            device.ClearDepthStencilView(depthStencilView, ClearFlag.Depth, 1.0f, (byte)0);

            //
            // Update variables that change once per frame
            //
            worldVariable.Matrix = worldMatrix;
            lightDirVariable.SetFloatVectorArray(vLightDirs);
            lightColorVariable.SetFloatVectorArray(vLightColors);

            //
            // Render the cube
            //
            TechniqueDescription techDesc = technique.Description;
            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            //
            // Render each light
            //
            TechniqueDescription techLightDesc = techniqueLight.Description;
            for (int m = 0; m < 2; m++)
            {
                Vector3F vLightPos = new Vector3F(vLightDirs[m].X * 5, vLightDirs[m].Y * 5, vLightDirs[m].Z * 5);
                Transform3DGroup tg = new Transform3DGroup();
                tg.Children.Add(new ScaleTransform3D(0.2, 0.2, 0.2));
                tg.Children.Add(new TranslateTransform3D(vLightPos.X, vLightPos.Y, vLightPos.Z));
                worldVariable.Matrix = tg.Value.ToMatrix4x4F();
                outputColorVariable.FloatVector = new Vector4F (vLightColors[m].X, vLightColors[m].Y, vLightColors[m].Z, vLightColors[m].W);

                for (uint p = 0; p < techLightDesc.Passes; ++p)
                {
                    techniqueLight.GetPassByIndex(p).Apply();
                    device.DrawIndexed(36, 0, 0);
                }
            }

            swapChain.Present(0, PresentFlag.Default);
        } 
예제 #47
0
        private void InitMatrices()
        {
            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 3.0f, -6.0f);
            Vector3F At = new Vector3F(0.0f, 0.0f, 0.0f);
            Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = DXUtil.Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)this.ClientSize.Width / (float)this.ClientSize.Height), 0.5f, 100.0f);

            // Update Variables that never change
            viewVariable.Matrix = viewMatrix;
            projectionVariable.Matrix = projectionMatrix;
        }
예제 #48
0
        /// <summary>
        /// Renders the mesh with the specified transformation
        /// </summary>
        /// <param name="modelTransform"></param>
        public void Render( Matrix4x4F modelTransform )
        {
            rDescription.FillMode = wireFrame ? FillMode.Wireframe : FillMode.Solid;
            // setup rasterization
            using (RasterizerState rState = this.manager.device.CreateRasterizerState(rDescription))
            {
                this.manager.device.RS.SetState(rState);
                this.manager.brightnessVariable.FloatValue = this.lightIntensity;

                // start rendering
                foreach (Part part in scene.parts)
                {
                    EffectTechnique technique = null;
                    if (part.material == null)
                    {
                        technique = this.manager.techniqueRenderVertexColor;
                    }
                    else
                    {
                        if (part.material.textureResource != null)
                        {
                            technique = this.manager.techniqueRenderTexture;
                            this.manager.diffuseVariable.SetResource(part.material.textureResource);
                        }
                        else
                        {
                            technique = this.manager.techniqueRenderMaterialColor;
                            this.manager.materialColorVariable.FloatVector = part.material.materialColor;
                        }
                    }

                    // set part transform
                    Transform3DGroup partGroup = new Transform3DGroup();
                    partGroup.Children.Add(new MatrixTransform3D(PartAnimation(part.name)));
                    partGroup.Children.Add(new MatrixTransform3D(part.partTransform.ToMatrix3D()));
                    partGroup.Children.Add(new MatrixTransform3D(scene.sceneTransform.ToMatrix3D()));
                    partGroup.Children.Add(new MatrixTransform3D(modelTransform.ToMatrix3D()));
                    this.manager.worldVariable.Matrix = partGroup.Value.ToMatrix4x4F();

                    if (part.vertexBuffer != null)
                    {
                        //set up vertex buffer and index buffer
                        uint stride = (uint)Marshal.SizeOf(typeof(XMeshVertex));
                        uint offset = 0;
                        this.manager.device.IA.SetVertexBuffers(0, new D3DBuffer[] { part.vertexBuffer }, new uint[] { stride }, new uint[] { offset });

                        //Set primitive topology
                        this.manager.device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList);

                        TechniqueDescription techDesc = technique.Description;
                        for (uint p = 0; p < techDesc.Passes; ++p)
                        {
                            technique.GetPassByIndex(p).Apply();
                            PassDescription passDescription = technique.GetPassByIndex(p).Description;

                            using (InputLayout inputLayout = this.manager.device.CreateInputLayout(
                                    part.dataDescription,
                                    passDescription.InputAssemblerInputSignature,
                                    passDescription.InputAssemblerInputSignatureSize))
                            {
                                // set vertex layout
                                this.manager.device.IA.SetInputLayout(inputLayout);

                                // draw part
                                this.manager.device.Draw((uint)part.vertexCount, 0);
                                this.manager.device.IA.SetInputLayout(null);
                            }
                        }
                    }
                }
                this.manager.device.RS.SetState(null);
            }
        }
예제 #49
0
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(
                    sd.BufferCount,
                    (uint)directControl.ClientSize.Width,
                    (uint)directControl.ClientSize.Height,
                    sd.BufferDescription.Format,
                    sd.Options);
                SetViews();
                // Update the projection matrix
                InitMatrices();
            }
            int dwCurrentTime = Environment.TickCount;
            float t = (dwCurrentTime - dwLastTime) / 1000f;
            dwLastTime = dwCurrentTime;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            // Clear the depth buffer to 1.0 (max depth)
            device.ClearDepthStencilView(depthStencilView, ClearOptions.Depth, 1.0f, (byte)0);

            lock (meshLock)
            {
                if (mesh != null)
                {
                    if (cbRotate.Checked)
                        worldMatrix *= MatrixMath.MatrixRotationY(-t);
                    mesh.Render(worldMatrix);
                }
            }

            Microsoft.WindowsAPICodePack.DirectX.ErrorCode error;
            swapChain.TryPresent(1, PresentOptions.None, out error);
        }
예제 #50
0
        /// <summary>
        /// Render the frame
        /// </summary>
        protected void RenderScene()
        {
            if (needsResizing)
            {
                needsResizing = false;
                renderTargetView.Dispose();
                SwapChainDescription sd = swapChain.Description;
                swapChain.ResizeBuffers(sd.BufferCount, (uint)directControl.ClientSize.Width, (uint)directControl.ClientSize.Height, sd.BufferDescription.Format, sd.Options);
                SetViews();
                // Update the projection matrix
                projectionMatrix = DXUtil.Camera.MatrixPerspectiveFovLH((float)Math.PI * 0.25f, ((float)directControl.ClientSize.Width / (float)directControl.ClientSize.Height), 0.5f, 100.0f);
                projectionVariable.Matrix = projectionMatrix;
            }
            Matrix4x4F worldMatrix;

            currentTime = (Environment.TickCount - dwTimeStart) / 1000.0f;

            //WPF transforms used here use degrees as opposed to D3DX which uses radians in the native tutorial
            //360 degrees == 2 * Math.PI
            //world matrix rotates the first cube by t degrees
            RotateTransform3D rt1 = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), currentTime*30));
            worldMatrix = rt1.Value.ToMatrix4x4F();

            // Modify the color
            meshColor.X = ((float)Math.Sin(currentTime * 1.0f) + 1.0f) * 0.5f;
            meshColor.Y = ((float)Math.Cos(currentTime * 3.0f) + 1.0f) * 0.5f;
            meshColor.Z = ((float)Math.Sin(currentTime * 5.0f) + 1.0f) * 0.5f;

            // Clear the backbuffer
            device.ClearRenderTargetView(renderTargetView, backColor);

            //
            // Update variables that change once per frame
            //
            worldVariable.Matrix = worldMatrix;
            meshColorVariable.FloatVector = meshColor;

            //
            // Render the cube
            //
            TechniqueDescription techDesc = technique.Description;
            for (uint p = 0; p < techDesc.Passes; ++p)
            {
                technique.GetPassByIndex(p).Apply();
                device.DrawIndexed(36, 0, 0);
            }

            swapChain.Present(0, PresentOptions.None);
        } 
        //
        // CADFile & Co Stuff
        //
        #region CADFile, Parts, MOPs and Tools

        //
        // Extents
        //
        /// <summary>
        /// Extension to GetScreenExtents
        ///
        /// Original does not take Toolpaths into account
        /// </summary>
        /// <param name="cadfile"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <param name="t"></param>
        public static void GetScreenExtentsEx(this CADFile cadfile, ref PointF min, ref PointF max, Matrix4x4F t)
        {
            cadfile.GetScreenExtents(ref min, ref max, t);

            PointF localMin = PointF.Empty;
            PointF localMax = PointF.Empty;

            foreach (CAMPart part in cadfile.Parts)
            {
                foreach (MachineOp mop in part.MachineOps)
                {
                    if (mop.Toolpaths2 != null)
                    {
                        foreach (ToolpathItem item in mop.Toolpaths2.Toolpaths)
                        {
                            item.Toolpath.GetScreenExtents(ref localMin, ref localMax, item.Toolpath.Transform * t, CamBamConfig.Defaults.ViewProjectionMode == ProjectionModes.Perspective);

                            if (double.IsNaN(min.X) || double.IsNaN(max.X) ||
                                double.IsNaN(min.Y) || double.IsNaN(max.Y))
                            {
                                min = localMin;
                                max = localMax;

                                continue;
                            }

                            if (!double.IsNaN(localMax.X))
                            {
                                max.X = Math.Max(max.X, localMax.X);
                            }

                            if (!double.IsNaN(localMax.Y))
                            {
                                max.Y = Math.Max(max.Y, localMax.Y);
                            }

                            if (!double.IsNaN(localMin.X))
                            {
                                min.X = Math.Min(min.X, localMin.X);
                            }

                            if (!double.IsNaN(localMin.Y))
                            {
                                min.Y = Math.Min(min.Y, localMin.Y);
                            }
                        }
                    }
                }
            }
        }