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

📄 d3dtriangle.cs

📁 Particle System Test Application on C#
💻 CS
📖 第 1 页 / 共 2 页
字号:
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using ParticleSystems.Verlet;
using ParticleSystems.Verlet.GlobalConstraints;
using ParticleSystems.Verlet.Constraints;
using ParticleSystems.Verlet.Effects;
using ParticleSystems.Verlet.Tools;
using Direct3D=Microsoft.DirectX.Direct3D;

public delegate void MessageDelegate(byte message); // Delegate for messages arriving via DirectPlay.
public delegate void AudioDelegate(); // Delegate to handle audio playback.
public delegate void PeerCloseCallback(); // This delegate will be called when the session terminated event is fired.

public class GraphicsClass : GraphicsSample
{
    private float x = 0;
    private float y = 0;
    private int bufferSize = 10000;
    private GraphicsFont drawingFont = null;
    private VertexBuffer linesVertexBuffer = null;
    private int renderedLines = 0;
    private int LastTick = Environment.TickCount;
    private int Elapsed = Environment.TickCount;
    private Point destination = new Point(0, 0);
    private ParticleSystem particleSystem = new ParticleSystem(0.02f);
    private bool updating = false;
    private Wind windEffect;

    public GraphicsClass()
    {
        this.MinimumSize = new Size(200,100);
        this.Text = "ParticleSystemTestApplication";
        this.KeyDown += new KeyEventHandler(this.OnPrivateKeyDown);
        this.KeyUp += new KeyEventHandler(this.OnPrivateKeyUp);
        drawingFont = new GraphicsFont( "Arial", System.Drawing.FontStyle.Bold );

        InitializeParticleSystem(particleSystem, out windEffect);
    }

    /// <summary>
    /// Initialize the particle system
    /// </summary>
    /// <param name="ps">A particle system</param>
    /// <param name="windEffect">out: A wind effect</param>
    static void InitializeParticleSystem(ParticleSystem ps, out Wind windEffect)
    {
        ParticleSystem.Transaction lTransaction = 
            ps.GetTransaction();

        // Set the gravity of the particle system
        ps.Gravity = new Vector3(0, -1, 0);

        // Create axis aligned box global constraint ( to prevent the particles
        // from falling out of view)
        Vector3 lCorner = new Vector3(-10, -15, -10);
        Vector3 lOppositeCorner = new Vector3(10, 15, 10);
        lTransaction.AddGlobalConstraint(new AxisAlignedBox(
            lCorner, 
            lOppositeCorner));

        // Create a RopeConstraintFactory for our parachute
        Tools.ITwoParticleConstraintFactory lConstraintFactory = 
            new Tools.RopeConstraintFactory(1.5f);

        // Generate a mesh of rope constraints. This will be the cloth of the 
        // parachute
        Particle[] lMeshParticles;
        int lParticleAlongXAxis = 10;
        int lParticleAlongYAxis = 10;
        {
            // The mesh is created in the x-y plane. We want it to be in the
            // x-z plane. Therefore rotate it
            Matrix lRotationMatrix = Matrix.RotationX((float)(Math.PI / 2.0));
            // Scale it as well
            Matrix lScaleMatrix = Matrix.Scaling(5.0f, 5.0f, 5.0f);

            // Create the mesh
            lMeshParticles = Tools.CreateMesh(
                10.0f, 
                lParticleAlongXAxis, 
                lParticleAlongYAxis, 
                lScaleMatrix * lRotationMatrix, 
                lConstraintFactory, 
                lTransaction);
        }

        // Index of the four corners of the mesh
        int l00CornerIndex = 0;
        int l01CornerIndex = lParticleAlongYAxis - 1;
        int l10CornerIndex = (lParticleAlongXAxis - 1)* lParticleAlongYAxis;
        int l11CornerIndex = lParticleAlongXAxis * lParticleAlongYAxis - 1;

        // Insert stick constraints between the corners to prevent the parachute
        // from falling together
        lTransaction.AddConstraint(new Stick(lMeshParticles[l00CornerIndex], lMeshParticles[l01CornerIndex]));
        lTransaction.AddConstraint(new Stick(lMeshParticles[l01CornerIndex], lMeshParticles[l11CornerIndex]));
        lTransaction.AddConstraint(new Stick(lMeshParticles[l11CornerIndex], lMeshParticles[l10CornerIndex]));
        lTransaction.AddConstraint(new Stick(lMeshParticles[l10CornerIndex], lMeshParticles[l00CornerIndex]));
        lTransaction.AddConstraint(new Stick(lMeshParticles[l11CornerIndex], lMeshParticles[l00CornerIndex]));
        lTransaction.AddConstraint(new Stick(lMeshParticles[l10CornerIndex], lMeshParticles[l01CornerIndex]));

        // Create a StickConstraint factory for our brave parachuter
        Tools.ITwoParticleConstraintFactory lStickConstraintFactory = 
            new Tools.StickConstraintFactory();

        Particle[] lJumperParticles;
        {
            // Translate the parachuter
            Matrix lTranslateMatrix = Matrix.Translation(0.0f, -5.0f, 0.0f);
            // And scale it
            Matrix lScaleMatrix = Matrix.Scaling(2.0f, 2.0f, 2.0f);

            Tools.IParticlePreProcessor lMatrixTransformPreProcessor = 
                new Tools.MatrixTransformParticlePreProcessor(lScaleMatrix * lTranslateMatrix);

            // This is an advanced feature. We want the top of the parachuter
            // to be "squeezed" together a bit. This is a nonlinear transform
            // which means we can't do it using matrices. However, 
            // SqueezeParticlePreProcessor comes to the rescure. We chain the 
            // this preprocessor together with the scale and rotation 
            // preprocessor
            Tools.IParticlePreProcessor lPreprocessor = 
                new Tools.SqueezeParticlePreProcessor(
                new Vector3(0.0f, -0.5f, 0.0f), 
                0.25f,
                new Vector3(1.0f, 0.0f, 1.0f),
                lMatrixTransformPreProcessor);

            // Create our parachuter
            lJumperParticles = Tools.CreateBox(
                100.0f, 
                lPreprocessor,
                lStickConstraintFactory, 
                lTransaction);
        }

        // Attach chains of rope constraints between the parachuter and the 
        // parachute. We use chains as it looks nicer. A simple rope constraint
        // would have a similar effect
        Tools.CreateChain(lJumperParticles[2], lMeshParticles[l00CornerIndex], 1.0f, 5, lConstraintFactory, lTransaction);
        Tools.CreateChain(lJumperParticles[3], lMeshParticles[l01CornerIndex], 1.0f, 5, lConstraintFactory, lTransaction);
        Tools.CreateChain(lJumperParticles[6], lMeshParticles[l10CornerIndex], 1.0f, 5, lConstraintFactory, lTransaction);
        Tools.CreateChain(lJumperParticles[7], lMeshParticles[l11CornerIndex], 1.0f, 5, lConstraintFactory, lTransaction);

        // Add a wind effect that blows upon the particles in the parachute only
        windEffect = new Wind(lMeshParticles, 0.5f, new Vector3(0.0f, 40.0f, 0.0f));
        lTransaction.AddEffect(windEffect);

        // We're done. Commit the changes into the particle system
        lTransaction.Commit();
    }

    /// <summary>
    /// Event Handler for windows messages
    /// </summary>
    private void OnPrivateKeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Up:
            {
                destination.X = 1;
                break;
            }
            case Keys.Down:
            {
                destination.X = -1;
                break;
            }
            case Keys.Left:
            {
                destination.Y = 1;
                break;
            }
            case Keys.Right:
            {
                destination.Y = -1;
                break;
            }
            case Keys.A:
            {
                particleSystem.Gravity = new Vector3(0, -1, 0);
                break;
            }
            case Keys.B:
            {
                particleSystem.Gravity = new Vector3(0, 1, 0);
                break;
            }
            case Keys.S:
            {
                Tools.Shake(10.0f, particleSystem);
                break;
            }
            case Keys.K:
            {
                windEffect.Direction = windEffect.Direction * 1.10f;
                break;
            }
            case Keys.L:
            {
                windEffect.Direction = windEffect.Direction * (1.0f/1.10f);
                break;
            }

        }
    }

    override public void OnUpdateTimer(object sender, System.EventArgs e) 
    {
        if( !updating )
        {
            updating = true;
            try
            {
                particleSystem.TimeStep(5);
                FillVertexBuffer(
                    linesVertexBuffer, 
                    out renderedLines,
                    particleSystem);
            }
            finally
            {
                updating = false;
            }
        }
    }

    private void OnPrivateKeyUp(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Up:
            case Keys.Down:
                destination.X = 0;
                break;
            case Keys.Left:
            case Keys.Right:
            {
                destination.Y = 0;
                break;
            }
        }
    }

    /// <summary>
    /// Called once per frame, the call is the entry point for 3d rendering. This 
    /// function sets up render states, clears the viewport, and renders the scene.
    /// </summary>
    protected override void Render()
    {
        //Clear the backbuffer to a Blue color 
        device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Blue, 1.0f, 0);
        //Begin the scene
        device.BeginScene();

        // Setup the world, view, and projection matrices
        Matrix m = new Matrix();
        
        if( destination.Y != 0 )
            y += DXUtil.Timer(DirectXTimer.GetElapsedTime) * (destination.Y * 25); 

        if( destination.X != 0 )
            x += DXUtil.Timer(DirectXTimer.GetElapsedTime) * (destination.X * 25);

        m = Matrix.RotationY(y);
        m *= Matrix.RotationX(x);

        device.Transform.World = m;
        device.Transform.View = Matrix.LookAtLH( new Vector3( 0.0f, 0.0f, 40.0f ), new Vector3( 0.0f, 0.0f, 0.0f ), new Vector3( 0.0f, 1.0f, 0.0f ) );   
        device.Transform.Projection = Matrix.PerspectiveFovLH( (float)Math.PI / 4, 1.0f, 1.0f, 100.0f );

        // set the vertexbuffer stream source
        device.SetStreamSource(0, linesVertexBuffer, 0, VertexInformation.GetFormatSize(CustomVertex.PositionColored.Format));
        device.VertexFormat = CustomVertex.PositionColored.Format;

        // set fill mode
        device.RenderState.FillMode = FillMode.Solid;
        device.DrawPrimitives(PrimitiveType.LineList, 0, renderedLines );

        device.EndScene();
    }

    /// <summary>
    /// Initialize scene objects.
    /// </summary>
    protected override void InitializeDeviceObjects()
    {
        drawingFont.InitializeDeviceObjects(device);
        
        // Now Create the VB
        linesVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), bufferSize, device, Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);
        linesVertexBuffer.Created += new System.EventHandler(this.OnCreateVertexBuffer);
        this.OnCreateVertexBuffer(linesVertexBuffer, null);
    }

    /// <summary>
    /// Called when a device needs to be restored.
    /// </summary>
    protected override void RestoreDeviceObjects(System.Object sender, System.EventArgs e)
    {

⌨️ 快捷键说明

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