load-gltf-shadows.html 12 KB

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