1
0

threejs-lesson-utils.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import * as THREE from 'three';
  2. import { OrbitControls } from '../../examples/jsm/controls/OrbitControls.js';
  3. export const threejsLessonUtils = {
  4. _afterPrettifyFuncs: [],
  5. init( options = { threejsOptions: {} } ) {
  6. if ( this.renderer ) {
  7. return;
  8. }
  9. const canvas = document.createElement( 'canvas' );
  10. canvas.id = 'c';
  11. document.body.appendChild( canvas );
  12. const renderer = new THREE.WebGLRenderer( {
  13. canvas,
  14. alpha: true,
  15. antialias: true,
  16. powerPreference: 'low-power',
  17. ...options.threejsOptions,
  18. } );
  19. this.pixelRatio = window.devicePixelRatio;
  20. this.renderer = renderer;
  21. this.elemToRenderFuncMap = new Map();
  22. const resizeRendererToDisplaySize = ( renderer ) => {
  23. const canvas = renderer.domElement;
  24. const width = canvas.clientWidth * this.pixelRatio | 0;
  25. const height = canvas.clientHeight * this.pixelRatio | 0;
  26. const needResize = canvas.width !== width || canvas.height !== height;
  27. if ( needResize ) {
  28. renderer.setSize( width, height, false );
  29. }
  30. return needResize;
  31. };
  32. const clearColor = new THREE.Color( '#000' );
  33. let needsUpdate = true;
  34. let rafRequestId;
  35. let rafRunning;
  36. const render = ( time ) => {
  37. rafRequestId = undefined;
  38. time *= 0.001;
  39. const resized = resizeRendererToDisplaySize( renderer );
  40. // only update if we drew last time
  41. // so the browser will not recomposite the page
  42. // of nothing is being drawn.
  43. if ( needsUpdate ) {
  44. needsUpdate = false;
  45. renderer.setScissorTest( false );
  46. renderer.setClearColor( clearColor, 0 );
  47. renderer.clear( true, true );
  48. renderer.setScissorTest( true );
  49. }
  50. this.elementsOnScreen.forEach( elem => {
  51. const fn = this.elemToRenderFuncMap.get( elem );
  52. const wasRendered = fn( renderer, time, resized );
  53. needsUpdate = needsUpdate || wasRendered;
  54. } );
  55. if ( needsUpdate ) {
  56. // maybe there is another way. Originally I used `position: fixed`
  57. // but the problem is if we can't render as fast as the browser
  58. // scrolls then our shapes lag. 1 or 2 frames of lag isn't too
  59. // horrible but iOS would often been 1/2 a second or worse.
  60. // By doing it this way the canvas will scroll which means the
  61. // worse that happens is part of the shapes scrolling on don't
  62. // get drawn for a few frames but the shapes that are on the screen
  63. // scroll perfectly.
  64. //
  65. // I'm using `transform` on the voodoo that it doesn't affect
  66. // layout as much as `top` since AFAIK setting `top` is in
  67. // the flow but `transform` is not though thinking about it
  68. // the given we're `position: absolute` maybe there's no difference?
  69. const transform = `translateY(${window.scrollY}px)`;
  70. renderer.domElement.style.transform = transform;
  71. }
  72. if ( rafRunning ) {
  73. startRAFLoop();
  74. }
  75. };
  76. function startRAFLoop() {
  77. rafRunning = true;
  78. if ( ! rafRequestId ) {
  79. rafRequestId = requestAnimationFrame( render );
  80. }
  81. }
  82. this.elementsOnScreen = new Set();
  83. this.intersectionObserver = new IntersectionObserver( ( entries ) => {
  84. entries.forEach( entry => {
  85. if ( entry.isIntersecting ) {
  86. this.elementsOnScreen.add( entry.target );
  87. } else {
  88. this.elementsOnScreen.delete( entry.target );
  89. }
  90. // Each entry describes an intersection change for one observed
  91. // target element:
  92. // entry.boundingClientRect
  93. // entry.intersectionRatio
  94. // entry.intersectionRect
  95. // entry.isIntersecting
  96. // entry.rootBounds
  97. // entry.target
  98. // entry.time
  99. } );
  100. if ( this.elementsOnScreen.size > 0 ) {
  101. startRAFLoop();
  102. } else {
  103. rafRunning = false;
  104. }
  105. } );
  106. },
  107. addDiagrams( diagrams ) {
  108. [ ...document.querySelectorAll( '[data-diagram]' ) ].forEach( ( elem ) => {
  109. const name = elem.dataset.diagram;
  110. const info = diagrams[ name ];
  111. if ( ! info ) {
  112. throw new Error( `no diagram: ${name}` );
  113. }
  114. this.addDiagram( elem, info );
  115. } );
  116. },
  117. addDiagram( elem, info ) {
  118. this.init();
  119. const scene = new THREE.Scene();
  120. let targetFOVDeg = 60;
  121. const aspect = 1;
  122. const near = 0.1;
  123. const far = 50;
  124. let camera = new THREE.PerspectiveCamera( targetFOVDeg, aspect, near, far );
  125. camera.position.z = 15;
  126. scene.add( camera );
  127. const root = new THREE.Object3D();
  128. scene.add( root );
  129. const renderInfo = {
  130. pixelRatio: this.pixelRatio,
  131. camera,
  132. scene,
  133. root,
  134. renderer: this.renderer,
  135. elem,
  136. };
  137. const obj3D = info.create( { scene, camera, renderInfo } );
  138. const promise = ( obj3D instanceof Promise ) ? obj3D : Promise.resolve( obj3D );
  139. const updateFunctions = [];
  140. const resizeFunctions = [];
  141. const settings = {
  142. lights: true,
  143. trackball: true,
  144. // resize(renderInfo) {
  145. // },
  146. // update(time, renderInfo) {
  147. // },
  148. render( renderInfo ) {
  149. renderInfo.renderer.render( renderInfo.scene, renderInfo.camera );
  150. },
  151. };
  152. promise.then( ( result ) => {
  153. const info = result instanceof THREE.Object3D ? {
  154. obj3D: result,
  155. } : result;
  156. if ( info.obj3D ) {
  157. root.add( info.obj3D );
  158. }
  159. if ( info.update ) {
  160. updateFunctions.push( info.update );
  161. }
  162. if ( info.resize ) {
  163. resizeFunctions.push( info.resize );
  164. }
  165. if ( info.camera ) {
  166. camera = info.camera;
  167. renderInfo.camera = camera;
  168. }
  169. Object.assign( settings, info );
  170. targetFOVDeg = camera.fov;
  171. if ( settings.trackball !== false ) {
  172. const controls = new OrbitControls( camera, elem );
  173. controls.rotateSpeed = 1 / 6;
  174. controls.enableZoom = false;
  175. controls.enablePan = false;
  176. elem.removeAttribute( 'tabIndex' );
  177. //resizeFunctions.push(controls.handleResize.bind(controls));
  178. updateFunctions.push( controls.update.bind( controls ) );
  179. }
  180. // add the lights as children of the camera.
  181. // this is because TrackballControls move the camera.
  182. // We really want to rotate the object itself but there's no
  183. // controls for that so we fake it by putting all the lights
  184. // on the camera so they move with it.
  185. if ( settings.lights !== false ) {
  186. camera.add( new THREE.HemisphereLight( 0xaaaaaa, 0x444444, .5 ) );
  187. const light = new THREE.DirectionalLight( 0xffffff, 1 );
  188. light.position.set( - 1, 2, 4 - 15 );
  189. camera.add( light );
  190. }
  191. } );
  192. let oldWidth = - 1;
  193. let oldHeight = - 1;
  194. const render = ( renderer, time ) => {
  195. root.rotation.x = time * .1;
  196. root.rotation.y = time * .11;
  197. const rect = elem.getBoundingClientRect();
  198. if ( rect.bottom < 0 || rect.top > renderer.domElement.clientHeight ||
  199. rect.right < 0 || rect.left > renderer.domElement.clientWidth ) {
  200. return false;
  201. }
  202. renderInfo.width = rect.width * this.pixelRatio;
  203. renderInfo.height = rect.height * this.pixelRatio;
  204. renderInfo.left = rect.left * this.pixelRatio;
  205. renderInfo.bottom = ( renderer.domElement.clientHeight - rect.bottom ) * this.pixelRatio;
  206. if ( renderInfo.width !== oldWidth || renderInfo.height !== oldHeight ) {
  207. oldWidth = renderInfo.width;
  208. oldHeight = renderInfo.height;
  209. resizeFunctions.forEach( fn => fn( renderInfo ) );
  210. }
  211. updateFunctions.forEach( fn => fn( time, renderInfo ) );
  212. const aspect = renderInfo.width / renderInfo.height;
  213. const fovDeg = aspect >= 1
  214. ? targetFOVDeg
  215. : THREE.MathUtils.radToDeg( 2 * Math.atan( Math.tan( THREE.MathUtils.degToRad( targetFOVDeg ) * .5 ) / aspect ) );
  216. camera.fov = fovDeg;
  217. camera.aspect = aspect;
  218. camera.updateProjectionMatrix();
  219. renderer.setViewport( renderInfo.left, renderInfo.bottom, renderInfo.width, renderInfo.height );
  220. renderer.setScissor( renderInfo.left, renderInfo.bottom, renderInfo.width, renderInfo.height );
  221. settings.render( renderInfo );
  222. return true;
  223. };
  224. this.intersectionObserver.observe( elem );
  225. this.elemToRenderFuncMap.set( elem, render );
  226. },
  227. onAfterPrettify( fn ) {
  228. this._afterPrettifyFuncs.push( fn );
  229. },
  230. afterPrettify() {
  231. this._afterPrettifyFuncs.forEach( ( fn ) => {
  232. fn();
  233. } );
  234. },
  235. };
  236. window.threejsLessonUtils = threejsLessonUtils;