Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (475)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (530)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1]
1  Game Development / Newbie & Debugging Questions / Re: [Solved] Distributing runnable files on: 2013-11-05 15:55:01
Sorry, I only put in the natives for windows. I tried it out on mac with mac natives but the error log wasn't very helpful (should read through it again, huge thing, hope to find a stacktrace). I don't have a linux machine to test on, and thus no linux version D:

Thanks for the eclipse tip! I'll try that too Wink
2  Game Development / Newbie & Debugging Questions / Re: [Solved] Distributing runnable files on: 2013-11-04 20:41:05
That's also an alternative Tongue
3  Game Development / Newbie & Debugging Questions / Re: Distributing runnable files on: 2013-11-04 19:40:17
Ok, I got my proverbial "shit" straightened out.

I had no real concept of the term classpath and thus my directory structure in eclipse was like this;
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
-name of project-
--src
---package
----foo.java
----bar.java
--lib
--res
---images
----image.png
----pic.png
---shaders
----fragment.glsl
----vertex.glsl


using this line to load the resources when testing the code in eclipse.
1  
BufferedReader reader = new BufferedReader(new FileReader("res/shaders/fragment.glsl"));


When it should have been like this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
-name of project-
--src
---package
----foo.java
----bar.java
---res.images
----image.png
----pic.png
---res.shaders
----vertex.glsl
----fragment.glsl
--lib


And use this to load the resources.
1  
2  
InputStream input = Renderer.class.getClass().getResourceAsStream("/res/shaders/fragment.glsl");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));


As for distributing everything, this should fix my issues and un-complicate things for me. Thanks for the answers everyone! They should get me on my way just fine.
4  Game Development / Newbie & Debugging Questions / Re: Distributing runnable files on: 2013-11-04 18:01:00
Hmm, yes, that seems to work. (Again I was overcomplicating things) Only now it can't find files (shaders, images) because they're not in the same directories anymore. Do you know an export-proof way of loading files?
5  Game Development / Newbie & Debugging Questions / [Solved] Distributing runnable files on: 2013-11-04 16:50:42
Ello JGO,

I want to throw my code into a runnable file, I've tried Launch4j, which looks fine. But I don't understand half of what I should be filling in. And I figure it wouldn't be a bad thing to know how to make an executable file myself. Is there any place I can find a detailed description of why and what things are/do and where to find this info on my project?

Some specifics:
Project in eclipse.
Build path libs: JRE 7, lwjgl.jar, lwjgl_util.jar
My OS: windows 8 64bit

Excuses if this is a redundant post, just point out to me the search terms you used so I can wallow in self-shame and be better at searching next time. Because I haven't found anything that seems like what I'm looking for using the search.

[Edit:] Eclipse's export as executable jar & correcting directory hierarchy got the job done. The result for the curious: http://149.210.136.93/~ramus/shared/varelseExecJar.rar
6  Java Game APIs & Engines / OpenGL Development / Re: Problem with updating a VBO on: 2013-10-29 10:57:56
Thanks! I'll be careful in Lighthouse3D waters, although the one from github looks very good.
7  Java Game APIs & Engines / OpenGL Development / Re: Problem with updating a VBO on: 2013-10-28 20:31:28
Wow, that was easier to implement than I thought... Thanks a lot!
If you don't mind me asking, what's your resource for learning GLSL?
8  Java Game APIs & Engines / OpenGL Development / Re: Problem with updating a VBO on: 2013-10-28 15:23:56
I guess it's time to dive into shaders then!

Solutions/tips to this problem still welcome ofc.
9  Java Game APIs & Engines / OpenGL Development / Problem with updating a VBO on: 2013-10-28 14:56:55
Ello JGO,

I'm trying to draw multiple differently coloured cubes without creating seperate render classes for each colour. The way I've gone about doing this is by updating the VBO with the correct colour before rendering it. (side question: is this actually faster than multiple classes with each a different colour?) I based my code on the "The Quad updating a VBO with BufferSubData" http://www.lwjgl.org/wiki/index.php?title=The_Quad_updating_a_VBO_with_BufferSubData tutorial on the lwjgl wiki.

The problem I'm having is that I get an invalid value error in my matrix logic every time I include the following piece of code before my rendering;
c is the cube I'm currently rendering.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
// Set the right colour
        GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboId);
         // Apply and update vertex data
        for (int i = 0; i < vertices.length; i++) {
            VertexData vertex = vertices[i];
           
            float[] rgba = c.getRGBA();
            vertex.setRGBA(rgba[0], rgba[1], rgba[2], rgba[3]);
             
            // Put the new data in a ByteBuffer (in the view of a FloatBuffer)
           FloatBuffer vertexFloatBuffer = verticesByteBuffer.asFloatBuffer();
            vertexFloatBuffer.rewind();
            vertexFloatBuffer.put(vertex.getElements());
            vertexFloatBuffer.flip();
             
            GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, i * VertexData.stride, verticesByteBuffer);
         }


The rgba values assigned by default (in RenderColourCube.setupVertices() seem to work without problems)
Complete RenderColourCube code is found here: http://pastebin.java-gaming.org/8c317474c72
ColourCube class is found here: http://pastebin.java-gaming.org/c31775c4279
10  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions [Kind of working, but in a bad way] on: 2013-10-05 10:46:44
Those are the same as res/shaders/Fragment.glsl and Vertex.glsl. Sorry for the confusion  Lips Sealed
11  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions [Kind of working, but in a bad way] on: 2013-10-04 17:28:11
Et voila, the code. I archived my eclipse project folder and ripped out the settings and old unused codethings.
https://dl.dropboxusercontent.com/u/29087694/BlockTool.rar
Do note, this in in working order, doing that opposite thing. See comments in the quaternioncamera class.
12  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions [Kind of working, but in a bad way] on: 2013-10-04 11:00:34
Will dump as soon as I'm home. Is a .rar of my eclipse workspace via DropBox good too? In case of no reaction, pastebin is the way to go.
13  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions [Kind of working, but in a bad way] on: 2013-10-01 12:47:55
Sorry for the late reaction, college kinda screwed me over with quite the workload. I hope you, or someone else is interested in looking into my renderer class and shaders. I've looked through it myself and can't find anything out of place.

If someone knows a good book/link that details this kind of stuff, I'd love that too.

Renderer, evolved from the lwjgl opengl tutorials
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
package varelse;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.util.*;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.ContextAttribs;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.PixelFormat;
import org.lwjgl.util.glu.GLU;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import org.lwjgl.util.vector.Vector4f;

import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;

public class Renderer {
   
   public final static String WINDOW_TITLE = "Varelse";
   private final int WIDTH = 1500;
   private final int HEIGHT = 800;
   private final double PI = 3.14159265358979323846;
   
   public int projectionMatrixLocation = 0; // OpenGL gives an integer to find objects at, this stores that
  public int viewMatrixLocation = 0;
   public int modelMatrixLocation = 0;
   private Matrix4f projectionMatrix = null;
   public Matrix4f viewMatrix = null;
   public Matrix4f modelMatrix = null;
   public Camera cameraModelling;
   public QuaternionCamera qCam;
   public Vector3f cameraPos = null;
   public Vector3f cameraAngle = null;
   private FloatBuffer matrix4fBuffer = null;
   
   private int vsId = 0;
   private int fsId = 0;
   public int pId = 0;
   
   public static ArrayList<Drawable> drawList;
   
   public Renderer() {
      drawList = new ArrayList<Drawable>();
      cameraModelling = new CameraModelling();
      qCam = new QuaternionCamera();
      Utils.renderer = this;
      setupOpenGL();
      setupMatrices();
      setupShaders();
      setupRenderables();
   }
   
   private void setupRenderables() {
      drawList.add(new RenderCube(modelMatrixLocation, matrix4fBuffer, vsId, fsId, pId));
      drawList.add(new RenderSelectBox(modelMatrixLocation, matrix4fBuffer, pId));
   }

   private void setupShaders() {
     
      int errorCheckValue = GL11.glGetError();
     
      // Load the vertex shader
     vsId = Renderer.loadShader("res/shaders/Vertex.glsl", GL20.GL_VERTEX_SHADER);
      // Load the fragment shader
     fsId = Renderer.loadShader("res/shaders/Fragment.glsl", GL20.GL_FRAGMENT_SHADER);
     
      // Create a new shader program that links both shaders
     pId = GL20.glCreateProgram();
      GL20.glAttachShader(pId, vsId);
      GL20.glAttachShader(pId, fsId);
      GL20.glLinkProgram(pId);

      // Position information will be attribute 0
     GL20.glBindAttribLocation(pId, 0, "in_Position");
      // Color information will be attribute 1
     GL20.glBindAttribLocation(pId, 1, "in_Color");
      // Texture information will be attribute 2
     GL20.glBindAttribLocation(pId, 2, "in_TextureCoord");
     
      GL20.glValidateProgram(pId);
     
      // Get the matrices uniform locations
     projectionMatrixLocation = GL20.glGetUniformLocation(pId, "projectionMatrix");
      viewMatrixLocation = GL20.glGetUniformLocation(pId, "viewMatrix");
      modelMatrixLocation = GL20.glGetUniformLocation(pId, "modelMatrix");
     
      errorCheckValue = GL11.glGetError();
      if (errorCheckValue != GL11.GL_NO_ERROR) {
         System.out.println("ERROR - Could not create the shaders:" + GLU.gluErrorString(errorCheckValue));
         System.exit(-1);
      }
   }

   private void setupMatrices() {
      // Setup projection Matrix
     projectionMatrix = new Matrix4f();
      float fieldOfView = 60f;
      float aspectRatio = (float)WIDTH / (float) HEIGHT;
      float near_plane = 0.01f;
      float far_plane = 100f;
     
      float y_scale = this.coTangent(this.degreesToRadians(fieldOfView / 2f));
      float x_scale = y_scale / aspectRatio;
      float frustum_length = far_plane - near_plane;
     
      projectionMatrix.m00 = x_scale;
      projectionMatrix.m11 = y_scale;
      projectionMatrix.m22 = -((far_plane + near_plane) / frustum_length);
      projectionMatrix.m23 = -1;
      projectionMatrix.m32 = -((2 * near_plane * far_plane) / frustum_length);
     
      viewMatrix = qCam.getCameraMatrix();
     
      // Create a FloatBuffer with the proper size to store our matrices later
     matrix4fBuffer = BufferUtils.createFloatBuffer(16);
     
      Main.exitOnGLError("Error in setupMatrices");
   }

   public void setupOpenGL() {
      // Setup an OpenGL context with API version 3.2
     try {
         PixelFormat pixelFormat = new PixelFormat();
         ContextAttribs contextAtrributes = new ContextAttribs(3, 2)
            .withForwardCompatible(true)
            .withProfileCore(true);
         
         Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
         Display.setTitle(WINDOW_TITLE);
         Display.create(pixelFormat, contextAtrributes);
         
         GL11.glViewport(0, 0, WIDTH, HEIGHT);
      } catch (LWJGLException e) {
         e.printStackTrace();
         System.exit(-1);
      }
     
      // Enable face culling
     GL11.glEnable(GL11.GL_CULL_FACE);
      // Enable depth testing (for gluUnProject
     GL11.glEnable(GL11.GL_DEPTH_TEST);
     
      // Setup an XNA like background color
     GL11.glClearColor(0.4f, 0.6f, 0.9f, 0f);
      //GL11.glClearColor(1.0f, 1.0f, 1.0f, 0f);
     
      // Map the internal OpenGL coordinate system to the entire screen
     GL11.glViewport(0, 0, WIDTH, HEIGHT);
     
      Main.exitOnGLError("Error in setupOpenGL");
   }
   
   public void matrixLogic() {
      viewMatrix = qCam.getCameraMatrix();
      GL20.glUseProgram(pId);
     
      // Upload matrices to the uniform variables
     projectionMatrix.store(matrix4fBuffer);
      matrix4fBuffer.flip();
      GL20.glUniformMatrix4(projectionMatrixLocation, false, matrix4fBuffer);
     
      viewMatrix.store(matrix4fBuffer);
      matrix4fBuffer.flip();
      GL20.glUniformMatrix4(viewMatrixLocation, false, matrix4fBuffer);
     
      GL20.glUseProgram(0);
     
      Main.exitOnGLError("Error in matrixLogic");
   }

   public void render() {
      GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
      for (Drawable d : drawList) {
         d.renderSubs();
      }
   }
   
   public long addRenderable(Drawable d) {
      drawList.add(d);
      long index = drawList.indexOf(d);
      return index;
   }
   
   public void removeRenderable(long i) {
      drawList.remove(i);
   }
   
   public static int loadPNGTexture(String filename, int textureUnit) {
      ByteBuffer buf = null;
      int tWidth = 0;
      int tHeight = 0;
     
      try {
         // Open the PNG file as an InputStream
        InputStream in = new FileInputStream(filename);
         // Link the PNG decoder to this stream
        PNGDecoder decoder = new PNGDecoder(in);
         
         // Get the width and height of the texture
        tWidth = decoder.getWidth();
         tHeight = decoder.getHeight();
         
         
         // Decode the PNG file in a ByteBuffer
        buf = ByteBuffer.allocateDirect(
               4 * decoder.getWidth() * decoder.getHeight());
         decoder.decode(buf, decoder.getWidth() * 4, Format.RGBA);
         buf.flip();
         
         in.close();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
     
      // Create a new texture object in memory and bind it
     int texId = GL11.glGenTextures();
      GL13.glActiveTexture(textureUnit);
      GL11.glBindTexture(GL11.GL_TEXTURE_2D, texId);
     
      // All RGB bytes are aligned to each other and each component is 1 byte
     GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
     
      // Upload the texture data and generate mip maps (for scaling)
     GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, tWidth, tHeight, 0,
            GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf);
      GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
     
      // Setup the ST coordinate system
     GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
      GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
     
      // Setup what to do when the texture has to be scaled
     GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER,
            GL11.GL_NEAREST);
      GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER,
            GL11.GL_LINEAR_MIPMAP_LINEAR);
     
      Main.exitOnGLError("loadPNGTexture");
     
      return texId;
   }
   
   public static int loadShader(String filename, int type) {
      StringBuilder shaderSource = new StringBuilder();
      int shaderID = 0;
     
      try {
         BufferedReader reader = new BufferedReader(new FileReader(filename));
         
         String line;
         while ((line = reader.readLine()) != null) {
            shaderSource.append(line).append("\n");
         }
         reader.close();
      } catch (IOException e) {
         System.err.println("Could not read file.");
         e.printStackTrace();
         System.exit(-1);
      }
     
      shaderID = GL20.glCreateShader(type);
      GL20.glShaderSource(shaderID, shaderSource);
      GL20.glCompileShader(shaderID);

      // GL20.glGetShader was deprecated, was told to use GL20.glGetShaderi. Still takes the same params though...
     if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
         System.err.println("Could not compile shader.");
         System.exit(-1);
      }
     
      return shaderID;
   }
   
   private float coTangent(float angle) {
      return (float)(1f / Math.tan(angle));
   }
   
   private float degreesToRadians(float degrees) {
      return degrees * (float)(PI / 180d);
   }
   
   public void destroy() {
      // TODO call destroy on RenderObjects and destroy ?matrices? and openGL
     for (Drawable d: drawList){
         d.destroy();
      }
      // Delete the shaders
     GL20.glUseProgram(0);
      GL20.glDetachShader(pId, vsId);
      GL20.glDetachShader(pId, fsId);
     
      GL20.glDeleteShader(vsId);
      GL20.glDeleteShader(fsId);
      GL20.glDeleteProgram(pId);
   }
   
   public void exitOnGLError(String errorMessage) {
      int errorValue = GL11.glGetError();
     
      if (errorValue != GL11.GL_NO_ERROR) {
         String errorString = GLU.gluErrorString(errorValue);
         System.err.println("f**k, SORRY MAN! Didn't mean to do this D: Here's an error to give to the dev - " + errorMessage + ": " + errorString);
         
         if (Display.isCreated()) Display.destroy();
         System.exit(-1);
      }
   }

   public Matrix4f getModelMatrix() {
      return modelMatrix;
   }

   public void setModelMatrix(Matrix4f modelMatrix) {
      this.modelMatrix = modelMatrix;
   }
}


Vertex shader
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
# version 150 core

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

in vec4 in_Position;
in vec4 in_Color;
in vec2 in_TextureCoord;

out vec4 pass_Color;
out vec2 pass_TextureCoord;

void main(void) {
   gl_Position = in_Position;
   // Override gl_Position with our new calculated position
  gl_Position = projectionMatrix * viewMatrix * modelMatrix * in_Position;
   
   pass_Color = in_Color;
   pass_TextureCoord = in_TextureCoord;
}


Fragment shader
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
#version 150 core

uniform sampler2D texture_diffuse;

in vec4 pass_Color;
in vec2 pass_TextureCoord;

out vec4 out_Color;

void main(void) {
   out_Color = pass_Color;
   // Override out_Color with the texture pixel (AAAAH, so that's why!)
  out_Color = texture2D(texture_diffuse, pass_TextureCoord);
}
14  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions [Partially solved] on: 2013-09-18 09:43:23
When fidgeting around with the viewMatrix, I had indeed noticed the position being the inverse of the world position, or at least the position I used for the modelMatrix. Stupidly, I let it fly because it was of no inconvenience... yet. Also since I had no idea what the implications were and how to deal with it.

I'll adapt my code later today, gotta catch the bus to college. I plan on making a video of the result, detailing the functionality I have in the program as of now. ( To hand in for a free choice ects assignment, it's not for a course, there isn't even a Java course ) I'll post it in this thread too, along with most of the code so future newbs like me won't have to take months to figure it out. With your permission of course, since the Quaternion & some, if not most, of the camera code is yours.

I guess I shouldn't cheer before editing the solution into my code... Got some typical problems, rotating still causes increasing roll when I pan my cam 90 deg to the side, 180 = no roll again. Plus pointing down makes the cam go up again when pressing forward, same effect on translation in other directions.

So here's the code again Tongue
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
package varelse;

import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;

//TODO Incorporate getting the time delta, or maybe do that in the inputManager.

public class QuaternionCamera {
   
   private Vector3f cameraPosition;
   public Quaternion cameraRotation;
   //private Vector3f maxRotation;
  //private Vector3f minRotation;
  private float moveSpeed;
   private float rotationSpeed;
   private Matrix4f camMatrix;
   
   QuaternionCamera () {
      setPosition(new Vector3f(0.0f, 0.0f, 10.0f));
      cameraRotation = new Quaternion();
      moveSpeed = 0.01f;
      rotationSpeed = 0.2f;
      camMatrix = new Matrix4f();
   }
   
   // Feed this guy a position vector and a quaternion
  QuaternionCamera (Vector3f pos, Quaternion rot) {
      setPosition(pos);
      this.cameraRotation = new Quaternion();
      this.cameraRotation.set(rot);
      moveSpeed = 0.01f;
      rotationSpeed = 0.2f;
      camMatrix = new Matrix4f();
   }
   
   private void updateCamMatrix() {      
     
      /* The Matrix is shaped like this:
      m00 m10 m20 m30      1.0 0.0 0.0 0.0      lx ux fx px
      m01 m11 m21 m31      0.0 1.0 0.0 0.0      ly uy fy py      // No animals were harmed during the testing of matrix order.
      m02 m12 m22 m32      0.0 0.0 1.0 0.0      lz uz fz pz      // My pride, however, was.
      m03 m13 m23 m33      0.0 0.0 0.0 1.0      lw uw fw pw
      */

     
      // Getting the rotation from a Quaternion into a matrix
     /*
       * 1 - 2y² - 2z²   2xy + 2wz      2xz - 2wy
       * 2xy - 2wz      1 - 2x² - 2z²   2yz + 2wx
       * 2xz + 2wy      2yz - 2wx      1 - 2x² - 2y²
       */

      camMatrix = cameraRotation.toMatrix().translate(cameraPosition);
   }
   
   public void rotate(int dx, int dy) {
     
      // rotation speed is still constant, putting delta into it later
     
      // pitch
     if (dy != 0) {
         cameraRotation = Utils.angleAxisDeg(-dy * rotationSpeed, new Vector3f(1.0f, 0.0f, 0.0f)).mul(cameraRotation);
         //cameraRotation = cameraRotation.mul(Utils.angleAxisDeg(-dy * rotationSpeed, new Vector3f(1.0f, 0.0f, 0.0f)));
     }
     
      // yaw
     if (dx != 0) {
         //cameraRotation = Utils.angleAxisDeg(dx * rotationSpeed, new Vector3f(0.0f, 1.0f, 0.0f)).mul(cameraRotation);
        cameraRotation = cameraRotation.mul(Utils.angleAxisDeg(dx * rotationSpeed, new Vector3f(0.0f, 1.0f, 0.0f)));
      }
     
      cameraRotation.normalize();
   }

   public void move(Vector3f dir, float deltaTime) {
     
      // Inverse quat
     Quaternion inverse = cameraRotation.copy().inverse();
     
      // Position delta is put in here
     Vector3f delta = new Vector3f();
     
      // Move method in my camera, takes a vector3f containing W & S in z, A & D in x, Lshift & Lctrl in y
     // Input processing is done in the InputManager class
     if(dir.z == 1) {
         delta.setZ(delta.getZ() + moveSpeed);
      } else if (dir.z == -1) {
         delta.setZ(-moveSpeed);
      }
     
      if(dir.y == -1) {
         delta.setY(delta.getY() + moveSpeed);
      } else if (dir.y == 1) {
         delta.setY(-moveSpeed);
      }
     
      if(dir.x == 1) {
         delta.setX(delta.getX() + moveSpeed);
      } else if (dir.x == -1) {
         delta.setX(-moveSpeed);
      }

        //delta.negate();
     Vector3f.add(cameraPosition, inverse.mul(delta), cameraPosition);
   }
   
   public Matrix4f getCameraMatrix() {
      updateCamMatrix();
      Matrix4f matrix = new Matrix4f(camMatrix);
      return matrix;
   }

   public void setRotation(Quaternion q) {
      this.cameraRotation = q;
   }

   public void setPosition(Vector3f v0) {
      cameraPosition = (Vector3f) new Vector3f(v0).negate();
   }

   public Quaternion getRotation() {
      Quaternion q = new Quaternion(cameraRotation);
      return q;
   }

   public Vector3f getPosition() {
      return (Vector3f) new Vector3f(cameraPosition).negate();
   }

   public void setMoveSpeed(float f) {
      moveSpeed = f;
   }

   public void setRotationSpeed(float f) {
      rotationSpeed = f;
   }

   public float getMoveSpeed() {
      float f = moveSpeed;
      return f;
   }

   public float getRotationSpeed() {
      float f = rotationSpeed;
      return f;
   }
   
   public void log() {
      updateCamMatrix();
      System.out.println(camMatrix.m00 + " " + camMatrix.m10 + " " + camMatrix.m20 + " " + camMatrix.m30);
      System.out.println(camMatrix.m01 + " " + camMatrix.m11 + " " + camMatrix.m21 + " " + camMatrix.m31);
      System.out.println(camMatrix.m02 + " " + camMatrix.m12 + " " + camMatrix.m22 + " " + camMatrix.m32);
      System.out.println(camMatrix.m03 + " " + camMatrix.m13 + " " + camMatrix.m23 + " " + camMatrix.m33);
   }
}
15  Game Development / Newbie & Debugging Questions / Re: Complete Newbie on: 2013-09-17 19:48:47
When I started out programming in Java (and programming altogether) I tried making a mod for Minecraft, despite being partially succesful in making throwing knives it made me realise I had a lot to learn about Java. So I read "Head First Java" from O'Reilly, it almost felt like putting on glasses for the first time Tongue Really nice, non boring-wall-of-text book, quite engaging. Plus it made me feel ashamed of the code I had written for my MC mod.

Moral of the story; Read a Java programming book. Most don't require you to use an IDE or even tell you to do everything in a console, but you're free to ignore that. Actually do the exercises, they help a lot in understanding and retaining that understanding. Do it beside making your game and you'll see that discovering new possibilities in programming helps you think of stuff for your game. Plus, actively thinking about putting fresh learned knowledge to use makes reading & learning easier. And when you're done you have a handy book to fall back on when you need info about (almost) anything java.

Side notes about Head First Java:
Starts out with pure basics, how to write a barebones java program, compile it and run it. Without IDE. When you've done that you can apply that knowledge to any IDE because you know the terminology.
It also covers a bunch of Java's built in libraries.
Already know about a subject (like operators) just skip it! Wink
16  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions [Partially solved] on: 2013-09-17 12:20:19
Here goes the code dump! Strangely enough, all my issues have been solved by partially doing the opposite of what you're suggesting Huh I guess it might be caused by my chaotic shenanigans constantly adding functionality and trying to make the code work.

Here's some of the code bits, first one is the rotate method in my QuaternionCamera class. Do note me using your suggestion on y (pitch) instead of x .

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
public void rotate(int dx, int dy) {
     
      // rotation speed is still constant, putting delta into it later
     
      // pitch
     if (dy != 0 || dx != 0) {
         //cameraRotation = Utils.angleAxisDeg(-dy * rotationSpeed, new Vector3f(1.0f, 0.0f, 0.0f)).mul(cameraRotation);
        cameraRotation = cameraRotation.mul(Utils.angleAxisDeg(-dy * rotationSpeed, new Vector3f(1.0f, 0.0f, 0.0f))); // Doing the opposite, cause I'm a rebel.
     }
     
      // yaw
     if (dx != 0) {
         cameraRotation = Utils.angleAxisDeg(dx * rotationSpeed, new Vector3f(0.0f, 1.0f, 0.0f)).mul(cameraRotation); // And again, it never stops with this guy...
        //cameraRotation = cameraRotation.mul(Utils.angleAxisDeg(dx * rotationSpeed, new Vector3f(0.0f, 1.0f, 0.0f)));
     }
     
      cameraRotation.normalize();
   }

Below is my move method from the QuaternionCamera class.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
public void move(Vector3f dir, float deltaTime) {
     
      // Still called inverse, despite not inverting. For reverting purposes of course.
     Quaternion inverse = cameraRotation.copy();
     
      // Position delta is put in here
     Vector3f delta = new Vector3f();
     
      // Move method in my camera class, takes a vector3f containing W & S in z, A & D in x, Lshift & Lctrl in y
     // Input processing is done in the InputManager class, deltaTime left out, will put in later.
     if(dir.z == 1) {
         delta.setZ(delta.getZ() + moveSpeed);
      } else if (dir.z == -1) {
         delta.setZ(-moveSpeed);
      }
     
      if(dir.y == 1) {
         delta.setY(delta.getY() + moveSpeed);
      } else if (dir.y == -1) {
         delta.setY(-moveSpeed);
      }
     
      if(dir.x == 1) {
         delta.setX(delta.getX() + moveSpeed);
      } else if (dir.x == -1) {
         delta.setX(-moveSpeed);
      }

        Vector3f.add(cameraPosition, inverse.mul(delta), cameraPosition);
     
   }


Since my endless mucking around with my code the last months, the problem might be outside these methods, so I'll post my QuaternionCamera, InputManager and Quaternion (your code) classes on pastebin. The Quaternion class was edited a bit to make it work with LWJGL's Vector3f and Matrix4f classes, and prewritten code which uses "mul" instead of "mult" ( I blame lwjgl! Tongue )
QuaternionCamera: http://pastebin.com/fKVe6cJN
InputManager: http://pastebin.com/NhhqpCv5
Quaternion: http://pastebin.com/48Vq9UhP
17  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions on: 2013-09-16 21:22:40
Now that I've found the time to integrate your solutions, and so graciously given code, into my code, I've run across some issues. First of all, I must say, the produced viewMatrix does its job well enough, no trippy deformations. (I managed those far too often) So, I seem to be doing something wrong >_<

Yet, when I move forward (or in any direction for that matter) there is a non-forward deviation. Looking straight has no effect, WASD translates like it should, yet when I look up and press W I move down instead of up, rotating 90 degrees has the effect of opposite movement (W = backwards), and rotating 180 degrees negates the effect again. Any idea what might be causing this? - I considered this solved when realising, thanks to you, that multiplying the delta position vector with a quaternion was the way to go. (I was mucking around with w&s & forward Vector from the viewmatrix) Well, bummer, I guess.
WHOA! Scratch that! Turns out that the orientation does not need to be inverted before multiplying the delta (change in position) vector. I guess it's because the multiply vector by quaternion already does the q*v*-q, wait that might not make sense... But it works now!

Yet one thing remains. (might be able to solve this myself given enough shower-contemplating and in-bed-sleep-stalling-contemplation)
Second, how do I negate rotation about the z axis? Meaning, I don't want roll, just yaw and pitch. Roll still happens when moving the mouse diagonally, an effect of using quaternions I guess.
18  Game Development / Game Mechanics / Re: Free flying Quaternion camera questions on: 2013-09-15 21:44:14
Wow, this is great! Thanks a ton for taking the time to answer my questions so well!  Cheesy
19  Game Development / Game Mechanics / Free flying Quaternion camera questions [Kind of working, but in a bad way] on: 2013-09-15 17:14:50
Ello! As the title indicates, I'm making a free flying camera in which the rotation component is defined by a quaternion. I've been wrestling with it for quite a while, making my own quaternion class and incorporating it into my camera class. I've run into some problems with trying to decipher C++ example code into Java code and understanding quaternions in general. Ergo, I have some questions before I dive into this never ending wrestling match with camera controls. - I've mostly based my Quaternion code on this guy's http://www.youtube.com/user/BSVino?feature=watch tuts and the "3D math primer for graphics and game development" book.

Q: Using mouse deltaX and deltaY to rotate the camera, do I multiply or SLERP?

  • Q: If SLERP is the way to go, what's the best way to do rotation, for example, about the y+ (or up relative to worldspace) axis? After a 180 deg rotation there isn't much to rotate to.

    Q: If multiplication is the way to go, how exacly? Dividing x, y and z up into different Quaternions and then multiplying?

Q: I want to rotate my camera's pitch and yaw with mouse movement in the x and y direction. Yet I get some roll, which is quite annoying. How can I negate all roll? Or is there some way to convert my x&y movement into a quaternion with which I can multiply my camera rotation quaternion?

Q: LWJGL's Quaternion class seems to be missing SLERP and multiplyVector methods, should I just extend it and use my own? Or use a quaternion class entirely of my own?

Q: When is normalising your quaternion appropriate?

Questions may seem obvious, but my head is quite the cluster-f**k after contemplating quaternions a lot. Yet, I'm not asking for anyone to provide ready-made code/pseudocode (unless you feel it's the easiest way to explain), telling me to multiply a with b for example helps me enough.

[Edit:] Edited some questions to be shorter and more to the point
20  Game Development / Newbie & Debugging Questions / Re: Forward vector y decreasing at certain Y rotation (OpenGL 3D Camera) on: 2013-08-25 15:34:20
Thanks, I'll look into it!
21  Game Development / Newbie & Debugging Questions / Forward vector y decreasing at certain Y rotation (OpenGL 3D Camera) on: 2013-08-24 17:23:07
Hey there,

I've got a problem with not being able to move down or up when the camera is facing right or left. (Forward being y rotation 0 looking along the z- axis)
What I've got:
- An environment with a few boxes
- A camera that has position and rotation vectors which are converted into an up, left and forward vector and put into a matrix. (the viewmatrix)
- The move method uses a given direction to translate the camera relative to where it is facing. (I.e. press w = move to forward vector)

Weird stuff: Somehow the Y direction gets inverted when between 90 and 270 rotation. (kinda sorta fixed that, but not very well)
Somehow the Y element of the forward vector decreases when getting closer to 90 & 270 rotation around y axis. (need to fix this)

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
package varelse;

import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;

//TODO Incorporate getting the time delta, or maybe do that in the inputManager.

public class CameraModelling implements Camera{
   
   private Vector3f cameraPosition;
   private Vector3f cameraRotation;
   private Vector3f maxRotation;
   private Vector3f minRotation;
   private float moveSpeed;
   private float rotationSpeed;
   private Vector3f lVec;            // The left vector, x
  private Vector3f uVec;            // The up vector, y
  private Vector3f fVec;            // The forward vector, z
  private Matrix4f camMatrix;
   
   CameraModelling () {
      cameraPosition = new Vector3f(0,0,0);
      cameraRotation = new Vector3f(0,0,0);
      maxRotation = new Vector3f(269,0,0);
      minRotation = new Vector3f(89,0,0);
      moveSpeed = 0.01f;
      rotationSpeed = 0.2f;
      camMatrix = new Matrix4f();
     
      lVec = new Vector3f(1,0,0);
      uVec = new Vector3f(0,1,0);
      fVec = new Vector3f(0,0,1);
      updateCamMatrix();
   }
   
   CameraModelling (Vector3f pos, Vector3f rot) {
      this.cameraPosition = pos;
      this.cameraRotation = rot;
      moveSpeed = 0.01f;
      rotationSpeed = 0.2f;
      camMatrix = new Matrix4f();
     
      lVec = new Vector3f(1,0,0);
      uVec = new Vector3f(0,1,0);
      fVec = new Vector3f(0,0,1);
      updateCamMatrix();
   }
   
   private void updateCamMatrix() {
     
      float DEG2RAD = 3.141593f / 180;
      float sx, sy, sz, cx, cy, cz, theta;
     
      theta = cameraRotation.x * DEG2RAD;
      sx = (float) Math.sin(theta);
      cx = (float) Math.cos(theta);
     
      theta = cameraRotation.y * DEG2RAD;
      sy = (float) Math.sin(theta);
      cy = (float) Math.cos(theta);
     
      theta = cameraRotation.z * DEG2RAD;
      sz = (float) Math.sin(theta);
      cz = (float) Math.cos(theta);
     
      lVec.x = cy*cz;
      lVec.y = sx*sy*cz + cx*sz;
      lVec.z = -cx*sy*cz + sx*sz;
     
      uVec.x = -cy*sz;            // up.x = -cy*sz;dd
     uVec.y = -sx*sy*sz + cx*cz;      // up.y = -sx*sy*sz + cx*cz;
     uVec.z = cx*sy*sz + sx*cz;      // up.z = cx*sy*sz + sx*cz;
     
      fVec.x = sy;
      fVec.y = -sx*cy;
      fVec.z = cx*cy;
     
      /* Matrix is shaped like this:
      m00 m10 m20 m30      1.0 0.0 0.0 0.0      lx ux fx px
      m01 m11 m21 m31      0.0 1.0 0.0 0.0      ly uy fy py      // No animals were harmed during the testing of matrix order.
      m02 m12 m22 m32      0.0 0.0 1.0 0.0      lz uz fz pz      // My pride, however, was.
      m03 m13 m23 m33      0.0 0.0 0.0 1.0      lw uw fw pw
      */

     
      camMatrix.m00 = lVec.x;
      camMatrix.m01 = lVec.y;
      camMatrix.m02 = lVec.z;
     
      camMatrix.m10 = uVec.x;
      camMatrix.m11 = uVec.y;
      camMatrix.m12 = uVec.z;
     
      camMatrix.m20 = fVec.x;
      camMatrix.m21 = fVec.y;
      camMatrix.m22 = fVec.z;
     
      camMatrix.m30 = 0;
      camMatrix.m31 = 0;
      camMatrix.m32 = 0;
     
      camMatrix.translate(cameraPosition); // figure out why l, u and f change on translation (lrn2matrix)
     /*
      camMatrix.m30 = cameraPosition.x;
      camMatrix.m31 = cameraPosition.y;   // Doing this causes shenanigans like orbiting around the origin.
      camMatrix.m32 = cameraPosition.z;
      */

      camMatrix.m33 = 1;
     
   }

   public void rotate(Vector3f v0) {
      this.cameraRotation.x += v0.x;
      this.cameraRotation.y += v0.y;
      this.cameraRotation.z += v0.z;
      if (this.cameraRotation.x > minRotation.x && this.cameraRotation.x < maxRotation.x && v0.x < 0) cameraRotation.x = 269;
      if (this.cameraRotation.x > minRotation.x && this.cameraRotation.x < maxRotation.x && v0.x > 0) cameraRotation.x = 89;
      updateCamMatrix();
   }

   public void move(Vector3f dir, float delta) {
     
      // Moves the camera relative to the way it is looking.
     System.out.println("y rotation is " + cameraRotation.y + " y forward vector is " + fVec.y);
      if (dir.z > 0) {
         cameraPosition.x -= (fVec.x * moveSpeed * delta);
         if (cameraRotation.y > 90 && cameraRotation.y < 270) { cameraPosition.y += (fVec.y * moveSpeed * delta); }
         else { cameraPosition.y -= (fVec.y * moveSpeed * delta); }
         cameraPosition.z += (fVec.z * moveSpeed * delta);
      } else if (dir.z < 0) {
         cameraPosition.x += (fVec.x * moveSpeed * delta);
         if (cameraRotation.y > 90 && cameraRotation.y < 270) { cameraPosition.y -= (fVec.y * moveSpeed * delta); } // still not sure why exactly Y goes inverse past 90 rot...
        else { cameraPosition.y += (fVec.y * moveSpeed * delta); }
         cameraPosition.z -= (fVec.z * moveSpeed * delta);
      } else if (dir.x > 0) {
         cameraPosition.x += lVec.x * moveSpeed * delta;
         //cameraPosition.y += lVec.y * moveSpeed; //Don't want to move in Y space when going sideways
        cameraPosition.z -= lVec.z * moveSpeed * delta;
      } else if (dir.x < 0) {
         cameraPosition.x -= lVec.x * moveSpeed * delta;
         //cameraPosition.y -= lVec.y * moveSpeed; //Don't want to move in Y space when going sideways
        cameraPosition.z += lVec.z * moveSpeed * delta;
      } else if (dir.y > 0) {
         cameraPosition.y -= moveSpeed * delta;
      } else if (dir.y < 0) {
         cameraPosition.y += moveSpeed * delta;
      }
      updateCamMatrix();
   }
   
   public Matrix4f getCameraMatrix() {
      Matrix4f matrix = camMatrix;
      return matrix;
   }

   public void setRotation(Vector3f v0) {
      this.cameraRotation.x = v0.x;
      this.cameraRotation.y = v0.y;
      this.cameraRotation.z = v0.z;
      updateCamMatrix();
   }

   public void setPosition(Vector3f v0) {
      this.cameraPosition.x = v0.x;
      this.cameraPosition.y = v0.y;
      this.cameraPosition.z = v0.z;
      updateCamMatrix();
   }

   public Vector3f getRotation() {
      Vector3f v0 = new Vector3f();
      v0 = cameraRotation;
      return v0;
   }

   public Vector3f getPosition() {
      Vector3f v0 = new Vector3f();
      v0 = cameraPosition;
      return v0;
   }

   public void setMoveSpeed(float f) {
      moveSpeed = f;
   }

   public void setRotationSpeed(float f) {
      rotationSpeed = f;
   }

   public float getMoveSpeed() {
      float f = moveSpeed;
      return f;
   }

   public float getRotationSpeed() {
      float f = rotationSpeed;
      return f;
   }
   
   public void log() {
      System.out.println(camMatrix.m00 + " " + camMatrix.m10 + " " + camMatrix.m20 + " " + camMatrix.m30 + " " + uVec.x);
      System.out.println(camMatrix.m01 + " " + camMatrix.m11 + " " + camMatrix.m21 + " " + camMatrix.m31);
      System.out.println(camMatrix.m02 + " " + camMatrix.m12 + " " + camMatrix.m22 + " " + camMatrix.m32);
      System.out.println(camMatrix.m03 + " " + camMatrix.m13 + " " + camMatrix.m23 + " " + camMatrix.m33);
   }
}


Since getting even this to work was a real headbreaker I now feel kinda overwhelmed trying to figure out more. Anyways, any help & pointing in the right direction is appreciated!

(Any other feedback on my code is also very welcome Tongue)
22  Java Game APIs & Engines / OpenGL Development / Re: [Help] mouse 2D coords to 3D coordinates, with a twist on: 2013-05-26 11:40:59
I got it to work!
When initialising OpenGL you need to be sure to add this line:
1  
GL11.glEnable(GL11.GL_DEPTH_TEST)

It allows for testing a pixel's depth value from the depth buffer with glReadPixels()

And for heaven's sake, don't forget to clear your depth buffer! (you do this just before rendering)
1  
GL11.glClear(GL11.COLOR_BUFFER_BIT | GL11.DEPTH_BUFFER_BIT)
23  Java Game APIs & Engines / OpenGL Development / Re: [Help] mouse 2D coords to 3D coordinates, with a twist on: 2013-05-21 11:12:04
Thanks! It seems to work now, apart from that I keep getting the same z value... I'll wrestle with it some more!

About the tutorials, it isn't so much that I'm not learning from them, it's just that understanding all the new stuff each tutorial introduces takes some time to grasp. I.e. I read about something new in tut 2, but only get to fully understanding it in tutorial 4, after using it a couple times.
24  Java Game APIs & Engines / OpenGL Development / [Solved] [Help] mouse 2D coords to 3D coordinates, with a twist on: 2013-05-20 22:48:01
I've rendered a textured 3D cube on screen with glDrawElements. Pretty much built upon the OpenGL tuts on the lwjgl wiki.

Now I want to add cubes to the sides of an existing cube by clicking on the sides, I figured I'd at least need some 3D coordinates for that. Now there's some great posts to find on the internet about using gluUnProject, but they seem to use matrices for immediate rendering, and not the matrices I've been using. (Stuff about Uniform, shader programs, location ints, etc. I only grasp half of it, but keep learning bit by bit)

Getting the 3D position
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
public static FloatBuffer getOGLPos(int x, int y){
     
      IntBuffer viewport = BufferUtils.createIntBuffer(16);
      FloatBuffer modelview = BufferUtils.createFloatBuffer(16);
      FloatBuffer projection = BufferUtils.createFloatBuffer(16);
      FloatBuffer winZ = BufferUtils.createFloatBuffer(3);
      float winX, winY;
      FloatBuffer position = BufferUtils.createFloatBuffer(16);
     
      /* This doesn't seem to be the right thing to do, since I use newer openGL and all...
      GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, modelview);
      GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
      GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);
      */

     

      GL20.glGetUniform(renderer.pId, renderer.modelMatrixLocation, modelview); // This is what I came up with after some google-ing am I doing this right?
     GL20.glGetUniform(renderer.pId, renderer.projectionMatrixLocation, projection);
      GL20.glGetUniform(renderer.pId, renderer.viewMatrixLocation, viewport);
     
      winX = (float)x;
      winY = (float)viewport.get(3) - (float)y;
     
      GL11.glReadPixels(x, (int)winY, 1, 1, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, winZ);
     
      if (winZ.get(0) == 1) {
           return null;
       }
     
      GLU.gluUnProject(winX, winY, winZ.get(), modelview, projection, viewport, position);
     
      return position;
   }


Printing the info in the console
1  
2  
3  
4  
5  
6  
while (Mouse.next()) {
         if (Mouse.isButtonDown(1)) {
            FloatBuffer posBuffer = Utils.getOGLPos(Mouse.getX(), Mouse.getY());
            System.out.println("Clicked @ x: " + posBuffer.get(0) + " y: " + posBuffer.get(1) + " z: " + posBuffer.get(2));
         }
      }


As output I get NaN's for the x, y and z. I'm doing something wrong, somewhere. Do I really need to use glGetUniform? Because using glGetFloat seemed to f**k with my matrices (I get the 3D position in the console, but an openGL error right after that). I figured that was because I was using GL_MODELVIEW_MATRIX, something I only used in openGL examples/tuts using immediate mode.

Please note, I've only used Java (and serious programming altogether) since October and OpenGL since a few weeks. I'm rushing head over heels into game programming to get a portfolio set up before/during the summer break. I'll make loads of mistakes, sorry. But at least I'm learning, and fast too.

Long story short: Look at code, facepalm, cuss, give link/corrected code/stuff I need to look up on.

Pages: [1]
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

ctomni231 (34 views)
2014-07-18 06:55:21

Zero Volt (30 views)
2014-07-17 23:47:54

danieldean (25 views)
2014-07-17 23:41:23

MustardPeter (27 views)
2014-07-16 23:30:00

Cero (42 views)
2014-07-16 00:42:17

Riven (44 views)
2014-07-14 18:02:53

OpenGLShaders (33 views)
2014-07-14 16:23:47

Riven (34 views)
2014-07-14 11:51:35

quew8 (30 views)
2014-07-13 13:57:52

SHC (66 views)
2014-07-12 17:50:04
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!