VRViewManagerOculus.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. * Copyright (c) 2009-2017 jMonkeyEngine
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are
  7. * met:
  8. *
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. *
  12. * * Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
  17. * may be used to endorse or promote products derived from this software
  18. * without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  22. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. package com.jme3.util;
  33. import com.jme3.app.VREnvironment;
  34. import com.jme3.input.vr.OculusVR;
  35. import com.jme3.input.vr.VRAPI;
  36. import com.jme3.math.ColorRGBA;
  37. import com.jme3.math.Quaternion;
  38. import com.jme3.math.Vector2f;
  39. import com.jme3.math.Vector3f;
  40. import com.jme3.renderer.Camera;
  41. import com.jme3.renderer.ViewPort;
  42. import com.jme3.scene.Spatial;
  43. import com.jme3.texture.*;
  44. import java.nio.IntBuffer;
  45. import java.util.Iterator;
  46. import java.util.logging.Logger;
  47. import org.lwjgl.ovr.*;
  48. import static org.lwjgl.ovr.OVR.*;
  49. import static org.lwjgl.ovr.OVRErrorCode.*;
  50. /**
  51. * A rendering system for Oculus's LibOVR API.
  52. *
  53. * @author Campbell Suter <[email protected]>
  54. */
  55. public class VRViewManagerOculus extends AbstractVRViewManager {
  56. private static final Logger LOG = Logger.getLogger(VRViewManagerOculus.class.getName());
  57. private final VREnvironment environment;
  58. private final OculusVR hardware;
  59. // Copied from OSVR
  60. //final & temp values for camera calculations
  61. private final Vector3f finalPosition = new Vector3f();
  62. private final Quaternion finalRotation = new Quaternion();
  63. private final Vector3f hmdPos = new Vector3f();
  64. private final Quaternion hmdRot = new Quaternion();
  65. public VRViewManagerOculus(VREnvironment environment) {
  66. this.environment = environment;
  67. VRAPI hardware = environment.getVRHardware();
  68. if (!(hardware instanceof OculusVR)) {
  69. throw new IllegalStateException("Cannot use Oculus VR view manager on non-Oculus hardware state!");
  70. }
  71. this.hardware = (OculusVR) hardware;
  72. if (!environment.compositorAllowed()) {
  73. throw new UnsupportedOperationException("Cannot render without compositor on LibOVR");
  74. }
  75. }
  76. @Override
  77. public void initialize() {
  78. setupCamerasAndViews();
  79. }
  80. private long session() {
  81. return hardware.getSessionPointer();
  82. }
  83. @Override
  84. public void update(float tpf) {
  85. // TODO
  86. hardware.updatePose();
  87. // TODO deduplicate
  88. if (environment != null) {
  89. // grab the observer
  90. Object obs = environment.getObserver();
  91. Quaternion objRot;
  92. Vector3f objPos;
  93. if (obs instanceof Camera) {
  94. objRot = ((Camera) obs).getRotation();
  95. objPos = ((Camera) obs).getLocation();
  96. } else {
  97. objRot = ((Spatial) obs).getWorldRotation();
  98. objPos = ((Spatial) obs).getWorldTranslation();
  99. }
  100. // grab the hardware handle
  101. VRAPI dev = environment.getVRHardware();
  102. if (dev != null) {
  103. // update the HMD's position & orientation
  104. dev.getPositionAndOrientation(hmdPos, hmdRot);
  105. if (obs != null) {
  106. // update hmdPos based on obs rotation
  107. finalRotation.set(objRot);
  108. finalRotation.mult(hmdPos, hmdPos);
  109. finalRotation.multLocal(hmdRot);
  110. }
  111. finalizeCamera(dev.getHMDVectorPoseLeftEye(), objPos, leftCamera);
  112. finalizeCamera(dev.getHMDVectorPoseRightEye(), objPos, rightCamera);
  113. } else {
  114. leftCamera.setFrame(objPos, objRot);
  115. rightCamera.setFrame(objPos, objRot);
  116. }
  117. if (environment.hasTraditionalGUIOverlay()) {
  118. // update the mouse?
  119. environment.getVRMouseManager().update(tpf);
  120. // update GUI position?
  121. if (environment.getVRGUIManager().wantsReposition || environment.getVRGUIManager().getPositioningMode() != VRGUIPositioningMode.MANUAL) {
  122. environment.getVRGUIManager().positionGuiNow(tpf);
  123. environment.getVRGUIManager().updateGuiQuadGeometricState();
  124. }
  125. }
  126. } else {
  127. throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
  128. }
  129. }
  130. /**
  131. * Place the camera within the scene.
  132. *
  133. * @param eyePos the eye position.
  134. * @param obsPosition the observer position.
  135. * @param cam the camera to place.
  136. */
  137. private void finalizeCamera(Vector3f eyePos, Vector3f obsPosition, Camera cam) {
  138. finalRotation.mult(eyePos, finalPosition);
  139. finalPosition.addLocal(hmdPos);
  140. if (obsPosition != null) {
  141. finalPosition.addLocal(obsPosition);
  142. }
  143. finalPosition.y += getHeightAdjustment();
  144. cam.setFrame(finalPosition, finalRotation);
  145. }
  146. @Override
  147. public void render() {
  148. for (int eye = 0; eye < 2; eye++) {
  149. // TODO do we need this? Don't we set the camera positions ourselves?
  150. OVRPosef eyePose = hardware.getEyePosesPtr()[eye];
  151. hardware.getLayer0().RenderPose(eye, eyePose);
  152. IntBuffer currentIndexB = BufferUtils.createIntBuffer(1);
  153. ovr_GetTextureSwapChainCurrentIndex(session(), hardware.getChain(), currentIndexB);
  154. int index = currentIndexB.get();
  155. (eye == ovrEye_Left ? leftViewPort : rightViewPort).setOutputFrameBuffer(hardware.getFramebuffers()[index]);
  156. }
  157. // Now the game will render into the buffers given to us by LibOVR
  158. }
  159. @Override
  160. public void postRender() {
  161. // We're done with our textures now - the game is done drawing into them.
  162. ovr_CommitTextureSwapChain(session(), hardware.getChain());
  163. // Send the result to the HMD
  164. int result = ovr_SubmitFrame(session(), 0, null, hardware.getLayers());
  165. if (result != ovrSuccess) {
  166. throw new IllegalStateException("Failed to submit frame!");
  167. }
  168. }
  169. /*
  170. *********************************************************
  171. * Show's over, now it's just boring camera stuff etc. *
  172. *********************************************************
  173. */
  174. /**
  175. * Set up the cameras and views for each eye and the mirror display.
  176. */
  177. private void setupCamerasAndViews() {
  178. // TODO: Use LobOVR IPD etc
  179. if (environment != null) {
  180. // get desired frustrum from original camera
  181. Camera origCam = environment.getCamera();
  182. float fFar = origCam.getFrustumFar();
  183. float fNear = origCam.getFrustumNear();
  184. // restore frustrum on distortion scene cam, if needed
  185. if (environment.isInstanceRendering()) {
  186. leftCamera = origCam;
  187. } else if (environment.compositorAllowed() == false) {
  188. origCam.setFrustumFar(100f);
  189. origCam.setFrustumNear(1f);
  190. leftCamera = origCam.clone();
  191. prepareCameraSize(origCam, 2f);
  192. } else {
  193. leftCamera = origCam.clone();
  194. }
  195. getLeftCamera().setFrustumPerspective(environment.getDefaultFOV(), environment.getDefaultAspect(), fNear, fFar);
  196. prepareCameraSize(getLeftCamera(), 1f);
  197. if (environment.getVRHardware() != null) {
  198. getLeftCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionLeftEye(getLeftCamera()));
  199. }
  200. //org.lwjgl.opengl.GL11.glEnable(org.lwjgl.opengl.GL30.GL_FRAMEBUFFER_SRGB);
  201. if (!environment.isInstanceRendering()) {
  202. leftViewPort = setupViewBuffers(getLeftCamera(), LEFT_VIEW_NAME);
  203. rightCamera = getLeftCamera().clone();
  204. if (environment.getVRHardware() != null) {
  205. getRightCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionRightEye(getRightCamera()));
  206. }
  207. rightViewPort = setupViewBuffers(getRightCamera(), RIGHT_VIEW_NAME);
  208. } else if (environment.getApplication() != null) {
  209. LOG.severe("THIS CODE NEED CHANGES !!!");
  210. leftViewPort = environment.getApplication().getViewPort();
  211. //leftViewport.attachScene(app.getRootNode());
  212. rightCamera = getLeftCamera().clone();
  213. if (environment.getVRHardware() != null) {
  214. getRightCamera().setProjectionMatrix(environment.getVRHardware().getHMDMatrixProjectionRightEye(getRightCamera()));
  215. }
  216. org.lwjgl.opengl.GL11.glEnable(org.lwjgl.opengl.GL30.GL_CLIP_DISTANCE0);
  217. //FIXME: [jme-vr] Fix with JMonkey next release
  218. //RenderManager._VRInstancing_RightCamProjection = camRight.getViewProjectionMatrix();
  219. // TODO: Add LibOVR support
  220. // setupFinalFullTexture(environment.getApplication().getViewPort().getCamera());
  221. } else {
  222. throw new IllegalStateException("This VR environment is not attached to any application.");
  223. }
  224. // setup gui
  225. environment.getVRGUIManager().setupGui(getLeftCamera(), getRightCamera(), getLeftViewPort(), getRightViewPort());
  226. if (environment.getVRHardware() != null) {
  227. // call these to cache the results internally
  228. environment.getVRHardware().getHMDMatrixPoseLeftEye();
  229. environment.getVRHardware().getHMDMatrixPoseRightEye();
  230. }
  231. } else {
  232. throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
  233. }
  234. }
  235. private void prepareCameraSize(Camera cam, float xMult) {
  236. // TODO this function is identical to that in VRViewManagerOpenVR; merge the two.
  237. if (environment != null) {
  238. if (environment.getApplication() != null) {
  239. Vector2f size = new Vector2f();
  240. VRAPI vrhmd = environment.getVRHardware();
  241. if (vrhmd == null) {
  242. size.x = 1280f;
  243. size.y = 720f;
  244. } else {
  245. vrhmd.getRenderSize(size);
  246. }
  247. if (size.x < environment.getApplication().getContext().getSettings().getWidth()) {
  248. size.x = environment.getApplication().getContext().getSettings().getWidth();
  249. }
  250. if (size.y < environment.getApplication().getContext().getSettings().getHeight()) {
  251. size.y = environment.getApplication().getContext().getSettings().getHeight();
  252. }
  253. if (environment.isInstanceRendering()) {
  254. size.x *= 2f;
  255. }
  256. // other adjustments
  257. size.x *= xMult;
  258. size.x *= getResolutionMuliplier();
  259. size.y *= getResolutionMuliplier();
  260. if (cam.getWidth() != size.x || cam.getHeight() != size.y) {
  261. cam.resize((int) size.x, (int) size.y, false);
  262. }
  263. } else {
  264. throw new IllegalStateException("This VR environment is not attached to any application.");
  265. }
  266. } else {
  267. throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
  268. }
  269. }
  270. private ViewPort setupViewBuffers(Camera cam, String viewName) {
  271. // TODO this function is identical to that in VRViewManagerOpenVR; merge the two.
  272. if (environment != null) {
  273. if (environment.getApplication() != null) {
  274. // create offscreen framebuffer
  275. FrameBuffer offBufferLeft = new FrameBuffer(cam.getWidth(), cam.getHeight(), 1);
  276. //offBufferLeft.setSrgb(true);
  277. //setup framebuffer's texture
  278. Texture2D offTex = new Texture2D(cam.getWidth(), cam.getHeight(), Image.Format.RGBA8);
  279. offTex.setMinFilter(Texture.MinFilter.BilinearNoMipMaps);
  280. offTex.setMagFilter(Texture.MagFilter.Bilinear);
  281. //setup framebuffer to use texture
  282. offBufferLeft.setDepthBuffer(Image.Format.Depth);
  283. offBufferLeft.setColorTexture(offTex);
  284. ViewPort viewPort = environment.getApplication().getRenderManager().createPreView(viewName, cam);
  285. viewPort.setClearFlags(true, true, true);
  286. viewPort.setBackgroundColor(ColorRGBA.Black);
  287. Iterator<Spatial> spatialIter = environment.getApplication().getViewPort().getScenes().iterator();
  288. while (spatialIter.hasNext()) {
  289. viewPort.attachScene(spatialIter.next());
  290. }
  291. //set viewport to render to offscreen framebuffer
  292. viewPort.setOutputFrameBuffer(offBufferLeft);
  293. return viewPort;
  294. } else {
  295. throw new IllegalStateException("This VR environment is not attached to any application.");
  296. }
  297. } else {
  298. throw new IllegalStateException("This VR view manager is not attached to any VR environment.");
  299. }
  300. }
  301. }