Browse Source

clean up on demand rendering

Gregg Tavares 6 years ago
parent
commit
9655246f5d

+ 73 - 32
threejs/lessons/threejs-rendering-on-demand.md

@@ -1,7 +1,9 @@
 Title: Three.js Rendering on Demand
 Description: How to use less energy.
 
-The topic might be obvious to many people but just in case ... most Three.js examples render continuously. In other words they setup a `requestAnimationFrame` loop or "rAF loop" something like this
+The topic might be obvious to many people but just in case ... most Three.js
+examples render continuously. In other words they setup a
+`requestAnimationFrame` loop or "*rAF loop*" something like this
 
 ```js
 function render() {
@@ -11,14 +13,20 @@ function render() {
 requestAnimationFrame(render);
 ```
 
-For something that animates this makes sense but what about for something that does not animate? In that case rendering continuously is a waste of the devices power and if the user is on portable device it wastes the user's battery. 
+For something that animates this makes sense but what about for something that
+does not animate? In that case rendering continuously is a waste of the devices
+power and if the user is on portable device it wastes the user's battery. 
 
-The most obvious way to solve this is to render once at the start and then render only when something changes. Changes include textures or models finally loading. Data arriving from some external source. The user adjusting a setting or the camera or giving other relevant input.
+The most obvious way to solve this is to render once at the start and then
+render only when something changes. Changes include textures or models finally
+loading, data arriving from some external source, the user adjusting a setting
+or the camera or giving other relevant input.
 
 Let's take an example from [the article on responsiveness](threejs-responsive.html)
 and modify it to render on demand.
 
-First we'll add in the `OrbitControls` so there is something that could change that we can render in response to.
+First we'll add in the `OrbitControls` so there is something that could change
+that we can render in response to.
 
 ```html
 <script src="resources/threejs/r98/three.min.js"></script>
@@ -87,14 +95,17 @@ then we need to render once
 render();
 ```
 
-We need to render anytime the `OrbitControls` change the camera settings. Fortunately the `OrbitControls` dispatch
-a `change` event anytime something changes.
+We need to render anytime the `OrbitControls` change the camera settings.
+Fortunately the `OrbitControls` dispatch a `change` event anytime something
+changes.
 
 ```js
 controls.addEventListener('change', render);
 ```
 
-We also need to handle the case where the user resizes the window. That was handled automatically before since we were rendering continuously but now what we are not we need to render when the window changes size.
+We also need to handle the case where the user resizes the window. That was
+handled automatically before since we were rendering continuously but now what
+we are not we need to render when the window changes size.
 
 ```js
 window.addEventListener('resize', render);
@@ -104,8 +115,9 @@ And with that we get something that renders on demand.
 
 {{{example url="../threejs-render-on-demand.html" }}}
 
-The `OrbitControls` have options to add a kind of inertia to make them feel less stiff. We can enable this
-by setting the `enableDamping` property to true and we can set how much inertia by adjusting the `dampingFactor`
+The `OrbitControls` have options to add a kind of inertia to make them feel less
+stiff. We can enable this by setting the `enableDamping` property to true and we
+can set how much inertia by adjusting the `dampingFactor`
 
 ```js
 controls.enableDamping = true;
@@ -113,41 +125,56 @@ controls.dampingFactor = 0.05;
 controls.rotateSpeed = 0.1;
 ```
 
-With `enableDamping` on we need to call `control.update` in our render function so that the `OrbitControls` can
-continue to give us new camera settings as they smooth out the movement. But, that means we can't call `render`
-directly from the `change` event because we'll end up in an infinite loop. The controls will send us a `change` event
-and call `render`, `render` will call `control.update`. `control.update` will send another `change` event.
+With `enableDamping` on we need to call `controls.update` in our render function
+so that the `OrbitControls` can continue to give us new camera settings as they
+smooth out the movement. But, that means we can't call `render` directly from
+the `change` event because we'll end up in an infinite loop. The controls will
+send us a `change` event and call `render`, `render` will call `controls.update`.
+`controls.update` will send another `change` event.
 
-We can fix that by using `requestAnimationFrame` to call `render` but we need to make sure
-we only ask for a new frame of one has not already been requested which we can do like this.
+We can fix that by using `requestAnimationFrame` to call `render` but we need to
+make sure we only ask for a new frame if one has not already been requested
+which we can do by keeping a variable that tracks if we've already requested a frame.
 
 ```js
-+let requestId;
++let renderRequested = false;
 
 function render() {
-+  requestId = undefined;
++  renderRequested = false;
+
   if (resizeRendererToDisplaySize(renderer)) {
     const canvas = renderer.domElement;
     camera.aspect = canvas.clientWidth / canvas.clientHeight;
     camera.updateProjectionMatrix();
   }
 
-  controls.update();
   renderer.render(scene, camera);
 }
 render();
 
--controls.addEventListener('change', render);
-+controls.addEventListener('change', () => {
-+  if (!requestId) {
-+    requestId = requestAnimationFrame(render);
++function requestRenderIfNotRequested() {
++  if (!renderRequested) {
++    renderRequested = true;
++    requestAnimationFrame(render);
 +  }
-+});
++}
+
+-controls.addEventListener('change', render);
++controls.addEventListener('change', requestRenderIfNotRequested);
+```
+
+We should probably also use `requestRenderIfNotRequested` for resizing as well
+
+```js
+-window.addEventListener('resize', render);
++window.addEventListener('resize', requestRenderIfNotRequested);
 ```
 
-It might be hard to see the difference. Try clicking on the example below and use the arrow keys to move around.
-Then try clicking on the example above and do the same thing and you should be able to tell the difference.
-The one above snaps when you press an arrow key, the one below slides.
+It might be hard to see the difference. Try clicking on the example below and
+use the arrow keys to move around or dragging to spin. Then try clicking on the
+example above and do the same thing and you should be able to tell the
+difference. The one above snaps when you press an arrow key or drag, the one
+below slides.
 
 {{{example url="../threejs-render-on-demand-w-damping.html" }}}
 
@@ -159,7 +186,9 @@ Let's also add a simple dat.GUI GUI and make its changes render on demand.
 +<script src="../3rdparty/dat.gui.min.js"></script>
 ```
 
-Let's allow setting the color and x scale of each cube. To be able to set the color we'll use the `ColorGUIHelper` we created in the [article on lights](threejs-lights.html).
+Let's allow setting the color and x scale of each cube. To be able to set the
+color we'll use the `ColorGUIHelper` we created in the [article on
+lights](threejs-lights.html).
 
 First we need to create a GUI
 
@@ -167,7 +196,8 @@ First we need to create a GUI
 const gui = new dat.GUI();
 ```
 
-and then for each cube we'll create a folder and add 2 controls, one for `material.color` and another for `cube.scale.x`.
+and then for each cube we'll create a folder and add 2 controls, one for
+`material.color` and another for `cube.scale.x`.
 
 ```js
 function makeInstance(geometry, color, x) {
@@ -179,16 +209,27 @@ function makeInstance(geometry, color, x) {
   cube.position.x = x;
 
 +  const folder = gui.addFolder(`Cube${x}`);
-+  folder.addColor(new ColorGUIHelper(material, 'color'), 'value').name('color').onChange(render);
-+  folder.add(cube.scale, 'x', .1, 1.5).name('scale x').onChange(render);
++  folder.addColor(new ColorGUIHelper(material, 'color'), 'value')
++      .name('color')
++      .onChange(rendrequestRenderIfNotRequesteder);
++  folder.add(cube.scale, 'x', .1, 1.5)
++      .name('scale x')
++      .onChange(requestRenderIfNotRequested);
 +  folder.open();
 
   return cube;
 }
 ```
 
-You can see above dat.GUI controls have an `onChange` method that you can pass a callback to be called when the GUI changes a value. In our case we just need it to call `render`. The call to `folder.open` makes the folder start expanded.
+You can see above dat.GUI controls have an `onChange` method that you can pass a
+callback to be called when the GUI changes a value. In our case we just need it
+to call `requestRenderIfNotRequested`. The call to `folder.open` makes the
+folder start expanded.
 
 {{{example url="../threejs-render-on-demand-w-gui.html" }}}
 
-I hope this gives some idea of how to make three.js render on demand instead of continuously. Apps/pages that render three.js on demand are not as common as most pages using three.js are either games or 3D animated art but examples of pages that might be better rendering on demand would be say a map viewer, a 3d editor, a 3d graph generator, a product catalog, etc...
+I hope this gives some idea of how to make three.js render on demand instead of
+continuously. Apps/pages that render three.js on demand are not as common as
+most pages using three.js are either games or 3D animated art but examples of
+pages that might be better rendering on demand would be say a map viewer, a 3d
+editor, a 3d graph generator, a product catalog, etc...

+ 10 - 7
threejs/threejs-lots-of-objects-merged-vertexcolors.html

@@ -190,10 +190,11 @@ function main() {
     return needResize;
   }
 
-  let requestId;
+  let renderRequested = false;
 
   function render() {
-    requestId = undefined;
+    renderRequested = undefined;
+
     if (resizeRendererToDisplaySize(renderer)) {
       const canvas = renderer.domElement;
       camera.aspect = canvas.clientWidth / canvas.clientHeight;
@@ -205,13 +206,15 @@ function main() {
   }
   render();
 
-  controls.addEventListener('change', () => {
-    if (!requestId) {
-      requestId = requestAnimationFrame(render);
+  function requestRenderIfNotRequested() {
+    if (!renderRequested) {
+      renderRequested = true;
+      requestAnimationFrame(render);
     }
-  });
+  }
 
-  window.addEventListener('resize', render);
+  controls.addEventListener('change', requestRenderIfNotRequested);
+  window.addEventListener('resize', requestRenderIfNotRequested);
 
   // note: this is a workaround for an OrbitControls issue
   // in an iframe. Will remove once the issue is fixed in

+ 10 - 7
threejs/threejs-lots-of-objects-merged.html

@@ -164,10 +164,11 @@ function main() {
     return needResize;
   }
 
-  let requestId;
+  let renderRequested = false;
 
   function render() {
-    requestId = undefined;
+    renderRequested = undefined;
+
     if (resizeRendererToDisplaySize(renderer)) {
       const canvas = renderer.domElement;
       camera.aspect = canvas.clientWidth / canvas.clientHeight;
@@ -179,13 +180,15 @@ function main() {
   }
   render();
 
-  controls.addEventListener('change', () => {
-    if (!requestId) {
-      requestId = requestAnimationFrame(render);
+  function requestRenderIfNotRequested() {
+    if (!renderRequested) {
+      renderRequested = true;
+      requestAnimationFrame(render);
     }
-  });
+  }
 
-  window.addEventListener('resize', render);
+  controls.addEventListener('change', requestRenderIfNotRequested);
+  window.addEventListener('resize', requestRenderIfNotRequested);
 
   // note: this is a workaround for an OrbitControls issue
   // in an iframe. Will remove once the issue is fixed in

+ 11 - 7
threejs/threejs-lots-of-objects-slow.html

@@ -161,10 +161,11 @@ function main() {
     return needResize;
   }
 
-  let requestId;
+  let renderRequested = false;
 
   function render() {
-    requestId = undefined;
+    renderRequested = undefined;
+
     if (resizeRendererToDisplaySize(renderer)) {
       const canvas = renderer.domElement;
       camera.aspect = canvas.clientWidth / canvas.clientHeight;
@@ -176,12 +177,15 @@ function main() {
   }
   render();
 
-  controls.addEventListener('change', () => {
-    if (!requestId) {
-      requestId = requestAnimationFrame(render);
+  function requestRenderIfNotRequested() {
+    if (!renderRequested) {
+      renderRequested = true;
+      requestAnimationFrame(render);
     }
-  });
-  window.addEventListener('resize', render);
+  }
+
+  controls.addEventListener('change', requestRenderIfNotRequested);
+  window.addEventListener('resize', requestRenderIfNotRequested);
 
   // note: this is a workaround for an OrbitControls issue
   // in an iframe. Will remove once the issue is fixed in

+ 11 - 7
threejs/threejs-render-on-demand-w-damping.html

@@ -85,10 +85,11 @@ function main() {
     return needResize;
   }
 
-  let requestId;
+  let renderRequested = false;
 
   function render() {
-    requestId = undefined;
+    renderRequested = undefined;
+
     if (resizeRendererToDisplaySize(renderer)) {
       const canvas = renderer.domElement;
       camera.aspect = canvas.clientWidth / canvas.clientHeight;
@@ -100,12 +101,15 @@ function main() {
   }
   render();
 
-  controls.addEventListener('change', () => {
-    if (!requestId) {
-      requestId = requestAnimationFrame(render);
+  function requestRenderIfNotRequested() {
+    if (!renderRequested) {
+      renderRequested = true;
+      requestAnimationFrame(render);
     }
-  });
-  window.addEventListener('resize', render);
+  }
+
+  controls.addEventListener('change', requestRenderIfNotRequested);
+  window.addEventListener('resize', requestRenderIfNotRequested);
 
   // note: this is a workaround for an OrbitControls issue
   // in an iframe. Will remove once the issue is fixed in

+ 17 - 9
threejs/threejs-render-on-demand-w-gui.html

@@ -84,8 +84,12 @@ function main() {
     cube.position.x = x;
 
     const folder = gui.addFolder(`Cube${x}`);
-    folder.addColor(new ColorGUIHelper(material, 'color'), 'value').name('color').onChange(render);
-    folder.add(cube.scale, 'x', .1, 1.5).name('scale x').onChange(render);
+    folder.addColor(new ColorGUIHelper(material, 'color'), 'value')
+        .name('color')
+        .onChange(requestRenderIfNotRequested);
+    folder.add(cube.scale, 'x', .1, 1.5)
+        .name('scale x')
+        .onChange(requestRenderIfNotRequested);
     folder.open();
 
     return cube;
@@ -106,10 +110,11 @@ function main() {
     return needResize;
   }
 
-  let requestId;
+  let renderRequested = false;
 
   function render() {
-    requestId = undefined;
+    renderRequested = undefined;
+
     if (resizeRendererToDisplaySize(renderer)) {
       const canvas = renderer.domElement;
       camera.aspect = canvas.clientWidth / canvas.clientHeight;
@@ -121,12 +126,15 @@ function main() {
   }
   render();
 
-  controls.addEventListener('change', () => {
-    if (!requestId) {
-      requestId = requestAnimationFrame(render);
+  function requestRenderIfNotRequested() {
+    if (!renderRequested) {
+      renderRequested = true;
+      requestAnimationFrame(render);
     }
-  });
-  window.addEventListener('resize', render);
+  }
+
+  controls.addEventListener('change', requestRenderIfNotRequested);
+  window.addEventListener('resize', requestRenderIfNotRequested);
 }
 
 main();