space-scene.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. export class space_scene {
  2. #manager;
  3. #renderer;
  4. #camera;
  5. #scene;
  6. #working;
  7. #framerate;
  8. constructor(manager) {
  9. this.#manager = manager;
  10. const canvas = manager.canvas;
  11. const context = manager.context;
  12. this.#framerate = 60;
  13. this.#renderer = new THREE.WebGLRenderer({canvas, context: context});
  14. this.#camera = new THREE.PerspectiveCamera(75, 1);
  15. this.#scene = new THREE.Scene();
  16. this.set_room();
  17. this.update_size();
  18. this.manager.mouse.add_listener((move) => this.#camera_rotate(move));
  19. }
  20. get manager() {
  21. return this.#manager;
  22. }
  23. get #canvas() {
  24. return this.manager.canvas;
  25. }
  26. update_size(width, height) {
  27. this.#canvas.width = width;
  28. this.#canvas.height = height;
  29. this.#camera.aspect = width / height;
  30. this.#camera.updateProjectionMatrix();
  31. this.#renderer.setSize(width, height);
  32. }
  33. get scene() {
  34. return this.#scene;
  35. }
  36. start() {
  37. this.#working = true;
  38. setTimeout(() => { this.#rendering(); }, 1);
  39. }
  40. stop() {
  41. this.#working = false;
  42. }
  43. set_room() {
  44. const url = this.manager.loader.texture("example_room.jpg");
  45. const texture = new THREE.TextureLoader().load(url, () => {
  46. texture.mapping = THREE.EquirectangularReflectionMapping;
  47. texture.colorSpace = THREE.SRGBColorSpace;
  48. this.scene.background = texture;
  49. });
  50. }
  51. get camera() {
  52. return this.#camera;
  53. }
  54. #animate() {
  55. }
  56. get maximum_rotation() {
  57. return Math.PI / 3;
  58. }
  59. #camera_rotate(move) {
  60. this.camera.rotation.reorder("YXZ");
  61. this.camera.rotation.x -= move.y / 100;
  62. this.camera.rotation.y -= move.x / 100;
  63. if (this.camera.rotation.x > this.maximum_rotation) {
  64. this.camera.rotation.x = this.maximum_rotation;
  65. }
  66. if (this.camera.rotation.x < -this.maximum_rotation) {
  67. this.camera.rotation.x = -this.maximum_rotation;
  68. }
  69. }
  70. #rendering() {
  71. const before = performance.now();
  72. this.#animate();
  73. this.#renderer.render(this.#scene, this.#camera);
  74. if (!this.#working) {
  75. return;
  76. }
  77. const after = performance.now();
  78. const delta = after - before;
  79. const next = 1000 / this.#framerate - ((delta >= 0) ? delta : 0);
  80. setTimeout(() => {
  81. requestAnimationFrame(() => { this.#rendering(); });
  82. }, (next > 0) ? next : 1);
  83. }
  84. }