load-gltf.html 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>加载 .gltf 文件</title>
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <meta name="twitter:card" content="summary_large_image">
  8. <meta name="twitter:site" content="@threejs">
  9. <meta name="twitter:title" content="Three.js – 加载 .gltf 文件">
  10. <meta property="og:image" content="https://threejs.org/files/share.png">
  11. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  12. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  13. <link rel="stylesheet" href="../resources/lesson.css">
  14. <link rel="stylesheet" href="../resources/lang.css">
  15. <script type="importmap">
  16. {
  17. "imports": {
  18. "three": "../../build/three.module.js"
  19. }
  20. }
  21. </script>
  22. </head>
  23. <body>
  24. <div class="container">
  25. <div class="lesson-title">
  26. <h1>加载 .gltf 文件</h1>
  27. </div>
  28. <div class="lesson">
  29. <div class="lesson-main">
  30. <p>在上一章中,我们<a href="load-obj.html">加载 .OBJ 文件</a>. 如果你还没有阅读它,你可能需要先查看一下。</p>
  31. <p>正如之前所指出的,“.OBJ 文件格式已经非常古老,并且相当简单”。
  32. 它没有提供任何场景图(scene graph),所以所有的数据都需要加载到一个巨大的Mesh中。 它被设计出来主要是作为3D编辑器之间的一种简单的数据传输方式。</p>
  33. <p><a href="https://github.com/KhronosGroup/glTF">gLTF 格式</a> 是从头开始设计的一种格式,用于显示图形。 3D 格式可被划分为3~4中基本类型。 </p>
  34. <ul>
  35. <li>
  36. <p>3D编辑器格式</p>
  37. <p>用于特定应用程序(主要是3D编辑器):. .blend (Blender), .max (3d Studio Max), .mb and .ma (Maya), etc...</p>
  38. </li>
  39. <li>
  40. <p>交换格式</p>
  41. <p>有.OBJ, .DAE (Collada), .FBX.等格式。它们被设计出来用于3D编辑器之间交换信息的。因此,它们通常比所需的大得多(内含3D编辑器内所需要的信息)。</p>
  42. </li>
  43. <li>
  44. <p>应用程序格式</p>
  45. <p>用于特定的应用程序:游戏</p>
  46. </li>
  47. <li>
  48. <p>传输格式</p>
  49. <p>gLTF可能是第一个真正意义上的传输格式。我猜想VRML可能会被认为是第一个,但是VRML实际上是个相当糟的格式。</p>
  50. <p>这是gLTF被设计出来擅长做的一些事情,其他格式没有的</p>
  51. <ol>
  52. <li>
  53. <p>体积小,适合用于传输</p>
  54. <p>例如:这意味着大量它们的大数据量的数据,像顶点(vertices),被存为二进制格式。当你下载.gLTF格式文件后,可以将它零处理的传入GPU。这是它准备好的。相比较之下,VRML, .OBJ, or
  55. .DAE 这些格式 顶点(vertices)的存储和解析都是通过文本(text)。 文本存储的顶点位置(vertex positions)大约有二进制存储的3倍到5倍大。</p>
  56. </li>
  57. <li>
  58. <p>易于被渲染(render)</p>
  59. <p>
  60. 与其他格式(尤其是应用程序格式)另一个不同是:glTF格式文件中的数据,意味着是用于渲染(render)的,而不是用于编辑的。对渲染不重要的那部分数据大都被删除了。多边形被转为三角形。材质有其应该有的值,可以在任何地方运行。
  61. </p>
  62. </li>
  63. </ol>
  64. </li>
  65. </ul>
  66. <p>gLTF是被特别设计的。因此你应该能轻易下载glTF文件,显示它们,很少出麻烦。祝我们好运,真是这种情况,因为没有其他格式已经能够这样做。</p>
  67. <p>我不确定我要展示什么。在某种程度上加载和显示gLTF文件比.OBJ文件要简单。不像.OBJ文件,材质是格式的一部分。我想我需要至少加载一个.OBJ文件,我遇到的问题可能会提供一些良好的信息</p>
  68. <p>在网上搜索我发现 <a href="https://sketchfab.com/models/edd1c604e1e045a0a2a552ddd9a293e6">这个低模城市</a>
  69. 作者: <a href="https://sketchfab.com/antonmoek">antonmoek</a> 这意味着我们可以做一个好的案例。</p>
  70. <div class="threejs_center"><img src="../resources/images/cartoon_lowpoly_small_city_free_pack.jpg"></div>
  71. <p><a href="load-obj.html">an example from the .OBJ article</a>从这里开始,我删除了加载.OBJ的代码 ,替换为加载.gLTF的</p>
  72. <p>旧.OBJ代码</p>
  73. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const mtlLoader = new MTLLoader();
  74. mtlLoader.loadMtl('resources/models/windmill/windmill-fixed.mtl', (mtl) =&gt; {
  75. mtl.preload();
  76. mtl.materials.Material.side = THREE.DoubleSide;
  77. objLoader.setMaterials(mtl);
  78. objLoader.load('resources/models/windmill/windmill.obj', (event) =&gt; {
  79. const root = event.detail.loaderRootNode;
  80. scene.add(root);
  81. ...
  82. });
  83. });
  84. </pre>
  85. <p>新.GLTF代码</p>
  86. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  87. const gltfLoader = new GLTFLoader();
  88. const url = 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf';
  89. gltfLoader.load(url, (gltf) =&gt; {
  90. const root = gltf.scene;
  91. scene.add(root);
  92. ...
  93. });
  94. </pre>
  95. <p>我像以前一样保持自动框架代码</p>
  96. <p>我们需要包含 <a href="/docs/#examples/loaders/GLTFLoader"><code class="notranslate"
  97. translate="no">GLTFLoader</code></a> 并删除 <a href="/docs/#examples/loaders/OBJLoader"><code
  98. class="notranslate" translate="no">OBJLoader</code></a>.</p>
  99. <pre class="prettyprint showlinemods notranslate lang-html" translate="no">-import {LoaderSupport} from 'three/addons/loaders/LoaderSupport.js';
  100. -import {OBJLoader} from 'three/addons/loaders/OBJLoader.js';
  101. -import {MTLLoader} from 'three/addons/loaders/MTLLoader.js';
  102. +import {GLTFLoader} from 'three/addons/loaders/GLTFLoader.js';
  103. </pre>
  104. <p>像这样运行</p>
  105. <p></p>
  106. <div translate="no" class="threejs_example_container notranslate">
  107. <div><iframe class="threejs_example notranslate" translate="no" style=" "
  108. src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf.html"></iframe></div>
  109. <a class="threejs_center" href="/manual/examples/load-gltf.html" target="_blank">点击这里在其他窗口打开</a>
  110. </div>
  111. <p></p>
  112. <p>神奇吧!它工作了,纹理和其他都工作了。</p>
  113. <p>然后,我想看看我能否给汽车添加绕圈动画(animate),我得检查场景有没有这些汽车的分离的实体,还得检查场景有没有一条路可以用。</p>
  114. <p>我写了一些代码将场景图(scenegraph)打印到 <a href="debugging-javascript.html">JavaScript
  115. console</a>.</p>
  116. <p>打印场景图(scenegraph)代码</p>
  117. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function dumpObject(obj, lines = [], isLast = true, prefix = '') {
  118. const localPrefix = isLast ? '└─' : '├─';
  119. lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  120. const newPrefix = prefix + (isLast ? ' ' : '│ ');
  121. const lastNdx = obj.children.length - 1;
  122. obj.children.forEach((child, ndx) =&gt; {
  123. const isLast = ndx === lastNdx;
  124. dumpObject(child, lines, isLast, newPrefix);
  125. });
  126. return lines;
  127. }
  128. </pre>
  129. <p>我将在场景加载完时调用</p>
  130. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const gltfLoader = new GLTFLoader();
  131. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  132. const root = gltf.scene;
  133. scene.add(root);
  134. console.log(dumpObject(root).join('\n'));
  135. </pre>
  136. <p><a href="../examples/load-gltf-dump-scenegraph.html">Running that</a> 获得清单</p>
  137. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">OSG_Scene [Scene]
  138. └─RootNode_(gltf_orientation_matrix) [Object3D]
  139. └─RootNode_(model_correction_matrix) [Object3D]
  140. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  141. └─RootNode [Object3D]
  142. │ ...
  143. ├─Cars [Object3D]
  144. │ ├─CAR_03_1 [Object3D]
  145. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  146. │ ├─CAR_03 [Object3D]
  147. │ │ └─CAR_03_World_ap_0 [Mesh]
  148. │ ├─Car_04 [Object3D]
  149. │ │ └─Car_04_World_ap_0 [Mesh]
  150. │ ├─CAR_03_2 [Object3D]
  151. │ │ └─CAR_03_2_World_ap_0 [Mesh]
  152. │ ├─Car_04_1 [Object3D]
  153. │ │ └─Car_04_1_World_ap_0 [Mesh]
  154. │ ├─Car_04_2 [Object3D]
  155. │ │ └─Car_04_2_World_ap_0 [Mesh]
  156. │ ├─Car_04_3 [Object3D]
  157. │ │ └─Car_04_3_World_ap_0 [Mesh]
  158. │ ├─Car_04_4 [Object3D]
  159. │ │ └─Car_04_4_World_ap_0 [Mesh]
  160. │ ├─Car_08_4 [Object3D]
  161. │ │ └─Car_08_4_World_ap8_0 [Mesh]
  162. │ ├─Car_08_3 [Object3D]
  163. │ │ └─Car_08_3_World_ap9_0 [Mesh]
  164. │ ├─Car_04_1_2 [Object3D]
  165. │ │ └─Car_04_1_2_World_ap_0 [Mesh]
  166. │ ├─Car_08_2 [Object3D]
  167. │ │ └─Car_08_2_World_ap11_0 [Mesh]
  168. │ ├─CAR_03_1_2 [Object3D]
  169. │ │ └─CAR_03_1_2_World_ap_0 [Mesh]
  170. │ ├─CAR_03_2_2 [Object3D]
  171. │ │ └─CAR_03_2_2_World_ap_0 [Mesh]
  172. │ ├─Car_04_2_2 [Object3D]
  173. │ │ └─Car_04_2_2_World_ap_0 [Mesh]
  174. ...
  175. </pre>
  176. <p>从这里我们可以看到所有的汽车,都在它们父节点<code class="notranslate" translate="no">"Cars"</code>中</p>
  177. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">* ├─Cars [Object3D]
  178. │ ├─CAR_03_1 [Object3D]
  179. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  180. │ ├─CAR_03 [Object3D]
  181. │ │ └─CAR_03_World_ap_0 [Mesh]
  182. │ ├─Car_04 [Object3D]
  183. │ │ └─Car_04_World_ap_0 [Mesh]
  184. </pre>
  185. <p>做一个简单的测试,我尝试将这些"Cars"节点的子节点绕它们的Y轴旋转。</p>
  186. <p>在加载场景后,我查找了“Cars”节点并保存了结果。</p>
  187. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+let cars;
  188. {
  189. const gltfLoader = new GLTFLoader();
  190. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  191. const root = gltf.scene;
  192. scene.add(root);
  193. + cars = root.getObjectByName('Cars');
  194. </pre>
  195. <p>然后在<code class="notranslate" translate="no">render</code> render函数中我们可以设置<code class="notranslate"
  196. translate="no">cars</code>Cars每个子节点旋转。</p>
  197. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function render(time) {
  198. + time *= 0.001; // convert to seconds
  199. if (resizeRendererToDisplaySize(renderer)) {
  200. const canvas = renderer.domElement;
  201. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  202. camera.updateProjectionMatrix();
  203. }
  204. + if (cars) {
  205. + for (const car of cars.children) {
  206. + car.rotation.y = time;
  207. + }
  208. + }
  209. renderer.render(scene, camera);
  210. requestAnimationFrame(render);
  211. }
  212. </pre>
  213. <p>于是我们得到</p>
  214. <p></p>
  215. <div translate="no" class="threejs_example_container notranslate">
  216. <div><iframe class="threejs_example notranslate" translate="no" style=" "
  217. src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-rotate-cars.html"></iframe>
  218. </div>
  219. <a class="threejs_center" href="/manual/examples/load-gltf-rotate-cars.html" target="_blank">click here to
  220. open in a separate window</a>
  221. </div>
  222. <p></p>
  223. <p>呃~,看起来很不幸,这场景没有设计汽车动画,因为他们当初不是用于此目的的。这卡车在错误的方向旋转。</p>
  224. <p>这引出一个很重要的点,当你把东西做成3D时,你需要预先计划并设计你的资源(assets),让它们拥有能正确使用的初始功能。所以它们应该有正确的比例...</p>
  225. <p>因为我不是艺术家,我不懂blender,我只能hack这个例子。我们将把每辆车,和它们的父节点,放到另一个
  226. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>.
  227. 我们将移动这些 <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no"> Object3D</code></a>
  228. 的对象去移动车,但是我们可以设置汽车的原始<a href="/docs/#api/en/core/Object3D"><code class="notranslate"
  229. translate="no">Object3D</code></a>
  230. 重新定位它,所以它是关于我们真正需要的地方。
  231. </p>
  232. <p>回顾下场景图(scene graph)看起来只有三种车,Car_08", "CAR_03", and "Car_04"。每种汽车都会使用相同的调整。</p>
  233. <p>我给每个汽车都写了代码,将它们的父节点换成新的
  234. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>, 将新
  235. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> 添加到场景,
  236. 应用于每种 <em>类型</em>的车的设置,修正它的朝向。 增加新的
  237. <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> a
  238. <code class="notranslate" translate="no">cars</code> array.
  239. </p>
  240. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-let cars;
  241. +const cars = [];
  242. {
  243. const gltfLoader = new GLTFLoader();
  244. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  245. const root = gltf.scene;
  246. scene.add(root);
  247. - cars = root.getObjectByName('Cars');
  248. + const loadedCars = root.getObjectByName('Cars');
  249. + const fixes = [
  250. + { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], },
  251. + { prefix: 'CAR_03', rot: [0, Math.PI, 0], },
  252. + { prefix: 'Car_04', rot: [0, Math.PI, 0], },
  253. + ];
  254. +
  255. + root.updateMatrixWorld();
  256. + for (const car of loadedCars.children.slice()) {
  257. + const fix = fixes.find(fix =&gt; car.name.startsWith(fix.prefix));
  258. + const obj = new THREE.Object3D();
  259. + car.getWorldPosition(obj.position);
  260. + car.position.set(0, 0, 0);
  261. + car.rotation.set(...fix.rot);
  262. + obj.add(car);
  263. + scene.add(obj);
  264. + cars.push(obj);
  265. + }
  266. ...
  267. </pre>
  268. <p>这些修正朝向的车 </p>
  269. <p></p>
  270. <div translate="no" class="threejs_example_container notranslate">
  271. <div><iframe class="threejs_example notranslate" translate="no" style=" "
  272. src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-rotate-cars-fixed.html"></iframe>
  273. </div>
  274. <a class="threejs_center" href="/manual/examples/load-gltf-rotate-cars-fixed.html" target="_blank">click here
  275. to open in a separate window</a>
  276. </div>
  277. <p></p>
  278. <p>现在让我们驾驶着它们绕圈</p>
  279. <p>制作一个简单的驾驶系统对这篇文章来说太多了,但作为代替我们可以做一个基于所有道路做一个弯曲路径,然后放置车到路上。下面的图是blender创建的路径。</p>
  280. <div class="threejs_center"><img src="../resources/images/making-path-for-cars.jpg" style="width: 1094px"></div>
  281. <p>我需要一种方式在Blender之外花去路径数据的方法
  282. 幸运的是,我能选择我的路径并通过"write nurbs"导出.OBJ</p>
  283. <div class="threejs_center"><img src="../resources/images/blender-export-obj-write-nurbs.jpg"
  284. style="width: 498px"></div>
  285. <p>打开.OBJ文件我能够获取点列表,我格式化后</p>
  286. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const controlPoints = [
  287. [1.118281, 5.115846, -3.681386],
  288. [3.948875, 5.115846, -3.641834],
  289. [3.960072, 5.115846, -0.240352],
  290. [3.985447, 5.115846, 4.585005],
  291. [-3.793631, 5.115846, 4.585006],
  292. [-3.826839, 5.115846, -14.736200],
  293. [-14.542292, 5.115846, -14.765865],
  294. [-14.520929, 5.115846, -3.627002],
  295. [-5.452815, 5.115846, -3.634418],
  296. [-5.467251, 5.115846, 4.549161],
  297. [-13.266233, 5.115846, 4.567083],
  298. [-13.250067, 5.115846, -13.499271],
  299. [4.081842, 5.115846, -13.435463],
  300. [4.125436, 5.115846, -5.334928],
  301. [-14.521364, 5.115846, -5.239871],
  302. [-14.510466, 5.115846, 5.486727],
  303. [5.745666, 5.115846, 5.510492],
  304. [5.787942, 5.115846, -14.728308],
  305. [-5.423720, 5.115846, -14.761919],
  306. [-5.373599, 5.115846, -3.704133],
  307. [1.004861, 5.115846, -3.641834],
  308. ];
  309. </pre>
  310. <p>THREE.js有几个曲线(curve)的类。 <a href="/docs/#api/en/extras/curves/CatmullRomCurve3"><code class="notranslate"
  311. translate="no">CatmullRomCurve3</code></a> 那种曲线的事情是尝试通过这些点进行平滑的曲线</p>
  312. <p>事实上直接提供这些点会生成这样的曲线</p>
  313. <div class="threejs_center"><img src="../resources/images/car-curves-before.png" style="width: 400px"></div>
  314. <p>但是,我想要更尖锐的转角。如果我们计算了一些额外的点,我们可以得到我们想要的东西。
  315. 每两对点之间,我们需要在两点之间的10%处和90%处计算额外的两个点,并将它们传递给
  316. <a href="/docs/#api/en/extras/curves/CatmullRomCurve3"><code class="notranslate"
  317. translate="no">CatmullRomCurve3</code></a>.
  318. </p>
  319. <p>这会得到这样的曲线</p>
  320. <div class="threejs_center"><img src="../resources/images/car-curves-after.png" style="width: 400px"></div>
  321. <p>曲线代码 </p>
  322. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">let curve;
  323. let curveObject;
  324. {
  325. const controlPoints = [
  326. [1.118281, 5.115846, -3.681386],
  327. [3.948875, 5.115846, -3.641834],
  328. [3.960072, 5.115846, -0.240352],
  329. [3.985447, 5.115846, 4.585005],
  330. [-3.793631, 5.115846, 4.585006],
  331. [-3.826839, 5.115846, -14.736200],
  332. [-14.542292, 5.115846, -14.765865],
  333. [-14.520929, 5.115846, -3.627002],
  334. [-5.452815, 5.115846, -3.634418],
  335. [-5.467251, 5.115846, 4.549161],
  336. [-13.266233, 5.115846, 4.567083],
  337. [-13.250067, 5.115846, -13.499271],
  338. [4.081842, 5.115846, -13.435463],
  339. [4.125436, 5.115846, -5.334928],
  340. [-14.521364, 5.115846, -5.239871],
  341. [-14.510466, 5.115846, 5.486727],
  342. [5.745666, 5.115846, 5.510492],
  343. [5.787942, 5.115846, -14.728308],
  344. [-5.423720, 5.115846, -14.761919],
  345. [-5.373599, 5.115846, -3.704133],
  346. [1.004861, 5.115846, -3.641834],
  347. ];
  348. const p0 = new THREE.Vector3();
  349. const p1 = new THREE.Vector3();
  350. curve = new THREE.CatmullRomCurve3(
  351. controlPoints.map((p, ndx) =&gt; {
  352. p0.set(...p);
  353. p1.set(...controlPoints[(ndx + 1) % controlPoints.length]);
  354. return [
  355. (new THREE.Vector3()).copy(p0),
  356. (new THREE.Vector3()).lerpVectors(p0, p1, 0.1),
  357. (new THREE.Vector3()).lerpVectors(p0, p1, 0.9),
  358. ];
  359. }).flat(),
  360. true,
  361. );
  362. {
  363. const points = curve.getPoints(250);
  364. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  365. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  366. curveObject = new THREE.Line(geometry, material);
  367. scene.add(curveObject);
  368. }
  369. }
  370. </pre>
  371. <p>
  372. 代码第一部分是创建了曲线。
  373. 代码第二部分是从曲线生成了250个点,然后创建了一个对象来显示这些点连起来的线。
  374. </p>
  375. <p>运行 <a href="../examples/load-gltf-car-path.html">the example</a>
  376. 我没有看见曲线。 为了让它可见我关闭了深度测试,并最后渲染它</p>
  377. <pre class="prettyprint showlinemods notranslate lang-js" translate="no"> curveObject = new THREE.Line(geometry, material);
  378. + material.depthTest = false;
  379. + curveObject.renderOrder = 1;
  380. </pre>
  381. <p>我发现路线实在太小了</p>
  382. <div class="threejs_center"><img src="../resources/images/car-curves-too-small.png" style="width: 498px"></div>
  383. <p>检查Blender中的层次结构我发现艺术家缩放了节点所有汽车。</p>
  384. <div class="threejs_center"><img src="../resources/images/cars-scale-0.01.png" style="width: 342px;"></div>
  385. <p>缩放对于实时3D应用程序是十分糟糕的。这会到这各种各样的问题,并且会以无休止的沮丧结束。
  386. 艺术家经常不知道这些,因为在3D编辑程序中缩放整个场景是非常容易的。
  387. 但是,如果你决定要做实时3D应用程序,我建议要求你的艺术家/设计人员不要缩放任何东西。
  388. 如果他们修改了scale,他们必须找到一种方式应用于缩放后的顶点。这样你就能,在导入程序后不用管缩放了。</p>
  389. <p>还有, 不仅是缩放, 在这个例子中,车辆是通过父节点缩放,偏移的。 <code class="notranslate" translate="no">Cars</code> 节点.
  390. 这将让在世界空间中实时移动车辆变得非常困难。
  391. 清楚地说,这个例子中,我们能希望车辆绕着世界空间开,这就会带来问题。
  392. 如果有些东西地数据处理在局部空间,如月球绕着地球转,就很少带来问题。
  393. </p>
  394. <p>
  395. 回到我写地打印场景图地方法。
  396. 让我们每个节点打印 位置, 旋转, 缩放 。</p>
  397. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">+function dumpVec3(v3, precision = 3) {
  398. + return `${v3.x.toFixed(precision)}, ${v3.y.toFixed(precision)}, ${v3.z.toFixed(precision)}`;
  399. +}
  400. function dumpObject(obj, lines, isLast = true, prefix = '') {
  401. const localPrefix = isLast ? '└─' : '├─';
  402. lines.push(`${prefix}${prefix ? localPrefix : ''}${obj.name || '*no-name*'} [${obj.type}]`);
  403. + const dataPrefix = obj.children.length
  404. + ? (isLast ? ' │ ' : '│ │ ')
  405. + : (isLast ? ' ' : '│ ');
  406. + lines.push(`${prefix}${dataPrefix} pos: ${dumpVec3(obj.position)}`);
  407. + lines.push(`${prefix}${dataPrefix} rot: ${dumpVec3(obj.rotation)}`);
  408. + lines.push(`${prefix}${dataPrefix} scl: ${dumpVec3(obj.scale)}`);
  409. const newPrefix = prefix + (isLast ? ' ' : '│ ');
  410. const lastNdx = obj.children.length - 1;
  411. obj.children.forEach((child, ndx) =&gt; {
  412. const isLast = ndx === lastNdx;
  413. dumpObject(child, lines, isLast, newPrefix);
  414. });
  415. return lines;
  416. }
  417. </pre>
  418. <p><a href="../examples/load-gltf-dump-scenegraph-extra.html">运行</a>的结果 </p>
  419. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">OSG_Scene [Scene]
  420. │ pos: 0.000, 0.000, 0.000
  421. │ rot: 0.000, 0.000, 0.000
  422. │ scl: 1.000, 1.000, 1.000
  423. └─RootNode_(gltf_orientation_matrix) [Object3D]
  424. │ pos: 0.000, 0.000, 0.000
  425. │ rot: -1.571, 0.000, 0.000
  426. │ scl: 1.000, 1.000, 1.000
  427. └─RootNode_(model_correction_matrix) [Object3D]
  428. │ pos: 0.000, 0.000, 0.000
  429. │ rot: 0.000, 0.000, 0.000
  430. │ scl: 1.000, 1.000, 1.000
  431. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  432. │ pos: 0.000, 0.000, 0.000
  433. │ rot: 1.571, 0.000, 0.000
  434. │ scl: 1.000, 1.000, 1.000
  435. └─RootNode [Object3D]
  436. │ pos: 0.000, 0.000, 0.000
  437. │ rot: 0.000, 0.000, 0.000
  438. │ scl: 1.000, 1.000, 1.000
  439. ├─Cars [Object3D]
  440. * │ │ pos: -369.069, -90.704, -920.159
  441. * │ │ rot: 0.000, 0.000, 0.000
  442. * │ │ scl: 1.000, 1.000, 1.000
  443. │ ├─CAR_03_1 [Object3D]
  444. │ │ │ pos: 22.131, 14.663, -475.071
  445. │ │ │ rot: -3.142, 0.732, 3.142
  446. │ │ │ scl: 1.500, 1.500, 1.500
  447. │ │ └─CAR_03_1_World_ap_0 [Mesh]
  448. │ │ pos: 0.000, 0.000, 0.000
  449. │ │ rot: 0.000, 0.000, 0.000
  450. │ │ scl: 1.000, 1.000, 1.000
  451. </pre>
  452. <p>这向我们展示了原始场景中的 <code class="notranslate" translate="no">Cars</code>
  453. 已移除其旋转和缩放并应用于其子节点。
  454. 这表明用于创建 .GLTF 文件的导出器在这里做了一些特殊的处理,或者艺术家更可能导出了与相应 .blend 文件不同的文件版本,这就是它们不匹配的原因。</p>
  455. <p>这意味着,我可能需要亲自下载这个.blend文件并导出它。导出它之前,我需要检查所有主要节点,并移除它的任何变换。</p>
  456. <p>顶部的所有节点</p>
  457. <pre class="prettyprint showlinemods notranslate lang-text" translate="no">OSG_Scene [Scene]
  458. │ pos: 0.000, 0.000, 0.000
  459. │ rot: 0.000, 0.000, 0.000
  460. │ scl: 1.000, 1.000, 1.000
  461. └─RootNode_(gltf_orientation_matrix) [Object3D]
  462. │ pos: 0.000, 0.000, 0.000
  463. │ rot: -1.571, 0.000, 0.000
  464. │ scl: 1.000, 1.000, 1.000
  465. └─RootNode_(model_correction_matrix) [Object3D]
  466. │ pos: 0.000, 0.000, 0.000
  467. │ rot: 0.000, 0.000, 0.000
  468. │ scl: 1.000, 1.000, 1.000
  469. └─4d4100bcb1c640e69699a87140df79d7fbx [Object3D]
  470. │ pos: 0.000, 0.000, 0.000
  471. │ rot: 1.571, 0.000, 0.000
  472. │ scl: 1.000, 1.000, 1.000
  473. </pre>
  474. <p>也是浪费。</p>
  475. <p>理想情况下,场景将由一个没有位置、旋转或缩放的“根”节点组成。
  476. 在运行时,我可以将所有子节点从该根中拉出,并将它们作为场景本身的父级。
  477. 可能有像“Cars”这样的根的子节点,它可以帮助我找到所有的汽车,但理想情况下它也没有平移、旋转或缩放,因此我可以用最少的工作将汽车重新设置为场景。
  478. </p>
  479. <p>
  480. 在任何情况下,最快速的(虽然可能不是最好的)修复,就是只调整用于显示曲线的对象。</p>
  481. <p>这是我完成后的</p>
  482. <p>首先,我调整了曲线的位置,然后发现了可以正常显示的数值,接着我把它隐藏了。</p>
  483. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  484. const points = curve.getPoints(250);
  485. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  486. const material = new THREE.LineBasicMaterial({color: 0xff0000});
  487. curveObject = new THREE.Line(geometry, material);
  488. + curveObject.scale.set(100, 100, 100);
  489. + curveObject.position.y = -621;
  490. + curveObject.visible = false;
  491. material.depthTest = false;
  492. curveObject.renderOrder = 1;
  493. scene.add(curveObject);
  494. }
  495. </pre>
  496. <p>然后,我写了代码来沿着曲线移动汽车。
  497. 给每辆车选取曲线上的从0到1的位置,用 <code class="notranslate" translate="no">curveObject</code>对象变换计算出一个世界空间的点
  498. 接下来,我们选取曲线远一点的点。
  499. 使用<code class="notranslate" translate="no">lookAt</code> 设置汽车的朝向 并将汽车放置在两点重点。</p>
  500. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">
  501. // 创建两个向量用于路径计算
  502. const carPosition = new THREE.Vector3();
  503. const carTarget = new THREE.Vector3();
  504. function render(time) {
  505. ...
  506. - for (const car of cars) {
  507. - car.rotation.y = time;
  508. - }
  509. + {
  510. + const pathTime = time * .01;
  511. + const targetOffset = 0.01;
  512. + cars.forEach((car, ndx) =&gt; {
  513. + // 一个介于 0 和 1 之间的数字,用于均匀间隔汽车
  514. + const u = pathTime + ndx / cars.length;
  515. +
  516. + // 获取第一个点
  517. + curve.getPointAt(u % 1, carPosition);
  518. + carPosition.applyMatrix4(curveObject.matrixWorld);
  519. +
  520. + // 曲线再远点获取第二个点
  521. + curve.getPointAt((u + targetOffset) % 1, carTarget);
  522. + carTarget.applyMatrix4(curveObject.matrixWorld);
  523. +
  524. + // 把汽车放置在第一个点 (暂时的)
  525. + car.position.copy(carPosition);
  526. + // 汽车的第二个点
  527. + car.lookAt(carTarget);
  528. +
  529. + // 放置小车在两个点中间
  530. + car.position.lerpVectors(carPosition, carTarget, 0.5);
  531. + });
  532. + }
  533. </pre>
  534. <p>
  535. 当我运行它时,我发现每种汽车车,它们的高度都不是固定的,所以我要给每种车调整一下。</p>
  536. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const loadedCars = root.getObjectByName('Cars');
  537. const fixes = [
  538. - { prefix: 'Car_08', rot: [Math.PI * .5, 0, Math.PI * .5], },
  539. - { prefix: 'CAR_03', rot: [0, Math.PI, 0], },
  540. - { prefix: 'Car_04', rot: [0, Math.PI, 0], },
  541. + { prefix: 'Car_08', y: 0, rot: [Math.PI * .5, 0, Math.PI * .5], },
  542. + { prefix: 'CAR_03', y: 33, rot: [0, Math.PI, 0], },
  543. + { prefix: 'Car_04', y: 40, rot: [0, Math.PI, 0], },
  544. ];
  545. root.updateMatrixWorld();
  546. for (const car of loadedCars.children.slice()) {
  547. const fix = fixes.find(fix =&gt; car.name.startsWith(fix.prefix));
  548. const obj = new THREE.Object3D();
  549. car.getWorldPosition(obj.position);
  550. - car.position.set(0, 0, 0);
  551. + car.position.set(0, fix.y, 0);
  552. car.rotation.set(...fix.rot);
  553. obj.add(car);
  554. scene.add(obj);
  555. cars.push(obj);
  556. }
  557. </pre>
  558. <p>结果是</p>
  559. <p></p>
  560. <div translate="no" class="threejs_example_container notranslate">
  561. <div><iframe class="threejs_example notranslate" translate="no" style=" "
  562. src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-animated-cars.html"></iframe>
  563. </div>
  564. <a class="threejs_center" href="/manual/examples/load-gltf-animated-cars.html" target="_blank">click here to
  565. open in a separate window</a>
  566. </div>
  567. <p></p>
  568. <p>几分钟运行的还不错</p>
  569. <p>最后我想做的是开启阴影</p>
  570. <p>我获取了所有
  571. <a href="/docs/#api/en/lights/DirectionalLight"><code class="notranslate"
  572. translate="no">DirectionalLight</code></a>的GUI代码,
  573. <a href="shadows.html">the article on shadows</a>中的阴影实例 。并粘贴到最新代码
  574. </p>
  575. <p>加载完之后,我们需要开启所有物体的阴影</p>
  576. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  577. const gltfLoader = new GLTFLoader();
  578. gltfLoader.load('resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) =&gt; {
  579. const root = gltf.scene;
  580. scene.add(root);
  581. + root.traverse((obj) =&gt; {
  582. + if (obj.castShadow !== undefined) {
  583. + obj.castShadow = true;
  584. + obj.receiveShadow = true;
  585. + }
  586. + });
  587. </pre>
  588. <p>我花了将近4小时,尝试搞清楚为啥shadow helpers不工作。因为我忘记了用以下代码开启阴影</p>
  589. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">renderer.shadowMap.enabled = true;
  590. </pre>
  591. <p>😭</p>
  592. <p>I then adjusted the values until our <code class="notranslate" translate="no">DirectionLight</code>的阴影
  593. 相机的视锥能覆盖所有场景。 我最后完成的设置</p>
  594. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">{
  595. const color = 0xFFFFFF;
  596. const intensity = 1;
  597. const light = new THREE.DirectionalLight(color, intensity);
  598. + light.castShadow = true;
  599. * light.position.set(-250, 800, -850);
  600. * light.target.position.set(-550, 40, -450);
  601. + light.shadow.bias = -0.004;
  602. + light.shadow.mapSize.width = 2048;
  603. + light.shadow.mapSize.height = 2048;
  604. scene.add(light);
  605. scene.add(light.target);
  606. + const cam = light.shadow.camera;
  607. + cam.near = 1;
  608. + cam.far = 2000;
  609. + cam.left = -1500;
  610. + cam.right = 1500;
  611. + cam.top = 1500;
  612. + cam.bottom = -1500;
  613. ...
  614. </pre>
  615. <p>我设置背景为蓝色</p>
  616. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  617. -scene.background = new THREE.Color('black');
  618. +scene.background = new THREE.Color('#DEFEFF');
  619. </pre>
  620. <p>阴影</p>
  621. <p></p>
  622. <div translate="no" class="threejs_example_container notranslate">
  623. <div><iframe class="threejs_example notranslate" translate="no" style=" "
  624. src="/manual/examples/resources/editor.html?url=/manual/examples/load-gltf-shadows.html"></iframe></div>
  625. <a class="threejs_center" href="/manual/examples/load-gltf-shadows.html" target="_blank">click here to open in
  626. a separate window</a>
  627. </div>
  628. <p></p>
  629. <p>我希望详细讲完这个工程是有用的,并且能作为 在使用场景图(scenegraph)加载文件时 解决一些问题(issues)很好的案例。
  630. </p>
  631. <p>
  632. 有一件趣事,当对比.blend文件时与.gltf文件时,.blend 文件有多个灯光(lights),但加载到场景中后它们不是灯光(lights)
  633. 一个.GLTF文件只是JSON文件,因此你能查看它内部。
  634. 它由几个数组构成(scenes,nodes, meshes,accessors,materials...),数组中每一项都通过索引来引用其他项。
  635. 虽然工作中有扩展,但它们指出了几乎所有 3d 格式的问题。
  636. <strong>它们无法涵盖任何情况</strong>.
  637. </p>
  638. <p>
  639. 总是需要更多的数据。
  640. 例如,我们手动导出的车辆绕着跑的路径。
  641. 理想的情况是,这些信息可以成为GLTF文件。但是这么做。我们需要自己写导出器,以及一些如何标记节点以了解我们希望它们如何导出或使用命名方案或类似的东西来从我们使用的任何工具获取数据 用于将数据创建到我们的应用程序中。
  642. </p>
  643. <p>所有这些练习都留给了读者了。</p>
  644. </div>
  645. </div>
  646. </div>
  647. <script src="../resources/prettify.js"></script>
  648. <script src="../resources/lesson.js"></script>
  649. </body>
  650. </html>