1
0

load-obj.html 27 KB

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