diff --git a/README.md b/README.md
index 493f9d2..95353c3 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
# JRTR Base Code
-This project contains base code developed for an introduction to computer graphics course taught by Matthias Zwicker at the University of Maryland, College Park ([CMSC427, Computer Graphics](https://cs.umd.edu/class)). This is educational code intended for students to learn about 3D graphics programming. The framework provides a skeleton for a real-time rendering engine.
+This project contains base code developed for an introduction to computer graphics course taught by Matthias Zwicker at the University of Maryland, College Park ([CMSC427, Computer Graphics](https://cs.umd.edu/class)). This is educational code intended for students to learn about 3D graphics programming. The framework provides a skeleton for a real-time rendering engine. It is modular to support different rendering back-ends, coming with an OpenGL-based renderer, and a renderer using OpenGL and OpenVR to render onto VR goggles.
## Getting Started
@@ -15,6 +15,11 @@ After importing the project, you'll need to make two adjustments in order for th
After that, you're all set! You should be able to run the base code on your machine.
+### For OpenVR sample
+To run the "simpleVR" project, you must have access to a Windows PC with a VR-compatible dedicated graphics card and a tethered VR headset. First, you should install [SteamVR on Steam](https://store.steampowered.com/app/250820/SteamVR/) in order to obtain the OpenVR runtime on your computer. You should try running the SteamVR app to make sure there are no issues connecting to the VR headset. After that, you should be able to run the "simpleVR" project.
+
+In some cases, your computer may default to running your Java project with your CPU's integrated graphics, which might cause nothing to render onto your VR headset's display. To fix this, you should force your computer to use the dedicated graphics card. On a computer with an NVIDIA GPU, this can be achieved using the NVIDIA Control Panel.
+
## Known issues
### Maven dependencies
diff --git a/jrtr/pom.xml b/jrtr/pom.xml
index b342e30..d36cc1d 100644
--- a/jrtr/pom.xml
+++ b/jrtr/pom.xml
@@ -5,7 +5,7 @@
0.0.1-SNAPSHOT
- 3.2.3
+ 3.3.0
@@ -128,6 +128,10 @@
org.lwjgllwjgl-opengl
+
+ org.lwjgl
+ lwjgl-openvr
+ org.lwjgllwjgl-stb
@@ -157,6 +161,11 @@
lwjgl-opengl${lwjgl.natives}
+
+ org.lwjgl
+ lwjgl-openvr
+ ${lwjgl.natives}
+ org.lwjgllwjgl-stb
diff --git a/jrtr/src/main/java/jrtr/gldeferredrenderer/FrameBuffer.java b/jrtr/src/main/java/jrtr/gldeferredrenderer/FrameBuffer.java
new file mode 100644
index 0000000..9d7f5e5
--- /dev/null
+++ b/jrtr/src/main/java/jrtr/gldeferredrenderer/FrameBuffer.java
@@ -0,0 +1,41 @@
+package jrtr.gldeferredrenderer;
+
+import static org.lwjgl.opengl.GL46.*;
+
+/**
+ * A simple GLBuffer, which contains only one texture.
+ * This class can be used for ping pong buffers.
+ * @author Heinrich Reich
+ *
+ */
+public class FrameBuffer extends GLBuffer{
+
+
+ public FrameBuffer(int width, int height, boolean useDepthBuffer) throws RuntimeException{
+ super(width, height, 1, useDepthBuffer, GL_RGB8);
+ }
+
+ FrameBuffer(int width, int height, boolean useDepthBuffer, int format){
+ super(width, height, 1, useDepthBuffer, format);
+ }
+
+ /**
+ * Basically the same as {@link GLBuffer#beginRead(int)}.
+ */
+ public void beginRead(){
+ super.beginRead(0);
+ }
+
+ @Override
+ protected void handleCreationError(boolean failed) throws RuntimeException{
+ if(failed)
+ throw new RuntimeException("Error occured while creating the framebuffer object!");
+ }
+
+ /**
+ * @return the internal OpenGL id of the texture.
+ */
+ public int getRenderedTexture(){
+ return this.textures.get(0);
+ }
+}
\ No newline at end of file
diff --git a/jrtr/src/main/java/jrtr/gldeferredrenderer/GLBuffer.java b/jrtr/src/main/java/jrtr/gldeferredrenderer/GLBuffer.java
new file mode 100644
index 0000000..c2d86cd
--- /dev/null
+++ b/jrtr/src/main/java/jrtr/gldeferredrenderer/GLBuffer.java
@@ -0,0 +1,212 @@
+package jrtr.gldeferredrenderer;
+
+import java.nio.*;
+
+import static org.lwjgl.opengl.GL46.*;
+import static org.lwjgl.system.MemoryUtil.*;
+
+/**
+ * A simple class for creating, reading, and writing to an OpenGL framebuffer object (FBO).
+ * FBOs are the key OpenGL data structures for writing (rendering) and reading from off-screen
+ * images and textures.
+ *
+ * @author Heinrich Reich
+ *
+ */
+public abstract class GLBuffer {
+
+ // references to the different OpenGL objects
+ public IntBuffer frameBuffer, drawBuffers, textures, depthBuffer;
+ // format and render target index
+ public final int format, renderTargets;
+ // temporary indices of read and written fbo
+ // width and height of the textures in this buffer
+ private int prevWriteFBO, prevReadFBO, width, height;
+ // whether to use depth buffer or not
+ public final boolean useDepthBuffer;
+
+ /**
+ * Creates a new OpenGL framebuffer object (FBO).
+ * @param gl the OpenGL context
+ * @param width the width of the textures
+ * @param height the height of the texture
+ * @param renderTargets number of textures/render targets
+ * @param useDepthBuffer whether to use a depth buffer
+ * @param format the format
+ */
+ public GLBuffer(int width, int height, int renderTargets, boolean useDepthBuffer, int format){
+ this.renderTargets = renderTargets;
+ this.width = width;
+ this.height = height;
+ this.format = format;
+ this.useDepthBuffer = useDepthBuffer;
+ this.init();
+ }
+
+ /**
+ * Creates a new OpenGL framebuffer object (FBO) with a default GL3.GL_RGB8 format.
+ * @param gl
+ * @param width
+ * @param height
+ * @param renderTargets
+ * @param useDepthBuffer
+ */
+ public GLBuffer(int width, int height, int renderTargets, boolean useDepthBuffer){
+ this(width, height, renderTargets, useDepthBuffer, GL_RGB8);
+ }
+
+ /**
+ * Initialize the OpenGL framebuffer object (FBO). First we generate a framebuffer object
+ * and bind it as the current buffer. Then we create as many textures as specified in
+ * {@link GLBuffer#GLBuffer}. If needed, we also create a depth buffer for the render target.
+ * Later (after we rendered into the FBO), we can read from these textures via the
+ * usual OpenGL functionality.
+ * The abstract method {@link GLBuffer#handleCreationError} gets called here.
+ */
+ private void init(){
+ this.frameBuffer = memAllocInt(1);
+ this.textures = memAllocInt(renderTargets);
+ this.drawBuffers = memAllocInt(renderTargets);
+
+ // Generate a reference to a FBO and bind it ("activate it")
+ glGenFramebuffers(frameBuffer);
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer.get(0));
+
+ // Create references for the FBO textures
+ glGenTextures(textures);
+
+ // Attach textures to the FBO
+ for (int i = 0 ; i < textures.capacity() ; i++) {
+ glBindTexture(GL_TEXTURE_2D, this.textures.get(i));
+ glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, GL_RGBA, GL_FLOAT, (FloatBuffer) null);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+ // Each texture will be linked to a buffer index i; the corresponding index is used in the shader
+ // using the directive layout(location = i) to address this texture
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, this.textures.get(i), 0);
+ }
+
+ // Depth texture
+ if(this.useDepthBuffer) this.createDepthBuffer();
+
+ for(int i = 0; i< drawBuffers.capacity(); i++)
+ drawBuffers.put(i, GL_COLOR_ATTACHMENT0+i);
+ glDrawBuffers(drawBuffers);
+
+ this.handleCreationError(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE);
+
+ // Bind default render and frame buffer ("deactivate" the FBO we just created)
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ glBindRenderbuffer(GL_RENDERBUFFER, 0);
+ }
+
+ /**
+ * Resizes the frame buffer, i.e. destroys the buffer and its textures,
+ * and re-initializes the buffer with the new dimensions.
+ * @param width
+ * @param height
+ */
+ public void resize(int width, int height){
+ this.width = width;
+ this.height = height;
+ this.dispose();
+ this.init();
+ }
+
+ /**
+ * Gets called after the initialization.
+ * @param failed true if an error occurred during initialization step.
+ */
+ protected abstract void handleCreationError(boolean failed);
+
+ /**
+ * Binds ("activate") this FBO, so any rendering calls will draw into this FBO.
+ * Use {@link GLBuffer#endWrite()} when you are finished with writing.
+ */
+ public void beginWrite(){
+ // Store current FBO to restore when done with writing
+ this.prevWriteFBO = glGetInteger(GL_DRAW_FRAMEBUFFER);
+
+ // Bind this FBO
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer.get(0));
+ glViewport(0, 0, width, height);
+ }
+
+ /**
+ * Unbinds this framebuffer, i.e. binds the previous buffer again.
+ * Only use this method if you called {@link GLBuffer#beginWrite()} before.
+ */
+ public void endWrite(){
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, this.prevWriteFBO);
+ }
+
+ /**
+ * Begins reading from a texture from this FBO by binding ("activating") it.
+ * Use {@link GLBuffer#endRead()} if you are done with reading.
+ * @param i the id of the wished texture.
+ */
+ public void beginRead(int i){
+ if(this.prevReadFBO != this.frameBuffer.get(0)){
+ this.prevReadFBO = glGetInteger(GL_READ_FRAMEBUFFER);
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBuffer.get(0));
+ }
+ glReadBuffer(GL_COLOR_ATTACHMENT0+i);
+ }
+
+ /**
+ * Ends reading from this buffer.
+ * Only use this method if you called {@link GLBuffer#beginRead(int)} before.
+ */
+ public void endRead(){
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, this.prevReadFBO);
+ }
+
+ /**
+ * Does all OpenGL calls for creating a depth buffer for this buffer.
+ */
+ private void createDepthBuffer(){
+ this.depthBuffer = memAllocInt(1);
+ glGenTextures(this.depthBuffer);
+ glBindTexture(GL_TEXTURE_2D, this.depthBuffer.get(0));
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, (FloatBuffer) null);
+ glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, this.depthBuffer.get(0), 0);
+ }
+
+ /**
+ * Disposes this buffer and its textures, i.e. releases all memory.
+ */
+ public void dispose(){
+ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
+ if(this.useDepthBuffer) glDeleteTextures(depthBuffer);
+ glDeleteTextures(textures);
+ glDeleteFramebuffers(frameBuffer);
+ memFree(frameBuffer);
+ memFree(textures);
+ if(this.useDepthBuffer) memFree(depthBuffer);
+ }
+
+ /**
+ * @return the current set width.
+ */
+ public int getWidth(){
+ return this.width;
+ }
+
+ /**
+ * @return the current set height.
+ */
+ public int getHeight(){
+ return this.height;
+ }
+
+ /**
+ * @param index
+ * @return the internal texture index in OpenGL, need for passing textures to a shader.
+ */
+ public int getTexture(int index){
+ return this.textures.get(index);
+ }
+
+}
diff --git a/jrtr/src/main/java/jrtr/gldeferredrenderer/package-info.java b/jrtr/src/main/java/jrtr/gldeferredrenderer/package-info.java
new file mode 100644
index 0000000..222d630
--- /dev/null
+++ b/jrtr/src/main/java/jrtr/gldeferredrenderer/package-info.java
@@ -0,0 +1,4 @@
+/**
+ * An OpenGL renderer with deferred shading implementing the {@link jrtr} interfaces.
+ */
+package jrtr.gldeferredrenderer;
\ No newline at end of file
diff --git a/jrtr/src/main/java/jrtr/glrenderer/GLVertexArrayObject.java b/jrtr/src/main/java/jrtr/glrenderer/GLVertexArrayObject.java
index ad2e645..ecf4844 100644
--- a/jrtr/src/main/java/jrtr/glrenderer/GLVertexArrayObject.java
+++ b/jrtr/src/main/java/jrtr/glrenderer/GLVertexArrayObject.java
@@ -1,10 +1,9 @@
package jrtr.glrenderer;
-import java.nio.IntBuffer;
+import java.nio.*;
-import static org.lwjgl.opengl.GL45.*;
-
-//import com.jogamp.opengl.GL3;
+import static org.lwjgl.opengl.GL46.*;
+import static org.lwjgl.system.MemoryUtil.*;
/**
* A utility class to encapsulate an OpenGL "vertex array object" (VAO).
@@ -13,9 +12,7 @@ public class GLVertexArrayObject {
private IntBuffer vao;
private IntBuffer vbo;
-
-// private GL3 gl;
-
+
/**
* Make an OpenGL "vertex array object" (VAO) with a desired number of
* "vertex buffer objects" (VBOs). Each VBO refers to a buffer
@@ -26,16 +23,15 @@ public class GLVertexArrayObject {
* the number of VBOs to be stored in the VAO
*/
public GLVertexArrayObject(int numberOfVBOs) {
-
// For all vertex attributes, make vertex buffer objects.
// References to the VBOs are stored in the array vbo.
- vbo = IntBuffer.allocate(numberOfVBOs);
+ vbo = memAllocInt(numberOfVBOs);
for(int i=0; i itr = vertexData.getElements().listIterator(0);
+ vertexData.getVAO().rewindVBO();
+ while (itr.hasNext()) {
+ VertexData.VertexElement e = itr.next();
+ int dim = e.getNumberOfComponents();
+
+ // Bind the next vertex buffer object
+ glBindBuffer(GL_ARRAY_BUFFER, vertexData.getVAO().getNextVBO());
+
+ // Tell OpenGL which "in" variable in the vertex shader corresponds
+ // to the current vertex buffer object.
+ // We use our own convention to name the variables, i.e.,
+ // "position", "normal", "color", "texcoord", or others if
+ // necessary.
+ int attribIndex = -1;
+ switch (e.getSemantic()) {
+ case POSITION:
+ attribIndex = glGetAttribLocation(activeShaderID, "position");
+ break;
+ case NORMAL:
+ attribIndex = glGetAttribLocation(activeShaderID, "normal");
+ break;
+ case COLOR:
+ attribIndex = glGetAttribLocation(activeShaderID, "color");
+ break;
+ case TEXCOORD:
+ attribIndex = glGetAttribLocation(activeShaderID, "texcoord");
+ break;
+ }
+
+ glVertexAttribPointer(attribIndex, dim, GL_FLOAT, false, 0, 0);
+ glEnableVertexAttribArray(attribIndex);
+ }
+
+ // Render the vertex buffer objects
+ glDrawElements(GL_TRIANGLES, renderItem.getShape().getVertexData().getIndices().length, GL_UNSIGNED_INT, 0);
+
+ // we are done with this shape, bind the default vertex array
+ glBindVertexArray(0);
+
+ cleanMaterial(renderItem.getShape().getMaterial());
+ }
+
+ /**
+ * A utility method to load vertex data into an OpenGL "vertex array object"
+ * (VAO) for efficient rendering.
+ *
+ * @param data
+ * reference to the vertex data to be loaded into a VAO
+ */
+ private void initArrayBuffer(GLVertexData data) {
+
+ // Make a vertex array object (VAO) for this vertex data
+ GLVertexArrayObject vao = new GLVertexArrayObject(data.getElements().size() + 1);
+ // vertexArrayObjects.add(vao);
+ data.setVAO(vao);
+
+ // Bind (activate) the VAO for the vertex data
+ vao.bind();
+
+ // Store all vertex attributes in the buffers
+ ListIterator itr = data.getElements()
+ .listIterator(0);
+ while (itr.hasNext()) {
+ VertexData.VertexElement e = itr.next();
+
+ // Bind the next vertex buffer object
+ glBindBuffer(GL_ARRAY_BUFFER, data.getVAO().getNextVBO());
+ // Upload vertex data
+ glBufferData(GL_ARRAY_BUFFER, e.getData(), GL_DYNAMIC_DRAW);
+ }
+
+ // bind the default vertex buffer objects
+ glBindBuffer(GL_ARRAY_BUFFER, 0);
+
+ // store the indices into the last buffer
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, data.getVAO().getNextVBO());
+ glBufferData(GL_ELEMENT_ARRAY_BUFFER, data.getIndices(), GL_DYNAMIC_DRAW);
+
+ // bind the default vertex array object
+ glBindVertexArray(0);
+ }
+
+ private void setTransformation(Matrix4f transformation) {
+ // Compute the modelview matrix by multiplying the camera matrix and
+ // the transformation matrix of the object
+ Matrix4f modelview = new Matrix4f(sceneManager.getCamera()
+ .getCameraMatrix());
+ modelview.mul(transformation);
+
+ // Set modelview and projection matrices in shader
+ glUniformMatrix4fv(
+ glGetUniformLocation(activeShaderID, "modelview"), false,
+ transformationToFloat16(modelview));
+ glUniformMatrix4fv(glGetUniformLocation(activeShaderID,
+ "projection"), false, transformationToFloat16(sceneManager
+ .getFrustum().getProjectionMatrix()));
+
+ }
+
+ /**
+ * Pass the material properties to OpenGL, including textures and shaders.
+ *
+ * Implementation here is incomplete. It's just for demonstration purposes.
+ */
+ private void setMaterial(Material m) {
+
+ // Set up the shader for the material, if it has one
+ if(m != null && m.shader != null) {
+ useShader(m.shader);
+
+ // Pass shininess parameter to shader
+ int id = glGetUniformLocation(activeShaderID, "shininess");
+ if(id!=-1)
+ glUniform1f(id, m.shininess);
+ else
+ System.out.print("Could not get location of uniform variable shininess\n");
+
+ // Activate the texture, if the material has one
+ if(m.texture != null) {
+ // OpenGL calls to activate the texture
+ glActiveTexture(GL_TEXTURE0); // Work with texture unit 0
+ glEnable(GL_TEXTURE_2D);
+ glBindTexture(GL_TEXTURE_2D, ((GLTexture)m.texture).getId());
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ id = glGetUniformLocation(activeShaderID, "myTexture");
+ glUniform1i(id, 0); // The variable in the shader needs to be set to the desired texture unit, i.e., 0
+ }
+
+ // Pass light source information to shader, iterate over all light sources
+ Iterator iter = sceneManager.lightIterator();
+ int i=0;
+ Light l;
+ if(iter != null) {
+
+ while(iter.hasNext() && i<8)
+ {
+ l = iter.next();
+
+ // Pass light direction to shader
+ String lightString = "lightDirection[" + i + "]";
+ id = glGetUniformLocation(activeShaderID, lightString);
+ if(id!=-1)
+ glUniform4f(id, l.direction.x, l.direction.y, l.direction.z, 0.f); // Set light direction
+ else
+ System.out.print("Could not get location of uniform variable " + lightString + "\n");
+
+ i++;
+ }
+
+ // Pass number of lights to shader
+ id = glGetUniformLocation(activeShaderID, "nLights");
+ if(id!=-1)
+ glUniform1i(id, i); // Set number of lights
+ else
+ System.out.print("Could not get location of uniform variable nLights\n");
+
+ }
+
+ }
+ }
+
+ /**
+ * Disable a material.
+ *
+ * To be implemented in the "Textures and Shading" project.
+ */
+ private void cleanMaterial(Material m) {
+ }
+
+ public void useShader(Shader s) {
+ if (s != null) {
+ activeShaderID = ((GLShader)s).programId();
+ glUseProgram(activeShaderID);
+ }
+ }
+
+ public Shader makeShader() {
+ return new GLShader();
+ }
+
+ public Texture makeTexture() {
+ return new GLTexture();
+ }
+
+ public VertexData makeVertexData(int n) {
+ return new GLVertexData(n);
+ }
+
+ /**
+ * Convert a Transformation to a float array in column major ordering, as
+ * used by OpenGL.
+ */
+ private static float[] transformationToFloat16(Matrix4f m) {
+ float[] f = new float[16];
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ f[j * 4 + i] = m.getElement(i, j);
+ return f;
+ }
+
+ /**
+ * Disposes all disposables
+ */
+ public void dispose(){
+ this.vrBuffer.dispose();
+ }
+
+ @Override
+ public void useDefaultShader() {
+ // TODO Auto-generated method stub
+
+ }
+
+}
+
diff --git a/jrtr/src/main/java/jrtr/glrenderer/VRRenderPanel.java b/jrtr/src/main/java/jrtr/glrenderer/VRRenderPanel.java
new file mode 100644
index 0000000..1677594
--- /dev/null
+++ b/jrtr/src/main/java/jrtr/glrenderer/VRRenderPanel.java
@@ -0,0 +1,307 @@
+package jrtr.glrenderer;
+
+import java.nio.*;
+
+import javax.vecmath.*;
+
+import org.lwjgl.glfw.*;
+import org.lwjgl.opengl.*;
+import org.lwjgl.openvr.*;
+import org.lwjgl.system.*;
+import static org.lwjgl.glfw.GLFW.*;
+import static org.lwjgl.opengl.GL11.*;
+import static org.lwjgl.openvr.VR.*;
+import static org.lwjgl.openvr.VRCompositor.*;
+import static org.lwjgl.openvr.VRSystem.*;
+import static org.lwjgl.system.MemoryStack.*;
+import static org.lwjgl.system.MemoryUtil.*;
+
+import jrtr.*;
+
+/**
+ * An implementation of the {@link RenderPanel} interface using
+ * OpenGL. The interface to OpenGL and the native window system
+ * are provided by the LWJGL and GLFW libraries. The class
+ * {@link VRRenderContext} performs the actual rendering. Note
+ * that all OpenGL calls apply to the GLFW window that is created
+ * by the current thread.
+ *
+ * The user needs to extend this class and provide an
+ * implementation for the init call-back function.
+ */
+public abstract class VRRenderPanel implements RenderPanel {
+
+ // Access to OpenVR native data structures containing 3D tracked device poses
+ protected static TrackedDevicePose.Buffer hmdTrackedDevicePoses;
+
+ public static final VRControllerState.Buffer cStates = VRControllerState.create(k_unMaxTrackedDeviceCount);
+
+ // Provides application access to data from OpenVR
+ public boolean posesReady;
+ public Matrix4f[] poseMatrices;
+ public boolean[] poseValid;
+ public Matrix4f headToLeftEye;
+ public Matrix4f headToRightEye;
+ public Matrix4f leftProjectionMatrix;
+ public Matrix4f rightProjectionMatrix;
+ public int controllerIndexHand, controllerIndexRacket;
+ public int targetWidth, targetHeight;
+
+ // The window handle
+ protected long window;
+
+ // Fixed time step to perform some periodic tasks
+ protected double timeStep;
+
+ private VRRenderContext renderContext;
+
+ public VRRenderPanel()
+ {
+ // Initizalize OpenVR
+
+ System.out.println("OpenVR library is present: " + VR_IsHmdPresent());
+
+ try (MemoryStack stack = stackPush()) {
+ IntBuffer hmdErrorStore = stack.mallocInt(1);
+ int token = VR_InitInternal(hmdErrorStore, EVRApplicationType_VRApplication_Scene);
+
+ // Get access to IVRSystem functions
+ if( hmdErrorStore.get(0) == 0 ) {
+ // Try and get the vrsystem pointer..
+ VR_GetGenericInterface(IVRSystem_Version, hmdErrorStore);
+ }
+ if( hmdErrorStore.get(0) != 0 ) {
+ System.out.println("OpenVR Initialize Result: " + VR_GetVRInitErrorAsEnglishDescription(hmdErrorStore.get(0)));
+ return;
+ }
+
+ OpenVR.create(token);
+
+ System.out.println("OpenVR System initialized & VR connected.");
+
+ IntBuffer width = stack.mallocInt(1);
+ IntBuffer height = stack.mallocInt(1);
+ VRSystem_GetRecommendedRenderTargetSize(width, height);
+ targetWidth = width.get(0);
+ targetHeight = height.get(0);
+ System.out.println("Target render size " + width.get(0) + " x " + height.get(0));
+
+ // Get access to IVRCompositor functions
+ VR_GetGenericInterface(IVRCompositor_Version, hmdErrorStore);
+ if(hmdErrorStore.get(0) != 0 ){
+ System.out.println("OpenVR Initialize Result: " + VR_GetVRInitErrorAsEnglishDescription(hmdErrorStore.get(0)));
+ return;
+ }
+
+ System.out.println("OpenVR Compositor initialized.\n");
+
+ VRCompositor_SetTrackingSpace(ETrackingUniverseOrigin_TrackingUniverseSeated);
+
+ // Prepare tracking matrices
+ hmdTrackedDevicePoses = TrackedDevicePose.create(k_unMaxTrackedDeviceCount);
+ poseMatrices = new Matrix4f[k_unMaxTrackedDeviceCount];
+ poseValid = new boolean[k_unMaxTrackedDeviceCount];
+ for(int i=0;i {
+ glViewport(0, 0, width, height);
+ renderContext.resize(width, height);
+ });
+
+ // Run the rendering loop until the user has attempted to close
+ // the window or has pressed the ESCAPE key.
+ double t0 = glfwGetTime();
+ timeStep = 1d/90; // 90 FPS
+ while ( !glfwWindowShouldClose(window) ) {
+
+ // Execute next time step
+ double t1 = glfwGetTime();
+ if(t1-t0 > timeStep)
+ {
+ executeStep();
+ renderContext.display();
+ t0=t1;
+ }
+
+ glfwSwapBuffers(window); // swap the color buffers
+
+ // Poll for window events. The key callback above will only be
+ // invoked during this call.
+ glfwPollEvents();
+ }
+ }
+
+ public boolean getSideTouched(int idx){
+ return cStates.get(idx).ulButtonTouched() == 4 || cStates.get(idx).ulButtonTouched() == 2;
+ }
+
+ public boolean getTriggerTouched(int idx){
+ //we have access to the raw data. If the trigger is pushed down, ulButtonTouched=8589934592
+ return cStates.get(idx).ulButtonTouched() == 8589934592l;
+ }
+
+ public void triggerHapticPulse(int idx, float t){
+ VRSystem_TriggerHapticPulse(idx, 0, (short)Math.round(3f * t / 1e-3f));
+ }
+
+ /**
+ * This call-back function needs to be implemented by the user.
+ */
+ abstract public void init(RenderContext renderContext);
+
+ /**
+ * May be overwritten by the user to clean up.
+ */
+ public void dispose()
+ {
+ renderContext.dispose(); //required if we don't use any FBOs?
+ // This call makes sure we wait and give other threads enough time
+ // (like a timer that triggers rendering of animation frames)
+ // that may still call OpenVR functionality to finish first
+ waitGetPoses();
+ VR_ShutdownInternal();
+ }
+
+ /**
+ * Wait and get 3D tracking poses (HMD and controllers) from OpenVR. Needs to be called before rendering
+ * and passing the rendered image to the OpenVR compositor.
+ */
+ public void waitGetPoses()
+ {
+ VRCompositor_WaitGetPoses(hmdTrackedDevicePoses, null);
+ posesReady = true;
+
+ VRSystem_GetControllerState(controllerIndexHand, cStates.get(controllerIndexHand));
+ cStates.get(controllerIndexHand).ulButtonTouched();
+
+ // Get head-to-eye transformations
+ HmdMatrix34 leftEyeToHead = HmdMatrix34.create();
+ VRSystem_GetEyeToHeadTransform(0, leftEyeToHead);
+ headToLeftEye = new Matrix4f(leftEyeToHead.m(0), leftEyeToHead.m(1), leftEyeToHead.m(2), leftEyeToHead.m(3),
+ leftEyeToHead.m(4), leftEyeToHead.m(5), leftEyeToHead.m(6), leftEyeToHead.m(7),
+ leftEyeToHead.m(8), leftEyeToHead.m(9), leftEyeToHead.m(10), leftEyeToHead.m(11),
+ 0f, 0f, 0f, 1f);
+ headToLeftEye.invert();
+ HmdMatrix34 rightEyeToHead = HmdMatrix34.create();
+ VRSystem_GetEyeToHeadTransform(1, rightEyeToHead);
+ headToRightEye = new Matrix4f(rightEyeToHead.m(0), rightEyeToHead.m(1), rightEyeToHead.m(2), rightEyeToHead.m(3),
+ rightEyeToHead.m(4), rightEyeToHead.m(5), rightEyeToHead.m(6), rightEyeToHead.m(7),
+ rightEyeToHead.m(8), rightEyeToHead.m(9), rightEyeToHead.m(10), rightEyeToHead.m(11),
+ 0f, 0f, 0f, 1f);
+ headToRightEye.invert();
+
+ // Get projection matrices
+ HmdMatrix44 lPr = HmdMatrix44.create();
+ VRSystem_GetProjectionMatrix(0, .1f, 40.f, lPr);
+ leftProjectionMatrix = new Matrix4f(lPr.m(0), lPr.m(1), lPr.m(2), lPr.m(3),
+ lPr.m(4), lPr.m(5), lPr.m(6), lPr.m(7),
+ lPr.m(8), lPr.m(9), lPr.m(10), lPr.m(11),
+ lPr.m(12), lPr.m(13), lPr.m(14), lPr.m(15));
+ HmdMatrix44 rPr = HmdMatrix44.create();
+ VRSystem_GetProjectionMatrix(1, .1f, 40.f, rPr);
+ rightProjectionMatrix = new Matrix4f(rPr.m(0), rPr.m(1), rPr.m(2), rPr.m(3),
+ rPr.m(4), rPr.m(5), rPr.m(6), rPr.m(7),
+ rPr.m(8), rPr.m(9), rPr.m(10), rPr.m(11),
+ rPr.m(12), rPr.m(13), rPr.m(14), rPr.m(15));
+
+ // Read tracked poses data from native
+ for (int nDevice = 0; nDevice < k_unMaxTrackedDeviceCount; ++nDevice ){
+ ;
+ if( hmdTrackedDevicePoses.get(nDevice).bPoseIsValid() ){
+ HmdMatrix34 hmdMatrix = hmdTrackedDevicePoses.get(nDevice).mDeviceToAbsoluteTracking();
+ poseMatrices[nDevice] = new Matrix4f(hmdMatrix.m(0), hmdMatrix.m(1), hmdMatrix.m(2), hmdMatrix.m(3),
+ hmdMatrix.m(4), hmdMatrix.m(5), hmdMatrix.m(6), hmdMatrix.m(7),
+ hmdMatrix.m(8), hmdMatrix.m(9), hmdMatrix.m(10), hmdMatrix.m(11),
+ 0f, 0f, 0f, 1f);
+ poseValid[nDevice] = true;
+ } else {
+ poseValid[nDevice] = false;
+ }
+ }
+ }
+}
diff --git a/simpleVR/.classpath b/simpleVR/.classpath
new file mode 100644
index 0000000..f17931c
--- /dev/null
+++ b/simpleVR/.classpath
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/simpleVR/.gitignore b/simpleVR/.gitignore
new file mode 100644
index 0000000..09e3bc9
--- /dev/null
+++ b/simpleVR/.gitignore
@@ -0,0 +1,2 @@
+/bin/
+/target/
diff --git a/simpleVR/.project b/simpleVR/.project
new file mode 100644
index 0000000..54e2a60
--- /dev/null
+++ b/simpleVR/.project
@@ -0,0 +1,23 @@
+
+
+ simpleVR
+
+
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+
+ org.eclipse.m2e.core.maven2Builder
+
+
+
+
+
+ org.eclipse.m2e.core.maven2Nature
+ org.eclipse.jdt.core.javanature
+
+
diff --git a/simpleVR/.settings/org.eclipse.jdt.core.prefs b/simpleVR/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000..2f5cc74
--- /dev/null
+++ b/simpleVR/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
+org.eclipse.jdt.core.compiler.release=disabled
+org.eclipse.jdt.core.compiler.source=1.8
diff --git a/simpleVR/.settings/org.eclipse.m2e.core.prefs b/simpleVR/.settings/org.eclipse.m2e.core.prefs
new file mode 100644
index 0000000..f897a7f
--- /dev/null
+++ b/simpleVR/.settings/org.eclipse.m2e.core.prefs
@@ -0,0 +1,4 @@
+activeProfiles=
+eclipse.preferences.version=1
+resolveWorkspaceProjects=true
+version=1
diff --git a/simpleVR/pom.xml b/simpleVR/pom.xml
new file mode 100644
index 0000000..a93d762
--- /dev/null
+++ b/simpleVR/pom.xml
@@ -0,0 +1,26 @@
+
+ 4.0.0
+ simpleOpenVR
+ simpleOpenVR
+ 0.0.1-SNAPSHOT
+
+ src
+
+
+ maven-compiler-plugin
+ 3.5.1
+
+
+
+
+
+
+
+
+
+ javax.vecmath
+ vecmath
+ 1.5.2
+
+
+
\ No newline at end of file
diff --git a/simpleVR/src/simpleVR/SimpleOpenVR.java b/simpleVR/src/simpleVR/SimpleOpenVR.java
new file mode 100644
index 0000000..64b371c
--- /dev/null
+++ b/simpleVR/src/simpleVR/SimpleOpenVR.java
@@ -0,0 +1,322 @@
+package simpleVR;
+
+import java.lang.reflect.*;
+
+import javax.vecmath.*;
+
+import jrtr.*;
+import jrtr.glrenderer.*;
+
+/**
+ * Implements a simple VR application that renders to an HMD via
+ * OpenVR. OpenVR functionality is provided by the {@link OpenVRRenderPanel}.
+ * Also demonstrates tracking of a VR hand controller.
+ */
+public class SimpleOpenVR
+{
+ static VRRenderPanel renderPanel;
+ static RenderContext renderContext;
+ static SimpleSceneManager sceneManager;
+
+ //shapes
+ static Shape ball;
+ static Shape controllerCube;
+ static Shape controllerCubeTriggered;
+ static Shape surroundingCube;
+ static Shape controllerRacket;
+
+ //stores bounding box for racket. Useful for collision detection with ball.
+ static Vector3f racketBoundsMax = new Vector3f(Float.MIN_VALUE, Float.MIN_VALUE, Float.MIN_VALUE);
+ static Vector3f racketBoundsMin = new Vector3f(Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE);
+
+ //scene-geometry parameters
+ static float ballRadius = 0.15f;
+ static float roomSize = 2.f;
+ static float controllerSize = 0.015f;
+
+ //additional parameters
+ static Vector3f throwingTranslationAccum;
+
+
+ /**
+ * An extension of {@link OpenVRRenderPanel} to
+ * provide a call-back function for initialization.
+ */
+ public final static class SimpleVRRenderPanel extends VRRenderPanel
+ {
+
+ /**
+ * Initialization call-back. We initialize our renderer here.
+ *
+ * @param r the render context that is associated with this render panel
+ */
+ public void init(RenderContext r)
+ {
+ renderContext = r;
+
+ // Make a simple geometric object: a cube
+
+ // The vertex positions of the cube
+ float v[] = {-1,-1,1, 1,-1,1, 1,1,1, -1,1,1, // front face
+ -1,-1,-1, -1,-1,1, -1,1,1, -1,1,-1, // left face
+ 1,-1,-1,-1,-1,-1, -1,1,-1, 1,1,-1, // back face
+ 1,-1,1, 1,-1,-1, 1,1,-1, 1,1,1, // right face
+ 1,1,1, 1,1,-1, -1,1,-1, -1,1,1, // top face
+ -1,-1,1, -1,-1,-1, 1,-1,-1, 1,-1,1}; // bottom face
+ //for(int i=0; i