1
0

useThree.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import * as THREE from 'three';
  2. import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
  3. // 导入轨道控制器
  4. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
  5. import { CSS3DRenderer } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
  6. import { CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
  7. // import gsap from 'gsap';
  8. import ResourceTracker from '/@/utils/threejs/ResourceTracker.js';
  9. import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
  10. import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
  11. import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
  12. import { FXAAShader } from 'three/examples/jsm/shaders/FXAAShader.js';
  13. import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js';
  14. import { setModalCenter } from '/@/utils/threejs/util';
  15. import Stats from 'three/examples/jsm/libs/stats.module.js';
  16. import { useModelStore } from '/@/store/modules/threejs';
  17. import { TWEEN } from 'three/examples/jsm/libs/tween.module.min.js';
  18. // import * as dat from 'dat.gui';
  19. // const gui = new dat.GUI();
  20. // gui.domElement.style = 'position:absolute;top:10px;left:10px;z-index:99999999999999';
  21. class UseThree {
  22. stats: Stats | null = null; // 帧
  23. canvasContainer: HTMLCanvasElement | null; //canvas 容器
  24. CSSCanvasContainer: HTMLCanvasElement | null = null; // css canvas 容器
  25. camera: THREE.PerspectiveCamera | null = null; // 相机
  26. scene: THREE.Scene | null = null;
  27. renderer: THREE.WebGLRenderer | null = null;
  28. renderEnabled = true;
  29. css3dRender: CSS3DRenderer | null = null;
  30. css2dRender: CSS2DRenderer | null = null;
  31. orbitControls: OrbitControls | null = null;
  32. animationAction: THREE.AnimationAction | null = null;
  33. clock: THREE.Clock | null = new THREE.Clock(); // 计时器
  34. timeoutId: NodeJS.Timeout | null = null;
  35. animationId = 0;
  36. spriteText: THREE.Sprite | null = null;
  37. mouse = new THREE.Vector2();
  38. rayCaster: THREE.Raycaster | null = null;
  39. animations: THREE.AnimationClip[] = [];
  40. mixers: THREE.AnimationMixer[] = [];
  41. renderT = 1 / 60;
  42. timeS = 0;
  43. resourceTracker: ResourceTracker | null = null;
  44. track: any = null;
  45. composer; //后期
  46. timeOut: NodeJS.Timeout | null = null; //
  47. constructor(canvasSelector, css3Canvas?, css2Canvas?) {
  48. this.animationId = 0;
  49. this.canvasContainer = document.querySelector(canvasSelector);
  50. //初始化
  51. this.init(css3Canvas, css2Canvas);
  52. // this.animate();
  53. window.addEventListener('resize', this.resizeRenderer.bind(this));
  54. // 添加滚动事件,鼠标滚动模型执行动画
  55. // window.addEventListener('wheel', this.wheelRenderer.bind(this));
  56. // this.canvasContainer?.appendChild(gui.domElement);
  57. }
  58. init(css3Canvas?, css2Canvas?) {
  59. // 初始化场景
  60. this.initScene();
  61. // 初始化环境光
  62. // this.initLight();
  63. // 初始化相机
  64. this.initCamera();
  65. //初始化渲染器
  66. this.initRenderer();
  67. // 初始化控制器
  68. this.initControles();
  69. if (css3Canvas) {
  70. this.initCSS3Renderer(css3Canvas);
  71. }
  72. if (css2Canvas) {
  73. this.initCSS2Renderer(css2Canvas);
  74. }
  75. // this.setTestPlane();
  76. this.rayCaster = new THREE.Raycaster();
  77. // this.createStats();
  78. // this.removeSawtooth();
  79. }
  80. createStats() {
  81. this.stats = Stats();
  82. this.stats?.setMode(0);
  83. this.stats.domElement.style = 'position: absolute; top: 300px';
  84. this.canvasContainer?.appendChild(this.stats.domElement);
  85. }
  86. initScene() {
  87. this.scene = new THREE.Scene();
  88. // const axesHelper = new THREE.AxesHelper(100);
  89. // this.scene?.add(axesHelper);
  90. // const size = 1000;
  91. // const divisions = 10;
  92. // const gridHelper = new THREE.GridHelper(size, divisions);
  93. // this.scene?.add(gridHelper);
  94. }
  95. initLight() {
  96. const light = new THREE.AmbientLight(0xffffff, 1);
  97. light.position.set(0, 1000, 1000);
  98. (this.scene as THREE.Scene).add(light);
  99. }
  100. initCamera() {
  101. this.camera = new THREE.PerspectiveCamera(50, this.canvasContainer.clientWidth / this.canvasContainer.clientHeight, 0.0000001, 1000);
  102. this.camera.layers.enableAll();
  103. //
  104. // const helper = new THREE.CameraHelper(this.camera);
  105. // this.scene?.add(helper);
  106. // gui.add(this.camera.position, 'x', 0.00001, 10000);
  107. // gui.add(this.camera.position, 'y', 0.00001, 10000);
  108. // gui.add(this.camera.position, 'z', 0.00001, 10000);
  109. // gui.add(this.camera, 'near', 0.01, 1).step(0.01);
  110. // gui.add(this.camera, 'far', 10, 100000);
  111. // gui.add(this.camera, 'fov', 0, 180);
  112. }
  113. initRenderer() {
  114. this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, logarithmicDepthBuffer: true }) as THREE.WebGLRenderer;
  115. // 设置屏幕像素比
  116. this.renderer?.setPixelRatio(window.devicePixelRatio);
  117. // 设置渲染的尺寸
  118. this.renderer?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  119. // 色调映射
  120. this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
  121. this.renderer.outputEncoding = THREE.sRGBEncoding;
  122. this.renderer.shadowMap.enabled = true;
  123. // 曝光程度
  124. this.renderer.toneMappingExposure = 1;
  125. // this.renderer.physicallyCorrectLights = true;
  126. // this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  127. this.canvasContainer?.appendChild(this.renderer.domElement);
  128. }
  129. initCSS3Renderer(cssCanvas) {
  130. this.CSSCanvasContainer = document.querySelector(cssCanvas);
  131. if (this.CSSCanvasContainer) {
  132. this.css3dRender = new CSS3DRenderer() as CSS3DRenderer;
  133. this.css3dRender.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  134. this.CSSCanvasContainer?.appendChild(this.css3dRender.domElement);
  135. this.css3dRender.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  136. // this.css3dRender.domElement.style.pointerEvents = 'none';
  137. // this.orbitControls = new OrbitControls(this.camera as THREE.Camera, this.css3dRender?.domElement) as OrbitControls;
  138. // this.orbitControls.update();
  139. }
  140. }
  141. initCSS2Renderer(cssCanvas) {
  142. this.CSSCanvasContainer = document.querySelector(cssCanvas);
  143. if (this.CSSCanvasContainer) {
  144. this.css2dRender = new CSS2DRenderer();
  145. this.css2dRender.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  146. this.CSSCanvasContainer?.appendChild(this.css2dRender.domElement);
  147. this.css2dRender.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  148. // this.orbitControls = new OrbitControls(this.camera as THREE.Camera, this.css2dRender?.domElement) as OrbitControls;
  149. // this.orbitControls.update();
  150. // this.css2dRender.domElement.style.pointerEvents = 'none';
  151. }
  152. }
  153. initControles() {
  154. this.orbitControls = new OrbitControls(this.camera as THREE.Camera, this.renderer?.domElement) as OrbitControls;
  155. this.orbitControls.update();
  156. // this.orbitControls.enableDamping = true;
  157. }
  158. setModel(modalName) {
  159. const modelStore = useModelStore();
  160. return new Promise(async (resolve, reject) => {
  161. try {
  162. const a = new Date().getTime();
  163. let modalValue = modelStore.modelArr.get(modalName);
  164. if (!modalValue) {
  165. const db = window['CustomDB'];
  166. const modalArr = await db.modal.where('modalName').equals(modalName).toArray();
  167. modalValue = modalArr[0].modalVal;
  168. }
  169. if (modalValue) {
  170. console.log('模型下载速度', new Date().getTime() - a);
  171. const b = new Date().getTime();
  172. try {
  173. const gltfLoader = new GLTFLoader();
  174. const dracoLoader = new DRACOLoader();
  175. dracoLoader.setDecoderPath('/model/draco/gltf/');
  176. dracoLoader.setDecoderConfig({ type: 'js' }); //使用兼容性强的draco_decoder.js解码器
  177. dracoLoader.preload();
  178. gltfLoader.setDRACOLoader(dracoLoader);
  179. gltfLoader.setPath('/model/glft/');
  180. gltfLoader.parse(
  181. modalValue,
  182. '/model/glft/',
  183. (gltf) => {
  184. const object = gltf.scene;
  185. setModalCenter(object);
  186. object.traverse((obj) => {
  187. if (obj instanceof THREE.Mesh) {
  188. obj.material.emissiveIntensity = 1;
  189. obj.material.emissiveMap = obj.material.map;
  190. obj.material.blending = THREE.CustomBlending;
  191. if (obj.material.opacity < 1) {
  192. obj.material.transparent = true;
  193. }
  194. obj.renderOrder = 1;
  195. // if (obj.name !== 'buxiugangse') {
  196. // obj.receiveShadow = true;
  197. // }
  198. // obj.castShadow = true;
  199. }
  200. });
  201. object.name = modalName;
  202. console.log('模型渲染时间', object, new Date().getTime() - b);
  203. resolve(gltf);
  204. dracoLoader.dispose();
  205. },
  206. (err) => {
  207. console.log(err);
  208. }
  209. );
  210. } catch (error) {
  211. console.log(error);
  212. }
  213. }
  214. } catch (error) {
  215. reject('加载模型出错');
  216. }
  217. });
  218. }
  219. setTestPlane() {
  220. const plane = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), new THREE.MeshPhongMaterial({ color: 0x999999, specular: 0x101010 }));
  221. plane.rotation.x = -Math.PI / 2;
  222. plane.position.y = 0.03;
  223. plane.receiveShadow = true;
  224. this.scene?.add(plane);
  225. }
  226. removeSawtooth() {
  227. this.composer = new EffectComposer(this.renderer as THREE.WebGLRenderer);
  228. const FXAAShaderPass = new ShaderPass(FXAAShader);
  229. FXAAShaderPass.uniforms['resolution'].value.set(1 / this.canvasContainer.clientWidth, 1 / this.canvasContainer.clientHeight);
  230. FXAAShaderPass.renderToScreen = true;
  231. this.composer.addPass(FXAAShaderPass);
  232. }
  233. /* 场景环境背景 */
  234. setEnvMap(hdr) {
  235. const pmremGenerator = new THREE.PMREMGenerator(this.renderer as THREE.WebGLRenderer); // 使用hdr作为背景色
  236. pmremGenerator.compileEquirectangularShader();
  237. new THREE.TextureLoader().setPath('/model/hdr/').load(hdr + '.jpeg', (texture) => {
  238. texture.mapping = THREE.EquirectangularReflectionMapping;
  239. const envMap = pmremGenerator.fromEquirectangular(texture).texture;
  240. (this.scene as THREE.Scene).environment = envMap;
  241. pmremGenerator.dispose();
  242. });
  243. }
  244. render() {
  245. this.startAnimation();
  246. this.orbitControls?.update();
  247. this.camera?.updateMatrixWorld();
  248. // this.composer?.render();
  249. this.css3dRender?.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  250. this.css2dRender?.render(this.scene as THREE.Scene, this.camera as THREE.PerspectiveCamera);
  251. this.renderer?.render(this.scene as THREE.Object3D, this.camera as THREE.Camera);
  252. }
  253. timeRender() {
  254. //设置为可渲染状态
  255. this.renderEnabled = true;
  256. //清除上次的延迟器
  257. if (this.timeOut) {
  258. clearTimeout(this.timeOut);
  259. }
  260. this.timeOut = setTimeout(() => {
  261. this.renderEnabled = false;
  262. }, 3000);
  263. }
  264. /* 漫游 */
  265. startMY() {}
  266. /* 初始动画 */
  267. startAnimation() {}
  268. renderAnimationScene() {}
  269. animate() {
  270. if (this.animationId != -1) {
  271. this.animationId = requestAnimationFrame(this.animate.bind(this));
  272. // const T = this.clock?.getDelta() || 0;
  273. // this.timeS = this.timeS + T;
  274. // if (this.timeS > this.renderT) {
  275. // this.stats?.update();
  276. // // this.renderAnimationScene();
  277. // if (this.renderEnabled) {
  278. // this.render();
  279. // }
  280. // this.timeS = 0;
  281. // }
  282. this.stats?.update();
  283. TWEEN.update();
  284. // this.renderAnimationScene();
  285. if (this.renderEnabled) {
  286. this.render();
  287. }
  288. }
  289. }
  290. resizeRenderer() {
  291. // 更新相机比例
  292. (this.camera as THREE.PerspectiveCamera).aspect = this.canvasContainer.clientWidth / this.canvasContainer.clientHeight;
  293. // 刷新相机矩阵
  294. this.camera?.updateProjectionMatrix();
  295. // 设置场景尺寸
  296. this.renderer?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  297. this.css3dRender?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  298. this.css2dRender?.setSize(this.canvasContainer.clientWidth, this.canvasContainer.clientHeight);
  299. }
  300. wheelRenderer(e: WheelEvent) {
  301. const timeScale = e.deltaY > 0 ? 1 : -1;
  302. this.animationAction?.setEffectiveTimeScale(timeScale);
  303. (this.animationAction as THREE.AnimationAction).paused = false;
  304. this.animationAction?.play();
  305. if (this.timeoutId) {
  306. clearTimeout(this.timeoutId);
  307. }
  308. this.timeoutId = setTimeout(() => {
  309. this.animationAction?.halt(0.5);
  310. }, 500);
  311. }
  312. // deleteModal() {
  313. // try {
  314. // const gl = this.renderer?.domElement?.getContext('webgl');
  315. // gl && gl.getExtension('WEBGL_lose_context')?.loseContext();
  316. // const gl1 = this.css3dRender?.domElement?.getContext('webgl');
  317. // gl1 && gl1.getExtension('WEBGL_lose_context')?.loseContext();
  318. // this.renderer?.forceContextLoss();
  319. // this.renderer?.dispose();
  320. // if (this.renderer) this.renderer.domElement = null;
  321. // this.renderer = null;
  322. // this.resourceTracker && this.resourceTracker.dispose();
  323. // if (this.canvasContainer) this.canvasContainer.innerHTML = '';
  324. // this.canvasContainer = null;
  325. // this.orbitControls = null;
  326. // this.css3dRender = null;
  327. // this.camera = null;
  328. // this.clock = null;
  329. // cancelAnimationFrame(this.animationId);
  330. // this.animationId = -1;
  331. // this.scene = null;
  332. // this.mixers = [];
  333. // console.log('销毁场景', this.scene);
  334. // } catch (error) {
  335. // console.log(error);
  336. // }
  337. // THREE.Cache.clear();
  338. // console.log('3D环境已清理干净');
  339. // }
  340. clearGroup(group) {
  341. const clearCache = (item) => {
  342. item.geometry?.dispose();
  343. item.material?.dispose();
  344. };
  345. const removeObj = (obj) => {
  346. if (obj?.children && obj?.children.length > 0) {
  347. for (let i = obj?.children.length - 1; i >= 0; i--) {
  348. const item = obj?.children[i];
  349. if (item.children.length > 0) {
  350. removeObj(item);
  351. } else {
  352. clearCache(item);
  353. item.clear();
  354. }
  355. }
  356. }
  357. obj?.removeFromParent();
  358. obj?.clear();
  359. };
  360. removeObj(group);
  361. }
  362. deleteModal() {
  363. cancelAnimationFrame(this.animationId);
  364. this.animationId = -1;
  365. for (let i = this.scene?.children.length - 1; i > -1; i--) {
  366. const obj: any = this.scene?.children[i];
  367. if (obj.type === 'Group') {
  368. this.clearGroup(obj);
  369. } else if (obj.type === 'Mesh') {
  370. if (obj.material) {
  371. obj.material.dispose();
  372. } else if (obj.geometry) {
  373. obj.geometry.dispose();
  374. }
  375. obj.clear();
  376. }
  377. obj.removeFromParent();
  378. this.scene?.remove(obj);
  379. }
  380. this.renderer?.clear();
  381. this.renderer?.dispose();
  382. this.renderer?.forceContextLoss();
  383. const gl = this.renderer?.getContext('webgl');
  384. gl && gl.getExtension('WEBGL_lose_context')?.loseContext();
  385. this.canvasContainer?.removeChild(this.renderer?.domElement as Node);
  386. // const glCss = this.css3dRender?.getContext('webgl');
  387. // glCss && glCss.getExtension('WEBGL_lose_context')?.loseContext();
  388. this.CSSCanvasContainer?.removeChild(this.css3dRender?.domElement as Node);
  389. this.camera = null;
  390. this.orbitControls = null;
  391. if (this.renderer) this.renderer.domElement = null;
  392. if (this.css3dRender) this.css3dRender.domElement = null;
  393. if (this.css2dRender) this.css2dRender.domElement = null;
  394. if (this.canvasContainer) this.canvasContainer.innerHTML = '';
  395. if (this.CSSCanvasContainer) this.CSSCanvasContainer.innerHTML = '';
  396. this.resourceTracker && this.resourceTracker.dispose();
  397. this.scene?.environment?.dispose();
  398. !!this.scene?.clear ?? this.scene?.clear();
  399. this.stats = null;
  400. this.scene = null;
  401. this.css3dRender = null;
  402. this.css2dRender = null;
  403. this.renderer = null;
  404. THREE.Cache.clear();
  405. }
  406. }
  407. export default UseThree;