load-gltf-shadows.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Load .GLTF - Shadows</title>
  8. <style>
  9. html, body {
  10. margin: 0;
  11. height: 100%;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <!-- Import maps polyfill -->
  24. <!-- Remove this when import maps will be widely supported -->
  25. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  26. <script type="importmap">
  27. {
  28. "imports": {
  29. "three": "../../build/three.module.js",
  30. "three/addons/": "../../examples/jsm/"
  31. }
  32. }
  33. </script>
  34. <script type="module">
  35. import * as THREE from 'three';
  36. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  37. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  38. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  39. function main() {
  40. const canvas = document.querySelector( '#c' );
  41. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  42. renderer.useLegacyLights = false;
  43. renderer.shadowMap.enabled = true;
  44. const fov = 45;
  45. const aspect = 2; // the canvas default
  46. const near = 0.1;
  47. const far = 100;
  48. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  49. camera.position.set( 0, 10, 20 );
  50. const controls = new OrbitControls( camera, canvas );
  51. controls.target.set( 0, 5, 0 );
  52. controls.update();
  53. const scene = new THREE.Scene();
  54. scene.background = new THREE.Color( '#DEFEFF' );
  55. {
  56. const planeSize = 40;
  57. const loader = new THREE.TextureLoader();
  58. const texture = loader.load( 'resources/images/checker.png' );
  59. texture.wrapS = THREE.RepeatWrapping;
  60. texture.wrapT = THREE.RepeatWrapping;
  61. texture.magFilter = THREE.NearestFilter;
  62. texture.colorSpace = THREE.SRGBColorSpace;
  63. const repeats = planeSize / 2;
  64. texture.repeat.set( repeats, repeats );
  65. const planeGeo = new THREE.PlaneGeometry( planeSize, planeSize );
  66. const planeMat = new THREE.MeshPhongMaterial( {
  67. map: texture,
  68. side: THREE.DoubleSide,
  69. } );
  70. const mesh = new THREE.Mesh( planeGeo, planeMat );
  71. mesh.rotation.x = Math.PI * - .5;
  72. scene.add( mesh );
  73. }
  74. {
  75. const skyColor = 0xB1E1FF; // light blue
  76. const groundColor = 0xB97A20; // brownish orange
  77. const intensity = 2;
  78. const light = new THREE.HemisphereLight( skyColor, groundColor, intensity );
  79. scene.add( light );
  80. }
  81. {
  82. const color = 0xFFFFFF;
  83. const intensity = 2.5;
  84. const light = new THREE.DirectionalLight( color, intensity );
  85. light.castShadow = true;
  86. light.position.set( - 250, 800, - 850 );
  87. light.target.position.set( - 550, 40, - 450 );
  88. light.shadow.bias = - 0.004;
  89. light.shadow.mapSize.width = 2048;
  90. light.shadow.mapSize.height = 2048;
  91. scene.add( light );
  92. scene.add( light.target );
  93. const cam = light.shadow.camera;
  94. cam.near = 1;
  95. cam.far = 2000;
  96. cam.left = - 1500;
  97. cam.right = 1500;
  98. cam.top = 1500;
  99. cam.bottom = - 1500;
  100. const cameraHelper = new THREE.CameraHelper( cam );
  101. scene.add( cameraHelper );
  102. cameraHelper.visible = false;
  103. const helper = new THREE.DirectionalLightHelper( light, 100 );
  104. scene.add( helper );
  105. helper.visible = false;
  106. function makeXYZGUI( gui, vector3, name, onChangeFn ) {
  107. const folder = gui.addFolder( name );
  108. folder.add( vector3, 'x', vector3.x - 500, vector3.x + 500 ).onChange( onChangeFn );
  109. folder.add( vector3, 'y', vector3.y - 500, vector3.y + 500 ).onChange( onChangeFn );
  110. folder.add( vector3, 'z', vector3.z - 500, vector3.z + 500 ).onChange( onChangeFn );
  111. folder.open();
  112. }
  113. function updateCamera() {
  114. // update the light target's matrixWorld because it's needed by the helper
  115. light.updateMatrixWorld();
  116. light.target.updateMatrixWorld();
  117. helper.update();
  118. // update the light's shadow camera's projection matrix
  119. light.shadow.camera.updateProjectionMatrix();
  120. // and now update the camera helper we're using to show the light's shadow camera
  121. cameraHelper.update();
  122. }
  123. updateCamera();
  124. class DimensionGUIHelper {
  125. constructor( obj, minProp, maxProp ) {
  126. this.obj = obj;
  127. this.minProp = minProp;
  128. this.maxProp = maxProp;
  129. }
  130. get value() {
  131. return this.obj[ this.maxProp ] * 2;
  132. }
  133. set value( v ) {
  134. this.obj[ this.maxProp ] = v / 2;
  135. this.obj[ this.minProp ] = v / - 2;
  136. }
  137. }
  138. class MinMaxGUIHelper {
  139. constructor( obj, minProp, maxProp, minDif ) {
  140. this.obj = obj;
  141. this.minProp = minProp;
  142. this.maxProp = maxProp;
  143. this.minDif = minDif;
  144. }
  145. get min() {
  146. return this.obj[ this.minProp ];
  147. }
  148. set min( v ) {
  149. this.obj[ this.minProp ] = v;
  150. this.obj[ this.maxProp ] = Math.max( this.obj[ this.maxProp ], v + this.minDif );
  151. }
  152. get max() {
  153. return this.obj[ this.maxProp ];
  154. }
  155. set max( v ) {
  156. this.obj[ this.maxProp ] = v;
  157. this.min = this.min; // this will call the min setter
  158. }
  159. }
  160. class VisibleGUIHelper {
  161. constructor( ...objects ) {
  162. this.objects = [ ...objects ];
  163. }
  164. get value() {
  165. return this.objects[ 0 ].visible;
  166. }
  167. set value( v ) {
  168. this.objects.forEach( ( obj ) => {
  169. obj.visible = v;
  170. } );
  171. }
  172. }
  173. const gui = new GUI();
  174. gui.close();
  175. gui.add( new VisibleGUIHelper( helper, cameraHelper ), 'value' ).name( 'show helpers' );
  176. gui.add( light.shadow, 'bias', - 0.1, 0.1, 0.001 );
  177. {
  178. const folder = gui.addFolder( 'Shadow Camera' );
  179. folder.open();
  180. folder.add( new DimensionGUIHelper( light.shadow.camera, 'left', 'right' ), 'value', 1, 4000 )
  181. .name( 'width' )
  182. .onChange( updateCamera );
  183. folder.add( new DimensionGUIHelper( light.shadow.camera, 'bottom', 'top' ), 'value', 1, 4000 )
  184. .name( 'height' )
  185. .onChange( updateCamera );
  186. const minMaxGUIHelper = new MinMaxGUIHelper( light.shadow.camera, 'near', 'far', 0.1 );
  187. folder.add( minMaxGUIHelper, 'min', 1, 1000, 1 ).name( 'near' ).onChange( updateCamera );
  188. folder.add( minMaxGUIHelper, 'max', 1, 4000, 1 ).name( 'far' ).onChange( updateCamera );
  189. folder.add( light.shadow.camera, 'zoom', 0.01, 1.5, 0.01 ).onChange( updateCamera );
  190. }
  191. makeXYZGUI( gui, light.position, 'position', updateCamera );
  192. makeXYZGUI( gui, light.target.position, 'target', updateCamera );
  193. }
  194. function frameArea( sizeToFitOnScreen, boxSize, boxCenter, camera ) {
  195. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  196. const halfFovY = THREE.MathUtils.degToRad( camera.fov * .5 );
  197. const distance = halfSizeToFitOnScreen / Math.tan( halfFovY );
  198. // compute a unit vector that points in the direction the camera is now
  199. // in the xz plane from the center of the box
  200. const direction = ( new THREE.Vector3() )
  201. .subVectors( camera.position, boxCenter )
  202. .multiply( new THREE.Vector3( 1, 0, 1 ) )
  203. .normalize();
  204. // move the camera to a position distance units way from the center
  205. // in whatever direction the camera was from the center already
  206. camera.position.copy( direction.multiplyScalar( distance ).add( boxCenter ) );
  207. // pick some near and far values for the frustum that
  208. // will contain the box.
  209. camera.near = boxSize / 100;
  210. camera.far = boxSize * 100;
  211. camera.updateProjectionMatrix();
  212. // point the camera to look at the center of the box
  213. camera.lookAt( boxCenter.x, boxCenter.y, boxCenter.z );
  214. }
  215. let curve;
  216. let curveObject;
  217. {
  218. const controlPoints = [
  219. [ 1.118281, 5.115846, - 3.681386 ],
  220. [ 3.948875, 5.115846, - 3.641834 ],
  221. [ 3.960072, 5.115846, - 0.240352 ],
  222. [ 3.985447, 5.115846, 4.585005 ],
  223. [ - 3.793631, 5.115846, 4.585006 ],
  224. [ - 3.826839, 5.115846, - 14.736200 ],
  225. [ - 14.542292, 5.115846, - 14.765865 ],
  226. [ - 14.520929, 5.115846, - 3.627002 ],
  227. [ - 5.452815, 5.115846, - 3.634418 ],
  228. [ - 5.467251, 5.115846, 4.549161 ],
  229. [ - 13.266233, 5.115846, 4.567083 ],
  230. [ - 13.250067, 5.115846, - 13.499271 ],
  231. [ 4.081842, 5.115846, - 13.435463 ],
  232. [ 4.125436, 5.115846, - 5.334928 ],
  233. [ - 14.521364, 5.115846, - 5.239871 ],
  234. [ - 14.510466, 5.115846, 5.486727 ],
  235. [ 5.745666, 5.115846, 5.510492 ],
  236. [ 5.787942, 5.115846, - 14.728308 ],
  237. [ - 5.423720, 5.115846, - 14.761919 ],
  238. [ - 5.373599, 5.115846, - 3.704133 ],
  239. [ 1.004861, 5.115846, - 3.641834 ],
  240. ];
  241. const p0 = new THREE.Vector3();
  242. const p1 = new THREE.Vector3();
  243. curve = new THREE.CatmullRomCurve3(
  244. controlPoints.map( ( p, ndx ) => {
  245. p0.set( ...p );
  246. p1.set( ...controlPoints[ ( ndx + 1 ) % controlPoints.length ] );
  247. return [
  248. ( new THREE.Vector3() ).copy( p0 ),
  249. ( new THREE.Vector3() ).lerpVectors( p0, p1, 0.1 ),
  250. ( new THREE.Vector3() ).lerpVectors( p0, p1, 0.9 ),
  251. ];
  252. } ).flat(),
  253. true,
  254. );
  255. {
  256. const points = curve.getPoints( 250 );
  257. const geometry = new THREE.BufferGeometry().setFromPoints( points );
  258. const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  259. curveObject = new THREE.Line( geometry, material );
  260. curveObject.scale.set( 100, 100, 100 );
  261. curveObject.position.y = - 621;
  262. curveObject.visible = false;
  263. scene.add( curveObject );
  264. }
  265. }
  266. const cars = [];
  267. {
  268. const gltfLoader = new GLTFLoader();
  269. gltfLoader.load( 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', ( gltf ) => {
  270. const root = gltf.scene;
  271. scene.add( root );
  272. root.traverse( ( obj ) => {
  273. if ( obj.castShadow !== undefined ) {
  274. obj.castShadow = true;
  275. obj.receiveShadow = true;
  276. }
  277. } );
  278. const loadedCars = root.getObjectByName( 'Cars' );
  279. const fixes = [
  280. { prefix: 'Car_08', y: 0, rot: [ Math.PI * .5, 0, Math.PI * .5 ], },
  281. { prefix: 'CAR_03', y: 33, rot: [ 0, Math.PI, 0 ], },
  282. { prefix: 'Car_04', y: 40, rot: [ 0, Math.PI, 0 ], },
  283. ];
  284. root.updateMatrixWorld();
  285. for ( const car of loadedCars.children.slice() ) {
  286. const fix = fixes.find( fix => car.name.startsWith( fix.prefix ) );
  287. const obj = new THREE.Object3D();
  288. car.position.set( 0, fix.y, 0 );
  289. car.rotation.set( ...fix.rot );
  290. obj.add( car );
  291. scene.add( obj );
  292. cars.push( obj );
  293. }
  294. // compute the box that contains all the stuff
  295. // from root and below
  296. const box = new THREE.Box3().setFromObject( root );
  297. const boxSize = box.getSize( new THREE.Vector3() ).length();
  298. const boxCenter = box.getCenter( new THREE.Vector3() );
  299. // set the camera to frame the box
  300. frameArea( boxSize * 0.5, boxSize, boxCenter, camera );
  301. // update the Trackball controls to handle the new size
  302. controls.maxDistance = boxSize * 10;
  303. controls.target.copy( boxCenter );
  304. controls.update();
  305. } );
  306. }
  307. function resizeRendererToDisplaySize( renderer ) {
  308. const canvas = renderer.domElement;
  309. const width = canvas.clientWidth;
  310. const height = canvas.clientHeight;
  311. const needResize = canvas.width !== width || canvas.height !== height;
  312. if ( needResize ) {
  313. renderer.setSize( width, height, false );
  314. }
  315. return needResize;
  316. }
  317. // create 2 Vector3s we can use for path calculations
  318. const carPosition = new THREE.Vector3();
  319. const carTarget = new THREE.Vector3();
  320. function render( time ) {
  321. time *= 0.001; // convert to seconds
  322. if ( resizeRendererToDisplaySize( renderer ) ) {
  323. const canvas = renderer.domElement;
  324. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  325. camera.updateProjectionMatrix();
  326. }
  327. {
  328. const pathTime = time * .01;
  329. const targetOffset = 0.01;
  330. cars.forEach( ( car, ndx ) => {
  331. // a number between 0 and 1 to evenly space the cars
  332. const u = pathTime + ndx / cars.length;
  333. // get the first point
  334. curve.getPointAt( u % 1, carPosition );
  335. carPosition.applyMatrix4( curveObject.matrixWorld );
  336. // get a second point slightly further down the curve
  337. curve.getPointAt( ( u + targetOffset ) % 1, carTarget );
  338. carTarget.applyMatrix4( curveObject.matrixWorld );
  339. // put the car at the first point (temporarily)
  340. car.position.copy( carPosition );
  341. // point the car the second point
  342. car.lookAt( carTarget );
  343. // put the car between the 2 points
  344. car.position.lerpVectors( carPosition, carTarget, 0.5 );
  345. } );
  346. }
  347. renderer.render( scene, camera );
  348. requestAnimationFrame( render );
  349. }
  350. requestAnimationFrame( render );
  351. }
  352. main();
  353. </script>
  354. </html>