scene.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. import * as THREE from "three";
  2. import { CSS2DRenderer, CSS2DObject } from "CSS2DRenderer";
  3. import { CSS3DRenderer, CSS3DObject } from "CSS3DRenderer";
  4. import { DragControls } from "DragControls";
  5. import { OrbitControls } from "OrbitControls";
  6. import { STLLoader } from "STLLoader";
  7. import { GLTFLoader } from "GLTFLoader";
  8. function texture_geometry(coords) {
  9. const geometry = new THREE.BufferGeometry();
  10. const nI = coords[0].length;
  11. const nJ = coords.length;
  12. const vertices = [];
  13. const indices = [];
  14. const uvs = [];
  15. for (let j = 0; j < nJ; ++j) {
  16. for (let i = 0; i < nI; ++i) {
  17. const XYZ = coords[j][i] || [0, 0, 0];
  18. vertices.push(...XYZ);
  19. uvs.push(i / (nI - 1), j / (nJ - 1));
  20. }
  21. }
  22. for (let j = 0; j < nJ - 1; ++j) {
  23. for (let i = 0; i < nI - 1; ++i) {
  24. if (coords[j][i] && coords[j][i + 1] && coords[j + 1][i] && coords[j + 1][i + 1]) {
  25. const idx00 = i + j * nI;
  26. const idx10 = i + j * nI + 1;
  27. const idx01 = i + j * nI + nI;
  28. const idx11 = i + j * nI + 1 + nI;
  29. indices.push(idx10, idx00, idx01);
  30. indices.push(idx11, idx10, idx01);
  31. }
  32. }
  33. }
  34. geometry.setIndex(new THREE.Uint32BufferAttribute(indices, 1));
  35. geometry.setAttribute("position", new THREE.Float32BufferAttribute(vertices, 3));
  36. geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
  37. geometry.computeVertexNormals();
  38. return geometry;
  39. }
  40. function texture_material(texture) {
  41. texture.flipY = false;
  42. texture.minFilter = THREE.LinearFilter;
  43. return new THREE.MeshLambertMaterial({
  44. map: texture,
  45. side: THREE.DoubleSide,
  46. transparent: true,
  47. });
  48. }
  49. export default {
  50. template: `
  51. <div style="position:relative">
  52. <canvas style="position:relative"></canvas>
  53. <div style="position:absolute;pointer-events:none;top:0"></div>
  54. <div style="position:absolute;pointer-events:none;top:0"></div>
  55. </div>`,
  56. mounted() {
  57. this.scene = new THREE.Scene();
  58. this.objects = new Map();
  59. this.objects.set("scene", this.scene);
  60. this.draggable_objects = [];
  61. window["scene_" + this.$el.id] = this.scene; // NOTE: for selenium tests only
  62. if (this.camera_type === "perspective") {
  63. this.camera = new THREE.PerspectiveCamera(
  64. this.camera_params.fov,
  65. this.width / this.height,
  66. this.camera_params.near,
  67. this.camera_params.far
  68. );
  69. } else {
  70. this.camera = new THREE.OrthographicCamera(
  71. (-this.camera_params.size / 2) * (this.width / this.height),
  72. (this.camera_params.size / 2) * (this.width / this.height),
  73. this.camera_params.size / 2,
  74. -this.camera_params.size / 2,
  75. this.camera_params.near,
  76. this.camera_params.far
  77. );
  78. }
  79. this.look_at = new THREE.Vector3(0, 0, 0);
  80. this.camera.lookAt(this.look_at);
  81. this.camera.up = new THREE.Vector3(0, 0, 1);
  82. this.camera.position.set(0, -3, 5);
  83. this.scene.add(new THREE.AmbientLight(0xffffff, 0.7 * Math.PI));
  84. const light = new THREE.DirectionalLight(0xffffff, 0.3 * Math.PI);
  85. light.position.set(5, 10, 40);
  86. this.scene.add(light);
  87. this.renderer = undefined;
  88. try {
  89. this.renderer = new THREE.WebGLRenderer({
  90. antialias: true,
  91. alpha: true,
  92. canvas: this.$el.children[0],
  93. });
  94. } catch {
  95. this.$el.innerHTML = "Could not create WebGL renderer.";
  96. this.$el.style.width = this.width + "px";
  97. this.$el.style.height = this.height + "px";
  98. this.$el.style.padding = "10px";
  99. this.$el.style.border = "1px solid silver";
  100. return;
  101. }
  102. this.renderer.setClearColor(this.background_color);
  103. this.renderer.setSize(this.width, this.height);
  104. this.text_renderer = new CSS2DRenderer({
  105. element: this.$el.children[1],
  106. });
  107. this.text_renderer.setSize(this.width, this.height);
  108. this.text3d_renderer = new CSS3DRenderer({
  109. element: this.$el.children[2],
  110. });
  111. this.text3d_renderer.setSize(this.width, this.height);
  112. this.$nextTick(() => this.resize());
  113. window.addEventListener("resize", this.resize, false);
  114. const gridSize = this.grid[0] || 100;
  115. const gridDivisions = this.grid[1] || 100;
  116. if (this.grid) {
  117. const ground = new THREE.Mesh(
  118. new THREE.PlaneGeometry(gridSize, gridSize),
  119. new THREE.MeshPhongMaterial({ color: this.background_color })
  120. );
  121. ground.translateZ(-0.01);
  122. ground.object_id = "ground";
  123. this.scene.add(ground);
  124. const grid = new THREE.GridHelper(gridSize, gridDivisions);
  125. grid.material.transparent = true;
  126. grid.material.opacity = 0.2;
  127. grid.rotateX(Math.PI / 2);
  128. this.scene.add(grid);
  129. }
  130. this.controls = new OrbitControls(this.camera, this.renderer.domElement);
  131. this.drag_controls = new DragControls(this.draggable_objects, this.camera, this.renderer.domElement);
  132. const applyConstraint = (constraint, position) => {
  133. if (!constraint) return;
  134. const [variable, expression] = constraint.split("=").map((s) => s.trim());
  135. position[variable] = eval(expression.replace(/x|y|z/g, (match) => `(${position[match]})`));
  136. };
  137. const handleDrag = (event) => {
  138. this.drag_constraints.split(",").forEach((constraint) => applyConstraint(constraint, event.object.position));
  139. this.$emit(event.type, {
  140. type: event.type,
  141. object_id: event.object.object_id,
  142. object_name: event.object.name,
  143. x: event.object.position.x,
  144. y: event.object.position.y,
  145. z: event.object.position.z,
  146. });
  147. if (event.type === "dragstart") this.controls.enabled = false;
  148. if (event.type === "dragend") this.controls.enabled = true;
  149. };
  150. this.drag_controls.addEventListener("dragstart", handleDrag);
  151. this.drag_controls.addEventListener("drag", handleDrag);
  152. this.drag_controls.addEventListener("dragend", handleDrag);
  153. const render = () => {
  154. requestAnimationFrame(() => setTimeout(() => render(), 1000 / 20));
  155. TWEEN.update();
  156. this.renderer.render(this.scene, this.camera);
  157. this.text_renderer.render(this.scene, this.camera);
  158. this.text3d_renderer.render(this.scene, this.camera);
  159. };
  160. render();
  161. const raycaster = new THREE.Raycaster();
  162. const click_handler = (mouseEvent) => {
  163. let x = (mouseEvent.offsetX / this.renderer.domElement.width) * 2 - 1;
  164. let y = -(mouseEvent.offsetY / this.renderer.domElement.height) * 2 + 1;
  165. raycaster.setFromCamera({ x: x, y: y }, this.camera);
  166. this.$emit("click3d", {
  167. hits: raycaster
  168. .intersectObjects(this.scene.children, true)
  169. .filter((o) => o.object.object_id)
  170. .map((o) => ({
  171. object_id: o.object.object_id,
  172. object_name: o.object.name,
  173. point: o.point,
  174. })),
  175. click_type: mouseEvent.type,
  176. button: mouseEvent.button,
  177. alt_key: mouseEvent.altKey,
  178. ctrl_key: mouseEvent.ctrlKey,
  179. meta_key: mouseEvent.metaKey,
  180. shift_key: mouseEvent.shiftKey,
  181. });
  182. };
  183. this.click_events.forEach((event) => this.$el.addEventListener(event, click_handler));
  184. this.texture_loader = new THREE.TextureLoader();
  185. this.stl_loader = new STLLoader();
  186. this.gltf_loader = new GLTFLoader();
  187. const connectInterval = setInterval(() => {
  188. if (window.socket.id === undefined) return;
  189. this.$emit("init", { socket_id: window.socket.id });
  190. clearInterval(connectInterval);
  191. }, 100);
  192. },
  193. beforeDestroy() {
  194. window.removeEventListener("resize", this.resize);
  195. },
  196. methods: {
  197. create(type, id, parent_id, ...args) {
  198. let mesh;
  199. if (type == "group") {
  200. mesh = new THREE.Group();
  201. } else if (type == "line") {
  202. const start = new THREE.Vector3(...args[0]);
  203. const end = new THREE.Vector3(...args[1]);
  204. const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
  205. const material = new THREE.LineBasicMaterial({ transparent: true });
  206. mesh = new THREE.Line(geometry, material);
  207. } else if (type == "curve") {
  208. const curve = new THREE.CubicBezierCurve3(
  209. new THREE.Vector3(...args[0]),
  210. new THREE.Vector3(...args[1]),
  211. new THREE.Vector3(...args[2]),
  212. new THREE.Vector3(...args[3])
  213. );
  214. const points = curve.getPoints(args[4] - 1);
  215. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  216. const material = new THREE.LineBasicMaterial({ transparent: true });
  217. mesh = new THREE.Line(geometry, material);
  218. } else if (type == "text") {
  219. const div = document.createElement("div");
  220. div.textContent = args[0];
  221. div.style.cssText = args[1];
  222. mesh = new CSS2DObject(div);
  223. } else if (type == "text3d") {
  224. const div = document.createElement("div");
  225. div.textContent = args[0];
  226. div.style.cssText = "userSelect:none;" + args[1];
  227. mesh = new CSS3DObject(div);
  228. } else if (type == "texture") {
  229. const url = args[0];
  230. const coords = args[1];
  231. const geometry = texture_geometry(coords);
  232. const material = texture_material(this.texture_loader.load(url));
  233. mesh = new THREE.Mesh(geometry, material);
  234. } else if (type == "spot_light") {
  235. mesh = new THREE.Group();
  236. const light = new THREE.SpotLight(...args);
  237. light.position.set(0, 0, 0);
  238. light.target = new THREE.Object3D();
  239. light.target.position.set(1, 0, 0);
  240. mesh.add(light);
  241. mesh.add(light.target);
  242. } else if (type == "point_cloud") {
  243. const geometry = new THREE.BufferGeometry();
  244. geometry.setAttribute("position", new THREE.Float32BufferAttribute(args[0].flat(), 3));
  245. geometry.setAttribute("color", new THREE.Float32BufferAttribute(args[1].flat(), 3));
  246. const material = new THREE.PointsMaterial({ size: args[2], vertexColors: true });
  247. mesh = new THREE.Points(geometry, material);
  248. } else if (type == "gltf") {
  249. const url = args[0];
  250. mesh = new THREE.Group();
  251. this.gltf_loader.load(
  252. url,
  253. (gltf) => mesh.add(gltf.scene),
  254. undefined,
  255. (error) => console.error(error)
  256. );
  257. } else {
  258. let geometry;
  259. const wireframe = args.pop();
  260. if (type == "box") geometry = new THREE.BoxGeometry(...args);
  261. if (type == "sphere") geometry = new THREE.SphereGeometry(...args);
  262. if (type == "cylinder") geometry = new THREE.CylinderGeometry(...args);
  263. if (type == "ring") geometry = new THREE.RingGeometry(...args);
  264. if (type == "quadratic_bezier_tube") {
  265. const curve = new THREE.QuadraticBezierCurve3(
  266. new THREE.Vector3(...args[0]),
  267. new THREE.Vector3(...args[1]),
  268. new THREE.Vector3(...args[2])
  269. );
  270. geometry = new THREE.TubeGeometry(curve, ...args.slice(3));
  271. }
  272. if (type == "extrusion") {
  273. const shape = new THREE.Shape();
  274. const outline = args[0];
  275. const height = args[1];
  276. shape.autoClose = true;
  277. if (outline.length) {
  278. shape.moveTo(outline[0][0], outline[0][1]);
  279. outline.slice(1).forEach((p) => shape.lineTo(p[0], p[1]));
  280. }
  281. const settings = { depth: height, bevelEnabled: false };
  282. geometry = new THREE.ExtrudeGeometry(shape, settings);
  283. }
  284. if (type == "stl") {
  285. const url = args[0];
  286. geometry = new THREE.BufferGeometry();
  287. this.stl_loader.load(url, (geometry) => (mesh.geometry = geometry));
  288. }
  289. let material;
  290. if (wireframe) {
  291. mesh = new THREE.LineSegments(
  292. new THREE.EdgesGeometry(geometry),
  293. new THREE.LineBasicMaterial({ transparent: true })
  294. );
  295. } else {
  296. material = new THREE.MeshPhongMaterial({ transparent: true });
  297. mesh = new THREE.Mesh(geometry, material);
  298. }
  299. }
  300. mesh.object_id = id;
  301. this.objects.set(id, mesh);
  302. this.objects.get(parent_id).add(this.objects.get(id));
  303. },
  304. name(object_id, name) {
  305. if (!this.objects.has(object_id)) return;
  306. this.objects.get(object_id).name = name;
  307. },
  308. material(object_id, color, opacity, side) {
  309. if (!this.objects.has(object_id)) return;
  310. const material = this.objects.get(object_id).material;
  311. if (!material) return;
  312. material.color.set(color);
  313. material.opacity = opacity;
  314. if (side == "front") material.side = THREE.FrontSide;
  315. else if (side == "back") material.side = THREE.BackSide;
  316. else material.side = THREE.DoubleSide;
  317. },
  318. move(object_id, x, y, z) {
  319. if (!this.objects.has(object_id)) return;
  320. this.objects.get(object_id).position.set(x, y, z);
  321. },
  322. scale(object_id, sx, sy, sz) {
  323. if (!this.objects.has(object_id)) return;
  324. this.objects.get(object_id).scale.set(sx, sy, sz);
  325. },
  326. rotate(object_id, R) {
  327. if (!this.objects.has(object_id)) return;
  328. const R4 = new THREE.Matrix4().makeBasis(
  329. new THREE.Vector3(...R[0]),
  330. new THREE.Vector3(...R[1]),
  331. new THREE.Vector3(...R[2])
  332. );
  333. this.objects.get(object_id).rotation.setFromRotationMatrix(R4.transpose());
  334. },
  335. visible(object_id, value) {
  336. if (!this.objects.has(object_id)) return;
  337. this.objects.get(object_id).visible = value;
  338. },
  339. draggable(object_id, value) {
  340. if (!this.objects.has(object_id)) return;
  341. const object = this.objects.get(object_id);
  342. if (value) this.draggable_objects.push(object);
  343. else {
  344. const index = this.draggable_objects.indexOf(object);
  345. if (index != -1) this.draggable_objects.splice(index, 1);
  346. }
  347. },
  348. delete(object_id) {
  349. if (!this.objects.has(object_id)) return;
  350. const object = this.objects.get(object_id);
  351. object.removeFromParent();
  352. this.objects.delete(object_id);
  353. const index = this.draggable_objects.indexOf(object);
  354. if (index != -1) this.draggable_objects.splice(index, 1);
  355. },
  356. set_texture_url(object_id, url) {
  357. if (!this.objects.has(object_id)) return;
  358. const obj = this.objects.get(object_id);
  359. if (obj.busy) return;
  360. obj.busy = true;
  361. const on_success = (texture) => {
  362. obj.material = texture_material(texture);
  363. obj.busy = false;
  364. };
  365. const on_error = () => (obj.busy = false);
  366. this.texture_loader.load(url, on_success, undefined, on_error);
  367. },
  368. set_texture_coordinates(object_id, coords) {
  369. if (!this.objects.has(object_id)) return;
  370. this.objects.get(object_id).geometry = texture_geometry(coords);
  371. },
  372. move_camera(x, y, z, look_at_x, look_at_y, look_at_z, up_x, up_y, up_z, duration) {
  373. if (this.camera_tween) this.camera_tween.stop();
  374. this.camera_tween = new TWEEN.Tween([
  375. this.camera.position.x,
  376. this.camera.position.y,
  377. this.camera.position.z,
  378. this.camera.up.x,
  379. this.camera.up.y,
  380. this.camera.up.z,
  381. this.look_at.x,
  382. this.look_at.y,
  383. this.look_at.z,
  384. ])
  385. .to(
  386. [
  387. x === null ? this.camera.position.x : x,
  388. y === null ? this.camera.position.y : y,
  389. z === null ? this.camera.position.z : z,
  390. up_x === null ? this.camera.up.x : up_x,
  391. up_y === null ? this.camera.up.y : up_y,
  392. up_z === null ? this.camera.up.z : up_z,
  393. look_at_x === null ? this.look_at.x : look_at_x,
  394. look_at_y === null ? this.look_at.y : look_at_y,
  395. look_at_z === null ? this.look_at.z : look_at_z,
  396. ],
  397. duration * 1000
  398. )
  399. .onUpdate((p) => {
  400. this.camera.position.set(p[0], p[1], p[2]);
  401. this.camera.up.set(p[3], p[4], p[5]); // NOTE: before calling lookAt
  402. this.look_at.set(p[6], p[7], p[8]);
  403. this.camera.lookAt(p[6], p[7], p[8]);
  404. this.controls.target.set(p[6], p[7], p[8]);
  405. })
  406. .start();
  407. },
  408. get_camera() {
  409. return {
  410. position: this.camera.position,
  411. up: this.camera.up,
  412. rotation: this.camera.rotation,
  413. quaternion: this.camera.quaternion,
  414. type: this.camera.type,
  415. fov: this.camera.fov,
  416. aspect: this.camera.aspect,
  417. near: this.camera.near,
  418. far: this.camera.far,
  419. left: this.camera.left,
  420. right: this.camera.right,
  421. top: this.camera.top,
  422. bottom: this.camera.bottom,
  423. };
  424. },
  425. resize() {
  426. const { clientWidth, clientHeight } = this.$el;
  427. this.renderer.setSize(clientWidth, clientHeight);
  428. this.text_renderer.setSize(clientWidth, clientHeight);
  429. this.text3d_renderer.setSize(clientWidth, clientHeight);
  430. this.camera.aspect = clientWidth / clientHeight;
  431. if (this.camera_type === "orthographic") {
  432. this.camera.left = (-this.camera.aspect * this.camera_params.size) / 2;
  433. this.camera.right = (this.camera.aspect * this.camera_params.size) / 2;
  434. }
  435. this.camera.updateProjectionMatrix();
  436. },
  437. init_objects(data) {
  438. for (const [
  439. type,
  440. id,
  441. parent_id,
  442. args,
  443. name,
  444. color,
  445. opacity,
  446. side,
  447. x,
  448. y,
  449. z,
  450. R,
  451. sx,
  452. sy,
  453. sz,
  454. visible,
  455. draggable,
  456. ] of data) {
  457. this.create(type, id, parent_id, ...args);
  458. this.name(id, name);
  459. this.material(id, color, opacity, side);
  460. this.move(id, x, y, z);
  461. this.rotate(id, R);
  462. this.scale(id, sx, sy, sz);
  463. this.visible(id, visible);
  464. this.draggable(id, draggable);
  465. }
  466. },
  467. },
  468. props: {
  469. width: Number,
  470. height: Number,
  471. grid: Object,
  472. camera_type: String,
  473. camera_params: Object,
  474. click_events: Array,
  475. drag_constraints: String,
  476. background_color: String,
  477. },
  478. };