2
0

load-gltf.html 32 KB

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