util.ts 17 KB

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