util.ts 19 KB

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