Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (476)
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   
Pages: [1]
  ignore  |  Print  
  Free flying Quaternion camera questions [Kind of working, but in a bad way]  (Read 3760 times)
0 Members and 1 Guest are viewing this topic.
Offline Graftwijgje

Senior Newbie


Medals: 1



« Posted 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
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #1 - Posted 2013-09-15 21:39:27 »

Q1 + Q2:
For a free-flying camera, you have only two components: a quaternion for orientation and a vec3 for position.

For looking around, you multiply the change in rotation with the current quaternion.
For position movement, you store the change in movement in a temporary vec3, multiply it by the inverse of the orientation quaternion, then add it in to the position vec3.

When rendering, the view matrix is built by converting the orientation quaternion to a matrix and translating by the position vec3.

Q3: Best to create your own. You can just copy mine.

Q4: Normalize your quaternion after every transformation.


Figuring this out took a shitton of thinking, visualizations, and drawing, so don't feel too bad that you couldn't easily figure it out. Smiley

Here's some code to get you started:
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  
//in your update code
float speed = (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) | Keyboard.isKeyDown(Keyboard.KEY_RSHIFT) ? 20 : 50) * deltaTime / (float)1e9;
float rotSpeed = 1.5f * speed;

//pitch
int dy = Mouse.getDY();
if(dy != 0)
   orientation = Utils.angleAxisDeg(-dy * rotSpeed, new Vector3(1, 0, 0)).mult(orientation);

//yaw
int dx = Mouse.getDX();
if(dx != 0)
   orientation = Utils.angleAxisDeg(dx * rotSpeed, new Vector3(0, 1, 0)).mult(orientation);

//roll
if(Keyboard.isKeyDown(Keyboard.KEY_E))
   orientation = Utils.angleAxisDeg(rotSpeed, new Vector3(0, 0, 1)).mult(orientation);
if(Keyboard.isKeyDown(Keyboard.KEY_Q))
   orientation = Utils.angleAxisDeg(-rotSpeed, new Vector3(0, 0, 1)).mult(orientation);

orientation.normalize();

Quaternion inverse = orientation.copy().inverse();

Vector3 delta = new Vector3();

if(Keyboard.isKeyDown(Keyboard.KEY_S))
   delta.z(-speed);
if(Keyboard.isKeyDown(Keyboard.KEY_W))
   delta.z(delta.z() + speed);

if(Keyboard.isKeyDown(Keyboard.KEY_D))
   delta.x(-speed);
if(Keyboard.isKeyDown(Keyboard.KEY_A))
   delta.x(delta.x() + speed);

if(Keyboard.isKeyDown(Keyboard.KEY_SPACE))
   delta.y(-speed);
if(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL))
   delta.y(delta.y() + speed);

position.add(inverse.mult(delta));


//in your render code
Matrix4 viewMatrix = orientation.toMatrix().translate(position);


//Utils.angleAxisDeg
public static Quaternion angleAxisDeg(float angle, Vector3 vec) {
   return new Quaternion((float)Math.toRadians(angle), vec);
}

Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #2 - Posted 2013-09-15 21:44:14 »

Wow, this is great! Thanks a ton for taking the time to answer my questions so well!  Cheesy
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #3 - Posted 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.
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #4 - Posted 2013-09-17 00:30:27 »

Concerning the deleted portion: that's the behavior when you multiply the delta by the original. The correct behavior is when you multiply the delta by the inverse, so you must be doing something wrong, post code Smiley

Second part: simple, you have to think about what space is being multiplied by. Since you don't want roll, you want horizontal movements to be fixed on the world's X-axis, therefore you should multiply the current orientation with the Quaternion created using (0, 1, 0) as the rotation angle (for Mouse.getDX()) so it looks like this:
1  
2  
if(dx != 0)
    orientation.mult(Utils.angleAxisDeg(dx * rotSpeed, new Vector3(0, 1, 0)));

Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #5 - Posted 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
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #6 - Posted 2013-09-18 06:03:16 »

I believe I have figured it out. I forgot to tell you that the
cameraPosition
should be negative the actual position.

In your
setPosition
method, negate the Vector3f. Make sure you call
setPosition
from the constructor. You can change the whole
setPosition
method to
this.cameraPosition = new Vector3f(v0).negate();


Also in your
getPosition
method, you're not creating a new object of the
cameraPosition
so it could be accidentally modified from outside. Make sure you do
return new Vector3f(cameraPosition).negate();



Now use the inverse quaternion again and test!

Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #7 - Posted 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);
   }
}
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #8 - Posted 2013-09-24 03:26:11 »

I don't see anything wrong with this code at all, so I'm assuming the problem is in rendering/shaders.

Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #9 - Posted 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);
}
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #10 - Posted 2013-10-03 22:33:08 »

I don't see anything wrong really. Can you post *all* your code to http://pastebin.java-gaminmg.org ? I want to run this locally.

Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #11 - Posted 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.
Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #12 - Posted 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.
Offline ra4king

JGO Kernel


Medals: 336
Projects: 2
Exp: 5 years


I'm the King!


« Reply #13 - Posted 2013-10-05 04:34:02 »

I seem to be missing two shaders: "src\newOpengl\texMatVertex.glsl" and the Fragment version.

Offline Graftwijgje

Senior Newbie


Medals: 1



« Reply #14 - Posted 2013-10-05 10:46:44 »

Those are the same as res/shaders/Fragment.glsl and Vertex.glsl. Sorry for the confusion  Lips Sealed
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

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

The first screenshot will be displayed as a thumbnail.

pw (12 views)
2014-07-24 01:59:36

Riven (10 views)
2014-07-23 21:16:32

Riven (11 views)
2014-07-23 21:07:15

Riven (12 views)
2014-07-23 20:56:16

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

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

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

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

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

Riven (50 views)
2014-07-14 18:02:53
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!