load-obj.html 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>Loading a .OBJ 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 .OBJ 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 .OBJ File</h1>
  18. </div>
  19. <div class="lesson">
  20. <div class="lesson-main">
  21. <p>One of the most common things people want to do with three.js
  22. is to load and display 3D models. A common format is the .OBJ
  23. 3D format so let's try loading one.</p>
  24. <p>Searching the net I found <a href="https://www.blendswap.com/blends/view/69174">this CC-BY-NC 3.0 windmill 3D model</a> by <a href="https://www.blendswap.com/user/ahedov">ahedov</a>.</p>
  25. <div class="threejs_center"><img src="../resources/images/windmill-obj.jpg"></div>
  26. <p>I downloaded the .blend file from that site, loaded it into <a href="https://blender.org">Blender</a>
  27. and exported it as an .OBJ file.</p>
  28. <div class="threejs_center"><img style="width: 827px;" src="../resources/images/windmill-export-as-obj.jpg"></div>
  29. <blockquote>
  30. <p>Note: If you've never used Blender you might be in for a surprise
  31. in that Blender does things differently than just about every
  32. other program you've ever used. Just be aware you might need to
  33. set aside some time to read some basic UI navigation for Blender.</p>
  34. <p>Let me also add that 3D programs in general are giant beasts with
  35. 1000s of features. They are some of the most complicated software there
  36. is. When I first learned 3D Studio Max in 1996 I read through 70% of the
  37. 600 page manual spending a few hours a day for around 3 weeks. That paid
  38. off in that when I learned Maya a few years later some of the lessons
  39. learned before were applicable to Maya. So, just be aware that if you
  40. really want to be able to use 3D software to either build 3D assets
  41. or to modify existing ones put it on your schedule and clear sometime
  42. to really go through some lessons.</p>
  43. </blockquote>
  44. <p>In any case I used these export options</p>
  45. <div class="threejs_center"><img style="width: 239px;" src="../resources/images/windmill-export-options.jpg"></div>
  46. <p>Let's try to display it!</p>
  47. <p>I started with the directional lighting example from
  48. <a href="lights.html">the lights article</a> and I combined it with
  49. the hemispherical lighting example so I ended up with one
  50. <a href="/docs/#api/en/lights/HemisphereLight"><code class="notranslate" translate="no">HemisphereLight</code></a> and one <a href="/docs/#api/en/lights/DirectionalLight"><code class="notranslate" translate="no">DirectionalLight</code></a>. I also removed all the GUI stuff
  51. related to adjusting the lights. I also removed the cube and sphere
  52. that were being added to the scene.</p>
  53. <p>From that the first thing we need to do is include the <a href="/docs/#examples/loaders/OBJLoader"><code class="notranslate" translate="no">OBJLoader</code></a> loader in our script.</p>
  54. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import {OBJLoader} from '/examples/jsm/loaders/OBJLoader.js';
  55. </pre>
  56. <p>Then to load the .OBJ file we create an instance of <a href="/docs/#examples/loaders/OBJLoader"><code class="notranslate" translate="no">OBJLoader</code></a>,
  57. pass it the URL of our .OBJ file, and pass in a callback that adds
  58. the loaded model to our scene.</p>
  59. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  60. const objLoader = new OBJLoader();
  61. objLoader.load('resources/models/windmill/windmill.obj', (root) =&gt; {
  62. scene.add(root);
  63. });
  64. }
  65. </pre>
  66. <p>If we run that what happens?</p>
  67. <p></p><div translate="no" class="threejs_example_container notranslate">
  68. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-no-materials.html"></iframe></div>
  69. <a class="threejs_center" href="/manual/examples/load-obj-no-materials.html" target="_blank">click here to open in a separate window</a>
  70. </div>
  71. <p></p>
  72. <p>Well it's close but we're getting errors about materials since we haven't
  73. given the scene any materials and .OBJ files don't have material
  74. parameters. </p>
  75. <p>The .OBJ loader can be passed an
  76. object of name / material pairs. When it loads the .OBJ file,
  77. any material name it finds it will look for the corresponding material
  78. in the map of materials set on the loader. If it finds a
  79. material that matches by name it will use that material. If
  80. not it will use the loader's default material.</p>
  81. <p>Sometimes .OBJ files come with a .MTL file that defines
  82. materials. In our case the exporter also created a .MTL file.
  83. .MTL format is plain ASCII so it's easy to look at. Looking at it here</p>
  84. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no"># Blender MTL File: 'windmill_001.blend'
  85. # Material Count: 2
  86. newmtl Material
  87. Ns 0.000000
  88. Ka 1.000000 1.000000 1.000000
  89. Kd 0.800000 0.800000 0.800000
  90. Ks 0.000000 0.000000 0.000000
  91. Ke 0.000000 0.000000 0.000000
  92. Ni 1.000000
  93. d 1.000000
  94. illum 1
  95. map_Kd windmill_001_lopatky_COL.jpg
  96. map_Bump windmill_001_lopatky_NOR.jpg
  97. newmtl windmill
  98. Ns 0.000000
  99. Ka 1.000000 1.000000 1.000000
  100. Kd 0.800000 0.800000 0.800000
  101. Ks 0.000000 0.000000 0.000000
  102. Ke 0.000000 0.000000 0.000000
  103. Ni 1.000000
  104. d 1.000000
  105. illum 1
  106. map_Kd windmill_001_base_COL.jpg
  107. map_Bump windmill_001_base_NOR.jpg
  108. map_Ns windmill_001_base_SPEC.jpg
  109. </pre>
  110. <p>We can see there are 2 materials referencing 5 jpg textures
  111. but where are the texture files?</p>
  112. <div class="threejs_center"><img style="width: 757px;" src="../resources/images/windmill-exported-files.png"></div>
  113. <p>All we got was an .OBJ file and an .MTL file.</p>
  114. <p>At least for this model it turns out the textures are embedded
  115. in the .blend file we downloaded. We can ask blender to
  116. export those files to by picking <strong>File-&gt;External Data-&gt;Unpack All Into Files</strong></p>
  117. <div class="threejs_center"><img style="width: 828px;" src="../resources/images/windmill-export-textures.jpg"></div>
  118. <p>and then choosing <strong>Write Files to Current Directory</strong></p>
  119. <div class="threejs_center"><img style="width: 828px;" src="../resources/images/windmill-overwrite.jpg"></div>
  120. <p>This ends up writing the files in the same folder as the .blend file
  121. in a sub folder called <strong>textures</strong>.</p>
  122. <div class="threejs_center"><img style="width: 758px;" src="../resources/images/windmill-exported-texture-files.png"></div>
  123. <p>I copied those textures into the same folder I exported the .OBJ
  124. file to.</p>
  125. <div class="threejs_center"><img style="width: 757px;" src="../resources/images/windmill-exported-files-with-textures.png"></div>
  126. <p>Now that we have the textures available we can load the .MTL file.</p>
  127. <p>First we need to include the <a href="/docs/#examples/loaders/MTLLoader"><code class="notranslate" translate="no">MTLLoader</code></a>;</p>
  128. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">import * as THREE from '/build/three.module.js';
  129. import {OrbitControls} from '/examples/jsm/controls/OrbitControls.js';
  130. import {OBJLoader} from '/examples/jsm/loaders/OBJLoader.js';
  131. +import {MTLLoader} from '/examples/jsm/loaders/MTLLoader.js';
  132. </pre>
  133. <p>Then we first load the .MTL file. When it's finished loading we add
  134. the just loaded materials on to the <a href="/docs/#examples/loaders/OBJLoader"><code class="notranslate" translate="no">OBJLoader</code></a> itself via the <code class="notranslate" translate="no">setMaterials</code>
  135. and then load the .OBJ file.</p>
  136. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  137. + const mtlLoader = new MTLLoader();
  138. + mtlLoader.load('resources/models/windmill/windmill.mtl', (mtl) =&gt; {
  139. + mtl.preload();
  140. + objLoader.setMaterials(mtl);
  141. objLoader.load('resources/models/windmill/windmill.obj', (root) =&gt; {
  142. scene.add(root);
  143. });
  144. + });
  145. }
  146. </pre>
  147. <p>And if we try that...</p>
  148. <p></p><div translate="no" class="threejs_example_container notranslate">
  149. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-materials.html"></iframe></div>
  150. <a class="threejs_center" href="/manual/examples/load-obj-materials.html" target="_blank">click here to open in a separate window</a>
  151. </div>
  152. <p></p>
  153. <p>Note that if we spin the model around you'll see the windmill cloth
  154. disappears</p>
  155. <div class="threejs_center"><img style="width: 528px;" src="../resources/images/windmill-missing-cloth.jpg"></div>
  156. <p>We need the material on the blades to be double sided, something
  157. we went over in <a href="materials.html">the article on materials</a>.
  158. There is no easy way to fix this in the .MTL file. Off the top of my
  159. head I can think of 3 ways to fix this.</p>
  160. <ol>
  161. <li><p>Loop over all the materials after loading them and set them all to double sided.</p>
  162. <pre class="prettyprint showlinemods notranslate notranslate" translate="no"> const mtlLoader = new MTLLoader();
  163. mtlLoader.load('resources/models/windmill/windmill.mtl', (mtl) =&gt; {
  164. mtl.preload();
  165. for (const material of Object.values(mtl.materials)) {
  166. material.side = THREE.DoubleSide;
  167. }
  168. ...
  169. </pre><p>This solution works but ideally we only want materials that need
  170. to be double sided to be double sided because drawing double sided
  171. is slower than single sided.</p>
  172. </li>
  173. <li><p>Manually set a specific material</p>
  174. <p>Looking in the .MTL file there are 2 materials. One called <code class="notranslate" translate="no">"windmill"</code>
  175. and the other called <code class="notranslate" translate="no">"Material"</code>. Through trial and error I figured
  176. out the blades use the material called <code class="notranslate" translate="no">"Material"</code>so we could set
  177. that one specifically </p>
  178. <pre class="prettyprint showlinemods notranslate notranslate" translate="no"> const mtlLoader = new MTLLoader();
  179. mtlLoader.load('resources/models/windmill/windmill.mtl', (mtl) =&gt; {
  180. mtl.preload();
  181. mtl.materials.Material.side = THREE.DoubleSide;
  182. ...
  183. </pre></li>
  184. <li><p>Realizing that the .MTL file is limited we could just not use it
  185. and instead create materials ourselves.</p>
  186. <p>In this case we'd need to look up the <a href="/docs/#api/en/objects/Mesh"><code class="notranslate" translate="no">Mesh</code></a> object after
  187. loading the obj file.</p>
  188. <pre class="prettyprint showlinemods notranslate notranslate" translate="no"> objLoader.load('resources/models/windmill/windmill.obj', (root) =&gt; {
  189. const materials = {
  190. Material: new THREE.MeshPhongMaterial({...}),
  191. windmill: new THREE.MeshPhongMaterial({...}),
  192. };
  193. root.traverse(node =&gt; {
  194. const material = materials[node.material?.name];
  195. if (material) {
  196. node.material = material;
  197. }
  198. })
  199. scene.add(root);
  200. });
  201. </pre></li>
  202. </ol>
  203. <p>Which one you pick is up to you. 1 is easiest. 3 is most flexible.
  204. 2 somewhere in between. For now I'll pick 2.</p>
  205. <p>And with that change you should still see the cloth on the blades
  206. when looking from behind but there's one more issue. If we zoom in close
  207. we see things are turning blocky.</p>
  208. <div class="threejs_center"><img style="width: 700px;" src="../resources/images/windmill-blocky.jpg"></div>
  209. <p>What's going on?</p>
  210. <p>Looking at the textures there are 2 textures labelled NOR for NORmal map.
  211. And looking at them they look like normal maps. Normal maps are generally
  212. purple where as bump maps are black and white. Normal maps represent
  213. the direction of the surface where as bump maps represent the height of
  214. the surface.</p>
  215. <div class="threejs_center"><img style="width: 256px;" src="../examples/resources/models/windmill/windmill_001_base_NOR.jpg"></div>
  216. <p>Looking at <a href="https://github.com/mrdoob/three.js/blob/1a560a3426e24bbfc9ca1f5fb0dfb4c727d59046/examples/js/loaders/MTLLoader.js#L432">the source for the MTLLoader</a>
  217. it expects the keyword <code class="notranslate" translate="no">norm</code> for normal maps so let's edit the .MTL file</p>
  218. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no"># Blender MTL File: 'windmill_001.blend'
  219. # Material Count: 2
  220. newmtl Material
  221. Ns 0.000000
  222. Ka 1.000000 1.000000 1.000000
  223. Kd 0.800000 0.800000 0.800000
  224. Ks 0.000000 0.000000 0.000000
  225. Ke 0.000000 0.000000 0.000000
  226. Ni 1.000000
  227. d 1.000000
  228. illum 1
  229. map_Kd windmill_001_lopatky_COL.jpg
  230. -map_Bump windmill_001_lopatky_NOR.jpg
  231. +norm windmill_001_lopatky_NOR.jpg
  232. newmtl windmill
  233. Ns 0.000000
  234. Ka 1.000000 1.000000 1.000000
  235. Kd 0.800000 0.800000 0.800000
  236. Ks 0.000000 0.000000 0.000000
  237. Ke 0.000000 0.000000 0.000000
  238. Ni 1.000000
  239. d 1.000000
  240. illum 1
  241. map_Kd windmill_001_base_COL.jpg
  242. -map_Bump windmill_001_base_NOR.jpg
  243. +norm windmill_001_base_NOR.jpg
  244. map_Ns windmill_001_base_SPEC.jpg
  245. </pre>
  246. <p>and now when we load it it will be using the normal maps as normal maps and
  247. we can see the back of the blades.</p>
  248. <p></p><div translate="no" class="threejs_example_container notranslate">
  249. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-materials-fixed.html"></iframe></div>
  250. <a class="threejs_center" href="/manual/examples/load-obj-materials-fixed.html" target="_blank">click here to open in a separate window</a>
  251. </div>
  252. <p></p>
  253. <p>Let's load a different file.</p>
  254. <p>Searching the net I found this <a href="https://creativecommons.org/licenses/by-nc/4.0/">CC-BY-NC</a> windmill 3D model made by <a href="http://www.gerzi.ch/">Roger Gerzner / GERIZ.3D Art</a>.</p>
  255. <div class="threejs_center"><img src="../resources/images/windmill-obj-2.jpg"></div>
  256. <p>It had a .OBJ version already available. Let's load it up (note I removed the .MTL loader for now)</p>
  257. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">- objLoader.load('resources/models/windmill/windmill.obj', ...
  258. + objLoader.load('resources/models/windmill-2/windmill.obj', ...
  259. </pre>
  260. <p></p><div translate="no" class="threejs_example_container notranslate">
  261. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-wat.html"></iframe></div>
  262. <a class="threejs_center" href="/manual/examples/load-obj-wat.html" target="_blank">click here to open in a separate window</a>
  263. </div>
  264. <p></p>
  265. <p>Hmmm, nothing appears. What's the problem? I wonder what size the model is?
  266. We can ask THREE.js what size the model is and try to set our
  267. camera automatically.</p>
  268. <p>First off we can ask THREE.js to compute a box that contains the scene
  269. we just loaded and ask for its size and center</p>
  270. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">objLoader.load('resources/models/windmill_2/windmill.obj', (root) =&gt; {
  271. scene.add(root);
  272. + const box = new THREE.Box3().setFromObject(root);
  273. + const boxSize = box.getSize(new THREE.Vector3()).length();
  274. + const boxCenter = box.getCenter(new THREE.Vector3());
  275. + console.log(boxSize);
  276. + console.log(boxCenter);
  277. </pre>
  278. <p>Looking in <a href="debugging-javascript.html">the JavaScript console</a> I see</p>
  279. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">size 2123.6499788469982
  280. center p {x: -0.00006103515625, y: 770.0909731090069, z: -3.313507080078125}
  281. </pre>
  282. <p>Our camera is currently only showing about 100 units with <code class="notranslate" translate="no">near</code> at 0.1 and <code class="notranslate" translate="no">far</code> at 100.
  283. Our ground plane is only 40 units across so basically this windmill model is so big, 2000 units,
  284. that it's surrounding our camera and all parts of it our outside our frustum.</p>
  285. <div class="threejs_center"><img style="width: 280px;" src="../resources/images/camera-inside-windmill.svg"></div>
  286. <p>We could manually fix that but we could also make the camera auto frame our scene.
  287. Let's try that. We can then use the box we just computed adjust the camera settings to
  288. view the entire scene. Note that there is no <em>right</em> answer
  289. on where to put the camera. We could be facing the scene from any direction at any
  290. altitude so we'll just have to pick something.</p>
  291. <p>As we went over in <a href="cameras.html">the article on cameras</a> the camera defines a frustum.
  292. That frustum is defined by the field of view (<code class="notranslate" translate="no">fov</code>) and the <code class="notranslate" translate="no">near</code> and <code class="notranslate" translate="no">far</code> settings. We
  293. want to know given whatever field of view the camera currently has, how far away does the camera
  294. need to be so the box containing the scene fits inside the frustum assuming the frustum
  295. extended forever. In other words let's assume <code class="notranslate" translate="no">near</code> is 0.00000001 and <code class="notranslate" translate="no">far</code> is infinity.</p>
  296. <p>Since we know the size of the box and we know the field of view we have this triangle</p>
  297. <div class="threejs_center"><img style="width: 600px;" src="../resources/images/camera-fit-scene.svg"></div>
  298. <p>You can see on the left is the camera and the blue frustum is projecting out in
  299. front of it. We just computed the box that contains the the windmill. We need to
  300. compute how far way the camera should be from the box so that the box appears
  301. inside the frustum.</p>
  302. <p>Using basic <em>right triangle</em> trigonometry and <a href="https://www.google.com/search?q=SOHCAHTOA">SOHCAHTOA</a>,
  303. given we know the field of view for the frustum and we know the size of the box we can compute the <em>distance</em>.</p>
  304. <div class="threejs_center"><img style="width: 600px;" src="../resources/images/field-of-view-camera.svg"></div>
  305. <p>Based on that diagram the formula for computing distance is</p>
  306. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">distance = halfSizeToFitOnScreen / tangent(halfFovY)
  307. </pre>
  308. <p>Let's translate that to code. First let's make a function that will compute <code class="notranslate" translate="no">distance</code> and then move the
  309. camera that <code class="notranslate" translate="no">distance</code> units from the center of the box. We'll then point the
  310. camera at the <code class="notranslate" translate="no">center</code> of the box.</p>
  311. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
  312. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  313. const halfFovY = THREE.MathUtils.degToRad(camera.fov * .5);
  314. const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
  315. // compute a unit vector that points in the direction the camera is now
  316. // from the center of the box
  317. const direction = (new THREE.Vector3()).subVectors(camera.position, boxCenter).normalize();
  318. // move the camera to a position distance units way from the center
  319. // in whatever direction the camera was from the center already
  320. camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));
  321. // pick some near and far values for the frustum that
  322. // will contain the box.
  323. camera.near = boxSize / 100;
  324. camera.far = boxSize * 100;
  325. camera.updateProjectionMatrix();
  326. // point the camera to look at the center of the box
  327. camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
  328. }
  329. </pre>
  330. <p>We pass in 2 sizes. The <code class="notranslate" translate="no">boxSize</code> and the <code class="notranslate" translate="no">sizeToFitOnScreen</code>. If we just passed in <code class="notranslate" translate="no">boxSize</code>
  331. and used that as <code class="notranslate" translate="no">sizeToFitOnScreen</code> then the math would make the box fit perfectly inside
  332. the frustum. We want a little extra space above and below so we'll pass in a slightly
  333. larger size. </p>
  334. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  335. const objLoader = new OBJLoader();
  336. objLoader.load('resources/models/windmill_2/windmill.obj', (root) =&gt; {
  337. scene.add(root);
  338. + // compute the box that contains all the stuff
  339. + // from root and below
  340. + const box = new THREE.Box3().setFromObject(root);
  341. +
  342. + const boxSize = box.getSize(new THREE.Vector3()).length();
  343. + const boxCenter = box.getCenter(new THREE.Vector3());
  344. +
  345. + // set the camera to frame the box
  346. + frameArea(boxSize * 1.2, boxSize, boxCenter, camera);
  347. +
  348. + // update the Trackball controls to handle the new size
  349. + controls.maxDistance = boxSize * 10;
  350. + controls.target.copy(boxCenter);
  351. + controls.update();
  352. });
  353. }
  354. </pre>
  355. <p>You can see above we pass in <code class="notranslate" translate="no">boxSize * 1.2</code> to give us 20% more space above and below the box when trying
  356. to fit it inside the frustum. We also updated the <a href="/docs/#examples/controls/OrbitControls"><code class="notranslate" translate="no">OrbitControls</code></a> so the camera will orbit the center
  357. of the scene.</p>
  358. <p>Now if we try that we get...</p>
  359. <p></p><div translate="no" class="threejs_example_container notranslate">
  360. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-auto-camera.html"></iframe></div>
  361. <a class="threejs_center" href="/manual/examples/load-obj-auto-camera.html" target="_blank">click here to open in a separate window</a>
  362. </div>
  363. <p></p>
  364. <p>This almost works. Use the mouse to rotate the camera and you
  365. should see the windmill. The problem is the windmill is large and the box's center is at about (0, 770, 0). So, when we move the camera from where it
  366. starts (0, 10, 20) to <code class="notranslate" translate="no">distance</code> units way from the center in the direction the camera
  367. is relative to the center that's moving the camera almost straight down below
  368. the windmill.</p>
  369. <div class="threejs_center"><img style="width: 360px;" src="../resources/images/computed-camera-position.svg"></div>
  370. <p>Let's change it to move sideways from the center of the box to in whatever direction
  371. the camera is from the center. All we need to do to do that is zero out the <code class="notranslate" translate="no">y</code> component
  372. of the vector from the box to the camera. Then, when we normalize that vector it will
  373. become a vector parallel to the XZ plane. In other words parallel to the ground.</p>
  374. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-// compute a unit vector that points in the direction the camera is now
  375. -// from the center of the box
  376. -const direction = (new THREE.Vector3()).subVectors(camera.position, boxCenter).normalize();
  377. +// compute a unit vector that points in the direction the camera is now
  378. +// in the xz plane from the center of the box
  379. +const direction = (new THREE.Vector3())
  380. + .subVectors(camera.position, boxCenter)
  381. + .multiply(new THREE.Vector3(1, 0, 1))
  382. + .normalize();
  383. </pre>
  384. <p>If you look at the bottom of the windmill you'll see a small square. That is our ground
  385. plane. </p>
  386. <div class="threejs_center"><img style="width: 365px;" src="../resources/images/tiny-ground-plane.jpg"></div>
  387. <p>It's only 40x40 units and so is way too small relative to the windmill.
  388. Since the windmill is over 2000 units big let's change the size of the ground plane to
  389. something more fitting. We also need to adjust the repeat otherwise our checkerboard
  390. will be so fine we won't even be able to see it unless we zoom way way in.</p>
  391. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-const planeSize = 40;
  392. +const planeSize = 4000;
  393. const loader = new THREE.TextureLoader();
  394. const texture = loader.load('resources/images/checker.png');
  395. texture.wrapS = THREE.RepeatWrapping;
  396. texture.wrapT = THREE.RepeatWrapping;
  397. texture.magFilter = THREE.NearestFilter;
  398. -const repeats = planeSize / 2;
  399. +const repeats = planeSize / 200;
  400. texture.repeat.set(repeats, repeats);
  401. </pre>
  402. <p>and now we can see this windmill</p>
  403. <p></p><div translate="no" class="threejs_example_container notranslate">
  404. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-auto-camera-xz.html"></iframe></div>
  405. <a class="threejs_center" href="/manual/examples/load-obj-auto-camera-xz.html" target="_blank">click here to open in a separate window</a>
  406. </div>
  407. <p></p>
  408. <p>Let's add the materials back. Like before there is a .MTL file that references
  409. some textures but looking at the files I quickly see an issue.</p>
  410. <pre class="prettyprint showlinemods notranslate lang-shell" translate="no"> $ ls -l windmill
  411. -rw-r--r--@ 1 gregg staff 299 May 20 2009 windmill.mtl
  412. -rw-r--r--@ 1 gregg staff 142989 May 20 2009 windmill.obj
  413. -rw-r--r--@ 1 gregg staff 12582956 Apr 19 2009 windmill_diffuse.tga
  414. -rw-r--r--@ 1 gregg staff 12582956 Apr 20 2009 windmill_normal.tga
  415. -rw-r--r--@ 1 gregg staff 12582956 Apr 19 2009 windmill_spec.tga
  416. </pre>
  417. <p>There are TARGA (.tga) files and they are giant!</p>
  418. <p>THREE.js actually has a TGA loader but it's arguably wrong to use it for most use cases.
  419. If you're making a viewer where you want to allow users to view random 3D files they
  420. find on the net then maybe, just maybe, you might want to load TGA files. (<a href="#loading-scenes">*</a>)</p>
  421. <p>One problem with TGA files are they can't be compressed well at all. TGA only supports very
  422. simple compression and looking above we can see the files are not compressed at all
  423. as the odds of them being all exactly the same size are extremely low. Further they
  424. are 12 megabytes each!!! If we used those files the user would have to download 36meg
  425. to see the windmill.</p>
  426. <p>Another issue with TGA is the browser itself has no support for them so loading them
  427. is likely going to be slower than loading supported formats like .JPG and .PNG</p>
  428. <p>I'm pretty sure for our purposes converting them to .JPG will be the best option.
  429. Looking inside I see they are 3 channels each, RGB, there is no alpha channel. JPG
  430. only supports 3 channels so that's a good fit. JPG also supports lossy compression
  431. so we can make the files much smaller to download</p>
  432. <p>Loading the files up they were each 2048x2048. That seemed like a waste to me but of
  433. course it depends on your use case. I made them each 1024x1024 and saved them at a
  434. 50% quality setting in Photoshop. Getting a file listing</p>
  435. <pre class="prettyprint showlinemods notranslate lang-shell" translate="no"> $ ls -l ../threejs.org/manual/examples/resources/models/windmill
  436. -rw-r--r--@ 1 gregg staff 299 May 20 2009 windmill.mtl
  437. -rw-r--r--@ 1 gregg staff 142989 May 20 2009 windmill.obj
  438. -rw-r--r--@ 1 gregg staff 259927 Nov 7 18:37 windmill_diffuse.jpg
  439. -rw-r--r--@ 1 gregg staff 98013 Nov 7 18:38 windmill_normal.jpg
  440. -rw-r--r--@ 1 gregg staff 191864 Nov 7 18:39 windmill_spec.jpg
  441. </pre>
  442. <p>We went from 36meg to 0.55meg! Of course the artist might not be pleased
  443. with this compression so be sure to consult with them to discuss the tradeoffs.</p>
  444. <p>Now, to use the .MTL file we need to edit it to reference the .JPG files
  445. instead of the .TGA files. Fortunately it's a simple text file so it's easy to edit</p>
  446. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no">newmtl blinn1SG
  447. Ka 0.10 0.10 0.10
  448. Kd 0.00 0.00 0.00
  449. Ks 0.00 0.00 0.00
  450. Ke 0.00 0.00 0.00
  451. Ns 0.060000
  452. Ni 1.500000
  453. d 1.000000
  454. Tr 0.000000
  455. Tf 1.000000 1.000000 1.000000
  456. illum 2
  457. -map_Kd windmill_diffuse.tga
  458. +map_Kd windmill_diffuse.jpg
  459. -map_Ks windmill_spec.tga
  460. +map_Ks windmill_spec.jpg
  461. -map_bump windmill_normal.tga
  462. -bump windmill_normal.tga
  463. +map_bump windmill_normal.jpg
  464. +bump windmill_normal.jpg
  465. </pre>
  466. <p>Now that the .MTL file points to some reasonable size textures we need to load it so we'll just do like we did above, first load the materials
  467. and then set them on the <a href="/docs/#examples/loaders/OBJLoader"><code class="notranslate" translate="no">OBJLoader</code></a></p>
  468. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  469. + const mtlLoader = new MTLLoader();
  470. + mtlLoader.load('resources/models/windmill_2/windmill-fixed.mtl', (mtl) =&gt; {
  471. + mtl.preload();
  472. + const objLoader = new OBJLoader();
  473. + objLoader.setMaterials(mtl);
  474. objLoader.load('resources/models/windmill/windmill.obj', (root) =&gt; {
  475. root.updateMatrixWorld();
  476. scene.add(root);
  477. // compute the box that contains all the stuff
  478. // from root and below
  479. const box = new THREE.Box3().setFromObject(root);
  480. const boxSize = box.getSize(new THREE.Vector3()).length();
  481. const boxCenter = box.getCenter(new THREE.Vector3());
  482. // set the camera to frame the box
  483. frameArea(boxSize * 1.2, boxSize, boxCenter, camera);
  484. // update the Trackball controls to handle the new size
  485. controls.maxDistance = boxSize * 10;
  486. controls.target.copy(boxCenter);
  487. controls.update();
  488. });
  489. + });
  490. }
  491. </pre>
  492. <p>Before we actually try it out I ran into some issues that rather than show a failure I'm just going to go over them.</p>
  493. <p>Issue #1: The three <a href="/docs/#examples/loaders/MTLLoader"><code class="notranslate" translate="no">MTLLoader</code></a> creates materials that multiply the material's diffuse color by the diffuse texture map.</p>
  494. <p>That's a useful feature but looking a the .MTL file above the line</p>
  495. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no">Kd 0.00 0.00 0.00
  496. </pre>
  497. <p>sets the diffuse color to 0. Texture map * 0 = black! It's possible the modeling tool used to make the windmill
  498. did not multiply the diffuse texture map by the diffuse color. That's why it worked for the artists that made this windmill.</p>
  499. <p>To fix this we can change the line to</p>
  500. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no">Kd 1.00 1.00 1.00
  501. </pre>
  502. <p>since Texture Map * 1 = Texture Map.</p>
  503. <p>Issue #2: The specular color is also black</p>
  504. <p>The line that starts with <code class="notranslate" translate="no">Ks</code> specifies the specular color. It's likely the modeling software used to make the windmill
  505. did something similar as it did with diffuse maps in that it used the specular map's color for specular highlights.
  506. Three.js uses only the red channel of a specular map as input to how much of the specular color to reflect but three still
  507. needs a specular color set.</p>
  508. <p>Like above we can fix that by editing the .MTL file like this.</p>
  509. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no">-Ks 0.00 0.00 0.00
  510. +Ks 1.00 1.00 1.00
  511. </pre>
  512. <p>Issue #3: The <code class="notranslate" translate="no">windmill_normal.jpg</code> is a normal map not a bump map.</p>
  513. <p>Just like above we just need to edit the .MTL file</p>
  514. <pre class="prettyprint showlinemods notranslate lang-mtl" translate="no">-map_bump windmill_normal.jpg
  515. -bump windmill_normal.jpg
  516. +norm windmill_normal.jpg
  517. </pre>
  518. <p>Given all that if we now try it out it should load up with materials.</p>
  519. <p></p><div translate="no" class="threejs_example_container notranslate">
  520. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/load-obj-materials-windmill2.html"></iframe></div>
  521. <a class="threejs_center" href="/manual/examples/load-obj-materials-windmill2.html" target="_blank">click here to open in a separate window</a>
  522. </div>
  523. <p></p>
  524. <p>Loading models often runs into these kinds of issues. Common issues include:</p>
  525. <ul>
  526. <li><p>Needing to know the size</p>
  527. <p>Above we made the camera try to frame the scene but that's not always the appropriate thing to do. Generally the most appropriate thing
  528. to do is to make your own models or download the models, load them up in some 3D software and look at their scale and adjust if need be.</p>
  529. </li>
  530. <li><p>Orientation Wrong</p>
  531. <p>THREE.js is generally Y = up. Some modeling packages default to Z = up, some Y = up. Some are settable.
  532. If you run into this case where you load a model and it's on its side. You can either hack your code to rotate the model after loading (not recommended),
  533. or you can load the model into your favorite modeling package or use some command line tools to rotate the object in the orientation you need it to be
  534. just like you'd edit an image for your website rather than download it and apply code to adjust it. Blender even has options when you export to
  535. change the orientation.</p>
  536. </li>
  537. <li><p>No .MTL file or wrong materials or incompatible parameters</p>
  538. <p>Above we used a .MTL file above which helped us load materials but there were issues. We manually edited the .MTL file to fix.
  539. It's also common to look inside the .OBJ file to see what materials there are, or to load the .OBJ file in THREE.js and walk the
  540. scene and print out all the materials. Then, go modify the code to make custom materials and assign them where appropriate either
  541. by making a name/material pair object to pass to the loader instead of loading the .MTL file, OR, after the scene has loaded, walking the
  542. scene and fixing things.</p>
  543. </li>
  544. <li><p>Textures too large</p>
  545. <p>Most 3D models are made for either architecture, movies and commercials, or
  546. games. For architecture and movies no one really cares about the size
  547. of the textures since. For games people care because games have limited
  548. memory but most games run locally. Webpages though you want to load
  549. as fast as possible and so you need to look at the textures and try
  550. to make them as small as possible and still look good. In fact the first windmill we should arguably done something about
  551. the textures. They are currently a total of 10meg!!!</p>
  552. <p>Also remember
  553. like we mentioned in the <a href="textures.html">article on textures</a> that
  554. textures take memory so a 50k JPG that expands to 4096x4096 will download
  555. fast but still take a ton of memory.</p>
  556. </li>
  557. </ul>
  558. <p>The last thing I wanted to show is spinning the windmills. Unfortunately, .OBJ files have no hierarchy. That means all parts of each
  559. windmill are basically considered 1 single mesh. You can't spin the blades of the mill as they aren't separated from the rest of the building.</p>
  560. <p>This is one of the main reasons why .OBJ is not really a good format. If I was to guess, the reason it's more common than other formats
  561. is because it's simple and doesn't support many features it works more often than not. Especially if you're making something still like
  562. an architectural image and there's no need to animate anything it's not a bad way to get static props into a scene.</p>
  563. <p>Next up we'll try <a href="load-gltf.html">loading a gLTF scene</a>. The gLTF format supports many more features.</p>
  564. </div>
  565. </div>
  566. </div>
  567. <script src="/manual/resources/prettify.js"></script>
  568. <script src="/manual/resources/lesson.js"></script>
  569. </body></html>