scene.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import * as THREE from "three";
  2. import { CSS2DRenderer } from "CSS2DRenderer";
  3. import { CSS3DRenderer } from "CSS3DRenderer";
  4. import { OrbitControls } from "OrbitControls";
  5. import { STLLoader } from "STLLoader";
  6. function texture_geometry(coords) {
  7. const geometry = new THREE.BufferGeometry();
  8. const nI = coords[0].length;
  9. const nJ = coords.length;
  10. const vertices = [];
  11. const indices = [];
  12. const uvs = [];
  13. for (let j = 0; j < nJ; ++j) {
  14. for (let i = 0; i < nI; ++i) {
  15. const XYZ = coords[j][i] || [0, 0, 0];
  16. vertices.push(...XYZ);
  17. uvs.push(i / (nI - 1), j / (nJ - 1));
  18. }
  19. }
  20. for (let j = 0; j < nJ - 1; ++j) {
  21. for (let i = 0; i < nI - 1; ++i) {
  22. if (coords[j][i] && coords[j][i + 1] && coords[j + 1][i] && coords[j + 1][i + 1]) {
  23. const idx00 = i + j * nI;
  24. const idx10 = i + j * nI + 1;
  25. const idx01 = i + j * nI + nI;
  26. const idx11 = i + j * nI + 1 + nI;
  27. indices.push(idx10, idx00, idx01);
  28. indices.push(idx11, idx10, idx01);
  29. }
  30. }
  31. }
  32. geometry.setIndex(new THREE.Uint32BufferAttribute(indices, 1));
  33. geometry.setAttribute("position", new THREE.Float32BufferAttribute(vertices, 3));
  34. geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
  35. geometry.computeVertexNormals();
  36. return geometry;
  37. }
  38. function texture_material(texture) {
  39. texture.flipY = false;
  40. texture.minFilter = THREE.LinearFilter;
  41. return new THREE.MeshLambertMaterial({
  42. map: texture,
  43. side: THREE.DoubleSide,
  44. transparent: true,
  45. });
  46. }
  47. export default {
  48. template: `
  49. <div style="position:relative">
  50. <canvas style="position:relative"></canvas>
  51. <div style="position:absolute;pointer-events:none;top:0"></div>
  52. <div style="position:absolute;pointer-events:none;top:0"></div>
  53. </div>`,
  54. mounted() {
  55. this.scene = new THREE.Scene();
  56. this.objects = new Map();
  57. this.objects.set("scene", this.scene);
  58. window["scene_" + this.$el.id] = this.scene; // NOTE: for selenium tests only
  59. this.look_at = new THREE.Vector3(0, 0, 0);
  60. this.camera = new THREE.PerspectiveCamera(75, this.width / this.height, 0.1, 1000);
  61. this.camera.lookAt(this.look_at);
  62. this.camera.up = new THREE.Vector3(0, 0, 1);
  63. this.camera.position.set(0, -3, 5);
  64. this.scene.add(new THREE.AmbientLight(0xffffff, 0.7));
  65. const light = new THREE.DirectionalLight(0xffffff, 0.3);
  66. light.position.set(5, 10, 40);
  67. this.scene.add(light);
  68. let renderer = undefined;
  69. try {
  70. renderer = new THREE.WebGLRenderer({
  71. antialias: true,
  72. alpha: true,
  73. canvas: this.$el.children[0],
  74. });
  75. } catch {
  76. this.$el.innerHTML = "Could not create WebGL renderer.";
  77. this.$el.style.width = this.width + "px";
  78. this.$el.style.height = this.height + "px";
  79. this.$el.style.padding = "10px";
  80. this.$el.style.border = "1px solid silver";
  81. return;
  82. }
  83. renderer.setClearColor("#eee");
  84. renderer.setSize(this.width, this.height);
  85. const text_renderer = new CSS2DRenderer({
  86. element: this.$el.children[1],
  87. });
  88. text_renderer.setSize(this.width, this.height);
  89. const text3d_renderer = new CSS3DRenderer({
  90. element: this.$el.children[2],
  91. });
  92. text3d_renderer.setSize(this.width, this.height);
  93. if (this.grid) {
  94. const ground = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshPhongMaterial({ color: "#eee" }));
  95. ground.translateZ(-0.01);
  96. ground.object_id = "ground";
  97. this.scene.add(ground);
  98. const grid = new THREE.GridHelper(100, 100);
  99. grid.material.transparent = true;
  100. grid.material.opacity = 0.2;
  101. grid.rotateX(Math.PI / 2);
  102. this.scene.add(grid);
  103. }
  104. this.controls = new OrbitControls(this.camera, renderer.domElement);
  105. const render = () => {
  106. requestAnimationFrame(() => setTimeout(() => render(), 1000 / 20));
  107. TWEEN.update();
  108. renderer.render(this.scene, this.camera);
  109. text_renderer.render(this.scene, this.camera);
  110. text3d_renderer.render(this.scene, this.camera);
  111. };
  112. render();
  113. const raycaster = new THREE.Raycaster();
  114. const click_handler = (mouseEvent) => {
  115. let x = (mouseEvent.offsetX / renderer.domElement.width) * 2 - 1;
  116. let y = -(mouseEvent.offsetY / renderer.domElement.height) * 2 + 1;
  117. raycaster.setFromCamera({ x: x, y: y }, this.camera);
  118. this.$emit("click3d", {
  119. hits: raycaster
  120. .intersectObjects(this.scene.children, true)
  121. .filter((o) => o.object.object_id)
  122. .map((o) => ({
  123. object_id: o.object.object_id,
  124. object_name: o.object.name,
  125. point: o.point,
  126. })),
  127. click_type: mouseEvent.type,
  128. button: mouseEvent.button,
  129. alt_key: mouseEvent.altKey,
  130. ctrl_key: mouseEvent.ctrlKey,
  131. meta_key: mouseEvent.metaKey,
  132. shift_key: mouseEvent.shiftKey,
  133. });
  134. };
  135. this.$el.onclick = click_handler;
  136. this.$el.ondblclick = click_handler;
  137. this.texture_loader = new THREE.TextureLoader();
  138. this.stl_loader = new STLLoader();
  139. const connectInterval = setInterval(async () => {
  140. if (window.socket.id === undefined) return;
  141. this.$emit("init", window.socket.id);
  142. clearInterval(connectInterval);
  143. }, 100);
  144. },
  145. methods: {
  146. create(type, id, parent_id, ...args) {
  147. let mesh;
  148. if (type == "group") {
  149. mesh = new THREE.Group();
  150. } else if (type == "line") {
  151. const start = new THREE.Vector3(...args[0]);
  152. const end = new THREE.Vector3(...args[1]);
  153. const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
  154. const material = new THREE.LineBasicMaterial({ transparent: true });
  155. mesh = new THREE.Line(geometry, material);
  156. } else if (type == "curve") {
  157. const curve = new THREE.CubicBezierCurve3(
  158. new THREE.Vector3(...args[0]),
  159. new THREE.Vector3(...args[1]),
  160. new THREE.Vector3(...args[2]),
  161. new THREE.Vector3(...args[3])
  162. );
  163. const points = curve.getPoints(args[4] - 1);
  164. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  165. const material = new THREE.LineBasicMaterial({ transparent: true });
  166. mesh = new THREE.Line(geometry, material);
  167. } else if (type == "text") {
  168. const div = document.createElement("div");
  169. div.textContent = args[0];
  170. div.style.cssText = args[1];
  171. mesh = new THREE.CSS2DObject(div);
  172. } else if (type == "text3d") {
  173. const div = document.createElement("div");
  174. div.textContent = args[0];
  175. div.style.cssText = "userSelect:none;" + args[1];
  176. mesh = new THREE.CSS3DObject(div);
  177. } else if (type == "texture") {
  178. const url = args[0];
  179. const coords = args[1];
  180. const geometry = texture_geometry(coords);
  181. const material = texture_material(this.texture_loader.load(url));
  182. mesh = new THREE.Mesh(geometry, material);
  183. } else if (type == "spot_light") {
  184. mesh = new THREE.Group();
  185. const light = new THREE.SpotLight(...args);
  186. light.position.set(0, 0, 0);
  187. light.target = new THREE.Object3D();
  188. light.target.position.set(1, 0, 0);
  189. mesh.add(light);
  190. mesh.add(light.target);
  191. } else if (type == "point_cloud") {
  192. const geometry = new THREE.BufferGeometry();
  193. geometry.setAttribute("position", new THREE.Float32BufferAttribute(args[0].flat(), 3));
  194. geometry.setAttribute("color", new THREE.Float32BufferAttribute(args[1].flat(), 3));
  195. const material = new THREE.PointsMaterial({ size: args[2], vertexColors: true });
  196. mesh = new THREE.Points(geometry, material);
  197. } else {
  198. let geometry;
  199. const wireframe = args.pop();
  200. if (type == "box") geometry = new THREE.BoxGeometry(...args);
  201. if (type == "sphere") geometry = new THREE.SphereGeometry(...args);
  202. if (type == "cylinder") geometry = new THREE.CylinderGeometry(...args);
  203. if (type == "ring") geometry = new THREE.RingGeometry(...args);
  204. if (type == "quadratic_bezier_tube") {
  205. const curve = new THREE.QuadraticBezierCurve3(
  206. new THREE.Vector3(...args[0]),
  207. new THREE.Vector3(...args[1]),
  208. new THREE.Vector3(...args[2])
  209. );
  210. geometry = new THREE.TubeGeometry(curve, ...args.slice(3));
  211. }
  212. if (type == "extrusion") {
  213. const shape = new THREE.Shape();
  214. const outline = args[0];
  215. const height = args[1];
  216. shape.autoClose = true;
  217. if (outline.length) {
  218. shape.moveTo(outline[0][0], outline[0][1]);
  219. outline.slice(1).forEach((p) => shape.lineTo(p[0], p[1]));
  220. }
  221. const settings = { depth: height, bevelEnabled: false };
  222. geometry = new THREE.ExtrudeGeometry(shape, settings);
  223. }
  224. if (type == "stl") {
  225. const url = args[0];
  226. geometry = new THREE.BufferGeometry();
  227. this.stl_loader.load(url, (geometry) => (mesh.geometry = geometry));
  228. }
  229. let material;
  230. if (wireframe) {
  231. mesh = new THREE.LineSegments(
  232. new THREE.EdgesGeometry(geometry),
  233. new THREE.LineBasicMaterial({ transparent: true })
  234. );
  235. } else {
  236. material = new THREE.MeshPhongMaterial({ transparent: true });
  237. mesh = new THREE.Mesh(geometry, material);
  238. }
  239. }
  240. mesh.object_id = id;
  241. this.objects.set(id, mesh);
  242. this.objects.get(parent_id).add(this.objects.get(id));
  243. },
  244. name(object_id, name) {
  245. if (!this.objects.has(object_id)) return;
  246. this.objects.get(object_id).name = name;
  247. },
  248. material(object_id, color, opacity, side) {
  249. if (!this.objects.has(object_id)) return;
  250. const material = this.objects.get(object_id).material;
  251. if (!material) return;
  252. material.color.set(color);
  253. material.opacity = opacity;
  254. if (side == "front") material.side = THREE.FrontSide;
  255. else if (side == "back") material.side = THREE.BackSide;
  256. else material.side = THREE.DoubleSide;
  257. },
  258. move(object_id, x, y, z) {
  259. if (!this.objects.has(object_id)) return;
  260. this.objects.get(object_id).position.set(x, y, z);
  261. },
  262. scale(object_id, sx, sy, sz) {
  263. if (!this.objects.has(object_id)) return;
  264. this.objects.get(object_id).scale.set(sx, sy, sz);
  265. },
  266. rotate(object_id, R) {
  267. if (!this.objects.has(object_id)) return;
  268. const R4 = new THREE.Matrix4().makeBasis(
  269. new THREE.Vector3(...R[0]),
  270. new THREE.Vector3(...R[1]),
  271. new THREE.Vector3(...R[2])
  272. );
  273. this.objects.get(object_id).rotation.setFromRotationMatrix(R4.transpose());
  274. },
  275. visible(object_id, value) {
  276. if (!this.objects.has(object_id)) return;
  277. this.objects.get(object_id).visible = value;
  278. },
  279. delete(object_id) {
  280. if (!this.objects.has(object_id)) return;
  281. this.objects.get(object_id).removeFromParent();
  282. this.objects.delete(object_id);
  283. },
  284. set_texture_url(object_id, url) {
  285. if (!this.objects.has(object_id)) return;
  286. const obj = this.objects.get(object_id);
  287. if (obj.busy) return;
  288. obj.busy = true;
  289. const on_success = (texture) => {
  290. obj.material = texture_material(texture);
  291. obj.busy = false;
  292. };
  293. const on_error = () => (obj.busy = false);
  294. this.texture_loader.load(url, on_success, undefined, on_error);
  295. },
  296. set_texture_coordinates(object_id, coords) {
  297. if (!this.objects.has(object_id)) return;
  298. this.objects.get(object_id).geometry = texture_geometry(coords);
  299. },
  300. move_camera(x, y, z, look_at_x, look_at_y, look_at_z, up_x, up_y, up_z, duration) {
  301. if (this.camera_tween) this.camera_tween.stop();
  302. this.camera_tween = new TWEEN.Tween([
  303. this.camera.position.x,
  304. this.camera.position.y,
  305. this.camera.position.z,
  306. this.camera.up.x,
  307. this.camera.up.y,
  308. this.camera.up.z,
  309. this.look_at.x,
  310. this.look_at.y,
  311. this.look_at.z,
  312. ])
  313. .to(
  314. [
  315. x === null ? this.camera.position.x : x,
  316. y === null ? this.camera.position.y : y,
  317. z === null ? this.camera.position.z : z,
  318. up_x === null ? this.camera.up.x : up_x,
  319. up_y === null ? this.camera.up.y : up_y,
  320. up_z === null ? this.camera.up.z : up_z,
  321. look_at_x === null ? this.look_at.x : look_at_x,
  322. look_at_y === null ? this.look_at.y : look_at_y,
  323. look_at_z === null ? this.look_at.z : look_at_z,
  324. ],
  325. duration * 1000
  326. )
  327. .onUpdate((p) => {
  328. this.camera.position.set(p[0], p[1], p[2]);
  329. this.camera.up.set(p[3], p[4], p[5]); // NOTE: before calling lookAt
  330. this.look_at.set(p[6], p[7], p[8]);
  331. this.camera.lookAt(p[6], p[7], p[8]);
  332. this.controls.target.set(p[6], p[7], p[8]);
  333. })
  334. .start();
  335. },
  336. },
  337. props: {
  338. width: Number,
  339. height: Number,
  340. grid: Boolean,
  341. },
  342. };