threejs-load-gltf-shadows.html 12 KB

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