load-gltf.html 32 KB

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