main.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. scene.add(cube);
  110. //camera.position.z = 25;
  111. camera.position.z = 1.0;
  112. const controls = new OrbitControls(camera, renderer.domElement);
  113. controls.enablePan = false; // 禁用右键平移功能
  114. controls.enableZoom = false; // 必须禁用轨道控制器的默认缩放[1](@ref)
  115. controls.enableDamping = true;
  116. controls.dampingFactor = 0.25;
  117. controls.screenSpacePanning = false;
  118. controls.maxPolarAngle = Math.PI / 2;
  119. // 兼容鼠标滚轮与触摸屏双指缩放
  120. const handleZoom = (delta) => {
  121. // console.log('--------',delta);
  122. cube.scale.multiplyScalar(delta);
  123. cube.scale.clampScalar(0.5, 2); // 限制缩放范围0.5-3倍[1,6](@ref)
  124. };
  125. // 鼠标滚轮事件
  126. window.addEventListener(
  127. "wheel",
  128. (e) => {
  129. e.preventDefault();
  130. const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
  131. handleZoom(zoomFactor);
  132. },
  133. { passive: false }
  134. );
  135. // 触摸屏双指缩放
  136. let initialDistance = 0;
  137. window.addEventListener("touchstart", (e) => {
  138. if (e.touches.length === 2) {
  139. initialDistance = Math.hypot(
  140. e.touches[0].pageX - e.touches[1].pageX,
  141. e.touches[0].pageY - e.touches[1].pageY
  142. );
  143. }
  144. });
  145. window.addEventListener("touchmove", (e) => {
  146. if (e.touches.length === 2) {
  147. const currentDistance = Math.hypot(
  148. e.touches[0].pageX - e.touches[1].pageX,
  149. e.touches[0].pageY - e.touches[1].pageY
  150. );
  151. const zoomFactor = currentDistance > initialDistance ? 1.03 : 0.97;
  152. handleZoom(zoomFactor);
  153. initialDistance = currentDistance;
  154. }
  155. });
  156. function animate() {
  157. //cube.rotation.x += 0.01;
  158. // cube.rotation.y += 0.02;
  159. controls.update();
  160. renderer.render(scene, camera);
  161. }
  162. window.addEventListener("resize", () => {
  163. camera.aspect = window.innerWidth / window.innerHeight;
  164. camera.updateProjectionMatrix();
  165. renderer.setSize(window.innerWidth, window.innerHeight);
  166. });
  167. });
  168. });