gasAssessmen.threejs.base.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import * as THREE from 'three';
  2. import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
  3. import { OutlinePass } from 'three/examples/jsm/postprocessing/OutlinePass.js';
  4. import { setModalCenter, setTag3D, gradientColors } from '/@/utils/threejs/util';
  5. import { CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
  6. import { green, yellow } from '@ant-design/colors';
  7. // import * as dat from 'dat.gui';
  8. // const gui = new dat.GUI();
  9. // gui.domElement.style = 'position:absolute;top:100px;left:10px;z-index:99999999999999';
  10. type Unit = {
  11. id: string;
  12. ratio: number;
  13. color: THREE.Color;
  14. };
  15. class GasAssessmen {
  16. model;
  17. modelName = 'workFace';
  18. group: THREE.Object3D = new THREE.Object3D();
  19. planeGroup: THREE.Group = new THREE.Group();
  20. bloomComposer: EffectComposer | null = null;
  21. finalComposer: EffectComposer | null = null;
  22. outlinePass: OutlinePass | null = null;
  23. positions: THREE.Vector3[][] = [];
  24. bloomLayer = new THREE.Layers();
  25. darkMaterial = new THREE.MeshBasicMaterial({ color: 'black', transparent: true, side: THREE.DoubleSide });
  26. materials = {};
  27. glob = {
  28. ENTIRE_SCENE: 0,
  29. BLOOM_SCENE: 10,
  30. N: 100,
  31. };
  32. locationTexture: THREE.Texture | null = null;
  33. warningLocationTexture: THREE.Texture | null = null;
  34. errorLocationTexture: THREE.Texture | null = null;
  35. playerStartClickTime1 = new Date().getTime();
  36. playerStartClickTime2 = new Date().getTime();
  37. planeNum = 0;
  38. unitList: Unit[] = [];
  39. constructor(model) {
  40. this.model = model;
  41. this.group.name = this.modelName;
  42. }
  43. addLight() {
  44. // const _this = this;
  45. const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  46. directionalLight.position.set(-196, 150, 258);
  47. this.group.add(directionalLight);
  48. directionalLight.target = this.group;
  49. }
  50. render() {
  51. this.model.renderer?.render(this.model.scene as THREE.Scene, this.model.camera as THREE.PerspectiveCamera);
  52. }
  53. setPlanes1 = (n) => {
  54. // const sizeList = [0.2, 0.3, 0.1, 0.2, 0.2];
  55. const colors = {
  56. c1: new THREE.Color(0x00fe00), // >90
  57. c2: new THREE.Color(0xf9b866), // >75 <90 249,184,102
  58. c3: new THREE.Color(0xfefe00), // 50-75 254,254,0
  59. c4: new THREE.Color(0xfe6600), // 25-50 254,102,0
  60. c5: new THREE.Color(0xb00101), // <25 176,1,1
  61. };
  62. const sizeList = [
  63. {
  64. id: '111',
  65. ratio: 0.5,
  66. color: colors.c1,
  67. },
  68. {
  69. id: '222',
  70. ratio: 0.3,
  71. color: colors.c2,
  72. },
  73. {
  74. id: '333',
  75. ratio: 0.2,
  76. color: colors.c4,
  77. },
  78. // {
  79. // id: '444',
  80. // ratio: 0.2,
  81. // color: colors.c5,
  82. // },
  83. // {
  84. // id: '555',
  85. // ratio: 0.2,
  86. // color: colors.c3,
  87. // },
  88. ];
  89. this.unitList = sizeList;
  90. // width = 7.713 height =3.717
  91. // const sizeList = [
  92. // {
  93. // ratio: 0.4,
  94. // color: colors.c1,
  95. // },
  96. // {
  97. // ratio: 0.5,
  98. // color: colors.c2,
  99. // },
  100. // {
  101. // ratio: 0.1,
  102. // color: colors.c4,
  103. // },
  104. // ];
  105. const geometry = new THREE.PlaneGeometry(7.723, 3.72, 1, 1);
  106. // 初始化累积比例数组和颜色数组
  107. const accumulatedRatios = [];
  108. const colorsArray = new Float32Array(3 * sizeList.length);
  109. // 计算累积比例和颜色数组
  110. function updateShaderData(sizeList) {
  111. let accRatio = 0;
  112. for (let i = 0; i < sizeList.length; i++) {
  113. const item = sizeList[i];
  114. accRatio += item.ratio;
  115. accumulatedRatios.push(accRatio);
  116. colorsArray[i * 3] = item.color.r;
  117. colorsArray[i * 3 + 1] = item.color.g;
  118. colorsArray[i * 3 + 2] = item.color.b;
  119. }
  120. }
  121. updateShaderData(sizeList); // 初始调用
  122. // 定义着色器代码
  123. const vertexShader = `
  124. varying vec2 vUv;
  125. void main() {
  126. vUv = uv;
  127. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  128. }
  129. `;
  130. const fragmentShader = `
  131. varying vec2 vUv;
  132. uniform float ratios[${sizeList.length}];
  133. uniform vec3 colors[${sizeList.length}];
  134. void main() {
  135. for(int i = 0; i < ${sizeList.length}; i++) {
  136. if(vUv.x < ratios[i]) {
  137. gl_FragColor = vec4(colors[i], 1.0);
  138. return;
  139. }
  140. }
  141. gl_FragColor = vec4(0.0, 0.0, 0.0, 0.5);
  142. }
  143. `;
  144. // const fragmentShader = `
  145. // varying vec2 vUv;
  146. // uniform float ratios[${sizeList.length + 1}]; // 加入了起始点 0
  147. // uniform vec3 colors[${sizeList.length}];
  148. // vec3 lerp(vec3 a, vec3 b, float t) {
  149. // return a + t * (b - a);
  150. // }
  151. // void main() {
  152. // int index = 0;
  153. // for(int i = 1; i <= ${sizeList.length}; i++) {
  154. // if(vUv.x >= ratios[i-1] && vUv.x < ratios[i]) {
  155. // index = i - 1;
  156. // break;
  157. // }
  158. // }
  159. // // 如果是最后一个颜色块,直接使用其颜色
  160. // if (index == ${sizeList.length - 1}) {
  161. // gl_FragColor = vec4(colors[index], 1.0);
  162. // } else {
  163. // // 计算该像素在当前颜色块内的相对位置
  164. // float t = (vUv.x - ratios[index]) / (ratios[index + 1] - ratios[index]);
  165. // // 在相邻颜色间进行线性插值
  166. // vec3 color = lerp(colors[index], colors[index + 1], t);
  167. // gl_FragColor = vec4(color, 1.0);
  168. // }
  169. // }
  170. // `;
  171. // 创建着色器材质
  172. const material = new THREE.ShaderMaterial({
  173. uniforms: {
  174. ratios: { value: accumulatedRatios },
  175. colors: { value: colorsArray },
  176. },
  177. vertexShader: vertexShader,
  178. fragmentShader: fragmentShader,
  179. depthTest: false,
  180. depthWrite: false,
  181. });
  182. // // 当 sizeList 数据变化时调用此函数
  183. // function updateSizeList(newSizeList) {
  184. // accumulatedRatios.length = 0; // 清空累积比例数组
  185. // updateShaderData(newSizeList);
  186. // material.uniforms.ratios.value = accumulatedRatios;
  187. // material.uniforms.colors.value = colorsArray;
  188. // material.needsUpdate = true;
  189. // }
  190. // 创建网格并添加到场景中
  191. const plane = new THREE.Mesh(geometry, material);
  192. plane.rotation.x = -Math.PI / 2;
  193. plane.position.set(-0.2, 0.15, -0.03);
  194. plane.name = 'unit';
  195. this.planeGroup.add(plane);
  196. this.group.add(this.planeGroup);
  197. };
  198. setPlanes = (unitList: any[]) => {
  199. if (!unitList || unitList.length === 0) return;
  200. // 要根据unitList来计算比例
  201. type Point = { u: number; v: number };
  202. let max = 0;
  203. const unitLen = unitList[unitList.length - 1]['unitLen'].split(',');
  204. max = Math.max(max, ...unitLen);
  205. const regions = <{ points: Point[]; color: any[] }[]>[];
  206. for (let i = 0; i < unitList.length; i++) {
  207. const item = unitList[i];
  208. const unitRatio: Point[] = [];
  209. const color = new THREE.Color(item['unitColor']);
  210. if (item['unitLen']) {
  211. const unitLen = item['unitLen'].split(',');
  212. const sortList = [1, 0, 2, 3];
  213. for (let j = 0; j < sortList.length; j++) {
  214. const x = unitLen[sortList[j]];
  215. const unitU = Number((x / max).toFixed(2));
  216. const unitV = sortList[j] % 2 === 0 ? 0.0 : 1.0;
  217. unitRatio.push({
  218. u: unitU == 0 ? 0.0 : unitU,
  219. v: unitV == 0 ? 0.0 : unitV,
  220. });
  221. }
  222. }
  223. regions.push({
  224. points: unitRatio,
  225. color: [color.r, color.g, color.b],
  226. // color: [1, 0, 0],
  227. });
  228. }
  229. // 自定义着色器
  230. const vertexShader = `
  231. varying vec2 vUv;
  232. void main() {
  233. vUv = uv; // 传递纹理坐标
  234. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  235. }
  236. `;
  237. const fragmentShader = `
  238. uniform vec3 regionColors[${regions.length}]; // 区域颜色数组
  239. uniform vec4 regionPoints[${regions.length * 4}]; // 区域顶点数组 (每个区域4个点)
  240. varying vec2 vUv;
  241. // 判断点是否在四边形内(通过叉积法)
  242. bool isPointInQuad(vec2 p, vec2 a, vec2 b, vec2 c, vec2 d) {
  243. vec2 ab = b - a;
  244. vec2 bc = c - b;
  245. vec2 cd = d - c;
  246. vec2 da = a - d;
  247. vec2 ap = p - a;
  248. vec2 bp = p - b;
  249. vec2 cp = p - c;
  250. vec2 dp = p - d;
  251. float cross1 = ab.x * ap.y - ab.y * ap.x;
  252. float cross2 = bc.x * bp.y - bc.y * bp.x;
  253. float cross3 = cd.x * cp.y - cd.y * cp.x;
  254. float cross4 = da.x * dp.y - da.y * dp.x;
  255. return (cross1 >= 0.0 && cross2 >= 0.0 && cross3 >= 0.0 && cross4 >= 0.0) ||
  256. (cross1 <= 0.0 && cross2 <= 0.0 && cross3 <= 0.0 && cross4 <= 0.0);
  257. }
  258. void main() {
  259. vec3 finalColor = vec3(0.0);
  260. for (int i = 0; i < ${regions.length}; i++) {
  261. vec4 p1 = regionPoints[i * 4];
  262. vec4 p2 = regionPoints[i * 4 + 1];
  263. vec4 p3 = regionPoints[i * 4 + 2];
  264. vec4 p4 = regionPoints[i * 4 + 3];
  265. // 判断当前片段是否在梯形区域内
  266. if (isPointInQuad(vUv, p1.xy, p2.xy, p3.xy, p4.xy)) {
  267. finalColor = regionColors[i];
  268. break;
  269. }
  270. }
  271. gl_FragColor = vec4(finalColor, 1.0);
  272. }
  273. `;
  274. const geometry = new THREE.PlaneGeometry(7.723, 3.72, 1, 1);
  275. // 创建材质
  276. const material = new THREE.ShaderMaterial({
  277. vertexShader,
  278. fragmentShader,
  279. uniforms: {
  280. regionColors: { value: regions.map((region) => new THREE.Vector3(...region.color)) },
  281. regionPoints: {
  282. value: regions.flatMap((region) => region.points.map((p) => new THREE.Vector4(p.u, p.v, 0, 0))),
  283. },
  284. },
  285. depthTest: false,
  286. depthWrite: false,
  287. });
  288. // 创建网格并添加到场景中
  289. const plane = new THREE.Mesh(geometry, material);
  290. plane.rotation.x = -Math.PI / 2;
  291. plane.position.set(-0.2, 0.15, -0.03);
  292. plane.name = 'unit';
  293. this.planeGroup.add(plane);
  294. this.group.add(this.planeGroup);
  295. };
  296. // 清除抽采单元绘制面
  297. clearPlanes = () => {
  298. for (let i = 0; i < this.planeNum; i++) {
  299. const plane = this.planeGroup.getObjectByName(`unit${i}`);
  300. const label = this.planeGroup.getObjectByName(`planeText${i}`);
  301. if (plane) this.planeGroup.remove(plane);
  302. if (label) this.planeGroup.remove(label);
  303. }
  304. };
  305. // 抽采单元内容显示
  306. setCss3D = (unitList: any[]) => {
  307. const sizeList: number[] = [];
  308. if (!unitList || unitList.length === 0) return;
  309. let max = 0;
  310. const unitLen = unitList[unitList.length - 1]['unitLen'].split(',');
  311. max = Math.max(max, ...unitLen);
  312. for (let i = 0; i < unitList.length; i++) {
  313. const item = unitList[i];
  314. const unitLen = item['unitLen'].split(',');
  315. const unitMax = Math.max(...unitLen);
  316. const unitMin = Math.min(...unitLen);
  317. sizeList.push((unitMax - unitMin) / max);
  318. }
  319. let leftW = 0;
  320. for (let i = 0; i < sizeList.length; i++) {
  321. const label = setTag3D(`抽采单元${i + 1}`, 'gas_unit_text');
  322. label.scale.set(0.02, 0.02, 0.02); //根据相机渲染范围控制HTML 3D标签尺寸
  323. label.position.set((leftW + sizeList[i] / 2) * 7.913 - 4.22, 0.015, 0.142);
  324. label.name = 'planeText' + i;
  325. this.planeGroup.add(label);
  326. const obj = this.group.getObjectByName(`unitText${i}`);
  327. if (!obj) {
  328. const element = document.getElementById(`gasUnitBox${i + 1}`) as HTMLElement;
  329. if (element) {
  330. const gasUnitCSS3D = new CSS3DObject(element);
  331. gasUnitCSS3D.name = `unitText${i}`;
  332. gasUnitCSS3D.scale.set(0.01, 0.01, 0.01);
  333. gasUnitCSS3D.position.set((leftW + sizeList[i] / 2) * 10.93 - 11.17, 0.015, -3.442);
  334. gasUnitCSS3D.lookAt(gasUnitCSS3D.position.x, gasUnitCSS3D.position.y + 1.2, gasUnitCSS3D.position.y);
  335. this.planeGroup.add(gasUnitCSS3D);
  336. }
  337. }
  338. leftW += sizeList[i];
  339. }
  340. };
  341. // 显示或隐藏抽采单元显示内容
  342. changeCss3D = () => {
  343. for (let i = 0; i < this.planeNum; i++) {
  344. const planeText = this.planeGroup.getObjectByName(`planeText${i}`);
  345. this.planeGroup.remove(planeText);
  346. const unitText = this.planeGroup.getObjectByName(`unitText${i}`);
  347. this.planeGroup.remove(unitText);
  348. }
  349. };
  350. // 清除抽采单元显示内容
  351. clearCss3D = () => {
  352. // const obj = this.group.getObjectByName(`unitText`);
  353. // if (obj) this.group.remove(obj);
  354. // const element = document.getElementById(`gasUnitBox`) as HTMLElement;
  355. // if (element) {
  356. // element.remove();
  357. // }
  358. // for (let i = 0; i < this.planeNum; i++) {
  359. // const label = this.planeGroup.getObjectByName(`planeText${i}`);
  360. // if (label) this.planeGroup.remove(label);
  361. // }
  362. this.model.clearGroup(this.planeGroup);
  363. this.planeGroup = new THREE.Group();
  364. };
  365. /* 点击 */
  366. mousedownModel(intersects: THREE.Intersection<THREE.Object3D<THREE.Event>>[]) {
  367. // 判断是否点击到视频
  368. return new Promise((resolve) => {
  369. intersects.find((intersect) => {
  370. const intersectedObject = intersect.object;
  371. if (intersectedObject.name == 'unit') {
  372. // 如果对象是我们的平面,并且它有自定义属性来标识它的 UV 范围
  373. if (intersectedObject && intersectedObject.material && intersectedObject.material.uniforms) {
  374. const uv = intersect.uv; // 点击点的 UV 坐标
  375. const clickedRatio = uv.x; // 使用 UV 的 x 分量作为比例值
  376. // 根据点击的比例找到对应的色块
  377. let clickedColorIndex = -1;
  378. let accRatio = 0;
  379. for (let i = 0; i < this.unitList.length - 1; i++) {
  380. const unitData = this.unitList[i];
  381. accRatio += unitData.ratio;
  382. if (clickedRatio < accRatio) {
  383. clickedColorIndex = i;
  384. break;
  385. }
  386. }
  387. if (clickedColorIndex !== -1) {
  388. const unitData = this.unitList[clickedColorIndex];
  389. const unitId = unitData.id;
  390. // window.open(`${location.origin}/gasUnitAssessment/home?id=${unitId}`);
  391. resolve(unitId);
  392. }
  393. }
  394. return true;
  395. }
  396. return false;
  397. });
  398. this.render();
  399. });
  400. }
  401. mouseUpModel() {
  402. //
  403. }
  404. mountedThree() {
  405. return new Promise(async (resolve) => {
  406. this.model.renderer.sortObjects = true;
  407. this.model.orbitControls.update();
  408. this.model.setGLTFModel(['workFace1'], this.group).then(async () => {
  409. this.group.children.forEach((object: THREE.Object3D) => {
  410. if (object.name.startsWith('workFace')) {
  411. setModalCenter(object);
  412. }
  413. });
  414. this.group.name = this.modelName;
  415. this.addLight();
  416. resolve(null);
  417. });
  418. });
  419. }
  420. destroy() {
  421. this.model.clearGroup(this.group);
  422. this.model = null;
  423. this.group = null;
  424. this.bloomComposer?.dispose();
  425. this.finalComposer?.dispose();
  426. }
  427. }
  428. export default GasAssessmen;