main.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import * as THREE from "../js/three.module.js";
  2. import initTinyUSDZ from "../js/tinyusdz.js";
  3. import { OrbitControls } from "../js/OrbitControls.js";
  4. const urlAll = window.location.href.split("?m=")[1];
  5. // console.log(123456,urlAll);
  6. const USDZ_FILEPATH = `https://4dkankan.oss-cn-shenzhen.aliyuncs.com/sxz/${urlAll}.usdz`;
  7. document.addEventListener("DOMContentLoaded", async () => {
  8. const loadingBar = document.getElementById("loading"); // 获取加载条元素
  9. loadingBar.style.display = "block"; // 显示加载条
  10. const usd_res = await fetch(USDZ_FILEPATH);
  11. const totalBytes = parseInt(usd_res.headers.get("Content-Length"), 10); // 获取总字节数
  12. const reader = usd_res.body.getReader(); // 获取读取器
  13. const chunks = []; // 存储数据块
  14. let receivedLength = 0; // 已接收字节数
  15. let timeOut = -1;
  16. // 更新加载条的函数
  17. const updateLoadingBar = (loaded) => {
  18. let percentage = (loaded / totalBytes) * 100;
  19. if (percentage >= 100) {
  20. percentage = 100;
  21. // 隐藏加载条
  22. clearTimeout(timeOut);
  23. timeOut = setTimeout(() => {
  24. const loadingBoxDom = document.querySelector(".loadingBox");
  25. loadingBoxDom.style.opacity = 0;
  26. loadingBoxDom.style.pointerEvents = "none";
  27. }, 300);
  28. }
  29. loadingBar.style.width = `${percentage}%`; // 更新加载条宽度
  30. };
  31. // 读取数据流
  32. while (true) {
  33. const { done, value } = await reader.read(); // 读取数据
  34. if (done) break; // 如果读取完成,退出循环
  35. chunks.push(value); // 存储数据块
  36. receivedLength += value.length; // 更新已接收字节数
  37. updateLoadingBar(receivedLength); // 更新加载条
  38. }
  39. const usd_data = new Uint8Array(receivedLength); // 创建最终数据数组
  40. let position = 0;
  41. for (const chunk of chunks) {
  42. usd_data.set(chunk, position); // 将数据块写入最终数组
  43. position += chunk.length; // 更新位置
  44. }
  45. // const usd_binary = new Uint8Array(usd_data);
  46. // 加载 TinyUSDZ
  47. initTinyUSDZ().then(function (TinyUSDZLoader) {
  48. const usd = new TinyUSDZLoader.TinyUSDZLoader(usd_data);
  49. // console.log(usd.numMeshes());
  50. const scene = new THREE.Scene();
  51. const camera = new THREE.PerspectiveCamera(
  52. 75,
  53. window.innerWidth / window.innerHeight,
  54. 0.1,
  55. 1000
  56. );
  57. const renderer = new THREE.WebGLRenderer({
  58. alpha: true, // 关键配置,设置背景透明
  59. antialias: true, // 可选抗锯齿
  60. });
  61. renderer.setClearColor(0x000000, 0); // 第二个参数为透明度(0表示完全透明)
  62. renderer.setSize(window.innerWidth, window.innerHeight);
  63. renderer.setAnimationLoop(animate);
  64. document.body.appendChild(renderer.domElement);
  65. // First mesh only
  66. const mesh = usd.getMesh(0);
  67. //console.log("usd", usd)
  68. //console.log("mesh", mesh);
  69. //const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  70. const geometry = new THREE.BufferGeometry();
  71. geometry.setAttribute(
  72. "position",
  73. new THREE.BufferAttribute(mesh.points, 3)
  74. );
  75. // TODO: set normal from mesh
  76. if (mesh.hasOwnProperty("texcoords")) {
  77. // console.log(mesh.texcoords);
  78. geometry.setAttribute("uv", new THREE.BufferAttribute(mesh.texcoords, 2));
  79. }
  80. const usdMaterial = usd.getMaterial(mesh.materialId);
  81. //console.log("usdMat", usdMaterial);
  82. //if (usdMaterial.aaa) {
  83. // console.log("aaa");
  84. //}
  85. var material;
  86. if (usdMaterial.hasOwnProperty("diffuseColorTextureId")) {
  87. const diffTex = usd.getTexture(usdMaterial.diffuseColorTextureId);
  88. const img = usd.getImage(diffTex.textureImageId);
  89. // console.log(img);
  90. // assume RGBA for now.
  91. let image8Array = new Uint8ClampedArray(img.data);
  92. let imgData = new ImageData(image8Array, img.width, img.height);
  93. const texture = new THREE.DataTexture(imgData, img.width, img.height);
  94. texture.flipY = true;
  95. texture.needsUpdate = true;
  96. material = new THREE.MeshBasicMaterial({
  97. map: texture,
  98. });
  99. } else {
  100. material = new THREE.MeshNormalMaterial();
  101. }
  102. // Assume triangulated indices.
  103. geometry.setIndex(
  104. new THREE.Uint32BufferAttribute(mesh.faceVertexIndices, 1)
  105. );
  106. geometry.computeVertexNormals();
  107. //const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  108. const cube = new THREE.Mesh(geometry, material);
  109. // 缩放模型
  110. cube.scale.set(2, 2, 2);
  111. cube.updateMatrixWorld(true); // 强制更新世界矩阵[3](@ref)
  112. // 计算包围盒
  113. const box = new THREE.Box3().setFromObject(cube);
  114. const center = new THREE.Vector3();
  115. box.getCenter(center);
  116. // 居中模型
  117. cube.position.sub(center);
  118. // 计算尺寸并调整相机
  119. const size = box.getSize(new THREE.Vector3()).length();
  120. camera.near = size / 100;
  121. camera.far = size * 100;
  122. camera.updateProjectionMatrix();
  123. camera.position.set(size * 0.5, size * 0.5, size * 0.5);
  124. camera.lookAt(0, 0, 0);
  125. scene.add(cube);
  126. //camera.position.z = 25;
  127. // camera.position.z = 1.0;
  128. const controls = new OrbitControls(camera, renderer.domElement);
  129. controls.enablePan = false; // 禁用右键平移功能
  130. controls.enableZoom = false; // 必须禁用轨道控制器的默认缩放[1](@ref)
  131. controls.enableDamping = true;
  132. controls.dampingFactor = 0.25;
  133. controls.screenSpacePanning = false;
  134. controls.maxPolarAngle = Math.PI / 2;
  135. // 兼容鼠标滚轮与触摸屏双指缩放
  136. const handleZoom = (delta) => {
  137. // console.log('--------',delta);
  138. cube.updateMatrixWorld(true);
  139. // 计算包围盒
  140. const box = new THREE.Box3().setFromObject(cube);
  141. const center = new THREE.Vector3();
  142. box.getCenter(center);
  143. // 居中模型
  144. cube.position.sub(center);
  145. cube.scale.multiplyScalar(delta);
  146. cube.scale.clampScalar(0.5, 4); // 限制缩放范围0.5-3倍[1,6](@ref)
  147. };
  148. // 鼠标滚轮事件
  149. window.addEventListener(
  150. "wheel",
  151. (e) => {
  152. e.preventDefault();
  153. const zoomFactor = e.deltaY > 0 ? 0.95 : 1.05;
  154. handleZoom(zoomFactor);
  155. },
  156. { passive: false }
  157. );
  158. // 触摸屏双指缩放
  159. let initialDistance = 0;
  160. window.addEventListener("touchstart", (e) => {
  161. if (e.touches.length === 2) {
  162. initialDistance = Math.hypot(
  163. e.touches[0].pageX - e.touches[1].pageX,
  164. e.touches[0].pageY - e.touches[1].pageY
  165. );
  166. }
  167. });
  168. window.addEventListener("touchmove", (e) => {
  169. if (e.touches.length === 2) {
  170. const currentDistance = Math.hypot(
  171. e.touches[0].pageX - e.touches[1].pageX,
  172. e.touches[0].pageY - e.touches[1].pageY
  173. );
  174. const zoomFactor = currentDistance > initialDistance ? 1.01 : 0.99;
  175. handleZoom(zoomFactor);
  176. initialDistance = currentDistance;
  177. }
  178. });
  179. function animate() {
  180. //cube.rotation.x += 0.01;
  181. // cube.rotation.y += 0.02;
  182. controls.update();
  183. renderer.render(scene, camera);
  184. }
  185. window.addEventListener("resize", () => {
  186. camera.aspect = window.innerWidth / window.innerHeight;
  187. camera.updateProjectionMatrix();
  188. renderer.setSize(window.innerWidth, window.innerHeight);
  189. });
  190. });
  191. });