util.ts 13 KB

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