util.ts 16 KB

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