useThree.ts 21 KB

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