useThree.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. import * as THREE from 'three';
  2. // 导入轨道控制器
  3. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
  4. import { CSS3DRenderer } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
  5. import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
  6. import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
  7. // import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';
  8. import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
  9. import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
  10. import { FXAAShader } from 'three/examples/jsm/shaders/FXAAShader.js';
  11. import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js';
  12. import Stats from 'three/examples/jsm/libs/stats.module.js';
  13. import { useModelStore } from '/@/store/modules/threejs';
  14. import TWEEN from 'three/examples/jsm/libs/tween.module.js';
  15. import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
  16. import { useGlobSetting } from '/@/hooks/setting';
  17. import { getList } from '@/views/vent/sys/resources/file.api';
  18. import { saveModel } from '/@/utils/threejs/util';
  19. const globSetting = useGlobSetting();
  20. const baseApiUrl = globSetting.domainUrl;
  21. export function useThree(containerID: string, css3dContainerID: string, css2dContainerID: string) {}
  22. class UseThree {
  23. constructor(canvasSelector, css3Canvas?, css2Canvas?) {
  24. this.canvasContainer = document.querySelector(canvasSelector);
  25. //初始化
  26. this.init(css3Canvas, css2Canvas);
  27. // this.animate();
  28. window.addEventListener('resize', this.resizeRenderer.bind(this));
  29. // 添加滚动事件,鼠标滚动模型执行动画
  30. // window.addEventListener('wheel', this.wheelRenderer.bind(this));
  31. // this.canvasContainer?.appendChild(gui.domElement);
  32. }
  33. init(css3Canvas?, css2Canvas?) {
  34. // 初始化场景
  35. this.initScene();
  36. // 初始化环境光
  37. // this.initLight();
  38. // 初始化相机
  39. this.initCamera();
  40. //初始化渲染器
  41. this.initRenderer();
  42. // 初始化控制器
  43. this.initControles();
  44. if (css3Canvas) {
  45. this.initCSS3Renderer(css3Canvas);
  46. }
  47. if (css2Canvas) {
  48. this.initCSS2Renderer(css2Canvas);
  49. }
  50. // this.setTestPlane();
  51. this.rayCaster = new THREE.Raycaster();
  52. // this.createStats();
  53. // this.removeSawtooth();
  54. }
  55. createStats() {
  56. this.stats = Stats();
  57. this.stats?.setMode(0);
  58. this.stats.domElement.style = 'position: absolute; top: 300px';
  59. this.canvasContainer?.appendChild(this.stats.domElement);
  60. }
  61. initScene() {
  62. this.scene = new THREE.Scene();
  63. // const axesHelper = new THREE.AxesHelper(100);
  64. // this.scene?.add(axesHelper);
  65. // const size = 1000;
  66. // const divisions = 10;
  67. // const gridHelper = new THREE.GridHelper(size, divisions);
  68. // this.scene?.add(gridHelper);
  69. }
  70. initLight() {
  71. // const light = new THREE.AmbientLight(0xffffff, 1);
  72. // light.position.set(0, 1000, 1000);
  73. // (this.scene as THREE.Scene).add(light);
  74. }
  75. initCamera() {
  76. // this.camera = new THREE.PerspectiveCamera(50, this.canvasContainer.clientWidth / this.canvasContainer.clientHeight, 0.0000001, 1000);
  77. if (!window['$camera']) {
  78. throw new Error('threejs摄像头初始化异常!');
  79. } else {
  80. this.camera = window['$camera'] as THREE.PerspectiveCamera;
  81. this.camera.layers.enableAll();
  82. if (this.canvasContainer) this.camera.aspect = this.canvasContainer.clientWidth / this.canvasContainer.clientHeight;
  83. this.camera.near = 0.0000001;
  84. this.camera.far = 1000;
  85. }
  86. //
  87. // const helper = new THREE.CameraHelper(this.camera);
  88. // this.scene?.add(helper);
  89. // gui.add(this.camera.position, 'x', 0.00001, 10000);
  90. // gui.add(this.camera.position, 'y', 0.00001, 10000);
  91. // gui.add(this.camera.position, 'z', 0.00001, 10000);
  92. // gui.add(this.camera, 'near', 0.01, 1).step(0.01);
  93. // gui.add(this.camera, 'far', 10, 100000);
  94. // gui.add(this.camera, 'fov', 0, 180);
  95. }
  96. initRenderer() {
  97. if (!window['$renderer']) {
  98. throw new Error('threejs渲染器初始化异常!');
  99. } else {
  100. this.renderer = window['$renderer'];
  101. if (this.canvasContainer) {
  102. this.renderer.toneMappingExposure = 1.0;
  103. this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
  104. // const gl = this.renderer?.getContext('webgl');
  105. // gl && gl.getExtension('WEBGL_lose_context')?.restoreContext();
  106. // this.renderer?.forceContextRestore()
  107. this.renderer?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  108. this.canvasContainer.appendChild(this.renderer.domElement);
  109. }
  110. }
  111. }
  112. initCSS3Renderer(cssCanvas) {
  113. this.CSSCanvasContainer = document.querySelector(cssCanvas);
  114. if (this.CSSCanvasContainer) {
  115. this.css3dRender = new CSS3DRenderer() as CSS3DRenderer;
  116. this.css3dRender.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  117. this.CSSCanvasContainer?.appendChild(this.css3dRender.domElement);
  118. this.css3dRender.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  119. // this.css3dRender.domElement.style.pointerEvents = 'none';
  120. // this.orbitControls = new OrbitControls(this.camera as THREE.Camera, this.css3dRender?.domElement) as OrbitControls;
  121. // this.orbitControls.update();
  122. }
  123. }
  124. initCSS2Renderer(cssCanvas) {
  125. this.CSSCanvasContainer = document.querySelector(cssCanvas);
  126. if (this.CSSCanvasContainer) {
  127. this.css2dRender = new CSS2DRenderer();
  128. this.css2dRender.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  129. this.CSSCanvasContainer?.appendChild(this.css2dRender.domElement);
  130. this.css2dRender.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  131. // this.orbitControls = new OrbitControls(this.camera as THREE.Camera, this.css2dRender?.domElement) as OrbitControls;
  132. // this.orbitControls.update();
  133. // this.css2dRender.domElement.style.pointerEvents = 'none';
  134. }
  135. }
  136. initControles() {
  137. if (!window['$orbitControls']) {
  138. throw new Error('threejs控制器初始化异常!');
  139. } else {
  140. this.orbitControls = window['$orbitControls'];
  141. this.orbitControls.panSpeed = 1;
  142. this.orbitControls.rotateSpeed = 1;
  143. this.orbitControls.maxPolarAngle = Math.PI;
  144. this.orbitControls.minPolarAngle = 0;
  145. }
  146. // this.orbitControls = new OrbitControls(this.camera as THREE.Camera, this.renderer?.domElement) as OrbitControls;
  147. // this.orbitControls.update();
  148. // this.orbitControls.minDistance = 1;
  149. // this.orbitControls.maxDistance = 100;
  150. // this.orbitControls.maxDistance = true;
  151. }
  152. setGLTFModel(modalNames, group = null, isBlender = false) {
  153. window['startTime'] = new Date().getTime();
  154. const modelStore = useModelStore();
  155. return new Promise(async (resolve, reject) => {
  156. try {
  157. const gltfLoader = new GLTFLoader();
  158. const dracoLoader = new DRACOLoader();
  159. dracoLoader.setDecoderPath('/model/draco/gltf/');
  160. dracoLoader.setDecoderConfig({ type: 'js' }); //使用兼容性强的draco_decoder.js解码器
  161. dracoLoader.preload();
  162. gltfLoader.setDRACOLoader(dracoLoader);
  163. const db = window['CustomDB'];
  164. const resolvePromise: Promise<any>[] = [];
  165. const modalNameArr = Object.prototype.toString.call(modalNames) === '[object Array]' ? modalNames : [modalNames];
  166. const len = modalNameArr.length;
  167. debugger;
  168. for (let i = 0; i < len; i++) {
  169. resolvePromise[i] = new Promise(async (childResolve, reject) => {
  170. try {
  171. // 解析模型
  172. const modalNameStr = modalNameArr[i];
  173. const data = modelStore.modelArr.get(modalNameStr) || null;
  174. let modalValue;
  175. if (!data) {
  176. const modalArr = await db.modal.where('modalName').equals(modalNameStr).toArray();
  177. if (modalArr.length > 0) {
  178. modalValue = modalArr[0].modalVal;
  179. }
  180. } else {
  181. modalValue = data.modalVal;
  182. }
  183. if (modalValue) {
  184. gltfLoader.parse(
  185. modalValue,
  186. '/model/glft/',
  187. (gltf) => {
  188. let object: THREE.Object3D = gltf.scene;
  189. // setModalCenter(object);
  190. object.traverse((obj) => {
  191. if (obj instanceof THREE.Mesh) {
  192. obj.material.emissiveIntensity = 1;
  193. obj.material.emissiveMap = obj.material.map;
  194. obj.material.blending = THREE.CustomBlending;
  195. if (obj.material.opacity < 1) {
  196. obj.material.transparent = true;
  197. }
  198. if (obj.material.map) {
  199. obj.material.map.colorSpace = THREE.SRGBColorSpace;
  200. obj.material.map.flipY = false;
  201. obj.material.map.anisotropy = 1;
  202. }
  203. if (obj.material.emissiveMap) {
  204. obj.material.emissiveMap.colorSpace = THREE.SRGBColorSpace;
  205. obj.material.emissiveMap.flipY = false;
  206. }
  207. if (obj.material.map || obj.material.emissiveMap) {
  208. obj.material.needsUpdate = true;
  209. }
  210. // if (envMap) {
  211. // obj.material.envMap = envMap;
  212. // obj.material.envMapIntensity = 1;
  213. // }
  214. // obj.renderOrder = 1;
  215. }
  216. });
  217. debugger;
  218. if (isBlender) {
  219. object = object.children[0];
  220. }
  221. object.animations = gltf.animations;
  222. object.name = modalNameStr;
  223. group?.add(object);
  224. childResolve(object);
  225. },
  226. (err) => {
  227. console.log(err);
  228. }
  229. );
  230. } else {
  231. // 开启线程下载
  232. console.log('需要开启线程下载模型资源。。。。。');
  233. const result = (await getList({ fileName: modalNameStr })) || [];
  234. const file = result['records'][0];
  235. if (file && file.path) {
  236. gltfLoader.load(`${baseApiUrl}/sys/common/static/${file.path}`, async (glft) => {
  237. if (glft) {
  238. const object = glft.scene;
  239. object.name = modalNameStr;
  240. if (glft.animations.length > 0) {
  241. object.animations = glft.animations;
  242. }
  243. group?.add(object);
  244. childResolve(object);
  245. const modalArr = await db.modal.where('modalName').equals(modalNameStr).toArray();
  246. if (modalArr.length < 1) {
  247. saveModel(modalNameStr, file.path, file.version);
  248. }
  249. }
  250. });
  251. } else {
  252. childResolve(null);
  253. }
  254. }
  255. } catch (error) {
  256. console.log(error);
  257. reject();
  258. }
  259. });
  260. }
  261. Promise.all(resolvePromise).then((objects) => {
  262. dracoLoader.dispose();
  263. resolve(objects);
  264. });
  265. } catch (error) {
  266. reject('加载模型出错');
  267. }
  268. });
  269. }
  270. // setFBXModel(modalNames, group = null) {
  271. // window['startTime'] = new Date().getTime();
  272. // const modelStore = useModelStore();
  273. // return new Promise(async (resolve, reject) => {
  274. // try {
  275. // const fbxLoader = new FBXLoader();
  276. // fbxLoader.setPath('/model/fbx/');
  277. // const db = window['CustomDB'];
  278. // const resolvePromise: Promise<any>[] = [];
  279. // let modalNameArr = Object.prototype.toString.call(modalNames) === '[object Array]' ? modalNames : [modalNames];
  280. // let len = modalNameArr.length;
  281. // for (let i = 0; i < len; i++) {
  282. // resolvePromise[i] = new Promise(async (childResolve, reject) => {
  283. // try {
  284. // // 解析模型
  285. // let modalValue;
  286. // const modalNameStr = modalNameArr[i];
  287. // let data = modelStore.modelArr.get(modalNameStr) || null;
  288. // if (!data) {
  289. // const modalArr = await db.modal.where('modalName').equals(modalNameStr).toArray();
  290. // if (modalArr.length > 0) modalValue = modalArr[0].modalVal;
  291. // } else {
  292. // modalValue = data.modalVal;
  293. // }
  294. // if (modalValue) {
  295. // const object = fbxLoader.parse(modalValue, '/model/fbx/');
  296. // // const object = fbx.scene;
  297. // // setModalCenter(object);
  298. // if (object) {
  299. // object.traverse((obj) => {
  300. // if (obj instanceof THREE.Mesh) {
  301. // obj.material.emissiveIntensity = 1;
  302. // obj.material.emissiveMap = obj.material.map;
  303. // obj.material.blending = THREE.CustomBlending;
  304. // if (obj.material.opacity < 1) {
  305. // obj.material.transparent = true;
  306. // }
  307. // if (obj.material.map) {
  308. // obj.material.map.encoding = THREE.sRGBEncoding;
  309. // obj.material.map.flipY = false;
  310. // obj.material.map.anisotropy = 1;
  311. // }
  312. // if (obj.material.emissiveMap) {
  313. // obj.material.emissiveMap.encoding = THREE.sRGBEncoding;
  314. // obj.material.emissiveMap.flipY = false;
  315. // }
  316. // if (obj.material.map || obj.material.emissiveMap) {
  317. // obj.material.needsUpdate = true;
  318. // }
  319. // // if (envMap) {
  320. // // obj.material.envMap = envMap;
  321. // // obj.material.envMapIntensity = 1;
  322. // // }
  323. // // obj.renderOrder = 1;
  324. // }
  325. // });
  326. // object.animations = object.animations;
  327. // object.name = modalNameStr;
  328. // group?.add(object);
  329. // childResolve(object);
  330. // }
  331. // }
  332. // } catch (error) {
  333. // console.log(error);
  334. // reject();
  335. // }
  336. // });
  337. // }
  338. // Promise.all(resolvePromise).then((objects) => {
  339. // resolve(objects);
  340. // });
  341. // } catch (error) {
  342. // reject('加载模型出错');
  343. // }
  344. // });
  345. // }
  346. setTestPlane() {
  347. const plane = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), new THREE.MeshPhongMaterial({ color: 0x999999, specular: 0x101010 }));
  348. plane.rotation.x = -Math.PI / 2;
  349. plane.position.y = 0.03;
  350. plane.receiveShadow = true;
  351. this.scene?.add(plane);
  352. }
  353. removeSawtooth() {
  354. this.composer = new EffectComposer(this.renderer as THREE.WebGLRenderer);
  355. const FXAAShaderPass = new ShaderPass(FXAAShader);
  356. FXAAShaderPass.uniforms['resolution'].value.set(1 / this.canvasContainer.clientWidth, 1 / this.canvasContainer.clientHeight);
  357. FXAAShaderPass.renderToScreen = true;
  358. this.composer.addPass(FXAAShaderPass);
  359. }
  360. /* 场景环境背景 */
  361. setEnvMap(hdr) {
  362. if (!this.scene) return;
  363. // (this.scene as THREE.Scene).environment
  364. new RGBELoader().setPath('/model/hdr/').load(hdr + '.hdr', (texture) => {
  365. texture.colorSpace = THREE.SRGBColorSpace;
  366. texture.mapping = THREE.EquirectangularReflectionMapping;
  367. if (this.scene) (this.scene as THREE.Scene).environment = texture;
  368. texture.dispose();
  369. });
  370. }
  371. render() {
  372. this.startAnimation();
  373. this.orbitControls?.update();
  374. this.camera?.updateMatrixWorld();
  375. // this.composer?.render();
  376. this.css3dRender?.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  377. this.css2dRender?.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  378. this.renderer?.render(this.scene as THREE.Object3D, this.camera as THREE.Camera);
  379. }
  380. timeRender() {
  381. //设置为可渲染状态
  382. this.renderEnabled = true;
  383. //清除上次的延迟器
  384. if (this.timeOut) {
  385. clearTimeout(this.timeOut);
  386. }
  387. this.timeOut = setTimeout(() => {
  388. this.renderEnabled = false;
  389. }, 3000);
  390. }
  391. /* 漫游 */
  392. startMY() {}
  393. /* 初始动画 */
  394. startAnimation() {}
  395. renderAnimationScene() {}
  396. animate() {
  397. if (this.isRender) {
  398. this.animationId = requestAnimationFrame(this.animate.bind(this));
  399. const T = this.clock?.getDelta() || 0;
  400. this.timeS = this.timeS + T;
  401. if (this.timeS > this.renderT) {
  402. this.renderAnimationScene();
  403. if (this.renderEnabled) {
  404. this.render();
  405. }
  406. this.stats?.update();
  407. this.timeS = 0;
  408. }
  409. // this.stats?.update();
  410. // // TWEEN.update();
  411. // // this.renderAnimationScene();
  412. // if (this.renderEnabled) {
  413. // this.render();
  414. // }
  415. }
  416. }
  417. resizeRenderer() {
  418. // 更新相机比例
  419. if (this.camera) {
  420. (this.camera as THREE.PerspectiveCamera).aspect = this.canvasContainer.clientWidth / this.canvasContainer.clientHeight;
  421. // 刷新相机矩阵
  422. this.camera?.updateProjectionMatrix();
  423. }
  424. // 设置场景尺寸
  425. this.renderer?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  426. this.css3dRender?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  427. this.css2dRender?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  428. }
  429. wheelRenderer(e: WheelEvent) {
  430. const timeScale = e.deltaY > 0 ? 1 : -1;
  431. this.animationAction?.setEffectiveTimeScale(timeScale);
  432. (this.animationAction as THREE.AnimationAction).paused = false;
  433. this.animationAction?.play();
  434. if (this.timeoutId) {
  435. clearTimeout(this.timeoutId);
  436. }
  437. this.timeoutId = setTimeout(() => {
  438. this.animationAction?.halt(0.5);
  439. }, 500);
  440. }
  441. clearMesh(item) {
  442. item.geometry?.dispose();
  443. if (item.material) {
  444. const material = item.material;
  445. for (const key of Object.keys(material)) {
  446. const value = material[key];
  447. // if (value && typeof value === 'object' && 'minFilter' in value) {
  448. // // this.textureMap.set(value.uuid, value);
  449. // value.dispose();
  450. // }
  451. if (value && typeof value === 'object' && value['dispose'] && typeof value['dispose'] === 'function') {
  452. value.dispose();
  453. }
  454. }
  455. material.dispose();
  456. }
  457. if (item.texture) {
  458. item.texture.dispose();
  459. }
  460. }
  461. clearGroup(group) {
  462. const removeObj = (obj) => {
  463. if (obj && obj?.children && obj?.children.length > 0) {
  464. for (let i = obj?.children.length - 1; i >= 0; i--) {
  465. const item = obj?.children[i];
  466. if (item && item.children && item.children.length > 0) {
  467. removeObj(item);
  468. item?.clear();
  469. } else {
  470. if (item) {
  471. if (item.parent) item.parent.remove(item);
  472. this.clearMesh(item);
  473. item.clear();
  474. }
  475. }
  476. }
  477. }
  478. };
  479. removeObj(group);
  480. }
  481. clearScene() {
  482. this.clearGroup(this.scene);
  483. // console.log('场景纹理数量----------->', this.textureMap.size);
  484. this.textureMap.forEach((texture) => {
  485. texture?.dispose();
  486. });
  487. this.textureMap.clear();
  488. }
  489. destroy() {
  490. TWEEN.getAll().forEach((item) => {
  491. item.stop();
  492. });
  493. TWEEN.removeAll();
  494. this.isRender = false;
  495. cancelAnimationFrame(this.animationId);
  496. this.clearScene();
  497. window.removeEventListener('resize', this.resizeRenderer);
  498. // this.orbitControls?.dispose();
  499. // this.scene?.environment?.dispose();
  500. this.scene?.clear();
  501. this.renderer?.dispose();
  502. this.renderer?.getRenderTarget()?.dispose();
  503. if (this.renderer && this.canvasContainer) this.canvasContainer.innerHTML = '';
  504. if (this.CSSCanvasContainer && this.css3dRender) this.CSSCanvasContainer.innerHTML = '';
  505. // if (this.renderer) this.renderer.domElement = null;
  506. this.renderer?.clear();
  507. if (this.css3dRender) this.css3dRender.domElement = null;
  508. if (this.css2dRender) this.css2dRender.domElement = null;
  509. if (this.canvasContainer) this.canvasContainer.innerHTML = '';
  510. if (this.CSSCanvasContainer) this.CSSCanvasContainer.innerHTML = '';
  511. this.camera = null;
  512. this.orbitControls = null;
  513. this.renderer = null;
  514. this.stats = null;
  515. this.scene = null;
  516. this.css3dRender = null;
  517. this.css2dRender = null;
  518. THREE.Cache.clear();
  519. console.log('场景销毁后信息----------->', window['$renderer']?.info, this.scene);
  520. }
  521. }
  522. export default UseThree;