load-gltf-shadows.html 12 KB

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