util.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import * as THREE from 'three';
  2. import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
  3. import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
  4. import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass.js';
  5. import { FXAAShader } from 'three/examples/jsm/shaders/FXAAShader.js';
  6. import { ShaderPass } from 'three/examples/jsm/postprocessing/ShaderPass.js';
  7. import TWEEN from 'three/examples/jsm/libs/tween.module.js';
  8. import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
  9. import gsap from 'gsap';
  10. import { useAppStore } from '/@/store/modules/app';
  11. import UseThree from './useThree';
  12. // import * as dat from "dat.gui";
  13. /* 设置模型居中 */
  14. export const setModalCenter = (group, modal?) => {
  15. const box3 = new THREE.Box3();
  16. // 计算层级模型group的包围盒
  17. // 模型group是加载一个三维模型返回的对象,包含多个网格模型
  18. box3.expandByObject(group);
  19. // 计算一个层级模型对应包围盒的几何体中心在世界坐标中的位置
  20. const center = new THREE.Vector3();
  21. box3.getCenter(center);
  22. // console.log('查看几何体中心坐标', center);
  23. // 重新设置模型的位置,使之居中。
  24. group.position.x = group.position.x - center.x;
  25. group.position.y = group.position.y - center.y;
  26. group.position.z = group.position.z - center.z;
  27. };
  28. // 获取一个canvas 图文纹理
  29. export const getTextCanvas = (w, h, textArr, imgUrl) => {
  30. // canvas 宽高最好是2的倍数
  31. const width = w;
  32. const height = h;
  33. // 创建一个canvas元素 获取上下文环境
  34. const canvas = document.createElement('canvas');
  35. canvas.style.letterSpacing = 10 + 'px';
  36. const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
  37. canvas.width = width;
  38. canvas.height = height;
  39. // 设置样式
  40. ctx.textAlign = 'start';
  41. ctx.fillStyle = 'rgba(0, 0, 0, 0)';
  42. // 创建渐变
  43. // var gradient=ctx.createLinearGradient(0,0, canvas.width,0);
  44. // gradient.addColorStop(0,"magenta");
  45. // gradient.addColorStop(0.5,"blue");
  46. // gradient.addColorStop(1.0,"red");
  47. // // 用渐变填色
  48. // ctx.fillStyle=gradient;
  49. ctx.shadowColor = 'rgba(0, 10,0,0.8)';
  50. ctx.shadowBlur = 4;
  51. ctx.shadowOffsetX = 1;
  52. ctx.shadowOffsetY = 1;
  53. ctx.fillRect(0, 0, width, height);
  54. //添加背景图片,进行异步,否则可能会过早渲染,导致空白
  55. return new Promise((resolve, reject) => {
  56. if (imgUrl) {
  57. const img = new Image();
  58. img.src = new URL('../../assets/images/vent/model_image/' + imgUrl, import.meta.url).href;
  59. img.onload = () => {
  60. //将画布处理为透明
  61. ctx.clearRect(0, 0, width, height);
  62. //绘画图片
  63. ctx.drawImage(img, 0, 0, width, height);
  64. ctx.textBaseline = 'middle';
  65. // 由于文字需要自己排版 所以循环一下
  66. // item 是自定义的文字对象 包含文字内容 字体大小颜色 位置信息等
  67. textArr.forEach((item) => {
  68. ctx.font = item.font;
  69. ctx.fillStyle = item.color;
  70. ctx.fillText(item.text, item.x, item.y, 1024);
  71. });
  72. resolve(canvas);
  73. };
  74. //图片加载失败的方法
  75. img.onerror = (e) => {
  76. reject(e);
  77. };
  78. } else {
  79. //将画布处理为透明
  80. ctx.clearRect(0, 0, width, height);
  81. ctx.textBaseline = 'middle';
  82. textArr.forEach((item) => {
  83. ctx.lineWidth = 2;
  84. ctx.font = item.font;
  85. ctx.fillStyle = item.color;
  86. // !!item.strokeStyle && (ctx.strokeStyle = item.strokeStyle);
  87. // if (item.strokeStyle) ctx.strokeText(item.text, item.x, item.y, 1024);
  88. ctx.fillText(item.text, item.x, item.y, 1024);
  89. });
  90. resolve(canvas);
  91. }
  92. });
  93. };
  94. // 发光路径
  95. export const setLineGeo = (scene) => {
  96. const box = new THREE.BoxGeometry(30, 30, 30);
  97. // 立方体几何体box作为EdgesGeometry参数创建一个新的几何体
  98. const edges = new THREE.EdgesGeometry(box);
  99. // 立方体线框,不显示中间的斜线
  100. new THREE.TextureLoader().setPath('/model/hdr/').load('8.png', (texture) => {
  101. const edgesMaterial = new THREE.MeshBasicMaterial({
  102. // color: 0x00ffff,
  103. map: texture,
  104. transparent: true,
  105. depthWrite: false,
  106. });
  107. const line = new THREE.LineSegments(edges, edgesMaterial);
  108. // 网格模型和网格模型对应的轮廓线框插入到场景中
  109. scene.add(line);
  110. texture.dispose();
  111. });
  112. box.attributes.position.array;
  113. const lightMaterial = new THREE.ShaderMaterial({
  114. vertexShader: `varying vec3 vPosition;
  115. varying vec2 vUv;
  116. uniform float uTime;
  117. void main(){
  118. // vec3 scalePosition = vec3(position.x+uTime,position.y,position.z+uTime);
  119. vec4 viewPosition = viewMatrix * modelMatrix * vec4(position,1);
  120. gl_Position = projectionMatrix * viewPosition;
  121. vPosition = position;
  122. vUv = uv;
  123. }`,
  124. fragmentShader: `varying vec3 vPosition;
  125. varying vec2 vUv;
  126. uniform vec3 uColor;
  127. uniform float uHeight;
  128. vec4 permute(vec4 x)
  129. {
  130. return mod(((x*34.0)+1.0)*x, 289.0);
  131. }
  132. vec2 fade(vec2 t)
  133. {
  134. return t*t*t*(t*(t*6.0-15.0)+10.0);
  135. }
  136. float cnoise(vec2 P)
  137. {
  138. vec4 Pi = floor(P.xyxy) + vec4(0.0, 0.0, 1.0, 1.0);
  139. vec4 Pf = fract(P.xyxy) - vec4(0.0, 0.0, 1.0, 1.0);
  140. Pi = mod(Pi, 289.0); // To avoid truncation effects in permutation
  141. vec4 ix = Pi.xzxz;
  142. vec4 iy = Pi.yyww;
  143. vec4 fx = Pf.xzxz;
  144. vec4 fy = Pf.yyww;
  145. vec4 i = permute(permute(ix) + iy);
  146. vec4 gx = 2.0 * fract(i * 0.0243902439) - 1.0; // 1/41 = 0.024...
  147. vec4 gy = abs(gx) - 0.5;
  148. vec4 tx = floor(gx + 0.5);
  149. gx = gx - tx;
  150. vec2 g00 = vec2(gx.x,gy.x);
  151. vec2 g10 = vec2(gx.y,gy.y);
  152. vec2 g01 = vec2(gx.z,gy.z);
  153. vec2 g11 = vec2(gx.w,gy.w);
  154. vec4 norm = 1.79284291400159 - 0.85373472095314 * vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11));
  155. g00 *= norm.x;
  156. g01 *= norm.y;
  157. g10 *= norm.z;
  158. g11 *= norm.w;
  159. float n00 = dot(g00, vec2(fx.x, fy.x));
  160. float n10 = dot(g10, vec2(fx.y, fy.y));
  161. float n01 = dot(g01, vec2(fx.z, fy.z));
  162. float n11 = dot(g11, vec2(fx.w, fy.w));
  163. vec2 fade_xy = fade(Pf.xy);
  164. vec2 n_x = mix(vec2(n00, n01), vec2(n10, n11), fade_xy.x);
  165. float n_xy = mix(n_x.x, n_x.y, fade_xy.y);
  166. return 2.3 * n_xy;
  167. }
  168. void main(){
  169. float strength = (vPosition.y+uHeight/2.0)/uHeight;
  170. gl_FragColor = vec4(uColor,1.0 - strength);
  171. // float strength =1.0 - abs(cnoise(vUv * 10.0)) ;
  172. // gl_FragColor =vec4(strength,strength,strength,1);
  173. }`,
  174. transparent: true,
  175. side: THREE.DoubleSide,
  176. });
  177. const lightMesh = new THREE.Mesh(box, lightMaterial);
  178. lightMesh.geometry.computeBoundingBox();
  179. const { min, max } = lightMesh.geometry.boundingBox;
  180. const uHeight = max.y - min.y;
  181. lightMaterial.uniforms.uHeight = {
  182. value: uHeight,
  183. };
  184. lightMaterial.uniforms.uColor = {
  185. value: new THREE.Color(0x00ff00),
  186. };
  187. lightMaterial.uniforms.uTime = {
  188. value: 0,
  189. };
  190. // gsap.to(lightMesh.scale, {
  191. // // x: 2,
  192. // // z: 2,
  193. // y: 0.8,
  194. // duration: 1,
  195. // ease: 'none',
  196. // repeat: -1,
  197. // yoyo: true,
  198. // });
  199. scene.add(lightMesh);
  200. };
  201. export const setOutline = (model, group) => {
  202. const { scene, renderer, camera } = model;
  203. const params = {
  204. edgeStrength: 10.0,
  205. edgeGlow: 1,
  206. edgeThickness: 1.0,
  207. pulsePeriod: 5,
  208. rotate: false,
  209. usePatternTexture: false,
  210. };
  211. const composer = new EffectComposer(renderer);
  212. const renderPass = new RenderPass(scene, camera);
  213. composer.addPass(renderPass);
  214. const outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, camera);
  215. composer.addPass(outlinePass);
  216. outlinePass.visibleEdgeColor.set(parseInt(0xffffff));
  217. outlinePass.hiddenEdgeColor.set('#190a05');
  218. outlinePass.edgeStrength = params.edgeStrength;
  219. outlinePass.edgeThickness = params.edgeThickness;
  220. outlinePass.pulsePeriod = params.pulsePeriod;
  221. outlinePass.usePatternTexture = params.usePatternTexture;
  222. // const textureLoader = new THREE.TextureLoader();
  223. // textureLoader.load('model/hdr/tri_pattern.jpg', function (texture) {
  224. // outlinePass.patternTexture = texture;
  225. // texture.wrapS = THREE.RepeatWrapping;
  226. // texture.wrapT = THREE.RepeatWrapping;
  227. // });
  228. const effectFXAA = new ShaderPass(FXAAShader);
  229. effectFXAA.uniforms['resolution'].value.set(1 / window.innerWidth, 1 / window.innerHeight);
  230. composer.addPass(effectFXAA);
  231. const scale = 1;
  232. group.traverse(function (child) {
  233. if (child instanceof THREE.Mesh) {
  234. // child.geometry.center();
  235. child.geometry.computeBoundingSphere();
  236. }
  237. });
  238. // group.scale.multiplyScalar(Math.random() * 0.3 + 0.1);
  239. group.scale.divideScalar(scale);
  240. return { outlinePass, composer };
  241. };
  242. /* 渲染视频 */
  243. export const renderVideo = (group, player, playerMeshName) => {
  244. //加载视频贴图;
  245. const texture = new THREE.VideoTexture(player);
  246. if (texture && group?.getObjectByName(playerMeshName)) {
  247. const player = group.getObjectByName(playerMeshName);
  248. player.material.map = texture;
  249. // texture.dispose();
  250. } else {
  251. //创建网格;
  252. const planeGeometry = new THREE.PlaneGeometry(30, 20);
  253. const material = new THREE.MeshBasicMaterial({
  254. map: texture,
  255. side: THREE.DoubleSide,
  256. });
  257. /* 消除摩尔纹 */
  258. texture.magFilter = THREE.LinearFilter;
  259. texture.minFilter = THREE.LinearFilter;
  260. texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
  261. texture.format = THREE.RGBAFormat;
  262. texture.anisotropy = 0.5;
  263. // texture.generateMipmaps = false
  264. const mesh = new THREE.Mesh(planeGeometry, material);
  265. mesh.name = playerMeshName;
  266. texture.dispose();
  267. // group.add(mesh);
  268. return mesh;
  269. }
  270. };
  271. // oldP 相机原来的位置
  272. // oldT target原来的位置
  273. // newP 相机新的位置
  274. // newT target新的位置
  275. // callBack 动画结束时的回调函数
  276. export const animateCamera = (oldP, oldT, newP, newT, model, duration = 0.5, callBack?) => {
  277. return new Promise((resolve) => {
  278. const camera = model.camera;
  279. const controls = model.orbitControls;
  280. controls.renderEnabled = false;
  281. controls.target.set(0, 0, 0);
  282. const animateObj = {
  283. x1: oldP.x, // 相机x
  284. y1: oldP.y, // 相机y
  285. z1: oldP.z, // 相机z
  286. x2: oldT.x, // 控制点的中心点x
  287. y2: oldT.y, // 控制点的中心点y
  288. z2: oldT.z, // 控制点的中心点z
  289. };
  290. gsap.fromTo(
  291. animateObj,
  292. {
  293. x1: oldP.x, // 相机x
  294. y1: oldP.y, // 相机y
  295. z1: oldP.z, // 相机z
  296. x2: oldT.x, // 控制点的中心点x
  297. y2: oldT.y, // 控制点的中心点y
  298. z2: oldT.z, // 控制点的中心点z
  299. },
  300. {
  301. x1: newP.x,
  302. y1: newP.y,
  303. z1: newP.z,
  304. x2: newT.x,
  305. y2: newT.y,
  306. z2: newT.z,
  307. duration: duration,
  308. ease: 'easeOutBounce',
  309. onUpdate: function (object) {
  310. // 这里写逻辑
  311. camera.position.set(object.x1, object.y1, object.z1);
  312. controls.target.set(object.x2, object.y2, object.z2);
  313. controls.update();
  314. if (callBack) callBack();
  315. },
  316. onUpdateParams: [animateObj],
  317. onComplete: function () {
  318. // 完成
  319. controls.renderEnabled = true;
  320. resolve(null);
  321. },
  322. }
  323. );
  324. });
  325. };
  326. export const transScreenCoord = (vector, camera) => {
  327. // const screenCoord = { x: 0, y: 0 };
  328. // vector.project(camera);
  329. // screenCoord.x = (0.5 + vector.x / 2) * window.innerWidth;
  330. // screenCoord.y = (0.5 - vector.y / 2) * window.innerHeight;
  331. // return screenCoord;
  332. const stdVector = vector.project(camera);
  333. const a = window.innerWidth / 2;
  334. const b = window.innerHeight / 2;
  335. const x = Math.round(stdVector.x * a + a);
  336. const y = Math.round(-stdVector.y * b + b);
  337. return { x, y };
  338. };
  339. export const drawHot = (scale: number) => {
  340. // const hotMap = new THREE.TextureLoader().load('/src/assets/images/hot-point.png');
  341. // const hotMap = new THREE.TextureLoader().setPath('/model/img/').load('/hot-point.png');
  342. const hotMap = new THREE.TextureLoader().load('/model/img/hot-point.png');
  343. const material = new THREE.SpriteMaterial({
  344. map: hotMap,
  345. });
  346. const hotPoint = new THREE.Sprite(material);
  347. const spriteTween = new TWEEN.Tween({
  348. scale: 1 * scale,
  349. })
  350. .to(
  351. {
  352. scale: 0.65 * scale,
  353. },
  354. 1000
  355. )
  356. .easing(TWEEN.Easing.Quadratic.Out);
  357. spriteTween.onUpdate(function (that) {
  358. hotPoint.scale.set(that.scale, that.scale, that.scale);
  359. });
  360. spriteTween.yoyo(true);
  361. spriteTween.repeat(Infinity);
  362. spriteTween.start();
  363. hotMap.dispose();
  364. return hotPoint;
  365. };
  366. export const deviceDetailCard = () => {
  367. //
  368. };
  369. export const updateAxisCenter = (modal: UseThree, group: THREE.Object3D, event, callBack?) => {
  370. if (!modal) return;
  371. const appStore = useAppStore();
  372. event.stopPropagation();
  373. const widthScale = appStore.getWidthScale;
  374. const heightScale = appStore.getHeightScale;
  375. // 将鼠标位置归一化为设备坐标。x 和 y 方向的取值范围是 (-1 to +1)
  376. modal.mouse.x =
  377. ((-modal.canvasContainer.getBoundingClientRect().left * widthScale + event.clientX) / (modal.canvasContainer.clientWidth * widthScale)) * 2 - 1;
  378. modal.mouse.y =
  379. -((-modal.canvasContainer.getBoundingClientRect().top + event.clientY) / (modal.canvasContainer.clientHeight * heightScale)) * 2 + 1;
  380. (modal.rayCaster as THREE.Raycaster).setFromCamera(modal.mouse, modal.camera as THREE.Camera);
  381. if (group) {
  382. const intersects = modal.rayCaster?.intersectObjects(group.children, true) as THREE.Intersection[];
  383. if (intersects.length > 0) {
  384. const point = intersects[0].point;
  385. const target0 = modal.orbitControls.target.clone();
  386. gsap.fromTo(
  387. modal.orbitControls.target,
  388. { x: target0.x, y: target0.y, z: target0.z },
  389. {
  390. x: point.x,
  391. y: point.y,
  392. z: point.z,
  393. duration: 0.4,
  394. ease: 'easeInCirc',
  395. onUpdate: function (object) {
  396. if (object) modal.camera?.lookAt(new THREE.Vector3(object.x, object.y, object.z));
  397. },
  398. }
  399. );
  400. callBack(intersects);
  401. }
  402. }
  403. // const factor = 1;
  404. // //这里定义深度值为0.5,深度值越大,意味着精度越高
  405. // var vector = new THREE.Vector3(modal.mouse.x, modal.mouse.y, 0.5);
  406. // //将鼠标坐标转换为3D空间坐标
  407. // vector.unproject(modal.camera);
  408. // //获得从相机指向鼠标所对应的3D空间点的射线(归一化)
  409. // vector.sub(modal.camera.position).normalize();
  410. // if (event.originalEvent && event.originalEvent.deltaY && event.originalEvent.deltaY < 0) {
  411. // modal.camera.position.x += vector.x * factor;
  412. // modal.camera.position.y += vector.y * factor;
  413. // modal.camera.position.z += vector.z * factor;
  414. // modal.orbitControls.target.x += vector.x * factor;
  415. // modal.orbitControls.target.y += vector.y * factor;
  416. // modal.orbitControls.target.z += vector.z * factor;
  417. // } else {
  418. // modal.camera.position.x -= vector.x * factor;
  419. // modal.camera.position.y -= vector.y * factor;
  420. // modal.camera.position.z -= vector.z * factor;
  421. // modal.orbitControls.target.x -= vector.x * factor;
  422. // modal.orbitControls.target.y -= vector.y * factor;
  423. // modal.orbitControls.target.z -= vector.z * factor;
  424. // }
  425. // modal.orbitControls.update();
  426. // modal.camera.updateMatrixWorld();
  427. };
  428. export const addEnvMap = (hdr, modal) => {
  429. return new Promise((resolve) => {
  430. const loader = new RGBELoader().setPath('/model/hdr/').load(hdr + '.hdr', (texture) => {
  431. texture.mapping = THREE.EquirectangularReflectionMapping;
  432. const defaultEnvironment = texture;
  433. modal.scene.environment = defaultEnvironment;
  434. resolve(null);
  435. texture.dispose();
  436. });
  437. loader.dispose()
  438. });
  439. };