Triangle ray intersection

Started by
1 comment, last by Norman Barrows 10 years, 9 months ago

Hi Guys

I got some pretty good advice from Krohm in a previous post and decided to provide a piece of code(below) that does triangle highlighting for a multitextured terrain(2D Heightmap), but I would like to go a step further and have the triangle change color for each of the texture coordinates it hits. I've tried several approaches so far but no luck. Im not sure how to modify the code to make this happen but if anyone could point me in the right direction it would be much appreciated ,and I know I have long way to go but I provided a couple of youtube links to give a visual of what I am working towards Thankyou.

The first youtube link is from a project called rigs of rods, and the second is from the game ultimate ninja storm which gives a pretty good illustrarion of my final goal of emitting certain particles from every impact of a certain area of the terrain

This code sends a ray into the terrain rendering a blue triangle with every triangle intersect


 //Triangle highlight intersect code 
        public void Tricolor(out Vector3 pointa, out Vector3 pointb, out Vector3 pointc) 
        { 
            
 
             
 
            int X, Z; 
 
            X = (int)Math.Floor(nearPoint.X); 
            Z = (int)Math.Floor(nearPoint.Z); 
 
            X = (int)Math.Ceiling(nearPoint.X); 
            Z = (int)Math.Ceiling(nearPoint.Z); 
 
            pointa = new Vector3(X, terrain.heightData[X, -Z], Z); // First Point of the Triangle 
            X = (int)Math.Floor(nearPoint.X); 
            Z = (int)Math.Ceiling(nearPoint.Z); 
            pointb = new Vector3(X, terrain.heightData[X, -Z], Z); // Second 
            X = (int)Math.Ceiling(nearPoint.X); 
            Z = (int)Math.Floor(nearPoint.Z); 
            pointc = new Vector3(X, terrain.heightData[X, -Z], Z); // And third 
 
            pickedTriangle[0].Position = pointa; 
            pickedTriangle[0].Color = Color.Blue; 
            pickedTriangle[1].Position = pointb; 
            pickedTriangle[1].Color = Color.Blue; 
            pickedTriangle[2].Position = pointc; 
            pickedTriangle[2].Color = Color.Blue; 
             
 
 
 
           return; 
        } 
 

Main game code


using System; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.Xna.Framework; 
using Microsoft.Xna.Framework.Audio; 
using Microsoft.Xna.Framework.Content; 
using Microsoft.Xna.Framework.GamerServices; 
using Microsoft.Xna.Framework.Graphics; 
using Microsoft.Xna.Framework.Input; 
using Microsoft.Xna.Framework.Media; 
using Microsoft.Xna.Framework.Net; 
using Microsoft.Xna.Framework.Storage; 
 
namespace TRIANGLE 
{ 
    /// <summary> 
    /// This is the main type for your game 
    /// </summary> 
    public class Game1 : Microsoft.Xna.Framework.Game 
    { 
        GraphicsDeviceManager graphics; 
        GraphicsDevice device; 
        
         
        
        VertexPositionColor[] pickedTriangle; 
       
         Viewport viewport; 
         Vector2 mouseLocation; 
       
         
       
        Vector3 nearPoint; 
        Vector3 farPoint; 
        Vector3 direction; 
 
        Effect effect; 
       
        Terrain terrain; 
        Camera camera; 
 
        Vector3 pointa; 
        Vector3 pointb; 
        Vector3 pointc; 
       
      
 
 
        public Game1() 
        { 
            this.IsMouseVisible = true; 
            graphics = new GraphicsDeviceManager(this); 
            Content.RootDirectory = "Content"; 
             
            
             
        } 
        
 
 
        /// <summary> 
        /// Allows the game to perform any initialization it needs to before starting to run. 
        /// This is where it can query for any required services and load any non-graphic 
        /// related content.  Calling base.Initialize will enumerate through any components 
        /// and initialize them as well. 
        /// </summary> 
        protected override void Initialize() 
        { 
            // TODO: Add your initialization logic here 
           
             
            pickedTriangle = new VertexPositionColor[3]; 
           
             
            base.Initialize(); 
        } 
      
        /// <summary> 
        /// LoadContent will be called once per game and is the place to load 
        /// all of your content. 
        /// </summary> 
        protected override void LoadContent() 
        { 
             
            device = graphics.GraphicsDevice; 
 
            effect = Content.Load<Effect>("Effect"); //load Effect 
 
            camera = new Camera(device); //load view 
 
            terrain = new Terrain(this, device); //load Terrain 
            
             
        } 
 
        
 
      
       
      
        
 
        //Triangle highlight code 
        public void Tricolor(out Vector3 pointa, out Vector3 pointb, out Vector3 pointc) 
        { 
            
 
             
 
            int X, Z; 
 
            X = (int)Math.Floor(nearPoint.X); 
            Z = (int)Math.Floor(nearPoint.Z); 
 
            X = (int)Math.Ceiling(nearPoint.X); 
            Z = (int)Math.Ceiling(nearPoint.Z); 
 
            pointa = new Vector3(X, terrain.heightData[X, -Z], Z); // First Point of the Triangle 
            X = (int)Math.Floor(nearPoint.X); 
            Z = (int)Math.Ceiling(nearPoint.Z); 
            pointb = new Vector3(X, terrain.heightData[X, -Z], Z); // Second 
            X = (int)Math.Ceiling(nearPoint.X); 
            Z = (int)Math.Floor(nearPoint.Z); 
            pointc = new Vector3(X, terrain.heightData[X, -Z], Z); // And third 
 
            pickedTriangle[0].Position = pointa; 
            pickedTriangle[0].Color = Color.Blue; 
            pickedTriangle[1].Position = pointb; 
            pickedTriangle[1].Color = Color.Blue; 
            pickedTriangle[2].Position = pointc; 
            pickedTriangle[2].Color = Color.Blue; 
             
 
 
 
           return; 
        } 
 
       
        // Picking code 
        public Ray CalculateRay(Vector2 mouseLocation, Matrix view, 
              Matrix projection, Viewport viewport) 
        { 
            nearPoint = viewport.Unproject(new Vector3(mouseLocation.X, 
                   mouseLocation.Y, 0f), 
                   projection, 
                   view, 
                   Matrix.Identity); 
 
            farPoint = viewport.Unproject(new Vector3(mouseLocation.X, 
                    mouseLocation.Y, 1f), 
                    projection, 
                    view, 
                    Matrix.Identity); 
 
            direction = farPoint - nearPoint; 
            direction.Normalize(); 
 
            return new Ray(nearPoint, direction); 
        } 
 
 
 
 
       /*
       * Draw debugging triangles
      */ 
        public void drawDebug() 
        { 
            effect.CurrentTechnique = effect.Techniques["Colored"]; 
            effect.Begin(); 
            foreach (EffectPass pass in effect.CurrentTechnique.Passes) 
            { 
                pass.Begin(); 
 
                device.VertexDeclaration = new VertexDeclaration(device, VertexPositionColor.VertexElements); 
                device.DrawUserPrimitives(PrimitiveType.TriangleList, pickedTriangle, 0, 1); 
 
                pass.End(); 
            } 
            effect.End(); 
        } 
 
 
 
        /// <summary> 
        /// UnloadContent will be called once per game and is the place to unload 
        /// all content. 
        /// </summary> 
        protected override void UnloadContent() 
        { 
            // TODO: Unload any non ContentManager content here 
        } 
 
        /// <summary> 
        /// Allows the game to run logic such as updating the world, 
        /// checking for collisions, gathering input, and playing audio. 
        /// </summary> 
        /// <param name="gameTime">Provides a snapshot of timing values.</param> 
        protected override void Update(GameTime gameTime) 
        { 
 
 
 
            // Allows the game to exit 
            KeyboardState keyState = Keyboard.GetState(); 
            if (keyState.IsKeyDown(Keys.Escape)) 
                this.Exit(); // Exit with ESC key 
 
            GamePadState gamePadState = GamePad.GetState(PlayerIndex.One); 
            if (gamePadState.Buttons.Back == ButtonState.Pressed) 
                this.Exit(); 
 
            camera.update(gameTime, effect); // update view 
            
            mouseLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); 
            viewport = this.GraphicsDevice.Viewport; 
 
 
            //Triangle highlight  
            Tricolor(out pointa, out  pointb, out  pointc); 
 
            //Picking code  
            CalculateRay(mouseLocation, camera.viewMatrix, camera.projectionMatrix, viewport); 
 
 
 
 
 
 
 
            base.Update(gameTime); 
        } 
   
 
 
 
        /// <summary> 
        /// This is called when the game should draw itself. 
        /// </summary> 
        /// <param name="gameTime">Provides a snapshot of timing values.</param> 
        protected override void Draw(GameTime gameTime) 
        { 
            device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1.0f, 0); 
 
            
            //draw triangles 
            drawDebug(); 
 
           //draw terrain 
            terrain.DrawTerrain(effect); // draw terrain 
 
             
            
 
            base.Draw(gameTime); 
        } 
        
    } 
} 

Terrain code


using System; 
using System.Collections.Generic; 
using Microsoft.Xna.Framework; 
using Microsoft.Xna.Framework.Audio; 
using Microsoft.Xna.Framework.Content; 
using Microsoft.Xna.Framework.GamerServices; 
using Microsoft.Xna.Framework.Graphics; 
using Microsoft.Xna.Framework.Input; 
using Microsoft.Xna.Framework.Net; 
using Microsoft.Xna.Framework.Storage; 
 
namespace TRIANGLE 
{ 
    public class Terrain 
    { 
        /*
         * Struct to hold vertex information with pos,normal,texcoord and texweight
         */ 
        public struct VertexMultitextured 
        { 
            public Vector3 Position; 
            public Vector3 Normal; 
            public Vector4 TextureCoordinate; 
            public Vector4 TexWeights; 
 
            public static int SizeInBytes = (3 + 3 + 4 + 4) * sizeof(float); // vec3 + vec3 + vec4 +vec4 
            public static VertexElement[] VertexElements = new VertexElement[] 
            { 
                // stream, offset, type, method, usage and usage index 
                new VertexElement( 0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0 ), 
                new VertexElement( 0, sizeof(float) * 3, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Normal, 0 ), 
                new VertexElement( 0, sizeof(float) * 6, VertexElementFormat.Vector4, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0 ), 
                new VertexElement( 0, sizeof(float) * 10, VertexElementFormat.Vector4, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 1 ), 
            }; 
        } 
 
        Game1 GameClass; 
        GraphicsDevice device; 
 
        public int terrainWidth; 
        public int terrainLength; 
        public float[,] heightData; 
 
        VertexBuffer terrainVertexBuffer; 
        IndexBuffer terrainIndexBuffer; 
        VertexDeclaration terrainVertexDeclaration; 
        VertexMultitextured[] terrainVertices; 
        int[] terrainIndices; 
 
        public Texture2D grassTexture; 
        public Texture2D sandTexture; 
        public Texture2D rockTexture; 
        public Texture2D snowTexture; 
 
        
 
 
      
 
        public Terrain(Game1 reference,GraphicsDevice device) 
        { 
            this.GameClass = reference; 
            this.device = device; 
             
            LoadVertices(); 
            LoadTextures(); 
        } 
 
        private void LoadTextures() 
        { 
            grassTexture = GameClass.Content.Load<Texture2D>("grass"); 
            sandTexture = GameClass.Content.Load<Texture2D>("sand"); 
            rockTexture = GameClass.Content.Load<Texture2D>("rock"); 
            snowTexture = GameClass.Content.Load<Texture2D>("snow"); 
        } 
 
       public void LoadVertices() 
        { 
 
            Texture2D heightMap = GameClass.Content.Load<Texture2D>("heightmap");  
            LoadHeightData(heightMap); 
 
            VertexMultitextured[] terrainVertices = SetUpTerrainVertices(); 
            int[] terrainIndices = SetUpTerrainIndices(); 
            terrainVertices = CalculateNormals(terrainVertices, terrainIndices); 
            CopyToTerrainBuffers(terrainVertices, terrainIndices); 
            terrainVertexDeclaration = new VertexDeclaration(device, VertexMultitextured.VertexElements); 
 
           
 
        } 
         
         
         
       
        
 
        public void LoadHeightData(Texture2D heightMap) 
        { 
            float minimumHeight = float.MaxValue; 
            float maximumHeight = float.MinValue; 
 
            terrainWidth = heightMap.Width; 
            terrainLength = heightMap.Height; 
 
            // get rgb values for each pixel of hightmap 
            Color[] heightMapColors = new Color[terrainWidth * terrainLength]; 
            heightMap.GetData(heightMapColors); 
 
            heightData = new float[terrainWidth, terrainLength]; 
            for (int x = 0; x < terrainWidth; x++) 
                for (int y = 0; y < terrainLength; y++) 
                { 
                    heightData[x, y] = heightMapColors[x + (y * terrainWidth)].R; // read r value 
                    // determine minimum and maximum height value in terrain 
                    if (heightData[x, y] < minimumHeight) minimumHeight = heightData[x, y]; 
                    if (heightData[x, y] > maximumHeight) maximumHeight = heightData[x, y]; 
                } 
 
            // get height values in a range between 0 and 30 
            for (int x = 0; x < terrainWidth; x++) 
                for (int y = 0; y < terrainLength; y++) 
                    heightData[x, y] = (heightData[x, y] - minimumHeight) / (maximumHeight - minimumHeight) * 30.0f; 
 
        } 
 
        /*
         * Define Vertices
         */ 
        private VertexMultitextured[] SetUpTerrainVertices() 
        { 
             terrainVertices = new VertexMultitextured[terrainWidth * terrainLength]; 
 
            for (int x = 0; x < terrainWidth; x++) 
            { 
                for (int y = 0; y < terrainLength; y++) 
                { 
                    // generate a vertex for each pixel of the heightmap 
                    // a terrain is generated in x,-y direction 
                    terrainVertices[x + (y * terrainWidth)].Position = new Vector3(x, heightData[x, y], -y); 
                    terrainVertices[x + (y * terrainWidth)].TextureCoordinate.X = (float)x / 30.0f; // /30 to stretch texture so it looks realistic 
                    terrainVertices[x + (y * terrainWidth)].TextureCoordinate.Y = (float)y / 30.0f; 
 
                    /*
                     * A vertex with height 12 should have texweight 1. 
                     * The weight should become 0 for heights 6 and 18, which are 12-6 and 12+6. In other words: all heights that 
                     * are within 6 meters from 12 meter high should have a weight factor for the grass texture. This explains the
                     * ‘abs(height-12)/6’: it will be 0 for height = 12, and become 1 as height approaches 6 or 18. But we need
                     * the opposite: at height 12 we need weight=1, and at heights 6 and 12 we need weight 0. So we subtract our
                     * line above from 1 and get ‘1- abs(height-12)/6’. This will become smaller than 0 for height lower than 6
                     * and larger than 18, so we clamp this value between 0 and 1.
                     * Although this is a step in the good direction, it isn’t perfect yet. For example: as their snow and
                     * rock weights are 0.2, the pixels corresponding to height 25 will get 20% of their color from the snow
                     * texture, and 20% from the rock texture. The remaining 60% will remain black, so they will look very dark.
                     * To solve this, we must make sure that for every vertex, the sum of all weights is exactly 1.
                     * To do this, for each vertex we’ll make the sum of all weights, and divide all weights by this sum. In case
                     * of the previous example, the sum would be 0.2 + 0.2 = 0.4. Next, 0.2 divided by 0.4 gives 0.5 for both the
                     * new snow and rock weights. And of course, 0.5 + 0.5 equals 1. This is what is shown in the right part 
                     * of the image above. You’ll notice that for each height, the summed weight value is 1.
                     */ 
 
                    // X = Sand, Y = Grass, Z = Stone and W = Snow 
                    terrainVertices[x + (y * terrainWidth)].TexWeights.X = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 0) / 8.0f, 0, 1); 
                    terrainVertices[x + (y * terrainWidth)].TexWeights.Y = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 12) / 6.0f, 0, 1); 
                    terrainVertices[x + (y * terrainWidth)].TexWeights.Z = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 20) / 6.0f, 0, 1); 
                    terrainVertices[x + (y * terrainWidth)].TexWeights.W = MathHelper.Clamp(1.0f - Math.Abs(heightData[x, y] - 30) / 6.0f, 0, 1); 
 
                    float total = terrainVertices[x + y * terrainWidth].TexWeights.X; 
                    total += terrainVertices[x + y * terrainWidth].TexWeights.Y; 
                    total += terrainVertices[x + y * terrainWidth].TexWeights.Z; 
                    total += terrainVertices[x + y * terrainWidth].TexWeights.W; 
 
                    terrainVertices[x + y * terrainWidth].TexWeights.X /= total; 
                    terrainVertices[x + y * terrainWidth].TexWeights.Y /= total; 
                    terrainVertices[x + y * terrainWidth].TexWeights.Z /= total; 
                    terrainVertices[x + y * terrainWidth].TexWeights.W /= total; 
                } 
            } 
 
            return terrainVertices; 
        } 
 
        /*
         * Set indices clockwise to build faces
         */ 
        private int[] SetUpTerrainIndices() 
        { 
            /*
             * new int[(terrainWidth - 1) * (terrainLength - 1) * 6]
             * Example, plane consisting of 4x3 points: first row is build out of 3 quads, second one also.
             *                                        row   col    3 points are needed for each triangle, 6 for one quad
             * so for a 4x3 points plane one can say (4-1)*(3-1) * 6
             */ 
            int[] indices = new int[(terrainWidth - 1) * (terrainLength - 1) * 6]; 
            int counter = 0; 
            for (int y = 0; y < terrainLength - 1; y++) 
            { 
                for (int x = 0; x < terrainWidth - 1; x++) 
                { 
                    int lowerLeft = x + y * terrainWidth; 
                    int lowerRight = (x + 1) + y * terrainWidth; 
                    int topLeft = x + (y + 1) * terrainWidth; 
                    int topRight = (x + 1) + (y + 1) * terrainWidth; 
 
                    // order clockwise 
                    indices[counter++] = topLeft; 
                    indices[counter++] = lowerRight; 
                    indices[counter++] = lowerLeft; 
 
                    indices[counter++] = topLeft; 
                    indices[counter++] = topRight; 
                    indices[counter++] = lowerRight; 
                } 
            } 
 
            return indices; 
        } 
 
        /* 
         * Calculate Normals on Terrain for realistic shadows
         */ 
        private VertexMultitextured[] CalculateNormals(VertexMultitextured[] vertices, int[] indices) 
        { 
            // initialise normals with 0 0 0 
            for (int i = 0; i < vertices.Length; i++) 
                vertices[i].Normal = new Vector3(0, 0, 0); 
 
            for (int i = 0; i < indices.Length / 3; i++) 
            { 
                // Calculate Triangle 
                int index1 = indices[i * 3]; 
                int index2 = indices[i * 3 + 1]; 
                int index3 = indices[i * 3 + 2]; 
 
                // Calculate normal on triangle 
                Vector3 side1 = vertices[index1].Position - vertices[index3].Position; 
                Vector3 side2 = vertices[index1].Position - vertices[index2].Position; 
                Vector3 normal = Vector3.Cross(side1, side2); 
 
                // apply normal on all three vertices of triangle 
                vertices[index1].Normal += normal; 
                vertices[index2].Normal += normal; 
                vertices[index3].Normal += normal; 
            } 
 
            // normalize all normals 
            for (int i = 0; i < vertices.Length; i++) 
                vertices[i].Normal.Normalize(); 
 
            return vertices; 
        } 
 
        /*
         * Copy vertices and indices onto grafikcard buffer to save performance (so this data has to be transferred ONLY ONCE)
         */ 
        private void CopyToTerrainBuffers(VertexMultitextured[] vertices, int[] indices) 
        { 
            terrainVertexBuffer = new VertexBuffer(device, vertices.Length * VertexMultitextured.SizeInBytes, BufferUsage.WriteOnly); 
            terrainVertexBuffer.SetData(vertices); 
 
            terrainIndexBuffer = new IndexBuffer(device, typeof(int), indices.Length, BufferUsage.WriteOnly); 
            terrainIndexBuffer.SetData(indices); 
        } 
 
        /* 
         * This draws the terrain
         */ 
        public void DrawTerrain(Effect effect) 
        { 
            effect.CurrentTechnique = effect.Techniques["MultiTextured"]; 
            effect.Parameters["xTexture0"].SetValue(sandTexture); 
            effect.Parameters["xTexture1"].SetValue(grassTexture); 
            effect.Parameters["xTexture2"].SetValue(rockTexture); 
            effect.Parameters["xTexture3"].SetValue(snowTexture); 
 
            Matrix worldMatrix = Matrix.Identity; 
            effect.Parameters["xWorld"].SetValue(worldMatrix); 
            effect.Parameters["xEnableLighting"].SetValue(true); 
            effect.Parameters["xAmbient"].SetValue(0.4f); 
            effect.Parameters["xLightDirection"].SetValue(new Vector3(-0.5f, -1, -0.5f)); 
 
            effect.Begin(); 
            foreach (EffectPass pass in effect.CurrentTechnique.Passes) 
            { 
                pass.Begin(); 
 
                device.Vertices[0].SetSource(terrainVertexBuffer, 0, VertexMultitextured.SizeInBytes); // tell it that this data is in graka buffer 
                device.Indices = terrainIndexBuffer; 
                device.VertexDeclaration = terrainVertexDeclaration; 
 
                int noVertices = terrainVertexBuffer.SizeInBytes / VertexMultitextured.SizeInBytes; 
                int noTriangles = terrainIndexBuffer.SizeInBytes / sizeof(int) / 3; 
                device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, noVertices, 0, noTriangles); 
 
                pass.End(); 
            } 
            effect.End(); 
        } 
 
 
 
        public float GetHeight(float x, float z) 
        { 
            int xmin = (int)Math.Floor(x); 
            int xmax = xmin + 1; 
            int zmin = (int)Math.Floor(z); 
            int zmax = zmin + 1; 
 
            if ( 
                (xmin < 0) || (zmin < 0) || 
                (xmax > heightData.GetUpperBound(0)) || 
                (zmax > heightData.GetUpperBound(1))) 
            { 
                return 0; 
            } 
 
            Vector3 p1 = new Vector3(xmin, heightData[xmin, zmax], zmax); 
            Vector3 p2 = new Vector3(xmax, heightData[xmax, zmin], zmin); 
            Vector3 p3; 
 
            if ((x - xmin) + (z - zmin) <= 1) 
            { 
                p3 = new Vector3(xmin, heightData[xmin, zmin], zmin); 
            } 
            else 
            { 
                p3 = new Vector3(xmax, heightData[xmax, zmax], zmax); 
            } 
 
            Plane plane = new Plane(p1, p2, p3); 
 
            Ray ray = new Ray(new Vector3(x, 0, z), Vector3.Up); 
 
            float? height = ray.Intersects(plane); 
 
            return height.HasValue ? height.Value : 0f; 
        } 
        
    } 
} 
Advertisement

Where is your ray-triangle intersection code? I saw your Game1::Update() function and you're just calling CalculateRay(..) which returns the ray generated in world-space but you're not even catching the return ray? Or do you specifically need help on this part?


but I would like to go a step further and have the triangle change color for each of the texture coordinates it hits.

change the color of the ground mesh triangle intersected, depending on the UV of the intersection point?

to determine the x,y,z,u,v of a ray triangle intersection, see the raypick sample in directx. it has all the code right there (for intersection with a single complex mesh). i used it to cobble together a raypick vs the plane y=0 for stuff like clicking on locations on a RTS game map. you can use something simple like that to get x,z then use your heightmap to get y, and you have your coordinates for the location of your particle emitter. or use their code and get the triangle number, x,y,z u, and v all at once.

Norm Barrows

Rockland Software Productions

"Building PC games since 1989"

rocklandsoftware.net

PLAY CAVEMAN NOW!

http://rocklandsoftware.net/beta.php

This topic is closed to new replies.

Advertisement