main.js 7.9 KB

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