load-gltf-shadows.html 12 KB

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