⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 graphicsform.cs

📁 清华大学出版社出版的 移动应用开发宝典 张大威(2008)的附书源代码
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsMobile.DirectX;
using Microsoft.WindowsMobile.DirectX.Direct3D;

namespace MoveTriangle
{


    public partial class GraphicsForm : Form
    {

        public class ImageBackground
        {

            /// <summary>
            /// Texture to be drawn with. Passed into the constructor.
            /// </summary>
            public Texture BackgroundTexture;

            /// <summary>
            /// This defines the shape of our background image and the texture of the 
            /// vertices.
            /// </summary>
            public CustomVertex.PositionNormalTextured[] Vertices;

            /// <summary>
            /// Vertex buffer which is used by the display hardware 
            /// recieve details of what we want to draw.
            /// </summary>
            public VertexBuffer VertBuffer = null;


            public ImageBackground(Device device, System.IO.Stream textureStream, float sz, float z)
            {
                BackgroundTexture = TextureLoader.FromStream(device, textureStream);

                Vertices = new CustomVertex.PositionNormalTextured[6];

                Vertices[0] = new CustomVertex.PositionNormalTextured(
                    -sz, -sz, z,         // position
                    0.0f, 0.0f, -1.0f,   // normal - looking out of the screen 
                    0.0f, 1.0f);

                Vertices[1] = new CustomVertex.PositionNormalTextured(
                    -sz, +sz, z,         // position
                    0.0f, 0.0f, -1.0f,   // normal - looking out of the screen 
                    0.0f, 0.0f);

                Vertices[2] = new CustomVertex.PositionNormalTextured(
                    +sz, -sz, z,          // position
                    0.0f, 0.0f, -1.0f,    // normal - looking out of the screen  
                    1.0f, 1.0f);

                Vertices[3] = new CustomVertex.PositionNormalTextured(
                    +sz, -sz, z,          // position
                    0.0f, 0.0f, -1.0f,    // normal - looking out of the screen  
                    1.0f, 1.0f);
                Vertices[4] = new CustomVertex.PositionNormalTextured(
                    -sz, +sz, z,          // position
                    0.0f, 0.0f, -1.0f,    // normal - looking out of the screen  
                    0.0f, 0.0f);
                Vertices[5] = new CustomVertex.PositionNormalTextured(
                    +sz, +sz, z,          // position
                    0.0f, 0.0f, -1.0f,    // normal - looking out of the screen  
                    1.0f, 0.0f);


                VertBuffer = new VertexBuffer(
                    typeof(CustomVertex.PositionNormalTextured),   // type of the buffer
                    Vertices.Length,                        // holding vertices array
                    device,                                 // for our device
                    Usage.WriteOnly,                        // never going to read it
                    CustomVertex.PositionNormalTextured.Format,    // source format
                    Pool.SystemMemory);                     // mobile 3D requires this
            }

            /// <summary>
            /// Draw the textured image.
            /// </summary>
            /// <param name="device">target device to draw on</param>
            public void Draw(Device device)
            {
                // Set the data in the vertex buffer to our triangles
                VertBuffer.SetData(Vertices, 0, LockFlags.None);

                // clear off any existing transformations
                device.Transform.World = Matrix.Identity;

                // Point the device at our vertex buffer
                device.SetStreamSource(0, VertBuffer, 0);

                // Assign the texture to the device.
                device.SetTexture(0, BackgroundTexture);

                // Ask the device to draw the contents of the buffer
                device.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);

                // Stop using this texture
                device.SetTexture(0, null);

            }
        }

        ImageBackground imageBackground;

        /// <summary>
        /// Currently executing assembly. Cached because it is used
        /// to load a lot of resources. 
        /// </summary>
        readonly System.Reflection.Assembly assembly =
            System.Reflection.Assembly.GetExecutingAssembly();

        /// <summary>
        /// Device we are going to use to render our graphics
        /// </summary>
        private Device device;

        public GraphicsForm()
        {
            InitializeComponent();
        }

        VertexBuffer vertBuffer;

        CustomVertex.PositionColored[] vertices;

        // position of the triangle
        float xPos = 0;
        float yPos = 0;
        float zPos = 0;

        public void InitializeGraphics()
        {
            PresentParameters presentParams = new PresentParameters();
            presentParams.Windowed = true;
            presentParams.SwapEffect = SwapEffect.Discard;

            device = new Device(0, DeviceType.Default, this, CreateFlags.None, presentParams);

            // no need for lighting, we are setting the color of our triangle ourselves
            device.RenderState.Lighting = false;

            // Add the camera to our world and point it at the triangle
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0.0f, 0.0f, -5.0f), // camera position
                new Vector3(0.0f, 0.0f, 0.0f),  // camera target
                new Vector3(0.0f, 1.0f, 0.0f)   // camera up vector
                );

            // Set up the projection for our world
            device.Transform.Projection =
                Matrix.PerspectiveFovLH(
                (float)Math.PI / 4,     // field of view
                1.0f,                   // aspect ratio
                1.0f,                   // near Z plane
                100.0f                  // far Z plane
                );

            // We want to see the back of the triangle - turn off culling
            device.RenderState.CullMode = Cull.None;

            // three vertices for a single triangle
            vertices = new CustomVertex.PositionColored[3];

            // Origin (0,0) is the middle of the screen 
            // The left hand edge is at X=-1, right hand edge at X=1
            // The top is y=1, the bottom is y=-1
            // This triangle will fill the screen

            vertices[0].X = 0.0f; 
            vertices[0].Y = 1.0f; 
            vertices[0].Z = 0.0f; 
            vertices[0].Color = Color.Red.ToArgb();

            vertices[1].X = 1.0f;
            vertices[1].Y = -1.0f; 
            vertices[1].Z = 0.0f; 
            vertices[1].Color = Color.Green.ToArgb();

            vertices[2].X = -1.0f; 
            vertices[2].Y = -1.0f; 
            vertices[2].Z = 0.0f; 
            vertices[2].Color = Color.Blue.ToArgb();

            // Create a vertex buffer to hold our triangle information
            vertBuffer = new VertexBuffer(
                typeof(CustomVertex.PositionColored),   // type of the buffer
                3,                                      // holding 3 vertices
                device,                                 // for our device
                Usage.WriteOnly,                        // never going to read it
                CustomVertex.PositionColored.Format,    // format required
                Pool.SystemMemory);                     // mobile 3D requires this

            // Set the data in the vertex buffer to our triangles
            vertBuffer.SetData(vertices, 0, LockFlags.None);

            imageBackground = new ImageBackground(device,
                assembly.GetManifestResourceStream("MoveTriangle.resources.Background.png"),
                3.0f,
                0.2f);

        }

        // Do not want the system to paint the window background on refresh
        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }

        // Called when the screen is redrawn
        protected override void OnPaint(PaintEventArgs e)
        {
            Render();
        }

        // rotation about Y
        float yawAngle = 0.0f;
        float yawStep = 0.1f;

        // rotation about X
        float pitchAngle = 0.0f;
        float pitchStep = 0.01f;

        // rotation about Z
        float rollAngle = 0.0f;
        float rollStep = 0.001f;

        /// <summary>
        /// Our render method
        /// </summary>
        private void Render()
        {
            // Make the screen white to start with
            device.Clear(ClearFlags.Target, Color.White, 1.0f, 0);

            // Beginning of the draw process
            device.BeginScene();

            // Get the background to draw itself
            imageBackground.Draw(device);

            // Point the device at our vertex buffer
            device.SetStreamSource(0, vertBuffer, 0);

            // Rotate the triangle
            yawAngle += yawStep;
            pitchAngle += pitchStep;
            rollAngle += rollStep;

            // Create a translation matrix to move our triangle
            device.Transform.World = Matrix.RotationYawPitchRoll(yawAngle, pitchAngle, rollAngle) *
                                     Matrix.Translation(xPos, yPos, zPos);

            // Ask the device to draw the contents of the buffer
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);

            // End of the draw process
            device.EndScene();

            // Now present the image on the screen
            device.Present();
        }

        private void exitProgram()
        {
            Application.Exit();
        }

        private void updateTriangle()
        {
            Text = "X:" + vertices[0].X + " Y:" + vertices[0].Y + " Z:" + vertices[0].Z;
            vertBuffer.SetData(vertices, 0, LockFlags.None);
            Invalidate();
        }

        private void resetTriangle()
        {
            xPos = 0.0f;
            yPos = 0.0f;
            zPos = 0.0f;
            updateTriangle();
        }

        private float step = 0.2f;

        private void moveLeft()
        {
            xPos -= step;
            updateTriangle();
        }

        private void moveRight()
        {
            xPos += step;
            updateTriangle();
        }

        private void moveUp()
        {
            yPos += step;
            updateTriangle();
        }

        private void moveDown()
        {
            yPos -= step;
            updateTriangle();
        }

        private void moveTowards()
        {
            zPos -= step;
            updateTriangle();
        }

        private void moveAway()
        {
            zPos += step;
            updateTriangle();
        }


        private void GraphicsForm_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == System.Windows.Forms.Keys.Up))
            {
                moveUp();
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Down))
            {
                moveDown();
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Left))
            {
                moveLeft();
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Right))
            {
                moveRight();
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter))
            {
                resetTriangle();
            }
        }

        private void resetMenuItem_Click(object sender, EventArgs e)
        {
            resetTriangle();
        }

        private void zMinusMenuItem_Click(object sender, EventArgs e)
        {
            moveTowards();
        }

        private void zPlusMenuItem_Click(object sender, EventArgs e)
        {
            moveAway();
        }

        private void yMinusMenuItem_Click(object sender, EventArgs e)
        {
            moveUp();
        }

        private void yPlusMenuItem_Click(object sender, EventArgs e)
        {
            moveDown();
        }

        private void xMinusMenuItem_Click(object sender, EventArgs e)
        {
            moveLeft();
        }

        private void xPulsMenuItem_Click(object sender, EventArgs e)
        {
            moveRight();
        }

        private void exitMenuItem_Click(object sender, EventArgs e)
        {
            exitProgram();
        }

        private void rotateTimer_Tick(object sender, EventArgs e)
        {
            Invalidate();
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -