webxr.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. Title: Three.js VR
  2. Description: How to use Virtual Reality in Three.js.
  3. TOC: VR - Basics
  4. Making a VR app in three.js is pretty simple. You basically just have to tell
  5. three.js you want to use WebXR. If you think about it a few things about WebXR
  6. should be clear. Which way the camera is pointing is supplied by the VR system
  7. itself since the user turns their head to choose a direction to look. Similarly
  8. the field of view and aspect will be supplied by the VR system since each system
  9. has a different field of view and display aspect.
  10. Let's take an example from the article on [making a responsive webpage](threejs-responsive.html)
  11. and make it support VR.
  12. Before we get started you're going to need a VR capable device like an Android
  13. smartphone, Google Daydream, Oculus Go, Oculus Rift, Vive, Samsung Gear VR., an
  14. iPhone with a [WebXR browser](https://apps.apple.com/us/app/webxr-viewer/id1295998056).
  15. Next, if you are running locally you need to run a simple web server like is
  16. covered in [the article on setting up](threejs-setup.html).
  17. If the device you are using to view VR is not the same computer you're running
  18. on you need to serve your webpage via https or else the browser will not allow using
  19. the WebXR API. The server mentioned in [the article on setting up](threejs-setup.html)
  20. called [Servez](https://greggman.github.io/servez) has an option to use https.
  21. Check it and start the server.
  22. <div class="threejs_center"><img src="resources/images/servez-https.png" class="nobg" style="width: 912px;"></div>
  23. The note the URLs. You need the one that is your computer's local ipaddress.
  24. It will usually start with `192`, `172` or `10`. Type that full address, including the `https://` part
  25. into your VR device's browser. Note: Your computer and your VR device need to be on the same local network
  26. or WiFi and you probably need to be on a home network. note: Many cafes are setup to disallow this kind of
  27. machine to machine connection.
  28. You'll be greeted with an error something like the one below. Click "advanced" and then click
  29. *proceed*.
  30. <div class="threejs_center"><img src="resources/images/https-warning.gif"></div>
  31. Now you can run your examples.
  32. If you're really going to do WebVR development another thing you should learn about is
  33. [remote debugging](https://developers.google.com/web/tools/chrome-devtools/remote-debugging/)
  34. so that you can see console warnings, errors, and of course actually
  35. [debug your code](threejs-debugging-javascript.html).
  36. If you just want to see the code work below you can just run the code from
  37. this site.
  38. The first thing we need to do is include the VR support after
  39. including three.js
  40. ```js
  41. import * as THREE from './resources/three/r132/build/three.module.js';
  42. +import {VRButton} from './resources/threejs/r132/examples/jsm/webxr/VRButton.js';
  43. ```
  44. Then we need to enable three.js's WebXR support and add its
  45. VR button to our page
  46. ```js
  47. function main() {
  48. const canvas = document.querySelector('#c');
  49. const renderer = new THREE.WebGLRenderer({canvas});
  50. + renderer.xr.enabled = true;
  51. + document.body.appendChild(VRButton.createButton(renderer));
  52. ```
  53. We need to let three.js run our render loop. Until now we have used a
  54. `requestAnimationFrame` loop but to support VR we need to let three.js handle
  55. our render loop for us. We can do that by calling
  56. `WebGLRenderer.setAnimationLoop` and passing a function to call for the loop.
  57. ```js
  58. function render(time) {
  59. time *= 0.001;
  60. if (resizeRendererToDisplaySize(renderer)) {
  61. const canvas = renderer.domElement;
  62. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  63. camera.updateProjectionMatrix();
  64. }
  65. cubes.forEach((cube, ndx) => {
  66. const speed = 1 + ndx * .1;
  67. const rot = time * speed;
  68. cube.rotation.x = rot;
  69. cube.rotation.y = rot;
  70. });
  71. renderer.render(scene, camera);
  72. - requestAnimationFrame(render);
  73. }
  74. -requestAnimationFrame(render);
  75. +renderer.setAnimationLoop(render);
  76. ```
  77. There is one more detail. We should probably set a camera height
  78. that's kind of average for a standing user.
  79. ```js
  80. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  81. +camera.position.set(0, 1.6, 0);
  82. ```
  83. and move the cubes up to be in front of the camera
  84. ```js
  85. const cube = new THREE.Mesh(geometry, material);
  86. scene.add(cube);
  87. cube.position.x = x;
  88. +cube.position.y = 1.6;
  89. +cube.position.z = -2;
  90. ```
  91. We set them to `z = -2` since the camera will now be at `z = 0` and
  92. camera defaults to looking down the -z axis.
  93. This brings up an extremely important point. **Units in VR are in meters**.
  94. In other words **One Unit = One Meter**. This means the camera is 1.6 meters above 0.
  95. The cube's centers are 2 meters in front of the camera. Each cube
  96. is 1x1x1 meter large. This is important because VR needs to adjust things to the
  97. user *in the real world*. That means we need the units used in three.js to match
  98. the user's own movements.
  99. And with that we should get 3 spinning cubes in front
  100. of the camera with a button to enter VR.
  101. {{{example url="../threejs-webvr-basic.html" }}}
  102. I find that VR works better if we have something surrounding the camera like
  103. room for reference so let's add a simple grid cubemap like we covered in
  104. [the article on backgrounds](threejs-backgrounds.html). We'll just use the same grid
  105. texture for each side of the cube which will give as a grid room.
  106. ```js
  107. const scene = new THREE.Scene();
  108. +{
  109. + const loader = new THREE.CubeTextureLoader();
  110. + const texture = loader.load([
  111. + 'resources/images/grid-1024.png',
  112. + 'resources/images/grid-1024.png',
  113. + 'resources/images/grid-1024.png',
  114. + 'resources/images/grid-1024.png',
  115. + 'resources/images/grid-1024.png',
  116. + 'resources/images/grid-1024.png',
  117. + ]);
  118. + scene.background = texture;
  119. +}
  120. ```
  121. That's better.
  122. {{{example url="../threejs-webvr-basic-w-background.html" }}}
  123. Note: To actually see VR you will need a WebXR compatible device.
  124. I believe most Android Phones can support WebXR using Chrome or Firefox.
  125. For iOS you might be able to use this [WebXR App](https://apps.apple.com/us/app/webxr-viewer/id1295998056)
  126. though in general WebXR support on iOS is unsupported as of May 2019.
  127. To use WebXR on Android or iPhone you'll need a *VR Headset*
  128. for phones. You can get them for anywhere from $5 for one made of cardboard
  129. to $100. Unfortunately I don't know which ones to recommend. I've purchased
  130. 6 of them over the years and they are all of varying quality. I've
  131. never paid more than about $25.
  132. Just to mention some of the issues
  133. 1. Do they fit your phone
  134. Phones come in a variety of sizes and so the VR headsets need to match.
  135. Many headsets claim to match a large variety of sizes. My experience
  136. is the more sizes they match the worse they actually are since instead
  137. of being designed for a specific size they have to make compromises
  138. to match more sizes. Unfortunately multi-size headsets are the most common type.
  139. 2. Can they focus for your face
  140. Some devices have more adjustments than others. Generally there
  141. are at most 2 adjustments. How far the lenses are from your eyes
  142. and how far apart the lenses are.
  143. 3. Are they too reflective
  144. Many headsets of a cone of plastic from your eye to the phone.
  145. If that plastic is shinny or reflective then it will act like
  146. a mirror reflecting the screen and be very distracting.
  147. Few if any of the reviews seem to cover this issue.
  148. 4. Are the comfortable on your face.
  149. Most of the devices rest on your nose like a pair of glasses.
  150. That can hurt after a few minutes. Some have straps that go around
  151. your head. Others have a 3rd strap that goes over your head. These
  152. may or may not help keep the device at the right place.
  153. It turns out for most (all?) devices, you eyes need to be centered
  154. with the lenses. If the lenses are slightly above or below your
  155. eyes the image gets out of focus. This can be very frustrating
  156. as things might start in focus but 45-60 seconds later the device
  157. has shifted up or down 1 millimeter and you suddenly realize you've
  158. been struggling to focus on a blurry image.
  159. 5. Can they support your glasses.
  160. If you wear eye glasses then you'll need to read the reviews to see
  161. if a particular headset works well with eye glasses.
  162. I really can't make any recommendations unfortunately. [Google has some
  163. cheap recommendations made from cardboard](https://vr.google.com/cardboard/get-cardboard/)
  164. some of them as low as $5 so maybe start there and if you enjoy it
  165. then consider upgrading. $5 is like the price of 1 coffee so seriously, give it try!
  166. There are also 3 basic types of devices.
  167. 1. 3 degrees of freedom (3dof), no input device
  168. This is generally the phone style although sometimes you can
  169. buy a 3rd party input device. The 3 degrees of freedom
  170. mean you can look up/down (1), left/right(2) and you can tilt
  171. your head left and right (3).
  172. 2. 3 degrees of freedom (3dof) with 1 input device (3dof)
  173. This is basically Google Daydream and Oculus GO
  174. These also allow 3 degrees of freedom and include a small
  175. controller that acts like a laser pointer inside VR.
  176. The laser pointer also only has 3 degrees of freedom. The
  177. system can tell which way the input device is pointing but
  178. it can not tell where the device is.
  179. 3. 6 degrees of freedom (6dof) with input devices (6dof)
  180. These are *the real deal* haha. 6 degrees of freedom
  181. means not only do these device know which way you are looking
  182. but they also know where your head actually is. That means
  183. if you move from left to right or forward and back or stand up / sit down
  184. the devices can register this and everything in VR moves accordingly.
  185. It's spookily and amazingly real feeling. With a good demo
  186. you'll be blown away or at least I was and still am.
  187. Further these devices usually include 2 controllers, one
  188. for each hand and the system can tell exactly where your
  189. hands are and which way they are oriented and so you can
  190. manipulate things in VR by just reaching out, touching,
  191. pushing, twisting, etc...
  192. 6 degree of freedom devices include the Vive and Vive Pro,
  193. the Oculus Rift and Quest, and I believe all of the Windows MR devices.
  194. With all that covered I don't for sure know which devices will work with WebXR.
  195. I'm 99% sure that most Android phones will work when running Chrome. You may
  196. need to turn on WebXR support in [`about:flags`](about:flags). I also know Google
  197. Daydream will also work and similarly you need to enable WebXR support in
  198. [`about:flags`](about:flags). Oculus Rift, Vive, and Vive Pro will work via
  199. Chrome or Firefox. I'm less sure about Oculus Go and Oculus Quest as both of
  200. them use custom OSes but according to the internet they both appear to work.
  201. Okay, after that long detour about VR Devices and WebXR
  202. there's some things to cover
  203. * Supporting both VR and Non-VR
  204. AFAICT, at least as of r112, there is no easy way to support
  205. both VR and non-VR modes with three.js. Ideally
  206. if not in VR mode you'd be able to control the camera using
  207. whatever means you want, for example the `OrbitControls`,
  208. and you'd get some kind of event when switching into and
  209. out of VR mode so that you could turn the controls on/off.
  210. If three.js adds some support to do both I'll try to update
  211. this article. Until then you might need 2 versions of your
  212. site OR pass in a flag in the URL, something like
  213. ```
  214. https://mysite.com/mycooldemo?allowvr=true
  215. ```
  216. Then we could add some links in to switch modes
  217. ```html
  218. <body>
  219. <canvas id="c"></canvas>
  220. + <div class="mode">
  221. + <a href="?allowvr=true" id="vr">Allow VR</a>
  222. + <a href="?" id="nonvr">Use Non-VR Mode</a>
  223. + </div>
  224. </body>
  225. ```
  226. and some CSS to position them
  227. ```css
  228. body {
  229. margin: 0;
  230. }
  231. #c {
  232. width: 100%;
  233. height: 100%;
  234. display: block;
  235. }
  236. +.mode {
  237. + position: absolute;
  238. + right: 1em;
  239. + top: 1em;
  240. +}
  241. ```
  242. in your code you could use that parameter like this
  243. ```js
  244. function main() {
  245. const canvas = document.querySelector('#c');
  246. const renderer = new THREE.WebGLRenderer({canvas});
  247. - renderer.xr.enabled = true;
  248. - document.body.appendChild(VRButton.createButton(renderer));
  249. const fov = 75;
  250. const aspect = 2; // the canvas default
  251. const near = 0.1;
  252. const far = 5;
  253. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  254. camera.position.set(0, 1.6, 0);
  255. + const params = (new URL(document.location)).searchParams;
  256. + const allowvr = params.get('allowvr') === 'true';
  257. + if (allowvr) {
  258. + renderer.xr.enabled = true;
  259. + document.body.appendChild(VRButton.createButton(renderer));
  260. + document.querySelector('#vr').style.display = 'none';
  261. + } else {
  262. + // no VR, add some controls
  263. + const controls = new OrbitControls(camera, canvas);
  264. + controls.target.set(0, 1.6, -2);
  265. + controls.update();
  266. + document.querySelector('#nonvr').style.display = 'none';
  267. + }
  268. ```
  269. Whether that's good or bad I don't know. I have a feeling the differences
  270. between what's needed for VR and what's needed for non-VR are often
  271. very different so for all but the most simple things maybe 2 separate pages
  272. are better? You'll have to decide.
  273. Note for various reasons this will not work in the live editor
  274. on this site so if you want to check it out
  275. <a href="../threejs-webvr-basic-vr-optional.html" target="_blank">click here</a>.
  276. It should start in non-VR mode and you can use the mouse or fingers to move
  277. the camera. Clicking "Allow VR" should switch to allow VR mode and you should
  278. be able to click "Enter VR" if you're on a VR device.
  279. * Deciding on the level of VR support
  280. Above we covered 3 types of VR devices.
  281. * 3DOF no input
  282. * 3DOF + 3DOF input
  283. * 6DOF + 6DOF input
  284. You need to decide how much effort you're willing to put in
  285. to support each type of device.
  286. For example the simplest device has no input. The best you can
  287. generally do is make it so there are some buttons or objects in the user's view
  288. and if the user aligns some marker in the center of the display
  289. on those objects for 1/2 a second or so then that button is clicked.
  290. A common UX is to display a small timer that will appear over the object indicating
  291. if you keep the marker there for a moment the object/button will be selected.
  292. Since there is no other input that's about the best you can do
  293. The next level up you have one 3DOF input device. Generally it
  294. can point at things and the user has at least 2 buttons. The Daydream
  295. also has a touchpad which provides normal touch inputs.
  296. In any case if a user has this type of device it's far more
  297. comfortable for the user to by able to point at things with
  298. their controller than it is to make them do it with their
  299. head by looking at things.
  300. A similar level to that might be 3DOF or 6DOF device with a
  301. game console controller. You'll have to decide what to do here.
  302. I suspect the most common thing is the user still has to look
  303. to point and the controller is just used for buttons.
  304. The last level is a user with a 6DOF headset and 2 6DOF controllers.
  305. Those users will find an experience that is only 3DOF to often
  306. be frustrating. Similarly they usually expect to be able to
  307. virtually manipulate things with their hands in VR so you'll
  308. have to decide if you want to support that or not.
  309. As you can see getting started in VR is pretty easy but
  310. actually making something shippable in VR will require
  311. lots of decision making and design.
  312. This was a pretty brief intro into VR with three.js. We'll
  313. cover some of the input methods in [future articles](threejs-webvr-look-to-select.html).