scene.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import * as THREE from "three";
  2. import { CSS2DRenderer, CSS2DObject } from "CSS2DRenderer";
  3. import { CSS3DRenderer, CSS3DObject } 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. this.renderer = undefined;
  69. try {
  70. this.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. this.renderer.setClearColor("#eee");
  84. this.renderer.setSize(this.width, this.height);
  85. this.text_renderer = new CSS2DRenderer({
  86. element: this.$el.children[1],
  87. });
  88. this.text_renderer.setSize(this.width, this.height);
  89. this.text3d_renderer = new CSS3DRenderer({
  90. element: this.$el.children[2],
  91. });
  92. this.text3d_renderer.setSize(this.width, this.height);
  93. this.$nextTick(() => this.resize());
  94. window.addEventListener("resize", this.resize, false);
  95. if (this.grid) {
  96. const ground = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshPhongMaterial({ color: "#eee" }));
  97. ground.translateZ(-0.01);
  98. ground.object_id = "ground";
  99. this.scene.add(ground);
  100. const grid = new THREE.GridHelper(100, 100);
  101. grid.material.transparent = true;
  102. grid.material.opacity = 0.2;
  103. grid.rotateX(Math.PI / 2);
  104. this.scene.add(grid);
  105. }
  106. this.controls = new OrbitControls(this.camera, this.renderer.domElement);
  107. const render = () => {
  108. requestAnimationFrame(() => setTimeout(() => render(), 1000 / 20));
  109. TWEEN.update();
  110. this.renderer.render(this.scene, this.camera);
  111. this.text_renderer.render(this.scene, this.camera);
  112. this.text3d_renderer.render(this.scene, this.camera);
  113. };
  114. render();
  115. const raycaster = new THREE.Raycaster();
  116. const click_handler = (mouseEvent) => {
  117. let x = (mouseEvent.offsetX / this.renderer.domElement.width) * 2 - 1;
  118. let y = -(mouseEvent.offsetY / this.renderer.domElement.height) * 2 + 1;
  119. raycaster.setFromCamera({ x: x, y: y }, this.camera);
  120. this.$emit("click3d", {
  121. hits: raycaster
  122. .intersectObjects(this.scene.children, true)
  123. .filter((o) => o.object.object_id)
  124. .map((o) => ({
  125. object_id: o.object.object_id,
  126. object_name: o.object.name,
  127. point: o.point,
  128. })),
  129. click_type: mouseEvent.type,
  130. button: mouseEvent.button,
  131. alt_key: mouseEvent.altKey,
  132. ctrl_key: mouseEvent.ctrlKey,
  133. meta_key: mouseEvent.metaKey,
  134. shift_key: mouseEvent.shiftKey,
  135. });
  136. };
  137. this.$el.onclick = click_handler;
  138. this.$el.ondblclick = click_handler;
  139. this.texture_loader = new THREE.TextureLoader();
  140. this.stl_loader = new STLLoader();
  141. const connectInterval = setInterval(async () => {
  142. if (window.socket.id === undefined) return;
  143. this.$emit("init", { socket_id: window.socket.id });
  144. clearInterval(connectInterval);
  145. }, 100);
  146. },
  147. beforeDestroy() {
  148. window.removeEventListener("resize", this.resize);
  149. },
  150. methods: {
  151. create(type, id, parent_id, ...args) {
  152. let mesh;
  153. if (type == "group") {
  154. mesh = new THREE.Group();
  155. } else if (type == "line") {
  156. const start = new THREE.Vector3(...args[0]);
  157. const end = new THREE.Vector3(...args[1]);
  158. const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
  159. const material = new THREE.LineBasicMaterial({ transparent: true });
  160. mesh = new THREE.Line(geometry, material);
  161. } else if (type == "curve") {
  162. const curve = new THREE.CubicBezierCurve3(
  163. new THREE.Vector3(...args[0]),
  164. new THREE.Vector3(...args[1]),
  165. new THREE.Vector3(...args[2]),
  166. new THREE.Vector3(...args[3])
  167. );
  168. const points = curve.getPoints(args[4] - 1);
  169. const geometry = new THREE.BufferGeometry().setFromPoints(points);
  170. const material = new THREE.LineBasicMaterial({ transparent: true });
  171. mesh = new THREE.Line(geometry, material);
  172. } else if (type == "text") {
  173. const div = document.createElement("div");
  174. div.textContent = args[0];
  175. div.style.cssText = args[1];
  176. mesh = new CSS2DObject(div);
  177. } else if (type == "text3d") {
  178. const div = document.createElement("div");
  179. div.textContent = args[0];
  180. div.style.cssText = "userSelect:none;" + args[1];
  181. mesh = new CSS3DObject(div);
  182. } else if (type == "texture") {
  183. const url = args[0];
  184. const coords = args[1];
  185. const geometry = texture_geometry(coords);
  186. const material = texture_material(this.texture_loader.load(url));
  187. mesh = new THREE.Mesh(geometry, material);
  188. } else if (type == "spot_light") {
  189. mesh = new THREE.Group();
  190. const light = new THREE.SpotLight(...args);
  191. light.position.set(0, 0, 0);
  192. light.target = new THREE.Object3D();
  193. light.target.position.set(1, 0, 0);
  194. mesh.add(light);
  195. mesh.add(light.target);
  196. } else if (type == "point_cloud") {
  197. const geometry = new THREE.BufferGeometry();
  198. geometry.setAttribute("position", new THREE.Float32BufferAttribute(args[0].flat(), 3));
  199. geometry.setAttribute("color", new THREE.Float32BufferAttribute(args[1].flat(), 3));
  200. const material = new THREE.PointsMaterial({ size: args[2], vertexColors: true });
  201. mesh = new THREE.Points(geometry, material);
  202. } else {
  203. let geometry;
  204. const wireframe = args.pop();
  205. if (type == "box") geometry = new THREE.BoxGeometry(...args);
  206. if (type == "sphere") geometry = new THREE.SphereGeometry(...args);
  207. if (type == "cylinder") geometry = new THREE.CylinderGeometry(...args);
  208. if (type == "ring") geometry = new THREE.RingGeometry(...args);
  209. if (type == "quadratic_bezier_tube") {
  210. const curve = new THREE.QuadraticBezierCurve3(
  211. new THREE.Vector3(...args[0]),
  212. new THREE.Vector3(...args[1]),
  213. new THREE.Vector3(...args[2])
  214. );
  215. geometry = new THREE.TubeGeometry(curve, ...args.slice(3));
  216. }
  217. if (type == "extrusion") {
  218. const shape = new THREE.Shape();
  219. const outline = args[0];
  220. const height = args[1];
  221. shape.autoClose = true;
  222. if (outline.length) {
  223. shape.moveTo(outline[0][0], outline[0][1]);
  224. outline.slice(1).forEach((p) => shape.lineTo(p[0], p[1]));
  225. }
  226. const settings = { depth: height, bevelEnabled: false };
  227. geometry = new THREE.ExtrudeGeometry(shape, settings);
  228. }
  229. if (type == "stl") {
  230. const url = args[0];
  231. geometry = new THREE.BufferGeometry();
  232. this.stl_loader.load(url, (geometry) => (mesh.geometry = geometry));
  233. }
  234. let material;
  235. if (wireframe) {
  236. mesh = new THREE.LineSegments(
  237. new THREE.EdgesGeometry(geometry),
  238. new THREE.LineBasicMaterial({ transparent: true })
  239. );
  240. } else {
  241. material = new THREE.MeshPhongMaterial({ transparent: true });
  242. mesh = new THREE.Mesh(geometry, material);
  243. }
  244. }
  245. mesh.object_id = id;
  246. this.objects.set(id, mesh);
  247. this.objects.get(parent_id).add(this.objects.get(id));
  248. },
  249. name(object_id, name) {
  250. if (!this.objects.has(object_id)) return;
  251. this.objects.get(object_id).name = name;
  252. },
  253. material(object_id, color, opacity, side) {
  254. if (!this.objects.has(object_id)) return;
  255. const material = this.objects.get(object_id).material;
  256. if (!material) return;
  257. material.color.set(color);
  258. material.opacity = opacity;
  259. if (side == "front") material.side = THREE.FrontSide;
  260. else if (side == "back") material.side = THREE.BackSide;
  261. else material.side = THREE.DoubleSide;
  262. },
  263. move(object_id, x, y, z) {
  264. if (!this.objects.has(object_id)) return;
  265. this.objects.get(object_id).position.set(x, y, z);
  266. },
  267. scale(object_id, sx, sy, sz) {
  268. if (!this.objects.has(object_id)) return;
  269. this.objects.get(object_id).scale.set(sx, sy, sz);
  270. },
  271. rotate(object_id, R) {
  272. if (!this.objects.has(object_id)) return;
  273. const R4 = new THREE.Matrix4().makeBasis(
  274. new THREE.Vector3(...R[0]),
  275. new THREE.Vector3(...R[1]),
  276. new THREE.Vector3(...R[2])
  277. );
  278. this.objects.get(object_id).rotation.setFromRotationMatrix(R4.transpose());
  279. },
  280. visible(object_id, value) {
  281. if (!this.objects.has(object_id)) return;
  282. this.objects.get(object_id).visible = value;
  283. },
  284. delete(object_id) {
  285. if (!this.objects.has(object_id)) return;
  286. this.objects.get(object_id).removeFromParent();
  287. this.objects.delete(object_id);
  288. },
  289. set_texture_url(object_id, url) {
  290. if (!this.objects.has(object_id)) return;
  291. const obj = this.objects.get(object_id);
  292. if (obj.busy) return;
  293. obj.busy = true;
  294. const on_success = (texture) => {
  295. obj.material = texture_material(texture);
  296. obj.busy = false;
  297. };
  298. const on_error = () => (obj.busy = false);
  299. this.texture_loader.load(url, on_success, undefined, on_error);
  300. },
  301. set_texture_coordinates(object_id, coords) {
  302. if (!this.objects.has(object_id)) return;
  303. this.objects.get(object_id).geometry = texture_geometry(coords);
  304. },
  305. move_camera(x, y, z, look_at_x, look_at_y, look_at_z, up_x, up_y, up_z, duration) {
  306. if (this.camera_tween) this.camera_tween.stop();
  307. this.camera_tween = new TWEEN.Tween([
  308. this.camera.position.x,
  309. this.camera.position.y,
  310. this.camera.position.z,
  311. this.camera.up.x,
  312. this.camera.up.y,
  313. this.camera.up.z,
  314. this.look_at.x,
  315. this.look_at.y,
  316. this.look_at.z,
  317. ])
  318. .to(
  319. [
  320. x === null ? this.camera.position.x : x,
  321. y === null ? this.camera.position.y : y,
  322. z === null ? this.camera.position.z : z,
  323. up_x === null ? this.camera.up.x : up_x,
  324. up_y === null ? this.camera.up.y : up_y,
  325. up_z === null ? this.camera.up.z : up_z,
  326. look_at_x === null ? this.look_at.x : look_at_x,
  327. look_at_y === null ? this.look_at.y : look_at_y,
  328. look_at_z === null ? this.look_at.z : look_at_z,
  329. ],
  330. duration * 1000
  331. )
  332. .onUpdate((p) => {
  333. this.camera.position.set(p[0], p[1], p[2]);
  334. this.camera.up.set(p[3], p[4], p[5]); // NOTE: before calling lookAt
  335. this.look_at.set(p[6], p[7], p[8]);
  336. this.camera.lookAt(p[6], p[7], p[8]);
  337. this.controls.target.set(p[6], p[7], p[8]);
  338. })
  339. .start();
  340. },
  341. resize() {
  342. const { clientWidth, clientHeight } = this.$el;
  343. this.renderer.setSize(clientWidth, clientHeight);
  344. this.text_renderer.setSize(clientWidth, clientHeight);
  345. this.text3d_renderer.setSize(clientWidth, clientHeight);
  346. this.camera.aspect = clientWidth / clientHeight;
  347. this.camera.updateProjectionMatrix();
  348. },
  349. },
  350. props: {
  351. width: Number,
  352. height: Number,
  353. grid: Boolean,
  354. },
  355. };