Search code examples
javaarraysfloating-pointvectormath

Vertex array to a float array


I am currently developing a game engine, and was asked to make a method that takes in a vertex array and outputs a float array. We have a class made for Vector3. Vector3 is a wrapper for 3 floats, x,y and z. The vertex is just a wrapper for a Vector3f. So if their is a vertex array how can i turn it into a float array. This is what i have so far


   public static float[] VertexArrayToFloatArray(Vertex[] vertices){
       float[] floats = new float[vertices.length];

       int i = 0;
       for (Vertex v : vertices){
           float x, y, z;
           x = v.getPosition().getX();
           y = v.getPosition().getY();
           z = v.getPosition().getZ();

           floats[i] = x;
           floats[i + 1] = y;
           floats[i + 2] = z;
       }
       System.out.println(floats);
       return floats;
   }


An expected output would be puting in a vertex array to make a square such as


Vertex[] vertices = new Vertex[]{

 new Vertex(new Vector3f(0.5f,-0.5f,0)), //Bottom Right
 new Vertex(new Vector3f(-0.5f,0.5f,0)), // Top Left
 new Vertex(new Vector3f(0.5f,0.5f,0)),  //Top Right
 new Vertex(new Vector3f(-0.5f,-0.5f,0)) //Bottom Left
}

and you would get

{0.5f,-0.5f,0,-0.5f,0.5f,0,0.5f,0.5f,0 ,-0.5f,-0.5f,0}

as the result


Solution

  • 1. In your example, you are creating an array with the size of the number of vertices from the input, but since every Vertex has 3 floats you want to create an array with triple the size of the input

    float[] floats = new float[vertices.length*3];
    

    2. Then you are correctly doing for loop but you are never changing the index i.

    That means that you are only overwriting index 0,1 and 2.
    Instead of that, you need to increment the i by 3 (You are adding on i,i+1, and i+2) every loop

    Something like this:

    for (Vertex v : vertices){
               float x, y, z;
               x = v.getPosition().getX();
               y = v.getPosition().getY();
               z = v.getPosition().getZ();
    
               floats[i] = x;
               floats[i + 1] = y;
               floats[i + 2] = z;
               i+=3;
    }
    

    Or you can use i++ which increase i by 1 and returns the value of i BEFORE increasing If we then combine those 2 advise we get

    public static float[] VertexArrayToFloatArray(Vertex[] vertices){
           float[] floats = new float[vertices.length*3];
    
           int i = 0;
           for (Vertex v : vertices){
               float x, y, z;
               x = v.getPosition().getX();
               y = v.getPosition().getY();
               z = v.getPosition().getZ();
    
               floats[i] = x;
               floats[i++] = y;
               floats[i++] = z;
           }
           System.out.println(floats);
           return floats;
       }