gr_tut6_screenshot.jpg

SimplePhysics.cs

#region Using directives

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

using Microsoft.DirectX;
using Microsoft.DirectX.DirectSound;
using Microsoft.DirectX.Direct3D;

using JadEngine;
using JadEngine.Video;
using JadEngine.Core;
using JadEngine.Mathematics;
using JadEngine.Scene;
using JadEngine.Scene.MD5;
using JadEngine.Physics;
using JadEngine.Particles;
using JadEngine.Sound;
using JadEngine.Tools;
using JadEngine.Input;

#endregion

namespace Tutorial
{
	/// <sumary>
    /// This example will teach you to create objects and assign them physic properties.
	/// The tutorial uses the default first-person camera of the engine. Use keys WASD
	/// and the mouse to control it.
	/// </sumary>
	public class SimplePhysics : JApplication
    {
        #region Fields

		/// <summary>
		/// Indicates if the help must be shown in the screen or not
		/// </summary>
        bool showHelp = true;

        /// <summary>
		/// Rigid body related with the sphere
		/// </summary>
        JRigidBody sphereBody;

        #endregion

        #region Methods

		/// <summary>
		/// The engine calls this method after creating the device
		/// </summary>
		/// <param name="form">Form used as window</param>
		/// <returns>True if everything went right</returns>
        public override bool InitGame(Form form)
        {
			// Create the fonts and texture objects
            Jad.AfterCreateDevice();

			// Load default textures, scenes, shaders,...
            Jad.LoadCreateInHouse();

            #region Objects

			// Activate Newton's physics system
            Jad.Physics.Create();

            CreateGround();

            CreateCubes();

            CreateSphere();

            #endregion

            #region Light

			// Create an omni light
            JOmniLight light = (JOmniLight) Jad.Scene.Lights.Create("light", JLightType.Omni);

			// Position of the light
            light.Transform.Position = new Vector3(0, 0, -2f);

            // Intensity
            light.Multiplier = 1f;

            // Attenuation
            light.Attenuation.Type = JLightAttenuationType.DualRadius;

			// Distance to start attenuating the light
			light.Attenuation.Start = 1f;

			// Distance where the light is completely attenuated
			light.Attenuation.End = 2f;

            // Color
            light.Color = JColor.Yellow;

			// The light affect the diffuse component of the material
			light.AffectDiffuse = true;


			// The light affect the specular component of the material
            light.AffectSpecular = true;

			// We don´t generate shadows
            light.CastShadows = false;

			// Put ambient light
            Jad.Scene.Lights.Ambient = new JColor(0.4f, 0.4f, 0.4f);

            #endregion

            Jad.Scene.Camera.Transform.Position = new Vector3(0, 1f, -6f);

			// Everything is set, start the engine
            Jad.Begin();

			// Create input class to manage the keyboard and the mouse
            Jad.CreateInput();

            return true;
        }

		/// <summary>
		/// Creates the ground of the scene
		/// </summary>
        void CreateGround()
        {
			// Create a cube to use as floor
            Vector3 size = new Vector3(10f, 1f, 10f);

            JMesh groundMesh = JMesh.CreateCube(size);

            JMeshObject ground = Jad.Scene.MeshObjects.Create("ground", false);

			// Now associate the mesh with the meshobject
            ground.Mesh = groundMesh;

			// Create a materials array of 1 element
            JMaterial[] material = new JMaterial[1];

			material[0] = Jad.Scene.Materials.Create();

			// Create the layer
            JMaterialLayer layer = new JMaterialLayer();

			// Add it to the material
            material[0].AddLayer(layer);

            layer.DiffuseMap.Texture = Jad.Video.Textures.Create2D("Pared_Difusse", true);

			// Set the material we have just created to our ground
            ground.Material = material;

			// In Newton, we must define first a "colisionable" object setting the
			// shape of the object

            JCollision collision=new JCollision();

			// It´ll have the same size as the one done to create the mesh
			// BECAUSE IN NEWTON, AS IN HADDD, THE DISTANCE MEASURE UNIT IS THE METER

            collision.CreateBox(ref size);

			// Create a Rigid body. Rigid bodies are the objects that have
			// the colision and physic properties set. We associate the collision
			// object we just created with the JMeshObject
            JRigidBody body = Jad.Physics.RigidBodies.Create(collision, ground);

			// Set the mass
			// In Newton, an object with 0 mass is considered a static object:
			// you can collide with it, but it won´t react to anything

			body.Mass=0f;

			// We need to set a matrix. We don´t use the same as in the meshobject
			// because we can have rigid bodies that ARE NOT associated with a mesh,
			// and because of that we have to set a matrix instead of using the one
			// of JMeshObject

			// In our example, we want that the top part of the object is y=0,
			// so we indicate the center and the object=-size.Y/2

            Matrix matrix = Matrix.Translation(new Vector3(0,-size.Y/2, 0));

            body.Matrix=matrix;

			// We don´t use the collision anymore, so we release it
            collision.Release();
        }

		/// <summary>
		/// Creates the stacked cubes
		/// </summary>
        void CreateCubes()
        {
            JMesh cubeMesh = JMesh.CreateCube(0.5f, 0.5f, 0.5f);

			// In Newton, we must define first a "colisionable" object setting the
			// shape of the object.
			// As the collision object is the same for all the cubes, we create it here
			// and reuse it

            JCollision collision = new JCollision();

			// It´ll have the same size as the one done to create the mesh
			// BECAUSE IN NEWTON, AS IN HADDD, THE DISTANCE MEASURE UNIT IS THE METER
            collision.CreateBox(0.5f, 0.5f, 0.5f);

            float x, y;

			// Create stacked cubes...
            for (int px = 0; px < 2; px++)
            {
                for (int py = 0; py < 6; py++)
                {
                    x = (float)px;
                    y = (float)py;

					// Put the cubes so that they are stacked and centered
                    Vector3 pos = new Vector3(-0.25f + (x * 0.5f), 0.25f + (y * 0.5f), 0);

                    JMeshObject cube = Jad.Scene.MeshObjects.Create("cube"+px.ToString()+py.ToString(), false);

					// Associate the mesh with the meshobject

                    cube.Mesh = cubeMesh;

					// Create a materials array of 1 element
                    JMaterial[] material = new JMaterial[1];

					material[0] = Jad.Scene.Materials.Create();

                    // Create the layer
                    JMaterialLayer layer = new JMaterialLayer();

					// Add it to the material
                    material[0].AddLayer(layer);

                    layer.DiffuseMap.Texture = Jad.Video.Textures.Create2D("brick_d", true);

					// Set the material we have just created to our JMeshObject
                    cube.Material = material;

					// Create a Rigid body. Rigid bodies are the objects that have
					// the colision and physic properties set. We associate the collision
					// object we just created with the JMeshObject
                    JRigidBody body = Jad.Physics.RigidBodies.Create(collision, cube);

					// Set the mass
                    body.Mass = 4f;

					// We need to set a matrix. We don´t use the same as in the meshobject
					// because we can have rigid bodies that ARE NOT associated with a mesh,
					// and because of that we have to set a matrix instead of using the one
					// of JMeshObject

                    Matrix matrix = Matrix.Translation(pos);

                    body.Matrix=matrix;
                }
            }

            collision.Release();
        }

		/// <summary>
		/// Creates the sphere that will wreak havoc in our cubes :p
		/// </summary>
        void CreateSphere()
        {
            // Now we create an sphere
            float radius=0.3f;

            JMesh sphereMesh = JMesh.CreateSphere(radius, 20, 20);

            JMeshObject sphere = Jad.Scene.MeshObjects.Create("sphere", false);

			// Associate the mesh with the meshobject
            sphere.Mesh = sphereMesh;

			// Create a materials array of 1 element
            JMaterial[] material = new JMaterial[1];

			material[0] = Jad.Scene.Materials.Create();

            // Create the layer
            JMaterialLayer layer = new JMaterialLayer();

			// Add it to the material
            material[0].AddLayer(layer);

            layer.DiffuseMap.Texture = Jad.Video.Textures.Create2D("mancha", true);

			// Set the material we have just created to our JMeshObject
            sphere.Material = material;

			// In Newton, we must define first a "colisionable" object setting the
			// shape of the object

            JCollision collision = new JCollision();

            collision.CreateSphere(radius, radius, radius);

			collision.ComputeInertia();

			// Create a Rigid body. Rigid bodies are the objects that have
			// the colision and physic properties set. We associate the collision
			// object we just created with the JMeshObject
            JRigidBody body = Jad.Physics.RigidBodies.Create(collision, sphere);

            // Set the mass
            body.Mass = 40f;

			// Set a low value of resistance to air
            body.LinearDamping = 0.01f;

            // Set the matrix
            Matrix matrix = Matrix.Translation(new Vector3(0,radius,-3.5f));

            body.Matrix=matrix;

			// We don´t use the collision anymore, so we release it
            collision.Release();

			// Tell the global variable that this is the body we are going to use
            sphereBody = body;
        }

		/// <summary>
		/// This method is called every frame and it´s where the input
		/// events and the game action must be placed
		/// </summary>
		/// <returns>True to continue, false to exit the application</returns>
        public override bool Update()
        {
            // Exit the app?
			if (Jad.Input.Keyboard[Key.Escape].Down) return false;

			if (Jad.Input.Keyboard[Key.F1].Pressed) showHelp = !showHelp;

            // If G key was pressed we activate / deactivate the gizmos
			// The diference between KeyTouch and KeyPressed is that KeyTouch only returns
			// true if the key was pressed for the first time and not when it´s down as in
			// KeyPressed

			// KeyTouch is like normal writting, returning true only once for every key press

			if (Jad.Input.Keyboard[Key.G].Pressed)
                Jad.Scene.ShowGizmos = !Jad.Scene.ShowGizmos;

            // If they P key was pressed you can see / hide Newton collision objects
			if (Jad.Input.Keyboard[Key.P].Pressed)
                Jad.Physics.Debug = !Jad.Physics.Debug;

			// If the I key was pressed we add impulse to the sphere
			if (Jad.Input.Keyboard[Key.I].Pressed)
                sphereBody.AddImpulse(new Vector3(0, 0, 3f));

			// Everything was right, continue
            return true;
        }

        /// <summary>
        /// Render method
        /// </summary>
        public override void Render()
        {
            JView backbuffer = Jad.Video.Views[0];

            // Render the Jad.Scene using the scene camera
            backbuffer.Render();

            if (showHelp)
            {
                // Get access to the 1st font. The engine creates a font by default
                JFont font = Jad.Video.Fonts[0];

                // Start fonts rendering
                Jad.Video.Fonts.Begin();

                // Write text in the first line, position x=0, yellow color
                font.RenderLine(Jad.Version + ". Press ESC to exit. Press G to Show/Hide Gizmos. F1 show/hide text", 0, JColor.Yellow);

                // Write text in the second line, position x=0, white color
                font.RenderLine(Jad.Video.Views.CurrentView.Stats.Fps + " FPS", 0, JColor.White);

                font.RenderLine("Press P to show Physic collisions", 0, JColor.Yellow);

                font.RenderLine("Press I to add impulse", 0, JColor.Yellow);

                // End fonts rendering
                Jad.Video.Fonts.End();
            }

            // Show the backbuffer
            backbuffer.Present();
        }

        #endregion
    }
}

Last edited Mar 8, 2007 at 11:16 AM by Vicente, version 7

Comments

No comments yet.