load-gltf.html 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Loading a .GLTF File</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – Loading a .GLTF File">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="../resources/lesson.css">
  12. <link rel="stylesheet" href="../resources/lang.css">
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../../build/three.module.js"
  17. }
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class="lesson-title">
  24. <h1>Loading a .GLTF File</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p>In a previous lesson we <a href="load-obj.html">loaded an .OBJ file</a>. If
  29. you haven't read it you might want to check it out first.</p>
  30. <p>As pointed out over there the .OBJ file format is very old and fairly
  31. simple. It provides no scene graph so everything loaded is one large
  32. mesh. It was designed mostly as a simple way to pass data between
  33. 3D editors.</p>
  34. <p><a href="https://github.com/KhronosGroup/glTF">The gLTF format</a> is actually
  35. a format designed from the ground up for be used for displaying
  36. graphics. 3D formats can be divided into 3 or 4 basic types.</p>
  37. <ul>
  38. <li><p>3D Editor Formats</p>
  39. <p>This are formats specific to a single app. .blend (Blender), .max (3d Studio Max),
  40. .mb and .ma (Maya), etc...</p>
  41. </li>
  42. <li><p>Exchange formats</p>
  43. <p>These are formats like .OBJ, .DAE (Collada), .FBX. They are designed to help exchange
  44. information between 3D editors. As such they are usually much larger than needed with
  45. extra info used only inside 3d editors</p>
  46. </li>
  47. <li><p>App formats</p>
  48. <p>These are usually specific to certain apps, usually games.</p>
  49. </li>
  50. <li><p>Transmission formats</p>
  51. <p>gLTF might be the first true transmission format. I suppose VRML might be considered
  52. one but VRML was actually a pretty poor format.</p>
  53. <p>gLTF is designed to do some things well that all those other formats don't do</p>
  54. <ol>
  55. <li><p>Be small for transmission</p>
  56. <p>For example this means much of their large data, like vertices, is stored in
  57. binary. When you download a .gLTF file that data can be uploaded to the GPU
  58. with zero processing. It's ready as is. This is in contrast to say VRML, .OBJ,
  59. or .DAE where vertices are stored as text and have to be parsed. Text vertex
  60. positions can easily be 3x to 5x larger than binary.</p>
  61. </li>
  62. <li><p>Be ready to render</p>
  63. <p>This again is different from other formats except maybe App formats. The data
  64. in a glTF file is mean to be rendered, not edited. Data that's not important to
  65. rendering has generally been removed. Polygons have been converted to triangles.
  66. Materials have known values that are supposed to work everywhere.</p>
  67. </li>
  68. </ol>
  69. </li>
  70. </ul>
  71. <p>gLTF was specifically designed so you should be able to download a glTF file and
  72. display it with a minimum of trouble. Let's cross our fingers that's truly the case
  73. as none of the other formats have been able to do this.</p>
  74. <p>I wasn't really sure what I should show. At some level loading and displaying a gLTF file
  75. is simpler than an .OBJ file. Unlike a .OBJ file materials are directly part of the format.
  76. That said I thought I should at least load one up and I think going over the issues I ran
  77. into might provide some good info.</p>
  78. <p>Searching the net I found <a href="https://sketchfab.com/models/edd1c604e1e045a0a2a552ddd9a293e6">this low-poly city</a>
  79. by <a href="https://sketchfab.com/antonmoek">antonmoek</a> which seemed like if we're lucky
  80. might make a good example.</p>
  81. <div class="threejs_center"><img src="../resources/images/cartoon_lowpoly_small_city_free_pack.jpg"></div>
  82. <p>Starting with <a href="load-obj.html">an example from the .OBJ article</a> I removed the code
  83. for loading .OBJ and replaced it with code for loading .GLTF</p>
  84. <p>The old .OBJ code was</p>
  85. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mtlLoader = new MTLLoader();
  86. mtlLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', (mtl) =&gt; {
  87. mtl.preload();
  88. mtl.materials.Material.side = THREE.DoubleSide;
  89. objLoader.setMaterials(mtl);
  90. objLoader.load('resources/models/windmill/windmill.obj', (event) =&gt; {
  91. const root = event.detail.loaderRootNode;
  92. scene.add(root);
  93. ...
  94. });
  95. });
  96. </pre>
  97. <p>The new .GLTF code is</p>
  98. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  99. const gltfLoader = new GLTFLoader();
  100. const url = 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf';
  101. gltfLoader.load(url, (gltf) =&gt; {
  102. const root = gltf.scene;
  103. scene.add(root);
  104. ...
  105. });
  106. </pre>
  107. <p>I kept the auto framing code as before</p>
  108. <p>We also need to include the <a href="/docs/#examples/loaders/GLTFLoader"><code class="notranslate" translate="no">GLTFLoader</code></a> and we can get rid of the <a href="/docs/#examples/loaders/OBJLoader"><code class="notranslate" translate="no">OBJLoader</code></a>.</p>
  109. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">-import {LoaderSupport} from 'three/addons/loaders/LoaderSupport.js';
  110. -import {OBJLoader} from 'three/addons/loaders/OBJLoader.js';
  111. -import {MTLLoader} from 'three/addons/loaders/MTLLoader.js';
  112. +import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';
  113. </pre>
  114. <p>And running that we get</p>
  115. <p></p><div translate="no" class="threejs_example_container notranslate">
  116. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf.html"></iframe></div>
  117. <a class="threejs_center" href="/manual/examples/load-gltf.html" target="_blank">click here to open in a separate window</a>
  118. </div>
  119. <p></p>
  120. <p>Magic! It just works, textures and all.</p>
  121. <p>Next I wanted to see if I could animate the cars driving around so
  122. I needed to check if the scene had the cars as separate entities
  123. and if they were setup in a way I could use them.</p>
  124. <p>I wrote some code to dump put the scenegraph to the <a href="debugging-javascript.html">JavaScript
  125. console</a>.</p>
  126. <p>Here's the code to print out the scenegraph.</p>
  127. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function dumpObject(obj, lines = [], isLast = true, prefix = '') {
  128. const localPrefix = isLast ? '└─' : '├─';
  129. lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  130. const newPrefix = prefix + (isLast ? ' ' : '│ ');
  131. const lastNdx = obj.children.length - 1;
  132. obj.children.forEach((child, ndx) =&gt; {
  133. const isLast = ndx === lastNdx;
  134. dumpObject(child, lines, isLast, newPrefix);
  135. });
  136. return lines;
  137. }
  138. </pre>
  139. <p>And I just called it right after loading the scene.</p>
  140. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const gltfLoader = new GLTFLoader();
  141. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  142. const root = gltf.scene;
  143. scene.add(root);
  144. console.log(dumpObject(root).join('\n'));
  145. </pre>
  146. <p><a href="../examples/load-gltf-dump-scenegraph.html">Running that</a> I got this listing</p>
  147. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">OSG_Scene [Scene]
  148. └─RootNode_(gltf_orientation_matrix) [Object3D]
  149. └─RootNode_(model_correction_matrix) [Object3D]
  150. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  151. └─RootNode [Object3D]
  152. │ ...
  153. ├─Cars [Object3D]
  154. │ ├─CAR_03_1 [Object3D]
  155. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  156. │ ├─CAR_03 [Object3D]
  157. │ │ └─CAR_03_World_ap_0 [Mesh]
  158. │ ├─Car_04 [Object3D]
  159. │ │ └─Car_04_World_ap_0 [Mesh]
  160. │ ├─CAR_03_2 [Object3D]
  161. │ │ └─CAR_03_2_World_ap_0 [Mesh]
  162. │ ├─Car_04_1 [Object3D]
  163. │ │ └─Car_04_1_World_ap_0 [Mesh]
  164. │ ├─Car_04_2 [Object3D]
  165. │ │ └─Car_04_2_World_ap_0 [Mesh]
  166. │ ├─Car_04_3 [Object3D]
  167. │ │ └─Car_04_3_World_ap_0 [Mesh]
  168. │ ├─Car_04_4 [Object3D]
  169. │ │ └─Car_04_4_World_ap_0 [Mesh]
  170. │ ├─Car_08_4 [Object3D]
  171. │ │ └─Car_08_4_World_ap8_0 [Mesh]
  172. │ ├─Car_08_3 [Object3D]
  173. │ │ └─Car_08_3_World_ap9_0 [Mesh]
  174. │ ├─Car_04_1_2 [Object3D]
  175. │ │ └─Car_04_1_2_World_ap_0 [Mesh]
  176. │ ├─Car_08_2 [Object3D]
  177. │ │ └─Car_08_2_World_ap11_0 [Mesh]
  178. │ ├─CAR_03_1_2 [Object3D]
  179. │ │ └─CAR_03_1_2_World_ap_0 [Mesh]
  180. │ ├─CAR_03_2_2 [Object3D]
  181. │ │ └─CAR_03_2_2_World_ap_0 [Mesh]
  182. │ ├─Car_04_2_2 [Object3D]
  183. │ │ └─Car_04_2_2_World_ap_0 [Mesh]
  184. ...
  185. </pre>
  186. <p>From that we can see all the cars happen to be under a parent
  187. called <code class="notranslate" translate="no">"Cars"</code></p>
  188. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">* ├─Cars [Object3D]
  189. │ ├─CAR_03_1 [Object3D]
  190. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  191. │ ├─CAR_03 [Object3D]
  192. │ │ └─CAR_03_World_ap_0 [Mesh]
  193. │ ├─Car_04 [Object3D]
  194. │ │ └─Car_04_World_ap_0 [Mesh]
  195. </pre>
  196. <p>So as a simple test I thought I would just try rotating
  197. all the children of the "Cars" node around their Y axis.</p>
  198. <p>I looked up the "Cars" node after loading the scene
  199. and saved the result.</p>
  200. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+let cars;
  201. {
  202. const gltfLoader = new GLTFLoader();
  203. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  204. const root = gltf.scene;
  205. scene.add(root);
  206. + cars = root.getObjectByName('Cars');
  207. </pre>
  208. <p>Then in the <code class="notranslate" translate="no">render</code> function we can just set the rotation
  209. of each child of <code class="notranslate" translate="no">cars</code>.</p>
  210. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function render(time) {
  211. + time *= 0.001; // convert to seconds
  212. if (resizeRendererToDisplaySize(renderer)) {
  213. const canvas = renderer.domElement;
  214. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  215. camera.updateProjectionMatrix();
  216. }
  217. + if (cars) {
  218. + for (const car of cars.children) {
  219. + car.rotation.y = time;
  220. + }
  221. + }
  222. renderer.render(scene, camera);
  223. requestAnimationFrame(render);
  224. }
  225. </pre>
  226. <p>And we get</p>
  227. <p></p><div translate="no" class="threejs_example_container notranslate">
  228. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-rotate-cars.html"></iframe></div>
  229. <a class="threejs_center" href="/manual/examples/load-gltf-rotate-cars.html" target="_blank">click here to open in a separate window</a>
  230. </div>
  231. <p></p>
  232. <p>Hmmm, it looks like unfortunately this scene wasn't designed to
  233. animate the cars as their origins are not setup for that purpose.
  234. The trucks are rotating in the wrong direction.</p>
  235. <p>This brings up an important point which is if you're going to
  236. do something in 3D you need to plan ahead and design your assets
  237. so they have their origins in the correct places, so they are
  238. the correct scale, etc.</p>
  239. <p>Since I'm not an artist and I don't know blender that well I
  240. will hack this example. We'll take each car and parent it to
  241. another <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>. We will then move those <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> objects
  242. to move the cars but separately we can set the car's original
  243. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> to re-orient it so it's about where we really need it.</p>
  244. <p>Looking back at the scene graph listing it looks like there
  245. are really only 3 types of cars, "Car_08", "CAR_03", and "Car_04".
  246. Hopefully each type of car will work with the same adjustments.</p>
  247. <p>I wrote this code to go through each car, parent it to a new
  248. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>, parent that new <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> to the scene, and apply
  249. some per car <em>type</em> settings to fix its orientation, and add
  250. the new <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> a <code class="notranslate" translate="no">cars</code> array.</p>
  251. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-let cars;
  252. +const cars = [];
  253. {
  254. const gltfLoader = new GLTFLoader();
  255. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  256. const root = gltf.scene;
  257. scene.add(root);
  258. - cars = root.getObjectByName('Cars');
  259. + const loadedCars = root.getObjectByName('Cars');
  260. + const fixes = [
  261. + { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], },
  262. + { prefix: 'CAR_03', rot: [0, Math.PI, 0], },
  263. + { prefix: 'Car_04', rot: [0, Math.PI, 0], },
  264. + ];
  265. +
  266. + root.updateMatrixWorld();
  267. + for (const car of loadedCars.children.slice()) {
  268. + const fix = fixes.find(fix =&gt; car.name.startsWith(fix.prefix));
  269. + const obj = new THREE.Object3D();
  270. + car.getWorldPosition(obj.position);
  271. + car.position.set(0, 0, 0);
  272. + car.rotation.set(...fix.rot);
  273. + obj.add(car);
  274. + scene.add(obj);
  275. + cars.push(obj);
  276. + }
  277. ...
  278. </pre>
  279. <p>This fixes the orientation of the cars. </p>
  280. <p></p><div translate="no" class="threejs_example_container notranslate">
  281. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-rotate-cars-fixed.html"></iframe></div>
  282. <a class="threejs_center" href="/manual/examples/load-gltf-rotate-cars-fixed.html" target="_blank">click here to open in a separate window</a>
  283. </div>
  284. <p></p>
  285. <p>Now let's drive them around.</p>
  286. <p>Making even a simple driving system is too much for this post but
  287. it seems instead we could just make one convoluted path that
  288. drives down all the roads and then put the cars on the path.
  289. Here's a picture from Blender about half way through building
  290. the path.</p>
  291. <div class="threejs_center"><img src="../resources/images/making-path-for-cars.jpg" style="width: 1094px"></div>
  292. <p>I needed a way to get the data for that path out of Blender.
  293. Fortunately I was able to select just my path and export .OBJ checking "write nurbs".</p>
  294. <div class="threejs_center"><img src="../resources/images/blender-export-obj-write-nurbs.jpg" style="width: 498px"></div>
  295. <p>Opening the .OBJ file I was able to get a list of points
  296. which I formatted into this</p>
  297. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const controlPoints = [
  298. [1.118281, 5.115846, -3.681386],
  299. [3.948875, 5.115846, -3.641834],
  300. [3.960072, 5.115846, -0.240352],
  301. [3.985447, 5.115846, 4.585005],
  302. [-3.793631, 5.115846, 4.585006],
  303. [-3.826839, 5.115846, -14.736200],
  304. [-14.542292, 5.115846, -14.765865],
  305. [-14.520929, 5.115846, -3.627002],
  306. [-5.452815, 5.115846, -3.634418],
  307. [-5.467251, 5.115846, 4.549161],
  308. [-13.266233, 5.115846, 4.567083],
  309. [-13.250067, 5.115846, -13.499271],
  310. [4.081842, 5.115846, -13.435463],
  311. [4.125436, 5.115846, -5.334928],
  312. [-14.521364, 5.115846, -5.239871],
  313. [-14.510466, 5.115846, 5.486727],
  314. [5.745666, 5.115846, 5.510492],
  315. [5.787942, 5.115846, -14.728308],
  316. [-5.423720, 5.115846, -14.761919],
  317. [-5.373599, 5.115846, -3.704133],
  318. [1.004861, 5.115846, -3.641834],
  319. ];
  320. </pre>
  321. <p>THREE.js has some curve classes. The <a href="/docs/#api/en/extras/curves/CatmullRomCurve3"><code class="notranslate" translate="no">CatmullRomCurve3</code></a> seemed
  322. like it might work. The thing about that kind of curve is
  323. it tries to make a smooth curve going through the points.</p>
  324. <p>In fact putting those points in directly will generate
  325. a curve like this</p>
  326. <div class="threejs_center"><img src="../resources/images/car-curves-before.png" style="width: 400px"></div>
  327. <p>but we want a sharper corners. It seemed like if we computed
  328. some extra points we could get what we want. For each pair
  329. of points we'll compute a point 10% of the way between
  330. the 2 points and another 90% of the way between the 2 points
  331. and pass the result to <a href="/docs/#api/en/extras/curves/CatmullRomCurve3"><code class="notranslate" translate="no">CatmullRomCurve3</code></a>.</p>
  332. <p>This will give us a curve like this</p>
  333. <div class="threejs_center"><img src="../resources/images/car-curves-after.png" style="width: 400px"></div>
  334. <p>Here's the code to make the curve </p>
  335. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">let curve;
  336. let curveObject;
  337. {
  338. const controlPoints = [
  339. [1.118281, 5.115846, -3.681386],
  340. [3.948875, 5.115846, -3.641834],
  341. [3.960072, 5.115846, -0.240352],
  342. [3.985447, 5.115846, 4.585005],
  343. [-3.793631, 5.115846, 4.585006],
  344. [-3.826839, 5.115846, -14.736200],
  345. [-14.542292, 5.115846, -14.765865],
  346. [-14.520929, 5.115846, -3.627002],
  347. [-5.452815, 5.115846, -3.634418],
  348. [-5.467251, 5.115846, 4.549161],
  349. [-13.266233, 5.115846, 4.567083],
  350. [-13.250067, 5.115846, -13.499271],
  351. [4.081842, 5.115846, -13.435463],
  352. [4.125436, 5.115846, -5.334928],
  353. [-14.521364, 5.115846, -5.239871],
  354. [-14.510466, 5.115846, 5.486727],
  355. [5.745666, 5.115846, 5.510492],
  356. [5.787942, 5.115846, -14.728308],
  357. [-5.423720, 5.115846, -14.761919],
  358. [-5.373599, 5.115846, -3.704133],
  359. [1.004861, 5.115846, -3.641834],
  360. ];
  361. const p0 = new THREE.Vector3();
  362. const p1 = new THREE.Vector3();
  363. curve = new THREE.CatmullRomCurve3(
  364. controlPoints.map((p, ndx) =&gt; {
  365. p0.set(...p);
  366. p1.set(...controlPoints[(ndx + 1) % controlPoints.length]);
  367. return [
  368. (new THREE.Vector3()).copy(p0),
  369. (new THREE.Vector3()).lerpVectors(p0, p1, 0.1),
  370. (new THREE.Vector3()).lerpVectors(p0, p1, 0.9),
  371. ];
  372. }).flat(),
  373. true,
  374. );
  375. {
  376. const points = curve.getPoints(250);
  377. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  378. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  379. curveObject = new THREE.Line(geometry, material);
  380. scene.add(curveObject);
  381. }
  382. }
  383. </pre>
  384. <p>The first part of that code makes a curve.
  385. The second part of that code generates 250 points
  386. from the curve and then creates an object to display
  387. the lines made by connecting those 250 points.</p>
  388. <p>Running <a href="../examples/load-gltf-car-path.html">the example</a> I didn't see
  389. the curve. To make it visible I made it ignore the depth test and
  390. render last</p>
  391. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> curveObject = new THREE.Line(geometry, material);
  392. + material.depthTest = false;
  393. + curveObject.renderOrder = 1;
  394. </pre>
  395. <p>And that's when I discovered it was way too small.</p>
  396. <div class="threejs_center"><img src="../resources/images/car-curves-too-small.png" style="width: 498px"></div>
  397. <p>Checking the hierarchy in Blender I found out that the artist had
  398. scaled the node all the cars are parented to.</p>
  399. <div class="threejs_center"><img src="../resources/images/cars-scale-0.01.png" style="width: 342px;"></div>
  400. <p>Scaling is bad for real time 3D apps. It causes all kinds of
  401. issues and ends up being no end of frustration when doing
  402. real time 3D. Artists often don't know this because it's so
  403. easy to scale an entire scene in a 3D editing program but
  404. if you decide to make a real time 3D app I suggest you request your
  405. artists to never scale anything. If they change the scale
  406. they should find a way to apply that scale to the vertices
  407. so that when it ends up making it to your app you can ignore
  408. scale.</p>
  409. <p>And, not just scale, in this case the cars are rotated and offset
  410. by their parent, the <code class="notranslate" translate="no">Cars</code> node. This will make it hard at runtime
  411. to move the cars around in world space. To be clear, in this case
  412. we want cars to drive around in world space which is why these
  413. issues are coming up. If something that is meant to be manipulated
  414. in a local space, like the moon revolving around the earth this
  415. is less of an issue.</p>
  416. <p>Going back to the function we wrote above to dump the scene graph,
  417. let's dump the position, rotation, and scale of each node.</p>
  418. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function dumpVec3(v3, precision = 3) {
  419. + return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`;
  420. +}
  421. function dumpObject(obj, lines, isLast = true, prefix = '') {
  422. const localPrefix = isLast ? '└─' : '├─';
  423. lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  424. + const dataPrefix = obj.children.length
  425. + ? (isLast ? ' │ ' : '│ │ ')
  426. + : (isLast ? ' ' : '│ ');
  427. + lines.push(`${prefix}${dataPrefix} pos: ${dumpVec3(obj.position)}`);
  428. + lines.push(`${prefix}${dataPrefix} rot: ${dumpVec3(obj.rotation)}`);
  429. + lines.push(`${prefix}${dataPrefix} scl: ${dumpVec3(obj.scale)}`);
  430. const newPrefix = prefix + (isLast ? ' ' : '│ ');
  431. const lastNdx = obj.children.length - 1;
  432. obj.children.forEach((child, ndx) =&gt; {
  433. const isLast = ndx === lastNdx;
  434. dumpObject(child, lines, isLast, newPrefix);
  435. });
  436. return lines;
  437. }
  438. </pre>
  439. <p>And the result from <a href="../examples/load-gltf-dump-scenegraph-extra.html">running it</a></p>
  440. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">OSG_Scene [Scene]
  441. │ pos: 0.000, 0.000, 0.000
  442. │ rot: 0.000, 0.000, 0.000
  443. │ scl: 1.000, 1.000, 1.000
  444. └─RootNode_(gltf_orientation_matrix) [Object3D]
  445. │ pos: 0.000, 0.000, 0.000
  446. │ rot: -1.571, 0.000, 0.000
  447. │ scl: 1.000, 1.000, 1.000
  448. └─RootNode_(model_correction_matrix) [Object3D]
  449. │ pos: 0.000, 0.000, 0.000
  450. │ rot: 0.000, 0.000, 0.000
  451. │ scl: 1.000, 1.000, 1.000
  452. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  453. │ pos: 0.000, 0.000, 0.000
  454. │ rot: 1.571, 0.000, 0.000
  455. │ scl: 1.000, 1.000, 1.000
  456. └─RootNode [Object3D]
  457. │ pos: 0.000, 0.000, 0.000
  458. │ rot: 0.000, 0.000, 0.000
  459. │ scl: 1.000, 1.000, 1.000
  460. ├─Cars [Object3D]
  461. * │ │ pos: -369.069, -90.704, -920.159
  462. * │ │ rot: 0.000, 0.000, 0.000
  463. * │ │ scl: 1.000, 1.000, 1.000
  464. │ ├─CAR_03_1 [Object3D]
  465. │ │ │ pos: 22.131, 14.663, -475.071
  466. │ │ │ rot: -3.142, 0.732, 3.142
  467. │ │ │ scl: 1.500, 1.500, 1.500
  468. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  469. │ │ pos: 0.000, 0.000, 0.000
  470. │ │ rot: 0.000, 0.000, 0.000
  471. │ │ scl: 1.000, 1.000, 1.000
  472. </pre>
  473. <p>This shows us that <code class="notranslate" translate="no">Cars</code> in the original scene has had its rotation and scale
  474. removed and applied to its children. That suggests either whatever exporter was
  475. used to create the .GLTF file did some special work here or more likely the
  476. artist exported a different version of the file than the corresponding .blend
  477. file, which is why things don't match.</p>
  478. <p>The moral of that is I should have probably downloaded the .blend
  479. file and exported myself. Before exporting I should have inspected
  480. all the major nodes and removed any transformations.</p>
  481. <p>All these nodes at the top</p>
  482. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">OSG_Scene [Scene]
  483. │ pos: 0.000, 0.000, 0.000
  484. │ rot: 0.000, 0.000, 0.000
  485. │ scl: 1.000, 1.000, 1.000
  486. └─RootNode_(gltf_orientation_matrix) [Object3D]
  487. │ pos: 0.000, 0.000, 0.000
  488. │ rot: -1.571, 0.000, 0.000
  489. │ scl: 1.000, 1.000, 1.000
  490. └─RootNode_(model_correction_matrix) [Object3D]
  491. │ pos: 0.000, 0.000, 0.000
  492. │ rot: 0.000, 0.000, 0.000
  493. │ scl: 1.000, 1.000, 1.000
  494. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  495. │ pos: 0.000, 0.000, 0.000
  496. │ rot: 1.571, 0.000, 0.000
  497. │ scl: 1.000, 1.000, 1.000
  498. </pre>
  499. <p>are also a waste.</p>
  500. <p>Ideally the scene would consist of a single "root" node with no position,
  501. rotation, or scale. At runtime I could then pull all the children out of that
  502. root and parent them to the scene itself. There might be children of the root
  503. like "Cars" which would help me find all the cars but ideally it would also have
  504. no translation, rotation, or scale so I could re-parent the cars to the scene
  505. with the minimal amount of work.</p>
  506. <p>In any case the quickest though maybe not the best fix is to just
  507. adjust the object we're using to view the curve.</p>
  508. <p>Here's what I ended up with.</p>
  509. <p>First I adjusted the position of the curve and found values
  510. that seemed to work. I then hid it.</p>
  511. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  512. const points = curve.getPoints(250);
  513. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  514. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  515. curveObject = new THREE.Line(geometry, material);
  516. + curveObject.scale.set(100, 100, 100);
  517. + curveObject.position.y = -621;
  518. + curveObject.visible = false;
  519. material.depthTest = false;
  520. curveObject.renderOrder = 1;
  521. scene.add(curveObject);
  522. }
  523. </pre>
  524. <p>Then I wrote code to move the cars along the curve. For each car we pick a
  525. position from 0 to 1 along the curve and compute a point in world space using
  526. the <code class="notranslate" translate="no">curveObject</code> to transform the point. We then pick another point slightly
  527. further down the curve. We set the car's orientation using <code class="notranslate" translate="no">lookAt</code> and put the
  528. car at the mid point between the 2 points.</p>
  529. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">// create 2 Vector3s we can use for path calculations
  530. const carPosition = new THREE.Vector3();
  531. const carTarget = new THREE.Vector3();
  532. function render(time) {
  533. ...
  534. - for (const car of cars) {
  535. - car.rotation.y = time;
  536. - }
  537. + {
  538. + const pathTime = time * .01;
  539. + const targetOffset = 0.01;
  540. + cars.forEach((car, ndx) =&gt; {
  541. + // a number between 0 and 1 to evenly space the cars
  542. + const u = pathTime + ndx / cars.length;
  543. +
  544. + // get the first point
  545. + curve.getPointAt(u % 1, carPosition);
  546. + carPosition.applyMatrix4(curveObject.matrixWorld);
  547. +
  548. + // get a second point slightly further down the curve
  549. + curve.getPointAt((u + targetOffset) % 1, carTarget);
  550. + carTarget.applyMatrix4(curveObject.matrixWorld);
  551. +
  552. + // put the car at the first point (temporarily)
  553. + car.position.copy(carPosition);
  554. + // point the car the second point
  555. + car.lookAt(carTarget);
  556. +
  557. + // put the car between the 2 points
  558. + car.position.lerpVectors(carPosition, carTarget, 0.5);
  559. + });
  560. + }
  561. </pre>
  562. <p>and when I ran it I found out for each type of car, their height above their origins
  563. are not consistently set and so I needed to offset each one
  564. a little.</p>
  565. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const loadedCars = root.getObjectByName('Cars');
  566. const fixes = [
  567. - { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], },
  568. - { prefix: 'CAR_03', rot: [0, Math.PI, 0], },
  569. - { prefix: 'Car_04', rot: [0, Math.PI, 0], },
  570. + { prefix: 'Car_08', y: 0, rot: [Math.PI * .5, 0, Math.PI * .5], },
  571. + { prefix: 'CAR_03', y: 33, rot: [0, Math.PI, 0], },
  572. + { prefix: 'Car_04', y: 40, rot: [0, Math.PI, 0], },
  573. ];
  574. root.updateMatrixWorld();
  575. for (const car of loadedCars.children.slice()) {
  576. const fix = fixes.find(fix =&gt; car.name.startsWith(fix.prefix));
  577. const obj = new THREE.Object3D();
  578. car.getWorldPosition(obj.position);
  579. - car.position.set(0, 0, 0);
  580. + car.position.set(0, fix.y, 0);
  581. car.rotation.set(...fix.rot);
  582. obj.add(car);
  583. scene.add(obj);
  584. cars.push(obj);
  585. }
  586. </pre>
  587. <p>And the result.</p>
  588. <p></p><div translate="no" class="threejs_example_container notranslate">
  589. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-animated-cars.html"></iframe></div>
  590. <a class="threejs_center" href="/manual/examples/load-gltf-animated-cars.html" target="_blank">click here to open in a separate window</a>
  591. </div>
  592. <p></p>
  593. <p>Not bad for a few minutes work.</p>
  594. <p>The last thing I wanted to do is turn on shadows.</p>
  595. <p>To do this I grabbed all the GUI code from the <a href="/docs/#api/en/lights/DirectionalLight"><code class="notranslate" translate="no">DirectionalLight</code></a> shadows
  596. example in <a href="shadows.html">the article on shadows</a> and pasted it
  597. into our latest code.</p>
  598. <p>Then, after loading, we need to turn on shadows on all the objects.</p>
  599. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  600. const gltfLoader = new GLTFLoader();
  601. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  602. const root = gltf.scene;
  603. scene.add(root);
  604. + root.traverse((obj) =&gt; {
  605. + if (obj.castShadow !== undefined) {
  606. + obj.castShadow = true;
  607. + obj.receiveShadow = true;
  608. + }
  609. + });
  610. </pre>
  611. <p>I then spent nearly 4 hours trying to figure out why the shadow helpers
  612. were not working. It was because I forgot to enable shadows with</p>
  613. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">renderer.shadowMap.enabled = true;
  614. </pre>
  615. <p>😭</p>
  616. <p>I then adjusted the values until our <code class="notranslate" translate="no">DirectionLight</code>'s shadow camera
  617. had a frustum that covered the entire scene. These are the settings
  618. I ended up with.</p>
  619. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  620. const color = 0xFFFFFF;
  621. const intensity = 1;
  622. const light = new THREE.DirectionalLight(color, intensity);
  623. + light.castShadow = true;
  624. * light.position.set(-250, 800, -850);
  625. * light.target.position.set(-550, 40, -450);
  626. + light.shadow.bias = -0.004;
  627. + light.shadow.mapSize.width = 2048;
  628. + light.shadow.mapSize.height = 2048;
  629. scene.add(light);
  630. scene.add(light.target);
  631. + const cam = light.shadow.camera;
  632. + cam.near = 1;
  633. + cam.far = 2000;
  634. + cam.left = -1500;
  635. + cam.right = 1500;
  636. + cam.top = 1500;
  637. + cam.bottom = -1500;
  638. ...
  639. </pre>
  640. <p>and I set the background color to light blue.</p>
  641. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  642. -scene.background = new THREE.Color('black');
  643. +scene.background = new THREE.Color('#DEFEFF');
  644. </pre>
  645. <p>And ... shadows</p>
  646. <p></p><div translate="no" class="threejs_example_container notranslate">
  647. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-shadows.html"></iframe></div>
  648. <a class="threejs_center" href="/manual/examples/load-gltf-shadows.html" target="_blank">click here to open in a separate window</a>
  649. </div>
  650. <p></p>
  651. <p>I hope walking through this project was useful and showed some
  652. good examples of working though some of the issues of loading
  653. a file with a scenegraph.</p>
  654. <p>One interesting thing is that comparing the .blend file to the .gltf
  655. file, the .blend file has several lights but they are not lights
  656. after being loaded into the scene. A .GLTF file is just a JSON
  657. file so you can easily look inside. It consists of several
  658. arrays of things and each item in an array is referenced by index
  659. else where. While there are extensions in the works they point
  660. to a problem with almost all 3d formats. <strong>They can never cover every
  661. case</strong>.</p>
  662. <p>There is always a need for more data. For example we manually exported
  663. a path for the cars to follow. Ideally that info could have been in
  664. the .GLTF file but to do that we'd need to write our own exporter
  665. and some how mark nodes for how we want them exported or use a
  666. naming scheme or something along those lines to get data from
  667. whatever tool we're using to create the data into our app.</p>
  668. <p>All of that is left as an exercise to the reader.</p>
  669. </div>
  670. </div>
  671. </div>
  672. <script src="../resources/prettify.js"></script>
  673. <script src="../resources/lesson.js"></script>
  674. </body></html>