angular-three 0.0.7 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (441) hide show
  1. package/esm2020/angular-three.mjs +1 -1
  2. package/esm2020/index.mjs +2 -35
  3. package/esm2020/lib/canvas.mjs +141 -128
  4. package/esm2020/lib/di/catalogue.mjs +7 -0
  5. package/esm2020/lib/directives/args.mjs +37 -17
  6. package/esm2020/lib/directives/repeat.mjs +5 -8
  7. package/esm2020/lib/events.mjs +341 -52
  8. package/esm2020/lib/loader.mjs +55 -0
  9. package/esm2020/lib/loop.mjs +137 -0
  10. package/esm2020/lib/renderer/di.mjs +3 -0
  11. package/esm2020/lib/renderer/enums.mjs +2 -0
  12. package/esm2020/lib/renderer/provider.mjs +19 -0
  13. package/esm2020/lib/renderer/renderer.mjs +293 -0
  14. package/esm2020/lib/renderer/state.mjs +350 -0
  15. package/esm2020/lib/renderer/utils.mjs +177 -0
  16. package/esm2020/lib/stores/rx-store.mjs +99 -0
  17. package/esm2020/lib/stores/store.mjs +190 -239
  18. package/esm2020/lib/types.mjs +1 -1
  19. package/esm2020/lib/utils/apply-props.mjs +37 -80
  20. package/esm2020/lib/utils/attach.mjs +29 -0
  21. package/esm2020/lib/utils/instance.mjs +43 -28
  22. package/esm2020/lib/utils/is.mjs +7 -11
  23. package/esm2020/lib/utils/make.mjs +30 -10
  24. package/esm2020/lib/utils/update.mjs +37 -0
  25. package/esm2020/lib/web/events.mjs +68 -0
  26. package/fesm2015/angular-three.mjs +2053 -2046
  27. package/fesm2015/angular-three.mjs.map +1 -1
  28. package/fesm2020/angular-three.mjs +2003 -1990
  29. package/fesm2020/angular-three.mjs.map +1 -1
  30. package/index.d.ts +1 -34
  31. package/lib/canvas.d.ts +29 -28
  32. package/lib/di/catalogue.d.ts +3 -0
  33. package/lib/directives/args.d.ts +8 -12
  34. package/lib/events.d.ts +7 -2
  35. package/lib/loader.d.ts +15 -0
  36. package/lib/{utils/loop.d.ts → loop.d.ts} +7 -6
  37. package/lib/renderer/di.d.ts +2 -0
  38. package/lib/renderer/enums.d.ts +25 -0
  39. package/lib/renderer/provider.d.ts +25 -0
  40. package/lib/renderer/renderer.d.ts +49 -0
  41. package/lib/renderer/state.d.ts +59 -0
  42. package/lib/renderer/utils.d.ts +20 -0
  43. package/lib/stores/rx-store.d.ts +17 -0
  44. package/lib/stores/store.d.ts +6 -23
  45. package/lib/types.d.ts +182 -191
  46. package/lib/utils/apply-props.d.ts +2 -6
  47. package/lib/utils/attach.d.ts +3 -0
  48. package/lib/utils/instance.d.ts +3 -3
  49. package/lib/utils/is.d.ts +6 -10
  50. package/lib/utils/make.d.ts +5 -2
  51. package/lib/utils/update.d.ts +4 -0
  52. package/lib/web/events.d.ts +4 -0
  53. package/package.json +30 -99
  54. package/attributes/README.md +0 -3
  55. package/attributes/index.d.ts +0 -22
  56. package/attributes/lib/buffer-attribute/buffer-attribute.d.ts +0 -8
  57. package/attributes/lib/color-attribute/color-attribute.d.ts +0 -8
  58. package/attributes/lib/common.d.ts +0 -1
  59. package/attributes/lib/float16-buffer-attribute/float16-buffer-attribute.d.ts +0 -8
  60. package/attributes/lib/float32-buffer-attribute/float32-buffer-attribute.d.ts +0 -8
  61. package/attributes/lib/float64-buffer-attribute/float64-buffer-attribute.d.ts +0 -8
  62. package/attributes/lib/fog-attribute/fog-attribute.d.ts +0 -8
  63. package/attributes/lib/fog-exp2-attribute/fog-exp2-attribute.d.ts +0 -8
  64. package/attributes/lib/instanced-buffer-attribute/instanced-buffer-attribute.d.ts +0 -8
  65. package/attributes/lib/int16-buffer-attribute/int16-buffer-attribute.d.ts +0 -8
  66. package/attributes/lib/int32-buffer-attribute/int32-buffer-attribute.d.ts +0 -8
  67. package/attributes/lib/int8-buffer-attribute/int8-buffer-attribute.d.ts +0 -8
  68. package/attributes/lib/interleaved-buffer-attribute/interleaved-buffer-attribute.d.ts +0 -8
  69. package/attributes/lib/matrix3-attribute/matrix3-attribute.d.ts +0 -8
  70. package/attributes/lib/matrix4-attribute/matrix4-attribute.d.ts +0 -8
  71. package/attributes/lib/uint16-buffer-attribute/uint16-buffer-attribute.d.ts +0 -8
  72. package/attributes/lib/uint32-buffer-attribute/uint32-buffer-attribute.d.ts +0 -8
  73. package/attributes/lib/uint8-buffer-attribute/uint8-buffer-attribute.d.ts +0 -8
  74. package/attributes/lib/uint8-clamped-buffer-attribute/uint8-clamped-buffer-attribute.d.ts +0 -8
  75. package/attributes/lib/value-attribute/value-attribute.d.ts +0 -8
  76. package/attributes/lib/vector2-attribute/vector2-attribute.d.ts +0 -8
  77. package/attributes/lib/vector3-attribute/vector3-attribute.d.ts +0 -8
  78. package/attributes/lib/vector4-attribute/vector4-attribute.d.ts +0 -8
  79. package/audios/README.md +0 -3
  80. package/audios/index.d.ts +0 -3
  81. package/audios/lib/audio/audio.d.ts +0 -49
  82. package/audios/lib/audio-listener/audio-listener.d.ts +0 -35
  83. package/audios/lib/common.d.ts +0 -3
  84. package/audios/lib/positional-audio/positional-audio.d.ts +0 -49
  85. package/cameras/README.md +0 -3
  86. package/cameras/index.d.ts +0 -5
  87. package/cameras/lib/array-camera/array-camera.d.ts +0 -56
  88. package/cameras/lib/common.d.ts +0 -3
  89. package/cameras/lib/cube-camera/cube-camera.d.ts +0 -36
  90. package/cameras/lib/orthographic-camera/orthographic-camera.d.ts +0 -54
  91. package/cameras/lib/perspective-camera/perspective-camera.d.ts +0 -55
  92. package/cameras/lib/stereo-camera/stereo-camera.d.ts +0 -42
  93. package/esm2020/attributes/angular-three-attributes.mjs +0 -5
  94. package/esm2020/attributes/index.mjs +0 -24
  95. package/esm2020/attributes/lib/buffer-attribute/buffer-attribute.mjs +0 -26
  96. package/esm2020/attributes/lib/color-attribute/color-attribute.mjs +0 -26
  97. package/esm2020/attributes/lib/common.mjs +0 -13
  98. package/esm2020/attributes/lib/float16-buffer-attribute/float16-buffer-attribute.mjs +0 -26
  99. package/esm2020/attributes/lib/float32-buffer-attribute/float32-buffer-attribute.mjs +0 -26
  100. package/esm2020/attributes/lib/float64-buffer-attribute/float64-buffer-attribute.mjs +0 -26
  101. package/esm2020/attributes/lib/fog-attribute/fog-attribute.mjs +0 -26
  102. package/esm2020/attributes/lib/fog-exp2-attribute/fog-exp2-attribute.mjs +0 -26
  103. package/esm2020/attributes/lib/instanced-buffer-attribute/instanced-buffer-attribute.mjs +0 -26
  104. package/esm2020/attributes/lib/int16-buffer-attribute/int16-buffer-attribute.mjs +0 -26
  105. package/esm2020/attributes/lib/int32-buffer-attribute/int32-buffer-attribute.mjs +0 -26
  106. package/esm2020/attributes/lib/int8-buffer-attribute/int8-buffer-attribute.mjs +0 -26
  107. package/esm2020/attributes/lib/interleaved-buffer-attribute/interleaved-buffer-attribute.mjs +0 -30
  108. package/esm2020/attributes/lib/matrix3-attribute/matrix3-attribute.mjs +0 -26
  109. package/esm2020/attributes/lib/matrix4-attribute/matrix4-attribute.mjs +0 -26
  110. package/esm2020/attributes/lib/uint16-buffer-attribute/uint16-buffer-attribute.mjs +0 -26
  111. package/esm2020/attributes/lib/uint32-buffer-attribute/uint32-buffer-attribute.mjs +0 -26
  112. package/esm2020/attributes/lib/uint8-buffer-attribute/uint8-buffer-attribute.mjs +0 -26
  113. package/esm2020/attributes/lib/uint8-clamped-buffer-attribute/uint8-clamped-buffer-attribute.mjs +0 -26
  114. package/esm2020/attributes/lib/value-attribute/value-attribute.mjs +0 -28
  115. package/esm2020/attributes/lib/vector2-attribute/vector2-attribute.mjs +0 -26
  116. package/esm2020/attributes/lib/vector3-attribute/vector3-attribute.mjs +0 -26
  117. package/esm2020/attributes/lib/vector4-attribute/vector4-attribute.mjs +0 -26
  118. package/esm2020/audios/angular-three-audios.mjs +0 -5
  119. package/esm2020/audios/index.mjs +0 -5
  120. package/esm2020/audios/lib/audio/audio.mjs +0 -45
  121. package/esm2020/audios/lib/audio-listener/audio-listener.mjs +0 -38
  122. package/esm2020/audios/lib/common.mjs +0 -54
  123. package/esm2020/audios/lib/positional-audio/positional-audio.mjs +0 -45
  124. package/esm2020/cameras/angular-three-cameras.mjs +0 -5
  125. package/esm2020/cameras/index.mjs +0 -7
  126. package/esm2020/cameras/lib/array-camera/array-camera.mjs +0 -44
  127. package/esm2020/cameras/lib/common.mjs +0 -54
  128. package/esm2020/cameras/lib/cube-camera/cube-camera.mjs +0 -30
  129. package/esm2020/cameras/lib/orthographic-camera/orthographic-camera.mjs +0 -42
  130. package/esm2020/cameras/lib/perspective-camera/perspective-camera.mjs +0 -43
  131. package/esm2020/cameras/lib/stereo-camera/stereo-camera.mjs +0 -38
  132. package/esm2020/geometries/angular-three-geometries.mjs +0 -5
  133. package/esm2020/geometries/index.mjs +0 -25
  134. package/esm2020/geometries/lib/box-geometry/box-geometry.mjs +0 -26
  135. package/esm2020/geometries/lib/buffer-geometry/buffer-geometry.mjs +0 -26
  136. package/esm2020/geometries/lib/capsule-geometry/capsule-geometry.mjs +0 -26
  137. package/esm2020/geometries/lib/circle-geometry/circle-geometry.mjs +0 -26
  138. package/esm2020/geometries/lib/common.mjs +0 -13
  139. package/esm2020/geometries/lib/cone-geometry/cone-geometry.mjs +0 -26
  140. package/esm2020/geometries/lib/cylinder-geometry/cylinder-geometry.mjs +0 -26
  141. package/esm2020/geometries/lib/dodecahedron-geometry/dodecahedron-geometry.mjs +0 -26
  142. package/esm2020/geometries/lib/edges-geometry/edges-geometry.mjs +0 -26
  143. package/esm2020/geometries/lib/extrude-geometry/extrude-geometry.mjs +0 -26
  144. package/esm2020/geometries/lib/icosahedron-geometry/icosahedron-geometry.mjs +0 -26
  145. package/esm2020/geometries/lib/instanced-buffer-geometry/instanced-buffer-geometry.mjs +0 -26
  146. package/esm2020/geometries/lib/lathe-geometry/lathe-geometry.mjs +0 -26
  147. package/esm2020/geometries/lib/octahedron-geometry/octahedron-geometry.mjs +0 -26
  148. package/esm2020/geometries/lib/plane-geometry/plane-geometry.mjs +0 -26
  149. package/esm2020/geometries/lib/polyhedron-geometry/polyhedron-geometry.mjs +0 -26
  150. package/esm2020/geometries/lib/ring-geometry/ring-geometry.mjs +0 -26
  151. package/esm2020/geometries/lib/shape-geometry/shape-geometry.mjs +0 -26
  152. package/esm2020/geometries/lib/sphere-geometry/sphere-geometry.mjs +0 -26
  153. package/esm2020/geometries/lib/tetrahedron-geometry/tetrahedron-geometry.mjs +0 -26
  154. package/esm2020/geometries/lib/torus-geometry/torus-geometry.mjs +0 -26
  155. package/esm2020/geometries/lib/torus-knot-geometry/torus-knot-geometry.mjs +0 -26
  156. package/esm2020/geometries/lib/tube-geometry/tube-geometry.mjs +0 -26
  157. package/esm2020/geometries/lib/wireframe-geometry/wireframe-geometry.mjs +0 -26
  158. package/esm2020/helpers/angular-three-helpers.mjs +0 -5
  159. package/esm2020/helpers/index.mjs +0 -15
  160. package/esm2020/helpers/lib/arrow-helper/arrow-helper.mjs +0 -26
  161. package/esm2020/helpers/lib/axes-helper/axes-helper.mjs +0 -26
  162. package/esm2020/helpers/lib/box-helper/box-helper.mjs +0 -36
  163. package/esm2020/helpers/lib/box3-helper/box3-helper.mjs +0 -36
  164. package/esm2020/helpers/lib/camera-helper/camera-helper.mjs +0 -36
  165. package/esm2020/helpers/lib/common.mjs +0 -13
  166. package/esm2020/helpers/lib/directional-light-helper/directional-light-helper.mjs +0 -36
  167. package/esm2020/helpers/lib/grid-helper/grid-helper.mjs +0 -26
  168. package/esm2020/helpers/lib/hemisphere-light-helper/hemisphere-light-helper.mjs +0 -36
  169. package/esm2020/helpers/lib/plane-helper/plane-helper.mjs +0 -36
  170. package/esm2020/helpers/lib/point-light-helper/point-light-helper.mjs +0 -36
  171. package/esm2020/helpers/lib/polar-grid-helper/polar-grid-helper.mjs +0 -26
  172. package/esm2020/helpers/lib/skeleton-helper/skeleton-helper.mjs +0 -36
  173. package/esm2020/helpers/lib/spot-light-helper/spot-light-helper.mjs +0 -36
  174. package/esm2020/lib/di/resize.mjs +0 -19
  175. package/esm2020/lib/di/window.mjs +0 -13
  176. package/esm2020/lib/directives/cursor.mjs +0 -35
  177. package/esm2020/lib/instance.mjs +0 -368
  178. package/esm2020/lib/pipes/math.mjs +0 -15
  179. package/esm2020/lib/pipes/pi.mjs +0 -14
  180. package/esm2020/lib/pipes/radian.mjs +0 -14
  181. package/esm2020/lib/pipes/side.mjs +0 -22
  182. package/esm2020/lib/ref.mjs +0 -15
  183. package/esm2020/lib/services/loader.mjs +0 -45
  184. package/esm2020/lib/services/resize.mjs +0 -127
  185. package/esm2020/lib/stores/component-store.mjs +0 -137
  186. package/esm2020/lib/utils/build-graph.mjs +0 -15
  187. package/esm2020/lib/utils/camera.mjs +0 -28
  188. package/esm2020/lib/utils/capitalize.mjs +0 -4
  189. package/esm2020/lib/utils/check-update.mjs +0 -22
  190. package/esm2020/lib/utils/events.mjs +0 -353
  191. package/esm2020/lib/utils/get-instance-local-state.mjs +0 -6
  192. package/esm2020/lib/utils/inject.mjs +0 -18
  193. package/esm2020/lib/utils/loop.mjs +0 -139
  194. package/esm2020/lib/utils/mutate.mjs +0 -24
  195. package/esm2020/lib/utils/proxy.mjs +0 -99
  196. package/esm2020/lib/utils/renderer.mjs +0 -15
  197. package/esm2020/lights/angular-three-lights.mjs +0 -5
  198. package/esm2020/lights/index.mjs +0 -11
  199. package/esm2020/lights/lib/ambient-light/ambient-light.mjs +0 -30
  200. package/esm2020/lights/lib/ambient-light-probe/ambient-light-probe.mjs +0 -30
  201. package/esm2020/lights/lib/common.mjs +0 -54
  202. package/esm2020/lights/lib/directional-light/directional-light.mjs +0 -30
  203. package/esm2020/lights/lib/hemisphere-light/hemisphere-light.mjs +0 -30
  204. package/esm2020/lights/lib/hemisphere-light-probe/hemisphere-light-probe.mjs +0 -30
  205. package/esm2020/lights/lib/light-probe/light-probe.mjs +0 -30
  206. package/esm2020/lights/lib/point-light/point-light.mjs +0 -30
  207. package/esm2020/lights/lib/rect-area-light/rect-area-light.mjs +0 -30
  208. package/esm2020/lights/lib/spot-light/spot-light.mjs +0 -42
  209. package/esm2020/materials/angular-three-materials.mjs +0 -5
  210. package/esm2020/materials/index.mjs +0 -19
  211. package/esm2020/materials/lib/common.mjs +0 -13
  212. package/esm2020/materials/lib/line-basic-material/line-basic-material.mjs +0 -77
  213. package/esm2020/materials/lib/line-dashed-material/line-dashed-material.mjs +0 -80
  214. package/esm2020/materials/lib/mesh-basic-material/mesh-basic-material.mjs +0 -89
  215. package/esm2020/materials/lib/mesh-depth-material/mesh-depth-material.mjs +0 -80
  216. package/esm2020/materials/lib/mesh-distance-material/mesh-distance-material.mjs +0 -80
  217. package/esm2020/materials/lib/mesh-lambert-material/mesh-lambert-material.mjs +0 -100
  218. package/esm2020/materials/lib/mesh-matcap-material/mesh-matcap-material.mjs +0 -86
  219. package/esm2020/materials/lib/mesh-normal-material/mesh-normal-material.mjs +0 -83
  220. package/esm2020/materials/lib/mesh-phong-material/mesh-phong-material.mjs +0 -103
  221. package/esm2020/materials/lib/mesh-physical-material/mesh-physical-material.mjs +0 -119
  222. package/esm2020/materials/lib/mesh-standard-material/mesh-standard-material.mjs +0 -100
  223. package/esm2020/materials/lib/mesh-toon-material/mesh-toon-material.mjs +0 -96
  224. package/esm2020/materials/lib/points-material/points-material.mjs +0 -78
  225. package/esm2020/materials/lib/raw-shader-material/raw-shader-material.mjs +0 -83
  226. package/esm2020/materials/lib/shader-material/shader-material.mjs +0 -83
  227. package/esm2020/materials/lib/shadow-material/shadow-material.mjs +0 -74
  228. package/esm2020/materials/lib/sprite-material/sprite-material.mjs +0 -78
  229. package/esm2020/objects/angular-three-objects.mjs +0 -5
  230. package/esm2020/objects/index.mjs +0 -14
  231. package/esm2020/objects/lib/bone/bone.mjs +0 -27
  232. package/esm2020/objects/lib/common.mjs +0 -54
  233. package/esm2020/objects/lib/group/group.mjs +0 -27
  234. package/esm2020/objects/lib/instanced-mesh/instanced-mesh.mjs +0 -40
  235. package/esm2020/objects/lib/line/line.mjs +0 -30
  236. package/esm2020/objects/lib/line-loop/line-loop.mjs +0 -30
  237. package/esm2020/objects/lib/line-segments/line-segments.mjs +0 -30
  238. package/esm2020/objects/lib/lod/lod.mjs +0 -30
  239. package/esm2020/objects/lib/mesh/mesh.mjs +0 -30
  240. package/esm2020/objects/lib/points/points.mjs +0 -30
  241. package/esm2020/objects/lib/skeleton/skeleton.mjs +0 -41
  242. package/esm2020/objects/lib/skinned-mesh/skinned-mesh.mjs +0 -39
  243. package/esm2020/objects/lib/sprite/sprite.mjs +0 -30
  244. package/esm2020/primitives/angular-three-primitives.mjs +0 -5
  245. package/esm2020/primitives/index.mjs +0 -3
  246. package/esm2020/primitives/lib/common.mjs +0 -54
  247. package/esm2020/primitives/lib/object-primitive/object-primitive.mjs +0 -27
  248. package/esm2020/primitives/lib/primitive/primitive.mjs +0 -38
  249. package/esm2020/stats/angular-three-stats.mjs +0 -5
  250. package/esm2020/stats/index.mjs +0 -2
  251. package/esm2020/stats/lib/stats/stats.mjs +0 -54
  252. package/esm2020/textures/angular-three-textures.mjs +0 -5
  253. package/esm2020/textures/index.mjs +0 -12
  254. package/esm2020/textures/lib/canvas-texture/canvas-texture.mjs +0 -26
  255. package/esm2020/textures/lib/common.mjs +0 -13
  256. package/esm2020/textures/lib/compressed-array-texture/compressed-array-texture.mjs +0 -26
  257. package/esm2020/textures/lib/compressed-texture/compressed-texture.mjs +0 -26
  258. package/esm2020/textures/lib/cube-texture/cube-texture.mjs +0 -26
  259. package/esm2020/textures/lib/data-array-texture/data-array-texture.mjs +0 -26
  260. package/esm2020/textures/lib/data-texture/data-texture.mjs +0 -26
  261. package/esm2020/textures/lib/data3-dtexture/data3-dtexture.mjs +0 -26
  262. package/esm2020/textures/lib/depth-texture/depth-texture.mjs +0 -26
  263. package/esm2020/textures/lib/framebuffer-texture/framebuffer-texture.mjs +0 -26
  264. package/esm2020/textures/lib/video-texture/video-texture.mjs +0 -26
  265. package/fesm2015/angular-three-attributes.mjs +0 -475
  266. package/fesm2015/angular-three-attributes.mjs.map +0 -1
  267. package/fesm2015/angular-three-audios.mjs +0 -179
  268. package/fesm2015/angular-three-audios.mjs.map +0 -1
  269. package/fesm2015/angular-three-cameras.mjs +0 -236
  270. package/fesm2015/angular-three-cameras.mjs.map +0 -1
  271. package/fesm2015/angular-three-geometries.mjs +0 -488
  272. package/fesm2015/angular-three-geometries.mjs.map +0 -1
  273. package/fesm2015/angular-three-helpers.mjs +0 -378
  274. package/fesm2015/angular-three-helpers.mjs.map +0 -1
  275. package/fesm2015/angular-three-lights.mjs +0 -297
  276. package/fesm2015/angular-three-lights.mjs.map +0 -1
  277. package/fesm2015/angular-three-materials.mjs +0 -1415
  278. package/fesm2015/angular-three-materials.mjs.map +0 -1
  279. package/fesm2015/angular-three-objects.mjs +0 -381
  280. package/fesm2015/angular-three-objects.mjs.map +0 -1
  281. package/fesm2015/angular-three-primitives.mjs +0 -120
  282. package/fesm2015/angular-three-primitives.mjs.map +0 -1
  283. package/fesm2015/angular-three-stats.mjs +0 -62
  284. package/fesm2015/angular-three-stats.mjs.map +0 -1
  285. package/fesm2015/angular-three-textures.mjs +0 -228
  286. package/fesm2015/angular-three-textures.mjs.map +0 -1
  287. package/fesm2020/angular-three-attributes.mjs +0 -475
  288. package/fesm2020/angular-three-attributes.mjs.map +0 -1
  289. package/fesm2020/angular-three-audios.mjs +0 -179
  290. package/fesm2020/angular-three-audios.mjs.map +0 -1
  291. package/fesm2020/angular-three-cameras.mjs +0 -236
  292. package/fesm2020/angular-three-cameras.mjs.map +0 -1
  293. package/fesm2020/angular-three-geometries.mjs +0 -488
  294. package/fesm2020/angular-three-geometries.mjs.map +0 -1
  295. package/fesm2020/angular-three-helpers.mjs +0 -378
  296. package/fesm2020/angular-three-helpers.mjs.map +0 -1
  297. package/fesm2020/angular-three-lights.mjs +0 -297
  298. package/fesm2020/angular-three-lights.mjs.map +0 -1
  299. package/fesm2020/angular-three-materials.mjs +0 -1415
  300. package/fesm2020/angular-three-materials.mjs.map +0 -1
  301. package/fesm2020/angular-three-objects.mjs +0 -381
  302. package/fesm2020/angular-three-objects.mjs.map +0 -1
  303. package/fesm2020/angular-three-primitives.mjs +0 -120
  304. package/fesm2020/angular-three-primitives.mjs.map +0 -1
  305. package/fesm2020/angular-three-stats.mjs +0 -62
  306. package/fesm2020/angular-three-stats.mjs.map +0 -1
  307. package/fesm2020/angular-three-textures.mjs +0 -228
  308. package/fesm2020/angular-three-textures.mjs.map +0 -1
  309. package/geometries/README.md +0 -3
  310. package/geometries/index.d.ts +0 -23
  311. package/geometries/lib/box-geometry/box-geometry.d.ts +0 -8
  312. package/geometries/lib/buffer-geometry/buffer-geometry.d.ts +0 -8
  313. package/geometries/lib/capsule-geometry/capsule-geometry.d.ts +0 -8
  314. package/geometries/lib/circle-geometry/circle-geometry.d.ts +0 -8
  315. package/geometries/lib/common.d.ts +0 -1
  316. package/geometries/lib/cone-geometry/cone-geometry.d.ts +0 -8
  317. package/geometries/lib/cylinder-geometry/cylinder-geometry.d.ts +0 -8
  318. package/geometries/lib/dodecahedron-geometry/dodecahedron-geometry.d.ts +0 -8
  319. package/geometries/lib/edges-geometry/edges-geometry.d.ts +0 -8
  320. package/geometries/lib/extrude-geometry/extrude-geometry.d.ts +0 -8
  321. package/geometries/lib/icosahedron-geometry/icosahedron-geometry.d.ts +0 -8
  322. package/geometries/lib/instanced-buffer-geometry/instanced-buffer-geometry.d.ts +0 -8
  323. package/geometries/lib/lathe-geometry/lathe-geometry.d.ts +0 -8
  324. package/geometries/lib/octahedron-geometry/octahedron-geometry.d.ts +0 -8
  325. package/geometries/lib/plane-geometry/plane-geometry.d.ts +0 -8
  326. package/geometries/lib/polyhedron-geometry/polyhedron-geometry.d.ts +0 -8
  327. package/geometries/lib/ring-geometry/ring-geometry.d.ts +0 -8
  328. package/geometries/lib/shape-geometry/shape-geometry.d.ts +0 -8
  329. package/geometries/lib/sphere-geometry/sphere-geometry.d.ts +0 -8
  330. package/geometries/lib/tetrahedron-geometry/tetrahedron-geometry.d.ts +0 -8
  331. package/geometries/lib/torus-geometry/torus-geometry.d.ts +0 -8
  332. package/geometries/lib/torus-knot-geometry/torus-knot-geometry.d.ts +0 -8
  333. package/geometries/lib/tube-geometry/tube-geometry.d.ts +0 -8
  334. package/geometries/lib/wireframe-geometry/wireframe-geometry.d.ts +0 -8
  335. package/helpers/README.md +0 -3
  336. package/helpers/index.d.ts +0 -13
  337. package/helpers/lib/arrow-helper/arrow-helper.d.ts +0 -8
  338. package/helpers/lib/axes-helper/axes-helper.d.ts +0 -8
  339. package/helpers/lib/box-helper/box-helper.d.ts +0 -8
  340. package/helpers/lib/box3-helper/box3-helper.d.ts +0 -8
  341. package/helpers/lib/camera-helper/camera-helper.d.ts +0 -8
  342. package/helpers/lib/common.d.ts +0 -1
  343. package/helpers/lib/directional-light-helper/directional-light-helper.d.ts +0 -8
  344. package/helpers/lib/grid-helper/grid-helper.d.ts +0 -8
  345. package/helpers/lib/hemisphere-light-helper/hemisphere-light-helper.d.ts +0 -8
  346. package/helpers/lib/plane-helper/plane-helper.d.ts +0 -8
  347. package/helpers/lib/point-light-helper/point-light-helper.d.ts +0 -8
  348. package/helpers/lib/polar-grid-helper/polar-grid-helper.d.ts +0 -8
  349. package/helpers/lib/skeleton-helper/skeleton-helper.d.ts +0 -8
  350. package/helpers/lib/spot-light-helper/spot-light-helper.d.ts +0 -8
  351. package/lib/di/resize.d.ts +0 -12
  352. package/lib/di/window.d.ts +0 -1
  353. package/lib/directives/cursor.d.ts +0 -7
  354. package/lib/instance.d.ts +0 -81
  355. package/lib/pipes/math.d.ts +0 -7
  356. package/lib/pipes/pi.d.ts +0 -7
  357. package/lib/pipes/radian.d.ts +0 -7
  358. package/lib/pipes/side.d.ts +0 -8
  359. package/lib/ref.d.ts +0 -5
  360. package/lib/services/loader.d.ts +0 -11
  361. package/lib/services/resize.d.ts +0 -19
  362. package/lib/stores/component-store.d.ts +0 -69
  363. package/lib/utils/build-graph.d.ts +0 -3
  364. package/lib/utils/camera.d.ts +0 -4
  365. package/lib/utils/capitalize.d.ts +0 -1
  366. package/lib/utils/check-update.d.ts +0 -2
  367. package/lib/utils/events.d.ts +0 -6
  368. package/lib/utils/get-instance-local-state.d.ts +0 -2
  369. package/lib/utils/inject.d.ts +0 -9
  370. package/lib/utils/mutate.d.ts +0 -2
  371. package/lib/utils/proxy.d.ts +0 -7
  372. package/lib/utils/renderer.d.ts +0 -3
  373. package/lights/README.md +0 -3
  374. package/lights/index.d.ts +0 -9
  375. package/lights/lib/ambient-light/ambient-light.d.ts +0 -39
  376. package/lights/lib/ambient-light-probe/ambient-light-probe.d.ts +0 -40
  377. package/lights/lib/common.d.ts +0 -3
  378. package/lights/lib/directional-light/directional-light.d.ts +0 -40
  379. package/lights/lib/hemisphere-light/hemisphere-light.d.ts +0 -41
  380. package/lights/lib/hemisphere-light-probe/hemisphere-light-probe.d.ts +0 -42
  381. package/lights/lib/light-probe/light-probe.d.ts +0 -40
  382. package/lights/lib/point-light/point-light.d.ts +0 -42
  383. package/lights/lib/rect-area-light/rect-area-light.d.ts +0 -42
  384. package/lights/lib/spot-light/spot-light.d.ts +0 -45
  385. package/materials/README.md +0 -3
  386. package/materials/index.d.ts +0 -17
  387. package/materials/lib/common.d.ts +0 -1
  388. package/materials/lib/line-basic-material/line-basic-material.d.ts +0 -55
  389. package/materials/lib/line-dashed-material/line-dashed-material.d.ts +0 -58
  390. package/materials/lib/mesh-basic-material/mesh-basic-material.d.ts +0 -67
  391. package/materials/lib/mesh-depth-material/mesh-depth-material.d.ts +0 -58
  392. package/materials/lib/mesh-distance-material/mesh-distance-material.d.ts +0 -58
  393. package/materials/lib/mesh-lambert-material/mesh-lambert-material.d.ts +0 -78
  394. package/materials/lib/mesh-matcap-material/mesh-matcap-material.d.ts +0 -64
  395. package/materials/lib/mesh-normal-material/mesh-normal-material.d.ts +0 -61
  396. package/materials/lib/mesh-phong-material/mesh-phong-material.d.ts +0 -81
  397. package/materials/lib/mesh-physical-material/mesh-physical-material.d.ts +0 -97
  398. package/materials/lib/mesh-standard-material/mesh-standard-material.d.ts +0 -78
  399. package/materials/lib/mesh-toon-material/mesh-toon-material.d.ts +0 -74
  400. package/materials/lib/points-material/points-material.d.ts +0 -56
  401. package/materials/lib/raw-shader-material/raw-shader-material.d.ts +0 -68
  402. package/materials/lib/shader-material/shader-material.d.ts +0 -68
  403. package/materials/lib/shadow-material/shadow-material.d.ts +0 -52
  404. package/materials/lib/sprite-material/sprite-material.d.ts +0 -56
  405. package/objects/README.md +0 -3
  406. package/objects/index.d.ts +0 -12
  407. package/objects/lib/bone/bone.d.ts +0 -35
  408. package/objects/lib/common.d.ts +0 -3
  409. package/objects/lib/group/group.d.ts +0 -35
  410. package/objects/lib/instanced-mesh/instanced-mesh.d.ts +0 -44
  411. package/objects/lib/line/line.d.ts +0 -41
  412. package/objects/lib/line-loop/line-loop.d.ts +0 -41
  413. package/objects/lib/line-segments/line-segments.d.ts +0 -41
  414. package/objects/lib/lod/lod.d.ts +0 -40
  415. package/objects/lib/mesh/mesh.d.ts +0 -41
  416. package/objects/lib/points/points.d.ts +0 -41
  417. package/objects/lib/skeleton/skeleton.d.ts +0 -16
  418. package/objects/lib/skinned-mesh/skinned-mesh.d.ts +0 -45
  419. package/objects/lib/sprite/sprite.d.ts +0 -38
  420. package/primitives/README.md +0 -3
  421. package/primitives/index.d.ts +0 -2
  422. package/primitives/lib/common.d.ts +0 -3
  423. package/primitives/lib/object-primitive/object-primitive.d.ts +0 -35
  424. package/primitives/lib/primitive/primitive.d.ts +0 -10
  425. package/schematics/README.md +0 -11
  426. package/stats/README.md +0 -3
  427. package/stats/index.d.ts +0 -1
  428. package/stats/lib/stats/stats.d.ts +0 -16
  429. package/textures/README.md +0 -3
  430. package/textures/index.d.ts +0 -10
  431. package/textures/lib/canvas-texture/canvas-texture.d.ts +0 -8
  432. package/textures/lib/common.d.ts +0 -1
  433. package/textures/lib/compressed-array-texture/compressed-array-texture.d.ts +0 -8
  434. package/textures/lib/compressed-texture/compressed-texture.d.ts +0 -8
  435. package/textures/lib/cube-texture/cube-texture.d.ts +0 -8
  436. package/textures/lib/data-array-texture/data-array-texture.d.ts +0 -8
  437. package/textures/lib/data-texture/data-texture.d.ts +0 -8
  438. package/textures/lib/data3-dtexture/data3-dtexture.d.ts +0 -8
  439. package/textures/lib/depth-texture/depth-texture.d.ts +0 -8
  440. package/textures/lib/framebuffer-texture/framebuffer-texture.d.ts +0 -8
  441. package/textures/lib/video-texture/video-texture.d.ts +0 -8
@@ -1,1160 +1,561 @@
1
- import { DOCUMENT, NgIf, NgTemplateOutlet, AsyncPipe, NgForOf } from '@angular/common';
2
1
  import * as i0 from '@angular/core';
3
- import { Injectable, InjectionToken, inject, NgZone, EventEmitter, Directive, Input, Output, ElementRef, Component, TemplateRef, ChangeDetectionStrategy, HostBinding, ViewChild, ContentChild, ViewContainerRef, Injector, Optional, Self, Inject, Pipe } from '@angular/core';
4
- import * as THREE from 'three';
5
- import { BehaviorSubject, filter, noop, tap, isObservable, combineLatest, Observable, Subject, pipe, debounceTime, takeUntil, fromEvent, share, ReplaySubject, from, retry, catchError, of, forkJoin, map, merge } from 'rxjs';
6
- import { ComponentStore } from '@ngrx/component-store';
2
+ import { ElementRef, Injectable, inject, InjectionToken, ViewContainerRef, TemplateRef, Directive, Input, EventEmitter, getDebugNode, ChangeDetectorRef, RendererFactory2, Component, Output, EnvironmentInjector, createEnvironmentInjector, HostBinding, ViewChild } from '@angular/core';
3
+ import { injectNgxResize, provideNgxResizeOptions } from 'ngx-resize';
4
+ import { BehaviorSubject, startWith, tap, isObservable, of, map, from, retry, catchError, share, ReplaySubject, switchMap, forkJoin, take, filter } from 'rxjs';
7
5
  import { __rest } from 'tslib';
6
+ import { DOCUMENT, NgForOf } from '@angular/common';
7
+ import { RxState, selectSlice } from '@rx-angular/state';
8
+ import * as THREE from 'three';
9
+ import { ɵDomRendererFactory2 } from '@angular/platform-browser';
8
10
 
9
- function getInstanceLocalState(obj) {
10
- if (!obj)
11
- return undefined;
12
- return obj['__ngt__'];
11
+ function createSubs(callback, subs) {
12
+ const sub = { callback };
13
+ subs.add(sub);
14
+ return () => void subs.delete(sub);
13
15
  }
14
-
15
- const idCache = {};
16
- function makeId(event) {
17
- if (event) {
18
- return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
19
- }
20
- const newId = THREE.MathUtils.generateUUID();
21
- // ensure not already used
22
- if (!idCache[newId]) {
23
- idCache[newId] = true;
24
- return newId;
16
+ const globalEffects = new Set();
17
+ const globalAfterEffects = new Set();
18
+ const globalTailEffects = new Set();
19
+ /**
20
+ * Adds a global render callback which is called each frame.
21
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
22
+ */
23
+ const addEffect = (callback) => createSubs(callback, globalEffects);
24
+ /**
25
+ * Adds a global after-render callback which is called each frame.
26
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
27
+ */
28
+ const addAfterEffect = (callback) => createSubs(callback, globalAfterEffects);
29
+ /**
30
+ * Adds a global callback which is called when rendering stops.
31
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
32
+ */
33
+ const addTail = (callback) => createSubs(callback, globalTailEffects);
34
+ function run(effects, timestamp) {
35
+ if (!effects.size)
36
+ return;
37
+ for (const { callback } of effects.values()) {
38
+ callback(timestamp);
25
39
  }
26
- return makeId();
27
40
  }
28
- function makeDpr(dpr, window) {
29
- const target = (window === null || window === void 0 ? void 0 : window.devicePixelRatio) || 1;
30
- return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], target), dpr[1]) : dpr;
41
+ function flushGlobalEffects(type, timestamp) {
42
+ switch (type) {
43
+ case 'before':
44
+ return run(globalEffects, timestamp);
45
+ case 'after':
46
+ return run(globalAfterEffects, timestamp);
47
+ case 'tail':
48
+ return run(globalTailEffects, timestamp);
49
+ }
31
50
  }
32
- function make(type, input) {
33
- if (!input)
34
- return new type();
35
- if (input instanceof type) {
36
- return input;
51
+ function render(timestamp, store, frame) {
52
+ const state = store.get();
53
+ // Run local effects
54
+ let delta = state.clock.getDelta();
55
+ // In frameloop='never' mode, clock times are updated using the provided timestamp
56
+ if (state.frameloop === 'never' && typeof timestamp === 'number') {
57
+ delta = timestamp - state.clock.elapsedTime;
58
+ state.clock.oldTime = state.clock.elapsedTime;
59
+ state.clock.elapsedTime = timestamp;
60
+ }
61
+ // Call subscribers (useFrame)
62
+ // subscribers = state.internal.subscribers;
63
+ for (let i = 0; i < state.internal.subscribers.length; i++) {
64
+ const subscriber = state.internal.subscribers[i];
65
+ subscriber.callback(Object.assign(Object.assign({}, state), { delta, frame }));
37
66
  }
38
- if (!Array.isArray(input)) {
39
- input = typeof input === 'number' ? [input, input, input, input] : [input];
67
+ // Render content
68
+ if (!state.internal.priority && state.gl.render) {
69
+ state.gl.render(state.scene, state.camera);
40
70
  }
41
- return new type(...input);
71
+ // Decrease frame count
72
+ state.internal.frames = Math.max(0, state.internal.frames - 1);
73
+ return state.frameloop === 'always' ? 1 : state.internal.frames;
42
74
  }
43
-
44
- /**
45
- * Release pointer captures.
46
- * This is called by releasePointerCapture in the API, and when an object is removed.
47
- */
48
- function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
49
- const captureData = captures.get(obj);
50
- if (captureData) {
51
- captures.delete(obj);
52
- // If this was the last capturing object for this pointer
53
- if (captures.size === 0) {
54
- capturedMap.delete(pointerId);
55
- captureData.target.releasePointerCapture(pointerId);
75
+ function createLoop(roots) {
76
+ let running = false;
77
+ let repeat;
78
+ let frame;
79
+ function loop(timestamp) {
80
+ var _a;
81
+ frame = requestAnimationFrame(loop);
82
+ running = true;
83
+ repeat = 0;
84
+ // Run effects
85
+ flushGlobalEffects('before', timestamp);
86
+ // Render all roots
87
+ for (const root of roots.values()) {
88
+ const state = root.get();
89
+ // If the frameloop is invalidated, do not run another frame
90
+ if (state.internal.active &&
91
+ (state.frameloop === 'always' || state.internal.frames > 0) &&
92
+ !((_a = state.gl.xr) === null || _a === void 0 ? void 0 : _a.isPresenting)) {
93
+ repeat += render(timestamp, root);
94
+ }
95
+ }
96
+ // Run after-effects
97
+ flushGlobalEffects('after', timestamp);
98
+ // Stop the loop if nothing invalidates it
99
+ if (repeat === 0) {
100
+ // Tail call effects, they are called when rendering stops
101
+ flushGlobalEffects('tail', timestamp);
102
+ // Flag end of operation
103
+ running = false;
104
+ return cancelAnimationFrame(frame);
56
105
  }
57
106
  }
58
- }
59
- function removeInteractivity(stateFactory, object) {
60
- const { internal } = stateFactory();
61
- // Removes every trace of an object from the data store
62
- internal.interaction = internal.interaction.filter((o) => o !== object);
63
- internal.initialHits = internal.initialHits.filter((o) => o !== object);
64
- internal.hovered.forEach((value, key) => {
65
- if (value.eventObject === object || value.object === object) {
66
- // Clear out intersects, they are outdated by now
67
- internal.hovered.delete(key);
107
+ function invalidate(store, frames = 1) {
108
+ var _a;
109
+ const state = store === null || store === void 0 ? void 0 : store.get();
110
+ if (!state)
111
+ return roots.forEach((root) => invalidate(root, frames));
112
+ if (((_a = state.gl.xr) === null || _a === void 0 ? void 0 : _a.isPresenting) || !state.internal.active || state.frameloop === 'never')
113
+ return;
114
+ // Increase frames, do not go higher than 60
115
+ state.internal.frames = Math.min(60, state.internal.frames + frames);
116
+ // If the render-loop isn't active, start it
117
+ if (!running) {
118
+ running = true;
119
+ requestAnimationFrame(loop);
68
120
  }
69
- });
70
- internal.capturedMap.forEach((captures, pointerId) => {
71
- releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
72
- });
73
- }
74
- function createEvents(stateFactory) {
75
- /** Calculates delta */
76
- function calculateDistance(event) {
77
- const { internal } = stateFactory();
78
- const dx = event.offsetX - internal.initialClick[0];
79
- const dy = event.offsetY - internal.initialClick[1];
80
- return Math.round(Math.sqrt(dx * dx + dy * dy));
81
121
  }
82
- /** Returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc */
83
- function filterPointerEvents(objects) {
84
- return objects.filter((obj) => ['move', 'over', 'enter', 'out', 'leave'].some((name) => {
85
- var _a;
86
- const eventName = ('pointer' + name);
87
- return (_a = getInstanceLocalState(obj)) === null || _a === void 0 ? void 0 : _a.handlers[eventName];
88
- }));
122
+ function advance(timestamp, runGlobalEffects = true, store, frame) {
123
+ const state = store === null || store === void 0 ? void 0 : store.get();
124
+ if (runGlobalEffects)
125
+ flushGlobalEffects('before', timestamp);
126
+ if (!state)
127
+ for (const root of roots.values())
128
+ render(timestamp, root);
129
+ // safe to assume store is available here
130
+ else
131
+ render(timestamp, store, frame);
132
+ if (runGlobalEffects)
133
+ flushGlobalEffects('after', timestamp);
89
134
  }
90
- function intersect(event, filter) {
91
- var _a, _b, _c, _d;
92
- const state = stateFactory();
93
- const duplicates = new Set();
94
- const intersections = [];
95
- // Allow callers to eliminate event objects
96
- const eventsObjects = filter ? filter(state.internal.interaction) : state.internal.interaction;
97
- // Reset all raycaster cameras to undefined
98
- for (let i = 0; i < eventsObjects.length; i++) {
99
- const instanceState = (_a = getInstanceLocalState(eventsObjects[i])) === null || _a === void 0 ? void 0 : _a.stateFactory();
100
- if (instanceState) {
101
- instanceState.raycaster.camera = undefined;
102
- }
135
+ return {
136
+ loop,
137
+ /**
138
+ * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state.
139
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
140
+ */
141
+ invalidate,
142
+ /**
143
+ * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`.
144
+ * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
145
+ */
146
+ advance,
147
+ };
148
+ }
149
+
150
+ const is = {
151
+ obj: (a) => a === Object(a) && !Array.isArray(a) && typeof a !== 'function',
152
+ material: (a) => !!a && a.isMaterial,
153
+ geometry: (a) => !!a && a.isBufferGeometry,
154
+ orthographicCamera: (a) => !!a && a.isOrthographicCamera,
155
+ perspectiveCamera: (a) => !!a && a.isPerspectiveCamera,
156
+ camera: (a) => !!a && a.isCamera,
157
+ renderer: (a) => !!a && a instanceof THREE.WebGLRenderer,
158
+ scene: (a) => !!a && a.isScene,
159
+ object3D: (a) => !!a && a.isObject3D,
160
+ instance: (a) => !!a && !!a['__ngt__'],
161
+ ref: (a) => a instanceof ElementRef,
162
+ equ(a, b, { arrays = 'shallow', objects = 'reference', strict = true } = {}) {
163
+ // Wrong type or one of the two undefined, doesn't match
164
+ if (typeof a !== typeof b || !!a !== !!b)
165
+ return false;
166
+ // Atomic, just compare a against b
167
+ if (typeof a === 'string' || typeof a === 'number')
168
+ return a === b;
169
+ const isObj = is.obj(a);
170
+ if (isObj && objects === 'reference')
171
+ return a === b;
172
+ const isArr = Array.isArray(a);
173
+ if (isArr && arrays === 'reference')
174
+ return a === b;
175
+ // Array or Object, shallow compare first to see if it's a match
176
+ if ((isArr || isObj) && a === b)
177
+ return true;
178
+ // Last resort, go through keys
179
+ let i;
180
+ for (i in a)
181
+ if (!(i in b))
182
+ return false;
183
+ for (i in strict ? b : a)
184
+ if (a[i] !== b[i])
185
+ return false;
186
+ if (i === void 0) {
187
+ if (isArr && a.length === 0 && b.length === 0)
188
+ return true;
189
+ if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0)
190
+ return true;
191
+ if (a !== b)
192
+ return false;
103
193
  }
104
- if (!state.previousStateFactory) {
105
- // Make sure root-level pointer and ray are set up
106
- (_c = (_b = state.events).compute) === null || _c === void 0 ? void 0 : _c.call(_b, event, () => state);
194
+ return true;
195
+ },
196
+ };
197
+
198
+ function checkNeedsUpdate(value) {
199
+ if (value !== null && is.obj(value) && 'needsUpdate' in value) {
200
+ value['needsUpdate'] = true;
201
+ if ('uniformsNeedUpdate' in value) {
202
+ value['uniformsNeedUpdate'] = true;
107
203
  }
108
- function handleRaycast(obj) {
109
- var _a, _b, _c;
110
- const state = (_a = getInstanceLocalState(obj)) === null || _a === void 0 ? void 0 : _a.stateFactory();
111
- // Skip event handling when noEvents is set, or when the raycasters camera is null
112
- if (!state || !state.events.enabled || state.raycaster.camera === null)
113
- return [];
114
- // When the camera is undefined we have to call the event layers update function
115
- if (state.raycaster.camera === undefined) {
116
- (_c = (_b = state.events).compute) === null || _c === void 0 ? void 0 : _c.call(_b, event, () => state, state.previousStateFactory);
117
- // If the camera is still undefined we have to skip this layer entirely
118
- if (state.raycaster.camera === undefined)
119
- state.raycaster.camera = null;
120
- }
121
- // Intersect object by object
122
- return state.raycaster.camera ? state.raycaster.intersectObject(obj, true) : [];
204
+ }
205
+ }
206
+ function checkUpdate(value) {
207
+ if (is.object3D(value)) {
208
+ value.updateMatrix();
209
+ }
210
+ if (is.camera(value)) {
211
+ if (is.perspectiveCamera(value) || is.orthographicCamera(value)) {
212
+ value.updateProjectionMatrix();
123
213
  }
124
- // Collect events
125
- let hits = eventsObjects
126
- // Intersect objects
127
- .flatMap(handleRaycast)
128
- // Sort by event priority and distance
129
- .sort((a, b) => {
130
- var _a, _b;
131
- const aState = (_a = getInstanceLocalState(a.object)) === null || _a === void 0 ? void 0 : _a.stateFactory();
132
- const bState = (_b = getInstanceLocalState(b.object)) === null || _b === void 0 ? void 0 : _b.stateFactory();
133
- if (!aState || !bState)
134
- return 0;
135
- return bState.events.priority - aState.events.priority || a.distance - b.distance;
136
- })
137
- // Filter out duplicates
138
- .filter((item) => {
139
- const id = makeId(item);
140
- if (duplicates.has(id))
141
- return false;
142
- duplicates.add(id);
143
- return true;
144
- });
145
- // https://github.com/mrdoob/three.js/issues/16031
146
- // Allow custom userland intersect sort order, this likely only makes sense on the root filter
147
- if (state.events.filter)
148
- hits = state.events.filter(hits, () => state);
149
- // Bubble up the events, find the event source (eventObject)
150
- for (const hit of hits) {
151
- let eventObject = hit.object;
152
- // Bubble event up
153
- while (eventObject) {
154
- if ((_d = getInstanceLocalState(eventObject)) === null || _d === void 0 ? void 0 : _d.eventCount)
155
- intersections.push(Object.assign(Object.assign({}, hit), { eventObject }));
156
- eventObject = eventObject.parent;
157
- }
214
+ value.updateMatrixWorld();
215
+ }
216
+ checkNeedsUpdate(value);
217
+ }
218
+ function updateCamera(camera, size) {
219
+ if (!camera.manual) {
220
+ if (is.orthographicCamera(camera)) {
221
+ camera.left = size.width / -2;
222
+ camera.right = size.width / 2;
223
+ camera.top = size.height / 2;
224
+ camera.bottom = size.height / -2;
158
225
  }
159
- // If the interaction is captured, make all capturing targets part of the intersect.
160
- if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) {
161
- for (const captureData of state.internal.capturedMap.get(event.pointerId).values()) {
162
- intersections.push(captureData.intersection);
163
- }
226
+ else {
227
+ camera.aspect = size.width / size.height;
164
228
  }
165
- return intersections;
166
- }
167
- /** Handles intersections by forwarding them to handlers */
168
- function handleIntersects(intersections, event, delta, callback) {
169
- var _a;
170
- const rootState = stateFactory();
171
- // If anything has been found, forward it to the event listeners
172
- if (intersections.length) {
173
- const localState = { stopped: false };
174
- for (const hit of intersections) {
175
- const state = ((_a = getInstanceLocalState(hit.object)) === null || _a === void 0 ? void 0 : _a.stateFactory()) || rootState;
176
- const { raycaster, pointer, camera, internal } = state;
177
- const unprojectedPoint = new THREE.Vector3(pointer.x, pointer.y, 0).unproject(camera);
178
- const hasPointerCapture = (id) => { var _a, _b; return (_b = (_a = internal.capturedMap.get(id)) === null || _a === void 0 ? void 0 : _a.has(hit.eventObject)) !== null && _b !== void 0 ? _b : false; };
179
- const setPointerCapture = (id) => {
180
- const captureData = {
181
- intersection: hit,
182
- target: event.target,
183
- };
184
- if (internal.capturedMap.has(id)) {
185
- // if the pointerId was previously captured, we add the hit to the
186
- // event capturedMap.
187
- internal.capturedMap.get(id).set(hit.eventObject, captureData);
188
- }
189
- else {
190
- // if the pointerId was not previously captured, we create a map
191
- // containing the hitObject, and the hit. hitObject is used for
192
- // faster access.
193
- internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
194
- }
195
- // Call the original event now
196
- event.target.setPointerCapture(id);
197
- };
198
- const releasePointerCapture = (id) => {
199
- const captures = internal.capturedMap.get(id);
200
- if (captures) {
201
- releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
202
- }
203
- };
204
- // Add native event props
205
- const extractEventProps = {};
206
- // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones.
207
- for (const prop in event) {
208
- const property = event[prop];
209
- // Only copy over atomics, leave functions alone as these should be
210
- // called as event.nativeEvent.fn()
211
- if (typeof property !== 'function')
212
- extractEventProps[prop] = property;
213
- }
214
- const raycastEvent = Object.assign(Object.assign(Object.assign({}, hit), extractEventProps), { pointer,
215
- intersections, stopped: localState.stopped, delta,
216
- unprojectedPoint, ray: raycaster.ray, camera: camera,
217
- // Hijack stopPropagation, which just sets a flag
218
- stopPropagation() {
219
- // https://github.com/pmndrs/react-three-fiber/issues/596
220
- // Events are not allowed to stop propagation if the pointer has been captured
221
- const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId);
222
- // We only authorize stopPropagation...
223
- if (
224
- // ...if this pointer hasn't been captured
225
- !capturesForPointer ||
226
- // ... or if the hit object is capturing the pointer
227
- capturesForPointer.has(hit.eventObject)) {
228
- raycastEvent.stopped = localState.stopped = true;
229
- // Propagation is stopped, remove all other hover records
230
- // An event handler is only allowed to flush other handlers if it is hovered itself
231
- if (internal.hovered.size &&
232
- Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
233
- // Objects cannot flush out higher up objects that have already caught the event
234
- const higher = intersections.slice(0, intersections.indexOf(hit));
235
- cancelPointer([...higher, hit]);
236
- }
237
- }
238
- },
239
- // there should be a distinction between target and currentTarget
240
- target: {
241
- hasPointerCapture,
242
- setPointerCapture,
243
- releasePointerCapture,
244
- }, currentTarget: {
245
- hasPointerCapture,
246
- setPointerCapture,
247
- releasePointerCapture,
248
- }, nativeEvent: event });
249
- // Call subscribers
250
- callback(raycastEvent);
251
- // Event bubbling may be interrupted by stopPropagation
252
- if (localState.stopped === true)
253
- break;
254
- }
255
- }
256
- return intersections;
257
- }
258
- function cancelPointer(intersections) {
259
- var _a, _b;
260
- const { internal } = stateFactory();
261
- for (const hoveredObj of internal.hovered.values()) {
262
- // When no objects were hit or the hovered object wasn't found underneath the cursor
263
- // we call onPointerOut and delete the object from the hovered-elements map
264
- if (!intersections.length ||
265
- !intersections.find((hit) => hit.object === hoveredObj.object &&
266
- hit.index === hoveredObj.index &&
267
- hit.instanceId === hoveredObj.instanceId)) {
268
- const eventObject = hoveredObj.eventObject;
269
- const instance = getInstanceLocalState(eventObject);
270
- const handlers = instance === null || instance === void 0 ? void 0 : instance.handlers;
271
- internal.hovered.delete(makeId(hoveredObj));
272
- if (instance === null || instance === void 0 ? void 0 : instance.eventCount) {
273
- // Clear out intersects, they are outdated by now
274
- const data = Object.assign(Object.assign({}, hoveredObj), { intersections });
275
- (_a = handlers === null || handlers === void 0 ? void 0 : handlers.pointerout) === null || _a === void 0 ? void 0 : _a.call(handlers, data);
276
- (_b = handlers === null || handlers === void 0 ? void 0 : handlers.pointerleave) === null || _b === void 0 ? void 0 : _b.call(handlers, data);
277
- }
278
- }
279
- }
280
- }
281
- function pointerMissed(event, objects) {
282
- var _a, _b;
283
- for (let i = 0; i < objects.length; i++) {
284
- const instance = getInstanceLocalState(objects[i]);
285
- (_b = instance === null || instance === void 0 ? void 0 : (_a = instance.handlers).pointermissed) === null || _b === void 0 ? void 0 : _b.call(_a, event);
286
- }
287
- }
288
- function handlePointer(name) {
289
- // Deal with cancelation
290
- switch (name) {
291
- case 'pointerleave':
292
- case 'pointercancel':
293
- return () => cancelPointer([]);
294
- case 'lostpointercapture':
295
- return (event) => {
296
- const { internal } = stateFactory();
297
- if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) {
298
- // If the object event interface had onLostPointerCapture, we'd call it here on every
299
- // object that's getting removed.
300
- internal.capturedMap.delete(event.pointerId);
301
- cancelPointer([]);
302
- }
303
- };
304
- }
305
- // Any other pointer goes here ...
306
- return function handleEvent(event) {
307
- const { onPointerMissed, internal } = stateFactory();
308
- // prepareRay(event)
309
- internal.lastEvent = event;
310
- // Get fresh intersects
311
- const isPointerMove = name === 'pointermove';
312
- const isClickEvent = name === 'click' || name === 'contextmenu' || name === 'dblclick';
313
- const filter = isPointerMove ? filterPointerEvents : undefined;
314
- // const hits = patchIntersects(intersect(filter), event)
315
- const hits = intersect(event, filter);
316
- const delta = isClickEvent ? calculateDistance(event) : 0;
317
- // Save initial coordinates on pointer-down
318
- if (name === 'pointerdown') {
319
- internal.initialClick = [event.offsetX, event.offsetY];
320
- internal.initialHits = hits.map((hit) => hit.eventObject);
321
- }
322
- // If a click yields no results, pass it back to the user as a miss
323
- // Missed events have to come first in order to establish user-land side-effect clean up
324
- if (isClickEvent && !hits.length) {
325
- if (delta <= 2) {
326
- pointerMissed(event, internal.interaction);
327
- if (onPointerMissed)
328
- onPointerMissed(event);
329
- }
330
- }
331
- // Take care of unhover
332
- if (isPointerMove)
333
- cancelPointer(hits);
334
- function onIntersect(data) {
335
- var _a, _b, _c;
336
- const eventObject = data.eventObject;
337
- const instance = getInstanceLocalState(eventObject);
338
- const handlers = instance === null || instance === void 0 ? void 0 : instance.handlers;
339
- // Check presence of handlers
340
- if (!(instance === null || instance === void 0 ? void 0 : instance.eventCount))
341
- return;
342
- if (isPointerMove) {
343
- // Move event ...
344
- if ((handlers === null || handlers === void 0 ? void 0 : handlers.pointerover) ||
345
- (handlers === null || handlers === void 0 ? void 0 : handlers.pointerenter) ||
346
- (handlers === null || handlers === void 0 ? void 0 : handlers.pointerout) ||
347
- (handlers === null || handlers === void 0 ? void 0 : handlers.pointerleave)) {
348
- // When enter or out is present take care of hover-state
349
- const id = makeId(data);
350
- const hoveredItem = internal.hovered.get(id);
351
- if (!hoveredItem) {
352
- // If the object wasn't previously hovered, book it and call its handler
353
- internal.hovered.set(id, data);
354
- (_a = handlers.pointerover) === null || _a === void 0 ? void 0 : _a.call(handlers, data);
355
- (_b = handlers.pointerenter) === null || _b === void 0 ? void 0 : _b.call(handlers, data);
356
- }
357
- else if (hoveredItem.stopped) {
358
- // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
359
- data.stopPropagation();
360
- }
361
- }
362
- // Call mouse move
363
- (_c = handlers === null || handlers === void 0 ? void 0 : handlers.pointermove) === null || _c === void 0 ? void 0 : _c.call(handlers, data);
364
- }
365
- else {
366
- // All other events ...
367
- const handler = handlers[name];
368
- if (handler) {
369
- // Forward all events back to their respective handlers with the exception of click events,
370
- // which must use the initial target
371
- if (!isClickEvent || internal.initialHits.includes(eventObject)) {
372
- // Missed events have to come first
373
- pointerMissed(event, internal.interaction.filter((object) => !internal.initialHits.includes(object)));
374
- // Now call the handler
375
- handler(data);
376
- }
377
- }
378
- else {
379
- // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit
380
- if (isClickEvent && internal.initialHits.includes(eventObject)) {
381
- pointerMissed(event, internal.interaction.filter((object) => !internal.initialHits.includes(object)));
382
- }
383
- }
384
- }
385
- }
386
- handleIntersects(hits, event, delta, onIntersect);
387
- };
388
- }
389
- return { handlePointer };
390
- }
391
-
392
- const DOM_EVENTS = {
393
- click: false,
394
- contextmenu: false,
395
- dblclick: false,
396
- wheel: false,
397
- pointerdown: true,
398
- pointerup: true,
399
- pointerleave: true,
400
- pointermove: true,
401
- pointercancel: true,
402
- lostpointercapture: true,
403
- };
404
- function createPointerEvents(stateFactory) {
405
- const { handlePointer } = createEvents(stateFactory);
406
- return {
407
- priority: 1,
408
- enabled: true,
409
- compute: (event, rootFactory) => {
410
- const state = rootFactory();
411
- // https://github.com/pmndrs/react-three-fiber/pull/782
412
- // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides
413
- state.pointer.set((event.offsetX / state.size.width) * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
414
- state.raycaster.setFromCamera(state.pointer, state.camera);
415
- },
416
- connected: undefined,
417
- handlers: Object.keys(DOM_EVENTS).reduce((handlers, supportedEventName) => {
418
- handlers[supportedEventName] = handlePointer(supportedEventName);
419
- return handlers;
420
- }, {}),
421
- connect: (target) => {
422
- var _a, _b, _c;
423
- const state = stateFactory();
424
- (_b = (_a = state.events).disconnect) === null || _b === void 0 ? void 0 : _b.call(_a);
425
- state.setEvents({ connected: target });
426
- Object.entries((_c = state.events.handlers) !== null && _c !== void 0 ? _c : {}).forEach(([eventName, eventHandler]) => {
427
- const passive = DOM_EVENTS[eventName];
428
- target.addEventListener(eventName, eventHandler, { passive });
429
- });
430
- },
431
- disconnect: () => {
432
- var _a;
433
- const { events, setEvents } = stateFactory();
434
- if (events.connected) {
435
- Object.entries((_a = events.handlers) !== null && _a !== void 0 ? _a : {}).forEach(([eventName, eventHandler]) => {
436
- if (events.connected instanceof HTMLElement) {
437
- events.connected.removeEventListener(eventName, eventHandler);
438
- }
439
- });
440
- setEvents({ connected: undefined });
441
- }
442
- },
443
- };
444
- }
445
-
446
- class NgtRef extends BehaviorSubject {
447
- constructor(value) {
448
- super(value ? value : null);
449
- }
450
- set(valueOrFactory) {
451
- if (typeof valueOrFactory === 'function') {
452
- this.next(valueOrFactory(this.value));
453
- }
454
- else {
455
- this.next(valueOrFactory);
456
- }
457
- }
458
- }
459
-
460
- const is = {
461
- obj: (a) => a === Object(a) && !Array.isArray(a) && typeof a !== 'function',
462
- material: (a) => !!a && a.isMaterial,
463
- geometry: (a) => !!a && a.isBufferGeometry,
464
- mesh: (a) => !!a && a.isMesh,
465
- color: (a) => !!a && a.isColor,
466
- orthographic: (a) => !!a && a.isOrthographicCamera,
467
- perspective: (a) => !!a && a.isPerspectiveCamera,
468
- camera: (a) => !!a && a.isCamera,
469
- glRenderer: (a) => !!a && a instanceof THREE.WebGLRenderer,
470
- scene: (a) => !!a && a.isScene,
471
- object3d: (a) => !!a && a.isObject3D,
472
- instance: (a) => !!a && !!a['__ngt__'],
473
- ref: (a) => !!a && a instanceof NgtRef,
474
- supportColorManagement: () => 'ColorManagement' in THREE,
475
- canvas: (a) => a instanceof HTMLCanvasElement,
476
- equ(a, b, { arrays = 'shallow', objects = 'reference', strict = true } = {}) {
477
- // Wrong type or one of the two undefined, doesn't match
478
- if (typeof a !== typeof b || !!a !== !!b)
479
- return false;
480
- // Atomic, just compare a against b
481
- if (typeof a === 'string' || typeof a === 'number')
482
- return a === b;
483
- const isObj = is.obj(a);
484
- if (isObj && objects === 'reference')
485
- return a === b;
486
- const isArr = Array.isArray(a);
487
- if (isArr && arrays === 'reference')
488
- return a === b;
489
- // Array or Object, shallow compare first to see if it's a match
490
- if ((isArr || isObj) && a === b)
491
- return true;
492
- // Last resort, go through keys
493
- let i;
494
- for (i in a)
495
- if (!(i in b))
496
- return false;
497
- for (i in strict ? b : a)
498
- if (a[i] !== b[i])
499
- return false;
500
- if (i === void 0) {
501
- if (isArr && a.length === 0 && b.length === 0)
502
- return true;
503
- if (isObj && Object.keys(a).length === 0 && Object.keys(b).length === 0)
504
- return true;
505
- if (a !== b)
506
- return false;
507
- }
508
- return true;
509
- },
510
- };
511
-
512
- /**
513
- * a default Selector that consumers can quickly use for their selectors projector
514
- */
515
- const defaultProjector = () => ({});
516
- /**
517
- * A custom operator that skips the first undefined value but allows subsequent undefined values.
518
- * NgRxComponentStore#select always emits the first value regardless of undefined or not after initialize
519
- */
520
- const skipFirstUndefined = () => filter((value, index) => index > 0 || value !== undefined);
521
- /**
522
- * An extended `tap` operator that accepts an `effectFn` which:
523
- * - runs on every `next` notification from `source$`
524
- * - can optionally return a `cleanUp` function that
525
- * invokes from the 2nd `next` notification onward and on `unsubscribe` (destroyed)
526
- *
527
- *
528
- * @example
529
- * ```typescript
530
- * source$.pipe(
531
- * tapEffect((sourceValue) = {
532
- * const cb = () => {
533
- * doStuff(sourceValue);
534
- * };
535
- * addListener('event', cb);
536
- *
537
- * return () => {
538
- * removeListener('event', cb);
539
- * }
540
- * })
541
- * )
542
- * ```
543
- */
544
- function tapEffect(effectFn) {
545
- let cleanupFn = noop;
546
- let firstRun = false;
547
- let prev = undefined;
548
- const teardown = (error) => {
549
- return () => {
550
- if (cleanupFn) {
551
- cleanupFn({ prev, complete: true, error });
552
- }
553
- };
554
- };
555
- return tap({
556
- next: (value) => {
557
- if (cleanupFn && firstRun) {
558
- cleanupFn({ prev, complete: false, error: false });
559
- }
560
- const cleanUpOrVoid = effectFn(value);
561
- if (cleanUpOrVoid) {
562
- cleanupFn = cleanUpOrVoid;
563
- }
564
- prev = value;
565
- if (!firstRun) {
566
- firstRun = true;
567
- }
568
- },
569
- complete: teardown(false),
570
- unsubscribe: teardown(false),
571
- error: teardown(true),
572
- });
573
- }
574
- class NgtComponentStore extends ComponentStore {
575
- constructor() {
576
- super({});
577
- // exposing get since THREE is imperative at its core
578
- // we need to imperatively get state sometimes for usages in Animation Loop
579
- // we also bind "this" instance, so we don't have to bind it later
580
- this.read = this.get.bind(this);
581
- this.initialize();
582
- }
583
- /**
584
- * A custom patchState that allows for:
585
- * - Partial state updates and Observable of partial state updates like patchState
586
- * - Pass a Record<string, ObservableInput> to update a specific key with an Observable.
587
- * This is similar to `RxState.connect()` API
588
- */
589
- write(partialStateOrFactory) {
590
- if (typeof partialStateOrFactory === 'function') {
591
- return this.write(partialStateOrFactory(this.read()));
592
- }
593
- const partialState = partialStateOrFactory;
594
- if (Object.keys(partialState).length === 0) {
595
- return;
596
- }
597
- if (isObservable(partialState)) {
598
- return this.patchState(partialState);
599
- }
600
- const entries = Object.entries(partialState);
601
- const hasObservable = entries.some(([_, value]) => isObservable(value) && !is.ref(value));
602
- if (!hasObservable) {
603
- return this.patchState(partialState);
604
- }
605
- const [rawValues, observableValues] = entries.reduce((result, [key, value]) => {
606
- if (isObservable(value)) {
607
- result[1][key] = value;
608
- }
609
- else {
610
- result[0][key] = value;
611
- }
612
- return result;
613
- }, [{}, {}]);
614
- if (Object.keys(rawValues).length > 0) {
615
- this.patchState(rawValues);
616
- }
617
- if (Object.keys(observableValues).length > 0) {
618
- this.patchState(combineLatest(observableValues));
619
- }
620
- }
621
- initialize() {
622
- return;
623
- }
624
- /**
625
- * A utility class method to select a state on the template as Observable
626
- * - This method always debounce the Observable
627
- */
628
- selectKey(key, skipFirst = false) {
629
- return this.select((s) => s[key], { debounce: true }).pipe(skipFirst ? skipFirstUndefined() : (s) => s);
630
- }
631
- /**
632
- * A utility class method to get a state on the template as imperative Value
633
- */
634
- readKey(key) {
635
- return this.read((s) => s[key]);
636
- }
637
- }
638
- NgtComponentStore.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtComponentStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
639
- NgtComponentStore.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtComponentStore });
640
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtComponentStore, decorators: [{
641
- type: Injectable
642
- }], ctorParameters: function () { return []; } });
643
-
644
- function createInjection(description, { defaultValueOrFactory, provideValueFactory, } = {}) {
645
- const factory = (defaultValueOrFactory && typeof defaultValueOrFactory === 'function'
646
- ? defaultValueOrFactory
647
- : () => defaultValueOrFactory);
648
- const injectionToken = new InjectionToken(description, { factory });
649
- function injectFn(options = {}) {
650
- return inject(injectionToken, options);
651
- }
652
- function provideFn(value) {
653
- return {
654
- provide: injectionToken,
655
- useValue: provideValueFactory ? provideValueFactory(value) : value,
656
- };
229
+ camera.updateProjectionMatrix();
230
+ camera.updateMatrixWorld();
657
231
  }
658
- return [injectFn, provideFn, injectionToken];
659
232
  }
660
233
 
661
- const [injectWindow] = createInjection('window', {
662
- defaultValueOrFactory: () => {
663
- const { defaultView } = inject(DOCUMENT);
664
- if (!defaultView) {
665
- throw `window is not available!`;
666
- }
667
- return defaultView;
668
- },
669
- });
670
-
671
- function checkNeedsUpdate(value) {
672
- if (value !== null && is.obj(value) && 'needsUpdate' in value) {
673
- value['needsUpdate'] = true;
674
- if ('uniformsNeedUpdate' in value) {
675
- value['uniformsNeedUpdate'] = true;
676
- }
677
- }
678
- }
679
- function checkUpdate(value) {
680
- if (is.object3d(value)) {
681
- value.updateMatrix();
682
- }
683
- else if (is.camera(value)) {
684
- if (is.perspective(value) || is.orthographic(value)) {
685
- value.updateProjectionMatrix();
686
- }
687
- value.updateMatrixWorld();
688
- }
689
- checkNeedsUpdate(value);
234
+ function getLocalState(obj) {
235
+ if (!obj)
236
+ return {};
237
+ return obj['__ngt__'] || {};
690
238
  }
691
-
692
239
  function invalidateInstance(instance) {
693
240
  var _a;
694
- const state = (_a = getInstanceLocalState(instance)) === null || _a === void 0 ? void 0 : _a.stateFactory();
241
+ const state = (_a = getLocalState(instance).store) === null || _a === void 0 ? void 0 : _a.get();
695
242
  if (state && state.internal.frames === 0)
696
243
  state.invalidate();
697
244
  checkUpdate(instance);
698
245
  }
699
- function prepare(instance, parentStateFactory, rootStateFactory, parentInstance, previousInstance, isPrimitive = false) {
700
- var _a, _b, _c, _d;
701
- const previousInstanceInternal = getInstanceLocalState(previousInstance === null || previousInstance === void 0 ? void 0 : previousInstance.value);
702
- const parent = parentInstance
703
- ? parentInstance
704
- : previousInstanceInternal
705
- ? previousInstanceInternal.parentRef
706
- : undefined;
707
- if (is.scene(instance)) {
708
- applyProps(instance, { dispose: null });
709
- }
710
- return Object.assign(instance, {
711
- __ngt__: {
712
- stateFactory: parentStateFactory,
713
- rootFactory: rootStateFactory,
714
- isPrimitive: !isPrimitive ? previousInstanceInternal === null || previousInstanceInternal === void 0 ? void 0 : previousInstanceInternal.isPrimitive : isPrimitive,
715
- eventCount: (_a = previousInstanceInternal === null || previousInstanceInternal === void 0 ? void 0 : previousInstanceInternal.eventCount) !== null && _a !== void 0 ? _a : 0,
716
- handlers: (_b = previousInstanceInternal === null || previousInstanceInternal === void 0 ? void 0 : previousInstanceInternal.handlers) !== null && _b !== void 0 ? _b : {},
717
- instancesRefs: (_c = previousInstanceInternal === null || previousInstanceInternal === void 0 ? void 0 : previousInstanceInternal.instancesRefs) !== null && _c !== void 0 ? _c : new NgtRef([]),
718
- objectsRefs: (_d = previousInstanceInternal === null || previousInstanceInternal === void 0 ? void 0 : previousInstanceInternal.objectsRefs) !== null && _d !== void 0 ? _d : new NgtRef([]),
719
- parentRef: parent ? (parent === instance || parent.value === instance ? null : parent) : null,
720
- },
721
- });
246
+ function prepare(object, localState) {
247
+ const instance = object;
248
+ if ((localState === null || localState === void 0 ? void 0 : localState.primitive) || !instance.__ngt__) {
249
+ const _a = localState || {}, { objects = new BehaviorSubject([]), nonObjects = new BehaviorSubject([]) } = _a, rest = __rest(_a, ["objects", "nonObjects"]);
250
+ instance.__ngt__ = Object.assign({ previousAttach: null, store: null, parent: null, memoized: {}, eventCount: 0, handlers: {}, objects,
251
+ nonObjects, add: (object, type) => {
252
+ instance.__ngt__[type].next([...instance.__ngt__[type].value, object]);
253
+ notifyAncestors(instance.__ngt__.parent);
254
+ }, remove: (object, type) => {
255
+ instance.__ngt__[type].next(instance.__ngt__[type].value.filter((o) => o !== object));
256
+ notifyAncestors(instance.__ngt__.parent);
257
+ } }, rest);
258
+ }
259
+ return instance;
260
+ }
261
+ function notifyAncestors(instance) {
262
+ if (!instance)
263
+ return;
264
+ const localState = getLocalState(instance);
265
+ if (localState.objects)
266
+ localState.objects.next(localState.objects.value);
267
+ if (localState.nonObjects)
268
+ localState.nonObjects.next(localState.nonObjects.value);
269
+ notifyAncestors(localState.parent);
722
270
  }
723
271
 
724
- const DEFAULT = '__default';
725
- function diffProps(instance, props, previousProps = {}, remove = false) {
726
- const localState = getInstanceLocalState(instance) || {};
272
+ function diffProps(instance, props) {
727
273
  const propsEntries = Object.entries(props);
728
274
  const changes = [];
729
- // Catch removed props, prepend them, so they can be reset or removed
730
- if (remove) {
731
- const previousKeys = Object.keys(previousProps);
732
- for (const previousKey of previousKeys) {
733
- // @ts-ignore
734
- if (!Object.hasOwn(props, previousKey)) {
735
- propsEntries.unshift([previousKey, DEFAULT + 'remove']);
736
- }
737
- }
738
- }
739
275
  for (const [propKey, propValue] of propsEntries) {
740
- if (is.equ(propValue, previousProps[propKey]))
276
+ if (is.equ(propValue, instance[propKey]))
741
277
  continue;
742
- changes.push([propKey, propValue]);
743
- }
744
- const memoized = Object.assign({}, props);
745
- if (localState.memoized && localState.memoized['args']) {
746
- memoized['args'] = localState.memoized['args'];
747
- }
748
- if (localState.memoized && localState.memoized['attach']) {
749
- memoized['attach'] = localState.memoized['attach'] || localState.attach;
750
- }
751
- return { changes, memoized };
752
- }
753
- function applyProps(instance, props) {
754
- var _a, _b, _c, _d;
755
- // props is empty
756
- if (!Object.keys(props).length)
757
- return instance;
758
- // Filter equals, events and reserved props
759
- const localState = getInstanceLocalState(instance) || {};
760
- const rootState = (_a = localState.stateFactory) === null || _a === void 0 ? void 0 : _a.call(localState);
761
- const { changes, memoized } = diffProps(instance, props);
762
- const instanceHandlers = localState.eventCount;
763
- if (getInstanceLocalState(instance)) {
764
- getInstanceLocalState(instance).memoized = memoized;
765
- }
766
- for (let i = 0; i < changes.length; i++) {
767
- const key = changes[i][0];
768
- const currentInstance = instance;
769
- const targetProp = currentInstance[key];
770
- let value = changes[i][1];
771
- if (is.ref(value)) {
772
- value = value.value;
773
- }
774
- if (value === DEFAULT + 'remove') {
775
- if (targetProp && targetProp.constructor) {
776
- // use the prop constructor to find the default it should be
777
- value = new targetProp.constructor(...((_b = memoized['args']) !== null && _b !== void 0 ? _b : []));
778
- }
779
- else if (currentInstance.constructor) {
780
- const dummyInstance = new currentInstance.constructor(...(((_d = (_c = getInstanceLocalState(currentInstance)) === null || _c === void 0 ? void 0 : _c.memoized) === null || _d === void 0 ? void 0 : _d['args']) || []));
781
- value = dummyInstance[targetProp];
782
- // destroy the instance
783
- if (dummyInstance.dispose)
784
- dummyInstance.dispose();
785
- }
786
- else {
787
- value = 0;
788
- }
789
- }
790
- // Special treatment for objects with support for set/copy, and layers
791
- if (targetProp && targetProp['set'] && (targetProp['copy'] || targetProp instanceof THREE.Layers)) {
792
- const isColor = targetProp instanceof THREE.Color;
793
- // If value is an array
794
- if (Array.isArray(value)) {
795
- if (targetProp['fromArray'])
796
- targetProp['fromArray'](value);
797
- else
798
- targetProp['set'](...value);
799
- }
800
- // Test again target.copy(class) next ...
801
- else if (targetProp['copy'] &&
802
- value &&
803
- value.constructor &&
804
- targetProp.constructor.name === value.constructor.name) {
805
- targetProp['copy'](value);
806
- if (!is.supportColorManagement() && !rootState.linear && isColor) {
807
- targetProp['convertSRGBToLinear']();
808
- }
809
- }
810
- // If nothing else fits, just set the single value, ignore undefined
811
- // https://github.com/pmndrs/react-three-fiber/issues/274
812
- else if (value !== undefined) {
813
- const isColor = targetProp instanceof THREE.Color;
814
- // Allow setting array scalars
815
- if (!isColor && targetProp['setScalar'])
816
- targetProp['setScalar'](value);
817
- // Layers have no copy function, we must therefore copy the mask property
818
- else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers)
819
- targetProp.mask = value.mask;
820
- // Otherwise just set ...
821
- else
822
- targetProp['set'](value);
823
- // For versions of three which don't support THREE.ColorManagement,
824
- // Auto-convert sRGB colors
825
- // https://github.com/pmndrs/react-three-fiber/issues/344
826
- if (!is.supportColorManagement() && !rootState.linear && isColor)
827
- targetProp.convertSRGBToLinear();
828
- }
829
- // Else, just overwrite the value
830
- }
831
- else {
832
- currentInstance[key] = value;
833
- // Auto-convert sRGB textures, for now ...
834
- // https://github.com/pmndrs/react-three-fiber/issues/344
835
- if (!(rootState === null || rootState === void 0 ? void 0 : rootState.linear) && currentInstance[key] instanceof THREE.Texture) {
836
- currentInstance[key]['encoding'] = THREE.sRGBEncoding;
837
- }
838
- }
839
- checkNeedsUpdate(targetProp);
840
- invalidateInstance(instance);
841
- }
842
- if (localState.parentRef &&
843
- rootState.internal &&
844
- instance['raycast'] &&
845
- instanceHandlers !== localState.eventCount) {
846
- // Pre-emptively remove the instance from the interaction manager
847
- rootState.removeInteraction(instance['uuid']);
848
- // Add the instance to the interaction manager only when it has handlers
849
- if (localState.eventCount)
850
- rootState.addInteraction(instance);
851
- }
852
- return instance;
853
- }
854
-
855
- function updateCamera(camera, size) {
856
- // https://github.com/pmndrs/react-three-fiber/issues/92
857
- // Do not mess with the camera if it belongs to the user
858
- if (!camera.manual) {
859
- if (is.orthographic(camera)) {
860
- camera.left = size.width / -2;
861
- camera.right = size.width / 2;
862
- camera.top = size.height / 2;
863
- camera.bottom = size.height / -2;
864
- }
865
- else {
866
- camera.aspect = size.width / size.height;
867
- }
868
- camera.updateProjectionMatrix();
869
- // https://github.com/pmndrs/react-three-fiber/issues/178
870
- // Update matrix world since the renderer is a frame late
871
- camera.updateMatrixWorld();
872
- }
873
- }
874
- function createDefaultCamera(isOrthographic, size) {
875
- if (isOrthographic) {
876
- return new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000);
877
- }
878
- return new THREE.PerspectiveCamera(75, size.width / size.height, 0.1, 1000);
879
- }
880
-
881
- function createSubs(callback, subs) {
882
- const sub = { callback };
883
- subs.add(sub);
884
- return () => void subs.delete(sub);
885
- }
886
- const globalEffects = new Set();
887
- const globalAfterEffects = new Set();
888
- const globalTailEffects = new Set();
889
- /**
890
- * Adds a global render callback which is called each frame.
891
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addEffect
892
- */
893
- const addEffect = (callback) => createSubs(callback, globalEffects);
894
- /**
895
- * Adds a global after-render callback which is called each frame.
896
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addAfterEffect
897
- */
898
- const addAfterEffect = (callback) => createSubs(callback, globalAfterEffects);
899
- /**
900
- * Adds a global callback which is called when rendering stops.
901
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#addTail
902
- */
903
- const addTail = (callback) => createSubs(callback, globalTailEffects);
904
- function run(effects, timestamp) {
905
- if (!effects.size)
906
- return;
907
- for (const { callback } of effects.values()) {
908
- callback(timestamp);
909
- }
910
- }
911
- function flushGlobalEffects(type, timestamp) {
912
- switch (type) {
913
- case 'before':
914
- return run(globalEffects, timestamp);
915
- case 'after':
916
- return run(globalAfterEffects, timestamp);
917
- case 'tail':
918
- return run(globalTailEffects, timestamp);
919
- }
920
- }
921
- function render(timestamp, stateFactory, frame) {
922
- const state = stateFactory();
923
- // Run local effects
924
- let delta = state.clock.getDelta();
925
- // In frameloop='never' mode, clock times are updated using the provided timestamp
926
- if (state.frameloop === 'never' && typeof timestamp === 'number') {
927
- delta = timestamp - state.clock.elapsedTime;
928
- state.clock.oldTime = state.clock.elapsedTime;
929
- state.clock.elapsedTime = timestamp;
930
- }
931
- // Call subscribers (useFrame)
932
- // subscribers = state.internal.subscribers;
933
- for (let i = 0; i < state.internal.subscribers.length; i++) {
934
- const subscriber = state.internal.subscribers[i];
935
- const object = is.ref(subscriber.obj) ? subscriber.obj.value : subscriber.obj;
936
- subscriber.callback(Object.assign(Object.assign({}, state), { delta, frame }), object);
278
+ changes.push([propKey, propValue]);
937
279
  }
938
- // Render content
939
- if (!state.internal.priority && state.gl.render)
940
- state.gl.render(state.scene, state.camera);
941
- // Decrease frame count
942
- state.internal.frames = Math.max(0, state.internal.frames - 1);
943
- return state.frameloop === 'always' ? 1 : state.internal.frames;
280
+ return changes;
944
281
  }
945
- function createLoop(roots) {
946
- let running = false;
947
- let repeat;
948
- let frame;
949
- let state;
950
- function loop(timestamp) {
951
- var _a;
952
- frame = requestAnimationFrame(loop);
953
- running = true;
954
- repeat = 0;
955
- // Run effects
956
- flushGlobalEffects('before', timestamp);
957
- // Render all roots
958
- for (const root of roots.values()) {
959
- state = root();
960
- // If the frameloop is invalidated, do not run another frame
961
- if (state.internal.active &&
962
- (state.frameloop === 'always' || state.internal.frames > 0) &&
963
- !((_a = state.gl.xr) === null || _a === void 0 ? void 0 : _a.isPresenting)) {
964
- repeat += render(timestamp, root);
282
+ function applyProps(instance, props) {
283
+ var _a;
284
+ // if props is empty
285
+ if (!Object.keys(props).length)
286
+ return instance;
287
+ // filter equals, events , and reserved props
288
+ const localState = getLocalState(instance);
289
+ const rootState = (_a = localState.store) === null || _a === void 0 ? void 0 : _a.get();
290
+ const changes = diffProps(instance, props);
291
+ for (let i = 0; i < changes.length; i++) {
292
+ const key = changes[i][0];
293
+ const currentInstance = instance;
294
+ const targetProp = currentInstance[key];
295
+ const value = changes[i][1];
296
+ // special treatmen for objects with support for set/copy, and layers
297
+ if (targetProp && targetProp['set'] && (targetProp['copy'] || targetProp instanceof THREE.Layers)) {
298
+ const isColor = targetProp instanceof THREE.Color;
299
+ // if value is an array
300
+ if (Array.isArray(value)) {
301
+ if (targetProp['fromArray'])
302
+ targetProp['fromArray'](value);
303
+ else
304
+ targetProp['set'](...value);
305
+ }
306
+ // test again target.copy
307
+ else if (targetProp['copy'] &&
308
+ value &&
309
+ value.constructor &&
310
+ targetProp.constructor.name === value.constructor.name) {
311
+ targetProp['copy'](value);
312
+ if (!THREE.ColorManagement && !rootState.linear && isColor) {
313
+ targetProp['convertSRGBToLinear']();
314
+ }
315
+ }
316
+ // if nothing else fits, just set the single value, ignore undefined
317
+ else if (value !== undefined) {
318
+ const isColor = targetProp instanceof THREE.Color;
319
+ // allow setting array scalars
320
+ if (!isColor && targetProp['setScalar'])
321
+ targetProp['setScalar'](value);
322
+ // layers have no copy function, copy the mask
323
+ else if (targetProp instanceof THREE.Layers && value instanceof THREE.Layers) {
324
+ targetProp.mask = value.mask;
325
+ }
326
+ // otherwise just set ...
327
+ else {
328
+ targetProp['set'](value);
329
+ }
330
+ // auto-convert srgb
331
+ if (!THREE.ColorManagement && !(rootState === null || rootState === void 0 ? void 0 : rootState.linear) && isColor) {
332
+ targetProp.convertSRGBToLinear();
333
+ }
965
334
  }
966
335
  }
967
- // Run after-effects
968
- flushGlobalEffects('after', timestamp);
969
- // Stop the loop if nothing invalidates it
970
- if (repeat === 0) {
971
- // Tail call effects, they are called when rendering stops
972
- flushGlobalEffects('tail', timestamp);
973
- // Flag end of operation
974
- running = false;
975
- return cancelAnimationFrame(frame);
336
+ // else just overwrite the value
337
+ else {
338
+ currentInstance[key] = value;
339
+ // auto-convert srgb textures
340
+ if (!(rootState === null || rootState === void 0 ? void 0 : rootState.linear) && currentInstance[key] instanceof THREE.Texture) {
341
+ currentInstance[key]['encoding'] = THREE.sRGBEncoding;
342
+ }
976
343
  }
344
+ checkUpdate(targetProp);
345
+ invalidateInstance(instance);
977
346
  }
978
- function invalidate(stateFactory, frames = 1) {
979
- var _a;
980
- const stateToInvalidate = stateFactory === null || stateFactory === void 0 ? void 0 : stateFactory();
981
- if (!stateToInvalidate)
982
- return roots.forEach((root) => invalidate(root, frames));
983
- if (((_a = stateToInvalidate.gl.xr) === null || _a === void 0 ? void 0 : _a.isPresenting) ||
984
- !stateToInvalidate.internal.active ||
985
- stateToInvalidate.frameloop === 'never')
986
- return;
987
- // Increase frames, do not go higher than 60
988
- stateToInvalidate.internal.frames = Math.min(60, stateToInvalidate.internal.frames + frames);
989
- // If the render-loop isn't active, start it
990
- if (!running) {
991
- running = true;
992
- requestAnimationFrame(loop);
993
- }
347
+ const instanceHandlers = localState.eventCount;
348
+ if (localState.parent && rootState.internal && instance['raycast'] && instanceHandlers !== localState.eventCount) {
349
+ // pre-emptively remove the interaction from manager
350
+ rootState.removeInteraction(instance['uuid']);
351
+ // add the instance to the interaction manager only when it has handlers
352
+ if (localState.eventCount)
353
+ rootState.addInteraction(instance);
994
354
  }
995
- function advance(timestamp, runGlobalEffects = true, stateFactory, frame) {
996
- if (runGlobalEffects)
997
- flushGlobalEffects('before', timestamp);
998
- if (!stateFactory)
999
- for (const root of roots.values())
1000
- render(timestamp, root);
1001
- else
1002
- render(timestamp, stateFactory, frame);
1003
- if (runGlobalEffects)
1004
- flushGlobalEffects('after', timestamp);
355
+ if (localState.parent && localState.afterUpdate && localState.afterUpdate.observed && changes.length) {
356
+ localState.afterUpdate.emit(instance);
1005
357
  }
1006
- return {
1007
- loop,
1008
- /**
1009
- * Invalidates the view, requesting a frame to be rendered. Will globally invalidate unless passed a root's state.
1010
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#invalidate
1011
- */
1012
- invalidate,
1013
- /**
1014
- * Advances the frameloop and runs render effects, useful for when manually rendering via `frameloop="never"`.
1015
- * @see https://docs.pmnd.rs/react-three-fiber/api/additional-exports#advance
1016
- */
1017
- advance,
1018
- };
358
+ return instance;
1019
359
  }
1020
360
 
1021
- function createRenderer(glOptions, canvasElement) {
361
+ const idCache = {};
362
+ function makeId(event) {
363
+ if (event) {
364
+ return (event.eventObject || event.object).uuid + '/' + event.index + event.instanceId;
365
+ }
366
+ const newId = THREE.MathUtils.generateUUID();
367
+ // ensure not already used
368
+ if (!idCache[newId]) {
369
+ idCache[newId] = true;
370
+ return newId;
371
+ }
372
+ return makeId();
373
+ }
374
+ function makeDpr(dpr, window) {
375
+ const target = (window === null || window === void 0 ? void 0 : window.devicePixelRatio) || 1;
376
+ return Array.isArray(dpr) ? Math.min(Math.max(dpr[0], target), dpr[1]) : dpr;
377
+ }
378
+ function makeDefaultCamera(isOrthographic, size) {
379
+ if (isOrthographic)
380
+ return new THREE.OrthographicCamera(0, 0, 0, 0, 0.1, 1000);
381
+ return new THREE.PerspectiveCamera(75, size.width / size.height, 0.1, 1000);
382
+ }
383
+ function makeDefaultRenderer(glOptions, canvasElement) {
1022
384
  const customRenderer = (typeof glOptions === 'function' ? glOptions(canvasElement) : glOptions);
1023
- if ((customRenderer === null || customRenderer === void 0 ? void 0 : customRenderer.render) != null) {
385
+ if ((customRenderer === null || customRenderer === void 0 ? void 0 : customRenderer.render) != null)
1024
386
  return customRenderer;
1025
- }
1026
387
  return new THREE.WebGLRenderer(Object.assign({ powerPreference: 'high-performance', canvas: canvasElement, antialias: true, alpha: true }, (glOptions || {})));
1027
388
  }
389
+ function makeObjectGraph(object) {
390
+ const data = { nodes: {}, materials: {} };
391
+ if (object) {
392
+ object.traverse((child) => {
393
+ if (child.name)
394
+ data.nodes[child.name] = child;
395
+ if ('material' in child && !data.materials[child.material.name]) {
396
+ data.materials[child.material.name] = child
397
+ .material;
398
+ }
399
+ });
400
+ }
401
+ return data;
402
+ }
403
+
404
+ const startWithUndefined = () => startWith(undefined);
405
+ /**
406
+ * An extended `tap` operator that accepts an `effectFn` which:
407
+ * - runs on every `next` notification from `source$`
408
+ * - can optionally return a `cleanUp` function that
409
+ * invokes from the 2nd `next` notification onward and on `unsubscribe` (destroyed)
410
+ *
411
+ *
412
+ * @example
413
+ * ```typescript
414
+ * source$.pipe(
415
+ * tapEffect((sourceValue) = {
416
+ * const cb = () => {
417
+ * doStuff(sourceValue);
418
+ * };
419
+ * addListener('event', cb);
420
+ *
421
+ * return () => {
422
+ * removeListener('event', cb);
423
+ * }
424
+ * })
425
+ * )
426
+ * ```
427
+ */
428
+ function tapEffect(effectFn) {
429
+ let cleanupFn = () => { };
430
+ let firstRun = false;
431
+ let prev = undefined;
432
+ const teardown = (error) => {
433
+ return () => {
434
+ if (cleanupFn) {
435
+ cleanupFn({ prev, complete: true, error });
436
+ }
437
+ };
438
+ };
439
+ return tap({
440
+ next: (value) => {
441
+ if (cleanupFn && firstRun) {
442
+ cleanupFn({ prev, complete: false, error: false });
443
+ }
444
+ const cleanUpOrVoid = effectFn(value);
445
+ if (cleanUpOrVoid) {
446
+ cleanupFn = cleanUpOrVoid;
447
+ }
448
+ prev = value;
449
+ if (!firstRun) {
450
+ firstRun = true;
451
+ }
452
+ },
453
+ complete: teardown(false),
454
+ unsubscribe: teardown(false),
455
+ error: teardown(true),
456
+ });
457
+ }
458
+ class NgtRxStore extends RxState {
459
+ constructor() {
460
+ super();
461
+ // set a dummy property so that initial this.get() won't return undefined
462
+ this.set({ __ngt_dummy__: '__ngt_dummy__' });
463
+ // call initialize that might be setup by derived Stores
464
+ this.initialize();
465
+ // override set so our consumers don't have to handle undefined for state that already have default values
466
+ const originalSet = this.set.bind(this);
467
+ Object.defineProperty(this, 'set', {
468
+ get: () => {
469
+ // Parameters type does not do well with overloads. So we use any[] here
470
+ return (...args) => {
471
+ const firstArg = args[0];
472
+ if (is.obj(firstArg)) {
473
+ const modArgs = Object.entries(firstArg).reduce((modded, [key, value]) => {
474
+ modded[key] = value === undefined ? this.get(key) : value;
475
+ return modded;
476
+ }, {});
477
+ return originalSet(modArgs);
478
+ }
479
+ // @ts-ignore
480
+ return originalSet(...args);
481
+ };
482
+ },
483
+ });
484
+ }
485
+ initialize() {
486
+ return;
487
+ }
488
+ effect(obs, sideEffectFn) {
489
+ return this.hold(obs.pipe(tapEffect(sideEffectFn)));
490
+ }
491
+ }
492
+ NgtRxStore.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRxStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
493
+ NgtRxStore.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRxStore });
494
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRxStore, decorators: [{
495
+ type: Injectable
496
+ }], ctorParameters: function () { return []; } });
1028
497
 
1029
498
  const rootStateMap = new Map();
1030
499
  const { invalidate, advance } = createLoop(rootStateMap);
1031
500
  const shallowLoose = { objects: 'shallow', strict: false };
1032
- class NgtStore extends NgtComponentStore {
501
+ class NgtStore extends NgtRxStore {
1033
502
  constructor() {
1034
503
  super(...arguments);
1035
504
  this.parentStore = inject(NgtStore, { optional: true, skipSelf: true });
1036
- this.zone = inject(NgZone);
1037
- this.window = injectWindow();
1038
- this.position = new THREE.Vector3();
1039
- this.defaultTarget = new THREE.Vector3();
1040
- this.tempTarget = new THREE.Vector3();
1041
- this.resize = this.effect(($) => {
1042
- let oldSize = this.read((s) => s.size);
1043
- let oldDpr = this.read((s) => { var _a; return (_a = s.viewport) === null || _a === void 0 ? void 0 : _a.dpr; });
1044
- return $.pipe(tap(() => {
1045
- const { camera, size, viewport, gl } = this.read();
1046
- // Resize camera and renderer on changes to size and pixelratio
1047
- if (size !== oldSize || viewport.dpr !== oldDpr) {
1048
- oldSize = size;
1049
- oldDpr = viewport.dpr;
1050
- // Update camera & renderer
1051
- updateCamera(camera, size);
1052
- gl.setPixelRatio(viewport.dpr);
1053
- gl.setSize(size.width, size.height, size.updateStyle);
1054
- }
1055
- }));
1056
- });
1057
- this.invalidate = this.effect(tap(() => void this.read((s) => s.invalidate)()));
505
+ this.window = inject(DOCUMENT).defaultView;
1058
506
  this.isInit = false;
1059
- this.isConfigured = false;
1060
- this.addInteraction = (interaction) => {
1061
- this.write((state) => (Object.assign(Object.assign({}, state), { internal: Object.assign(Object.assign({}, state.internal), { interaction: [...state.internal.interaction, interaction] }) })));
1062
- };
1063
- this.removeInteraction = (uuid) => {
1064
- this.write((state) => (Object.assign(Object.assign({}, state), { internal: Object.assign(Object.assign({}, state.internal), { interaction: state.internal.interaction.filter((interaction) => interaction.uuid !== uuid) }) })));
1065
- };
1066
- this.setPerformanceCurrent = (current) => {
1067
- this.write((s) => ({ performance: Object.assign(Object.assign({}, s.performance), { current }) }));
1068
- };
1069
- this.setEvents = (events) => {
1070
- this.write((s) => ({ events: Object.assign(Object.assign({}, s.events), events) }));
1071
- };
1072
- this.setSize = (width, height, top, left, updateStyle) => {
1073
- const camera = this.read((s) => s.camera);
1074
- const size = { width, height, top: top || 0, left: left || 0, updateStyle };
1075
- this.write((state) => ({
1076
- size,
1077
- viewport: Object.assign(Object.assign({}, state.viewport), this.getCurrentViewport(camera, this.defaultTarget, size)),
1078
- }));
1079
- };
1080
- this.setCamera = (camera) => {
1081
- this.write((s) => ({
1082
- camera,
1083
- viewport: Object.assign(Object.assign({}, s.viewport), this.getCurrentViewport(camera)),
1084
- }));
1085
- this.read((s) => s.cameraRef).set(camera);
1086
- };
1087
- this.setDpr = (dpr) => {
1088
- const resolved = makeDpr(dpr, this.window);
1089
- this.write((s) => ({
1090
- viewport: Object.assign(Object.assign({}, s.viewport), { dpr: resolved, initialDpr: s.viewport.initialDpr || resolved }),
1091
- }));
1092
- };
1093
- this.setFrameloop = (frameloop = 'always') => {
1094
- const clock = this.read((s) => s.clock);
1095
- // if frameloop === "never" clock.elapsedTime is updated using advance(timestamp)
1096
- clock.stop();
1097
- clock.elapsedTime = 0;
1098
- if (frameloop !== 'never') {
1099
- clock.start();
1100
- clock.elapsedTime = 0;
1101
- }
1102
- this.write({ frameloop });
1103
- };
1104
- this.getCurrentViewport = (camera = this.read((s) => s.camera), target = this.defaultTarget, size = this.read((s) => s.size)) => {
1105
- const { width, height, top, left } = size;
1106
- const aspect = width / height;
1107
- if (target instanceof THREE.Vector3)
1108
- this.tempTarget.copy(target);
1109
- else
1110
- this.tempTarget.set(...target);
1111
- const distance = camera.getWorldPosition(this.position).distanceTo(this.tempTarget);
1112
- if (is.orthographic(camera)) {
507
+ }
508
+ init() {
509
+ if (!this.isInit) {
510
+ const position = new THREE.Vector3();
511
+ const defaultTarget = new THREE.Vector3();
512
+ const tempTarget = new THREE.Vector3();
513
+ const getCurrentViewport = (camera = this.get('camera'), target = defaultTarget, size = this.get('size')) => {
514
+ const { width, height, top, left } = size;
515
+ const aspect = width / height;
516
+ if (target instanceof THREE.Vector3)
517
+ tempTarget.copy(target);
518
+ else
519
+ tempTarget.set(...target);
520
+ const distance = camera.getWorldPosition(position).distanceTo(tempTarget);
521
+ if (is.orthographicCamera(camera)) {
522
+ return {
523
+ width: width / camera.zoom,
524
+ height: height / camera.zoom,
525
+ top,
526
+ left,
527
+ factor: 1,
528
+ distance,
529
+ aspect,
530
+ };
531
+ }
532
+ const fov = (camera.fov * Math.PI) / 180; // convert vertical fov to radians
533
+ const h = 2 * Math.tan(fov / 2) * distance; // visible height
534
+ const w = h * aspect;
1113
535
  return {
1114
- width: width / camera.zoom,
1115
- height: height / camera.zoom,
536
+ width: w,
537
+ height: h,
1116
538
  top,
1117
539
  left,
1118
- factor: 1,
540
+ factor: width / w,
1119
541
  distance,
1120
542
  aspect,
1121
543
  };
1122
- }
1123
- const fov = (camera.fov * Math.PI) / 180; // convert vertical fov to radians
1124
- const h = 2 * Math.tan(fov / 2) * distance; // visible height
1125
- const w = h * (width / height);
1126
- return {
1127
- width: w,
1128
- height: h,
1129
- top,
1130
- left,
1131
- factor: width / w,
1132
- distance,
1133
- aspect,
1134
544
  };
1135
- };
1136
- }
1137
- get rootStateFactory() {
1138
- let root = this.read((s) => s.previousStateFactory);
1139
- while (root && root().previousStateFactory) {
1140
- root = root().previousStateFactory;
1141
- }
1142
- return root || this.read;
1143
- }
1144
- init() {
1145
- var _a, _b;
1146
- if (!this.isInit) {
1147
545
  const pointer = new THREE.Vector2();
1148
- const scene = prepare(new THREE.Scene(), this.read, this.rootStateFactory, (_a = this.parentStore) === null || _a === void 0 ? void 0 : _a.get((s) => s.sceneRef));
1149
546
  let performanceTimeout;
1150
- this.write({
547
+ const setPerformanceCurrent = (current) => {
548
+ this.set((state) => ({ performance: Object.assign(Object.assign({}, state.performance), { current }) }));
549
+ };
550
+ this.set({
551
+ get: this.get.bind(this),
552
+ set: this.set.bind(this),
553
+ select: this.select.bind(this),
1151
554
  ready: false,
1152
- cameraRef: new NgtRef(),
1153
- scene,
1154
- sceneRef: new NgtRef(scene),
555
+ scene: prepare(new THREE.Scene(), { store: this }),
1155
556
  events: { priority: 1, enabled: true, connected: false },
1156
- invalidate: (frames = 1) => invalidate(this.read, frames),
1157
- advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, this.read),
557
+ invalidate: (frames = 1) => invalidate(this, frames),
558
+ advance: (timestamp, runGlobalEffects) => advance(timestamp, runGlobalEffects, this),
1158
559
  legacy: false,
1159
560
  linear: false,
1160
561
  flat: false,
@@ -1168,20 +569,19 @@ class NgtStore extends NgtComponentStore {
1168
569
  max: 1,
1169
570
  debounce: 200,
1170
571
  regress: () => {
1171
- this.zone.runOutsideAngular(() => {
1172
- const state = this.read();
1173
- // Clear timeout
1174
- if (performanceTimeout)
1175
- clearTimeout(performanceTimeout);
1176
- // Set lower bound performance
1177
- if (state.performance.current !== state.performance.min)
1178
- this.setPerformanceCurrent(state.performance.min);
1179
- // Go back to upper bound performance after a while unless something regresses meanwhile
1180
- performanceTimeout = setTimeout(() => { var _a; return this.setPerformanceCurrent(((_a = this.read((s) => s.performance)) === null || _a === void 0 ? void 0 : _a.max) || 1); }, state.performance.debounce);
1181
- });
572
+ const state = this.get();
573
+ // clear timeout
574
+ if (performanceTimeout)
575
+ clearTimeout(performanceTimeout);
576
+ // set lower bound
577
+ if (state.performance.current !== state.performance.min) {
578
+ setPerformanceCurrent(state.performance.min);
579
+ }
580
+ // go back to upper bound
581
+ performanceTimeout = setTimeout(() => setPerformanceCurrent(this.get('performance', 'max') || 1), state.performance.debounce);
1182
582
  },
1183
583
  },
1184
- size: { width: 0, height: 0, top: 0, left: 0, updateStyle: false },
584
+ size: { width: 0, height: 0, top: 0, left: 0 },
1185
585
  viewport: {
1186
586
  initialDpr: 0,
1187
587
  dpr: 0,
@@ -1192,9 +592,9 @@ class NgtStore extends NgtComponentStore {
1192
592
  aspect: 0,
1193
593
  distance: 0,
1194
594
  factor: 0,
1195
- getCurrentViewport: this.getCurrentViewport,
595
+ getCurrentViewport,
1196
596
  },
1197
- previousStateFactory: (_b = this.parentStore) === null || _b === void 0 ? void 0 : _b.read.bind(this.parentStore),
597
+ previousStore: this.parentStore,
1198
598
  internal: {
1199
599
  active: false,
1200
600
  priority: 0,
@@ -1202,128 +602,146 @@ class NgtStore extends NgtComponentStore {
1202
602
  lastEvent: null,
1203
603
  interaction: [],
1204
604
  hovered: new Map(),
1205
- capturedMap: new Map(),
1206
- animations: new Map(),
1207
605
  subscribers: [],
1208
606
  initialClick: [0, 0],
1209
607
  initialHits: [],
1210
- subscribe: (callback, priority = 0, stateFactory = this.read, obj) => {
1211
- const internal = this.read((s) => s.internal);
608
+ capturedMap: new Map(),
609
+ subscribe: (callback, priority = 0, store = this) => {
610
+ const internal = this.get('internal');
1212
611
  // If this subscription was given a priority, it takes rendering into its own hands
1213
612
  // For that reason we switch off automatic rendering and increase the manual flag
1214
613
  // As long as this flag is positive there can be no internal rendering at all
1215
614
  // because there could be multiple render subscriptions
1216
615
  internal.priority = internal.priority + (priority > 0 ? 1 : 0);
1217
- internal.subscribers.push({ priority, stateFactory, callback, obj });
616
+ internal.subscribers.push({ priority, store, callback });
1218
617
  // Register subscriber and sort layers from lowest to highest, meaning,
1219
618
  // highest priority renders last (on top of the other frames)
1220
619
  internal.subscribers.sort((a, b) => (a.priority || 0) - (b.priority || 0));
1221
620
  return () => {
1222
- const internalOnCleanUp = this.read((s) => s.internal);
1223
- if (internalOnCleanUp.subscribers) {
621
+ const internal = this.get('internal');
622
+ if (internal === null || internal === void 0 ? void 0 : internal.subscribers) {
1224
623
  // Decrease manual flag if this subscription had a priority
1225
- internalOnCleanUp.priority = internalOnCleanUp.priority - (priority > 0 ? 1 : 0);
624
+ internal.priority = internal.priority - (priority > 0 ? 1 : 0);
1226
625
  // Remove subscriber from list
1227
- internalOnCleanUp.subscribers = internalOnCleanUp.subscribers.filter((s) => s.callback !== callback);
626
+ internal.subscribers = internal.subscribers.filter((s) => s.callback !== callback);
1228
627
  }
1229
628
  };
1230
629
  },
1231
630
  },
1232
- setPerformanceCurrent: this.setPerformanceCurrent,
1233
- setEvents: this.setEvents,
1234
- setFrameloop: this.setFrameloop,
1235
- setSize: this.setSize,
1236
- setDpr: this.setDpr,
1237
- setCamera: this.setCamera,
1238
- addInteraction: this.addInteraction,
1239
- removeInteraction: this.removeInteraction,
631
+ setEvents: (events) => {
632
+ this.set((state) => ({ events: Object.assign(Object.assign({}, state.events), events) }));
633
+ },
634
+ setSize: (width, height, top, left) => {
635
+ const camera = this.get('camera');
636
+ const size = { width, height, top: top || 0, left: left || 0 };
637
+ this.set((state) => ({
638
+ size,
639
+ viewport: Object.assign(Object.assign({}, state.viewport), getCurrentViewport(camera, defaultTarget, size)),
640
+ }));
641
+ },
642
+ setDpr: (dpr) => {
643
+ const resolved = makeDpr(dpr, this.window);
644
+ this.set((state) => ({
645
+ viewport: Object.assign(Object.assign({}, state.viewport), { dpr: resolved, initialDpr: state.viewport.initialDpr || resolved }),
646
+ }));
647
+ },
648
+ setFrameloop: (frameloop = 'always') => {
649
+ const clock = this.get('clock');
650
+ clock.stop();
651
+ clock.elapsedTime = 0;
652
+ if (frameloop !== 'never') {
653
+ clock.start();
654
+ clock.elapsedTime = 0;
655
+ }
656
+ this.set({ frameloop });
657
+ },
658
+ addInteraction: (interaction) => {
659
+ this.set((state) => ({
660
+ internal: Object.assign(Object.assign({}, state.internal), { interaction: [...state.internal.interaction, interaction] }),
661
+ }));
662
+ },
663
+ removeInteraction: (uuid) => {
664
+ this.set((state) => ({
665
+ internal: Object.assign(Object.assign({}, state.internal), { interaction: state.internal.interaction.filter((interaction) => interaction.uuid !== uuid) }),
666
+ }));
667
+ },
1240
668
  });
1241
669
  this.isInit = true;
670
+ this.resize();
1242
671
  }
1243
672
  }
1244
673
  configure(inputs, canvasElement) {
1245
- var _a;
1246
- const { gl: glOptions, size: sizeOptions, camera: cameraOptions, raycaster: raycasterOptions, events, orthographic, lookAt, shadows, linear, flat, legacy, dpr, frameloop, performance, } = inputs;
1247
- const state = this.read();
1248
- // Set up renderer (one time only!)
674
+ const { gl: glOptions, size: sizeOptions, camera: cameraOptions, raycaster: raycasterOptions, events, orthographic, lookAt, shadows, linear, legacy, flat, dpr, frameloop, performance, } = inputs;
675
+ const state = this.get();
676
+ const stateToUpdate = {};
677
+ // setup renderer
1249
678
  let gl = state.gl;
1250
679
  if (!state.gl) {
1251
- this.write({ gl: (gl = createRenderer(glOptions, canvasElement)) });
680
+ stateToUpdate.gl = gl = makeDefaultRenderer(glOptions, canvasElement);
1252
681
  }
1253
- // Set up raycaster (one time only!)
682
+ // setup raycaster
1254
683
  let raycaster = state.raycaster;
1255
684
  if (!raycaster) {
1256
- this.write({ raycaster: (raycaster = new THREE.Raycaster()) });
685
+ stateToUpdate.raycaster = raycaster = new THREE.Raycaster();
1257
686
  }
1258
- // Set raycaster options
1259
- const _b = raycasterOptions || {}, { params } = _b, options = __rest(_b, ["params"]);
1260
- if (!is.equ(options, raycaster, shallowLoose)) {
687
+ // set raycaster options
688
+ const _a = raycasterOptions || {}, { params } = _a, options = __rest(_a, ["params"]);
689
+ if (!is.equ(options, raycaster, shallowLoose))
1261
690
  applyProps(raycaster, Object.assign({}, options));
1262
- }
1263
691
  if (!is.equ(params, raycaster.params, shallowLoose)) {
1264
- applyProps(raycaster, {
1265
- params: Object.assign(Object.assign({}, raycaster.params), (params || {})),
1266
- });
692
+ applyProps(raycaster, { params: Object.assign(Object.assign({}, raycaster.params), (params || {})) });
1267
693
  }
1268
- // Create default camera (one time only!)
694
+ // create default camera
1269
695
  if (!state.camera) {
1270
696
  const isCamera = is.camera(cameraOptions);
1271
- let camera = isCamera ? cameraOptions : createDefaultCamera(orthographic, state.size);
697
+ let camera = isCamera ? cameraOptions : makeDefaultCamera(orthographic || false, state.size);
1272
698
  if (!isCamera) {
1273
- if (cameraOptions) {
699
+ if (cameraOptions)
1274
700
  applyProps(camera, cameraOptions);
1275
- }
1276
- // Set position.z if position not passed in
1277
- if (!(cameraOptions === null || cameraOptions === void 0 ? void 0 : cameraOptions.position)) {
701
+ // set position.z
702
+ if (!(cameraOptions === null || cameraOptions === void 0 ? void 0 : cameraOptions.position))
1278
703
  camera.position.z = 5;
1279
- }
1280
- // Always look at center or passed-in lookAt by default
704
+ // always look at center or passed-in lookAt by default
1281
705
  if (!(cameraOptions === null || cameraOptions === void 0 ? void 0 : cameraOptions.rotation)) {
1282
- if (Array.isArray(lookAt)) {
706
+ if (Array.isArray(lookAt))
1283
707
  camera.lookAt(lookAt[0], lookAt[1], lookAt[2]);
1284
- }
1285
- else if (lookAt instanceof THREE.Vector3) {
708
+ else if (lookAt instanceof THREE.Vector3)
1286
709
  camera.lookAt(lookAt);
1287
- }
1288
- else {
710
+ else
1289
711
  camera.lookAt(0, 0, 0);
1290
- }
1291
712
  }
1292
- // Update projection matrix after applying props
713
+ // update projection matrix after applyprops
1293
714
  camera.updateProjectionMatrix();
1294
715
  }
1295
716
  if (!is.instance(camera)) {
1296
- camera = prepare(camera, this.read, this.rootStateFactory, (_a = this.parentStore) === null || _a === void 0 ? void 0 : _a.get((s) => s.cameraRef));
717
+ camera = prepare(camera, { store: this });
1297
718
  }
1298
- this.write({ camera });
1299
- this.read((s) => s.cameraRef).set(camera);
719
+ stateToUpdate.camera = camera;
1300
720
  }
1301
721
  // Set up XR (one time only!)
1302
722
  if (!state.xr) {
1303
723
  // Handle frame behavior in WebXR
1304
724
  const handleXRFrame = (timestamp, frame) => {
1305
- const state = this.read();
725
+ const state = this.get();
1306
726
  if (state.frameloop === 'never')
1307
727
  return;
1308
- advance(timestamp, true, this.read, frame);
728
+ advance(timestamp, true, this, frame);
1309
729
  };
1310
730
  // Toggle render switching on session
1311
731
  const handleSessionChange = () => {
1312
- const state = this.read();
732
+ const state = this.get();
1313
733
  state.gl.xr.enabled = state.gl.xr.isPresenting;
1314
734
  state.gl.xr.setAnimationLoop(state.gl.xr.isPresenting ? handleXRFrame : null);
1315
735
  if (!state.gl.xr.isPresenting)
1316
- invalidate(this.read);
736
+ invalidate(this);
1317
737
  };
1318
738
  // WebXR session manager
1319
739
  const xr = {
1320
740
  connect: () => {
1321
- const gl = this.read((s) => s.gl);
1322
741
  gl.xr.addEventListener('sessionstart', handleSessionChange);
1323
742
  gl.xr.addEventListener('sessionend', handleSessionChange);
1324
743
  },
1325
744
  disconnect: () => {
1326
- const gl = this.read((s) => s.gl);
1327
745
  gl.xr.removeEventListener('sessionstart', handleSessionChange);
1328
746
  gl.xr.removeEventListener('sessionend', handleSessionChange);
1329
747
  },
@@ -1331,7 +749,7 @@ class NgtStore extends NgtComponentStore {
1331
749
  // Subscribe to WebXR session events
1332
750
  if (gl.xr)
1333
751
  xr.connect();
1334
- this.write({ xr });
752
+ stateToUpdate.xr = xr;
1335
753
  }
1336
754
  // Set shadowmap
1337
755
  if (gl.shadowMap) {
@@ -1349,9 +767,8 @@ class NgtStore extends NgtComponentStore {
1349
767
  }
1350
768
  // Safely set color management if available.
1351
769
  // Avoid accessing THREE.ColorManagement to play nice with older versions
1352
- if (is.supportColorManagement()) {
770
+ if (THREE.ColorManagement)
1353
771
  THREE.ColorManagement.legacyMode = state.legacy;
1354
- }
1355
772
  const outputEncoding = linear ? THREE.LinearEncoding : THREE.sRGBEncoding;
1356
773
  const toneMapping = flat ? THREE.NoToneMapping : THREE.ACESFilmicToneMapping;
1357
774
  if (gl.outputEncoding !== outputEncoding)
@@ -1360,71 +777,482 @@ class NgtStore extends NgtComponentStore {
1360
777
  gl.toneMapping = toneMapping;
1361
778
  // Update color management state
1362
779
  if (state.legacy !== legacy)
1363
- this.write({ legacy });
780
+ stateToUpdate.legacy = legacy;
1364
781
  if (state.linear !== linear)
1365
- this.write({ linear });
782
+ stateToUpdate.linear = linear;
1366
783
  if (state.flat !== flat)
1367
- this.write({ flat });
784
+ stateToUpdate.flat = flat;
1368
785
  // Set gl props
1369
786
  gl.setClearAlpha(0);
1370
787
  gl.setPixelRatio(makeDpr(state.viewport.dpr));
1371
- gl.setSize(state.size.width, state.size.height, state.size.updateStyle);
788
+ gl.setSize(state.size.width, state.size.height);
1372
789
  if (is.obj(glOptions) &&
1373
790
  !(typeof glOptions === 'function') &&
1374
- !is.glRenderer(glOptions) &&
791
+ !is.renderer(glOptions) &&
1375
792
  !is.equ(glOptions, gl, shallowLoose)) {
1376
793
  applyProps(gl, glOptions);
1377
794
  }
1378
795
  // Store events internally
1379
796
  if (events && !state.events.handlers) {
1380
- this.write({ events: events(this.read) });
797
+ stateToUpdate.events = events(this);
1381
798
  }
799
+ // Check performance
800
+ if (performance && !is.equ(performance, state.performance, shallowLoose)) {
801
+ stateToUpdate.performance = Object.assign(Object.assign({}, state.performance), performance);
802
+ }
803
+ this.set(stateToUpdate);
1382
804
  // Check pixelratio
1383
- if (dpr && state.viewport.dpr !== makeDpr(dpr)) {
805
+ if (dpr && state.viewport.dpr !== makeDpr(dpr))
1384
806
  state.setDpr(dpr);
1385
- }
1386
807
  // Check size, allow it to take on container bounds initially
1387
808
  const size = computeInitialSize(canvasElement, sizeOptions);
1388
- if (!is.equ(size, state.size, shallowLoose)) {
809
+ if (!is.equ(size, state.size, shallowLoose))
1389
810
  state.setSize(size.width, size.height, size.top, size.left);
1390
- }
1391
811
  // Check frameloop
1392
812
  if (state.frameloop !== frameloop)
1393
813
  state.setFrameloop(frameloop);
1394
- // Check performance
1395
- if (performance && !is.equ(performance, state.performance, shallowLoose)) {
1396
- this.write((state) => ({
1397
- performance: Object.assign(Object.assign({}, state.performance), performance),
1398
- }));
1399
- }
1400
- this.write({ ready: true });
1401
- this.resize(this.select(this.select((s) => s.size), this.select((s) => s.viewport.dpr), defaultProjector, { debounce: true }));
1402
- this.invalidate(this.select((s) => s, { debounce: true }));
1403
- this.zone.run(() => {
1404
- this.isConfigured = true;
814
+ if (!this.get('ready')) {
815
+ this.set({ ready: true });
816
+ }
817
+ this.invalidate();
818
+ }
819
+ resize() {
820
+ const state = this.get();
821
+ let oldSize = state.size;
822
+ let oldDpr = state.viewport.dpr;
823
+ let oldCamera = state.camera;
824
+ this.hold(this.select(selectSlice(['camera', 'size', 'viewport', 'gl'])), () => {
825
+ const { camera, size, viewport, gl, set } = this.get();
826
+ // resize camera and renderer on changes to size and dpr
827
+ if (size !== oldSize || viewport.dpr !== oldDpr) {
828
+ oldSize = size;
829
+ oldDpr = viewport.dpr;
830
+ // update camera
831
+ updateCamera(camera, size);
832
+ gl.setPixelRatio(viewport.dpr);
833
+ gl.setSize(size.width, size.height);
834
+ }
835
+ // update viewport when camera changes
836
+ if (camera !== oldCamera) {
837
+ updateCamera(camera, size);
838
+ oldCamera = camera;
839
+ set((state) => ({ viewport: Object.assign(Object.assign({}, state.viewport), state.viewport.getCurrentViewport(camera)) }));
840
+ }
1405
841
  });
1406
842
  }
1407
- onReady(cb) {
1408
- return this.effect(tapEffect(cb))(this.select((s) => s.ready).pipe(filter((ready) => ready)));
843
+ invalidate() {
844
+ this.hold(this.select(), () => invalidate(this));
1409
845
  }
1410
846
  }
1411
- NgtStore.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtStore, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
1412
- NgtStore.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtStore });
1413
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtStore, decorators: [{
847
+ NgtStore.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtStore, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
848
+ NgtStore.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtStore });
849
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtStore, decorators: [{
1414
850
  type: Injectable
1415
851
  }] });
1416
852
  function computeInitialSize(canvas, defaultSize) {
1417
853
  if (defaultSize) {
1418
854
  return defaultSize;
1419
855
  }
1420
- if (is.canvas(canvas) && canvas.parentElement) {
856
+ if (canvas instanceof HTMLCanvasElement && canvas.parentElement) {
1421
857
  const { width, height, top, left } = canvas.parentElement.getBoundingClientRect();
1422
858
  return { width, height, top, left };
1423
859
  }
1424
- return { width: 0, height: 0, top: 0, left: 0 };
860
+ return { width: 0, height: 0, top: 0, left: 0 };
861
+ }
862
+
863
+ const NGT_COMPOUND_PREFIXES = new InjectionToken('NgtCompoundPrefixes');
864
+
865
+ const catalogue = {};
866
+ function extend(objects) {
867
+ Object.assign(catalogue, objects);
868
+ }
869
+ const NGT_CATALOGUE = new InjectionToken('THREE Constructors Catalogue', { factory: () => catalogue });
870
+
871
+ class NgtArgs {
872
+ constructor() {
873
+ this.vcr = inject(ViewContainerRef);
874
+ this.template = inject(TemplateRef);
875
+ this.injectedArgs = [];
876
+ this.injected = false;
877
+ const commentNode = this.vcr.element.nativeElement;
878
+ if (commentNode['__ngt_renderer_add_comment__']) {
879
+ commentNode['__ngt_renderer_add_comment__']();
880
+ delete commentNode['__ngt_renderer_add_comment__'];
881
+ }
882
+ }
883
+ set args(args) {
884
+ if (args == null || !Array.isArray(args))
885
+ return;
886
+ if (args.length === 1 && args[0] === null)
887
+ return;
888
+ this.injected = false;
889
+ this.injectedArgs = args;
890
+ this.createView();
891
+ }
892
+ get args() {
893
+ if (this.validate()) {
894
+ this.injected = true;
895
+ return this.injectedArgs;
896
+ }
897
+ return null;
898
+ }
899
+ validate() {
900
+ return !this.injected && !!this.injectedArgs.length;
901
+ }
902
+ createView() {
903
+ if (this.view && !this.view.destroyed) {
904
+ this.view.destroy();
905
+ }
906
+ this.view = this.vcr.createEmbeddedView(this.template);
907
+ this.view.detectChanges();
908
+ }
909
+ }
910
+ NgtArgs.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtArgs, deps: [], target: i0.ɵɵFactoryTarget.Directive });
911
+ NgtArgs.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.1.1", type: NgtArgs, isStandalone: true, selector: "[args]", inputs: { args: "args" }, ngImport: i0 });
912
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtArgs, decorators: [{
913
+ type: Directive,
914
+ args: [{ selector: '[args]', standalone: true }]
915
+ }], ctorParameters: function () { return []; }, propDecorators: { args: [{
916
+ type: Input
917
+ }] } });
918
+
919
+ function releaseInternalPointerCapture(capturedMap, obj, captures, pointerId) {
920
+ const captureData = captures.get(obj);
921
+ if (captureData) {
922
+ captures.delete(obj);
923
+ // if this was the last captured object for this pointer
924
+ if (captures.size === 0) {
925
+ capturedMap.delete(pointerId);
926
+ captureData.target.releasePointerCapture(pointerId);
927
+ }
928
+ }
929
+ }
930
+ function removeInteractivity(store, object) {
931
+ const internal = store.get('internal');
932
+ // removes every trace of an object from data store
933
+ internal.interaction = internal.interaction.filter((o) => o !== object);
934
+ internal.initialHits = internal.initialHits.filter((o) => o !== object);
935
+ internal.hovered.forEach((value, key) => {
936
+ if (value.eventObject === object || value.object === object) {
937
+ // clear out intersects, they are outdated by now
938
+ internal.hovered.delete(key);
939
+ }
940
+ });
941
+ internal.capturedMap.forEach((captures, pointerId) => {
942
+ releaseInternalPointerCapture(internal.capturedMap, object, captures, pointerId);
943
+ });
944
+ if (store.get('previousStore')) {
945
+ removeInteractivity(store.get('previousStore'), object);
946
+ }
947
+ }
948
+ function createEvents(store) {
949
+ /** calculates delta **/
950
+ function calculateDistance(event) {
951
+ const internal = store.get('internal');
952
+ const dx = event.offsetX - internal.initialClick[0];
953
+ const dy = event.offsetY - internal.initialClick[1];
954
+ return Math.round(Math.sqrt(dx * dx + dy * dy));
955
+ }
956
+ /** returns true if an instance has a valid pointer-event registered, this excludes scroll, clicks etc... **/
957
+ function filterPointerEvents(objects) {
958
+ return objects.filter((obj) => ['move', 'over', 'enter', 'out', 'leave'].some((name) => {
959
+ var _a;
960
+ const eventName = `pointer${name}`;
961
+ return (_a = getLocalState(obj).handlers) === null || _a === void 0 ? void 0 : _a[eventName];
962
+ }));
963
+ }
964
+ function intersect(event, filter) {
965
+ var _a, _b, _c;
966
+ const state = store.get();
967
+ const duplicates = new Set();
968
+ const intersections = [];
969
+ // allow callers to eliminate event objects
970
+ const eventObjects = filter ? filter(state.internal.interaction) : state.internal.interaction;
971
+ // reset all raycaster cameras to undefined
972
+ for (let i = 0; i < eventObjects.length; i++) {
973
+ const instanceState = (_a = getLocalState(eventObjects[i]).store) === null || _a === void 0 ? void 0 : _a.get();
974
+ if (instanceState) {
975
+ instanceState.raycaster.camera = undefined;
976
+ }
977
+ }
978
+ if (!state.previousStore) {
979
+ // make sure root-level pointer and ray are setup
980
+ (_c = (_b = state.events).compute) === null || _c === void 0 ? void 0 : _c.call(_b, event, store);
981
+ }
982
+ function handleRaycast(obj) {
983
+ var _a, _b;
984
+ const objLocalState = getLocalState(obj);
985
+ const objStore = objLocalState.store;
986
+ const objState = objStore === null || objStore === void 0 ? void 0 : objStore.get();
987
+ // skip event handling when noEvents is set, or when raycaster camera is null
988
+ if (!objState || !objState.events.enabled || objState.raycaster.camera === null)
989
+ return [];
990
+ // when the camera is undefined, we have to call the events layers to update function
991
+ if (objState.raycaster.camera === undefined) {
992
+ (_b = (_a = objState.events).compute) === null || _b === void 0 ? void 0 : _b.call(_a, event, objStore, objState.previousStore);
993
+ // if the camera is still undefined, we have to skip this layer entirely
994
+ if (objState.raycaster.camera === undefined)
995
+ objState.raycaster.camera = null;
996
+ }
997
+ // intersect object by object
998
+ return objState.raycaster.camera ? objState.raycaster.intersectObject(obj, true) : [];
999
+ }
1000
+ // collect events
1001
+ let hits = eventObjects
1002
+ // intersect objects
1003
+ .flatMap(handleRaycast)
1004
+ // sort by event priority
1005
+ .sort((a, b) => {
1006
+ const aState = getLocalState(a.object).store.get();
1007
+ const bState = getLocalState(b.object).store.get();
1008
+ if (!aState || !bState)
1009
+ return a.distance - b.distance;
1010
+ return bState.events.priority - aState.events.priority || a.distance - b.distance;
1011
+ })
1012
+ // filter out duplicates
1013
+ .filter((item) => {
1014
+ const id = makeId(item);
1015
+ if (duplicates.has(id))
1016
+ return false;
1017
+ duplicates.add(id);
1018
+ return true;
1019
+ });
1020
+ // allow custom userland intersect sort order, this likely only makes sense on the root
1021
+ if (state.events.filter)
1022
+ hits = state.events.filter(hits, store);
1023
+ // bubble up the events, find the event source
1024
+ for (const hit of hits) {
1025
+ let eventObject = hit.object;
1026
+ // bubble event up
1027
+ while (eventObject) {
1028
+ if (getLocalState(eventObject).eventCount) {
1029
+ intersections.push(Object.assign(Object.assign({}, hit), { eventObject }));
1030
+ }
1031
+ eventObject = eventObject.parent;
1032
+ }
1033
+ }
1034
+ // if the interaction is captured, make all capturing targets part of the intersects
1035
+ if ('pointerId' in event && state.internal.capturedMap.has(event.pointerId)) {
1036
+ for (const capturedData of state.internal.capturedMap.get(event.pointerId).values()) {
1037
+ if (!duplicates.has(makeId(capturedData.intersection))) {
1038
+ intersections.push(capturedData.intersection);
1039
+ }
1040
+ }
1041
+ }
1042
+ return intersections;
1043
+ }
1044
+ /** handle intersections by forwarding them to handlers */
1045
+ function handleIntersects(intersections, event, delta, callback) {
1046
+ var _a;
1047
+ const rootState = store.get();
1048
+ // if anything has been found, forward it to the event listeners
1049
+ if (intersections.length) {
1050
+ const localState = { stopped: false };
1051
+ for (const hit of intersections) {
1052
+ const state = ((_a = getLocalState(hit.object).store) === null || _a === void 0 ? void 0 : _a.get()) || rootState;
1053
+ const { raycaster, pointer, camera, internal } = state;
1054
+ const unprojectedPoint = new THREE.Vector3(pointer.x, pointer.y, 0).unproject(camera);
1055
+ const hasPointerCapture = (id) => { var _a, _b; return (_b = (_a = internal.capturedMap.get(id)) === null || _a === void 0 ? void 0 : _a.has(hit.eventObject)) !== null && _b !== void 0 ? _b : false; };
1056
+ const setPointerCapture = (id) => {
1057
+ const captureData = { intersection: hit, target: event.target };
1058
+ if (internal.capturedMap.has(id)) {
1059
+ // if the pointerId was previously captured, we add the hit to the event capturedMap
1060
+ internal.capturedMap.get(id).set(hit.eventObject, captureData);
1061
+ }
1062
+ else {
1063
+ // if the pointerId was not previously captured, we create a Map containing the hitObject, and the hit. hitObject is used for faster access
1064
+ internal.capturedMap.set(id, new Map([[hit.eventObject, captureData]]));
1065
+ }
1066
+ // call the original event now
1067
+ event.target.setPointerCapture(id);
1068
+ };
1069
+ const releasePointerCapture = (id) => {
1070
+ const captures = internal.capturedMap.get(id);
1071
+ if (captures) {
1072
+ releaseInternalPointerCapture(internal.capturedMap, hit.eventObject, captures, id);
1073
+ }
1074
+ };
1075
+ // add native event props
1076
+ const extractEventProps = {};
1077
+ // This iterates over the event's properties including the inherited ones. Native PointerEvents have most of their props as getters which are inherited, but polyfilled PointerEvents have them all as their own properties (i.e. not inherited). We can't use Object.keys() or Object.entries() as they only return "own" properties; nor Object.getPrototypeOf(event) as that *doesn't* return "own" properties, only inherited ones.
1078
+ for (const prop in event) {
1079
+ const property = event[prop];
1080
+ // only copy over atomics, leave functions alone as these should be called as event.nativeEvent.fn()
1081
+ if (typeof property !== 'function') {
1082
+ extractEventProps[prop] = property;
1083
+ }
1084
+ }
1085
+ const raycastEvent = Object.assign(Object.assign(Object.assign({}, hit), extractEventProps), { pointer,
1086
+ intersections, stopped: localState.stopped, delta,
1087
+ unprojectedPoint, ray: raycaster.ray, camera: camera,
1088
+ // Hijack stopPropagation, which just sets a flag
1089
+ stopPropagation() {
1090
+ // https://github.com/pmndrs/react-three-fiber/issues/596
1091
+ // Events are not allowed to stop propagation if the pointer has been captured
1092
+ const capturesForPointer = 'pointerId' in event && internal.capturedMap.get(event.pointerId);
1093
+ // We only authorize stopPropagation...
1094
+ if (
1095
+ // ...if this pointer hasn't been captured
1096
+ !capturesForPointer ||
1097
+ // ... or if the hit object is capturing the pointer
1098
+ capturesForPointer.has(hit.eventObject)) {
1099
+ raycastEvent.stopped = localState.stopped = true;
1100
+ // Propagation is stopped, remove all other hover records
1101
+ // An event handler is only allowed to flush other handlers if it is hovered itself
1102
+ if (internal.hovered.size &&
1103
+ Array.from(internal.hovered.values()).find((i) => i.eventObject === hit.eventObject)) {
1104
+ // Objects cannot flush out higher up objects that have already caught the event
1105
+ const higher = intersections.slice(0, intersections.indexOf(hit));
1106
+ cancelPointer([...higher, hit]);
1107
+ }
1108
+ }
1109
+ },
1110
+ // there should be a distinction between target and currentTarget
1111
+ target: { hasPointerCapture, setPointerCapture, releasePointerCapture }, currentTarget: { hasPointerCapture, setPointerCapture, releasePointerCapture }, nativeEvent: event });
1112
+ // call subscribers
1113
+ callback(raycastEvent);
1114
+ // event bubbling may be interupted by stopPropagation
1115
+ if (localState.stopped === true)
1116
+ break;
1117
+ }
1118
+ }
1119
+ return intersections;
1120
+ }
1121
+ function cancelPointer(intersections) {
1122
+ var _a, _b;
1123
+ const { internal } = store.get();
1124
+ for (const hoveredObj of internal.hovered.values()) {
1125
+ // When no objects were hit or the hovered object wasn't found underneath the cursor
1126
+ // we call onPointerOut and delete the object from the hovered-elements map
1127
+ if (!intersections.length ||
1128
+ !intersections.find((hit) => hit.object === hoveredObj.object &&
1129
+ hit.index === hoveredObj.index &&
1130
+ hit.instanceId === hoveredObj.instanceId)) {
1131
+ const eventObject = hoveredObj.eventObject;
1132
+ const instance = getLocalState(eventObject);
1133
+ const handlers = instance === null || instance === void 0 ? void 0 : instance.handlers;
1134
+ internal.hovered.delete(makeId(hoveredObj));
1135
+ if (instance === null || instance === void 0 ? void 0 : instance.eventCount) {
1136
+ // Clear out intersects, they are outdated by now
1137
+ const data = Object.assign(Object.assign({}, hoveredObj), { intersections });
1138
+ (_a = handlers === null || handlers === void 0 ? void 0 : handlers.pointerout) === null || _a === void 0 ? void 0 : _a.call(handlers, data);
1139
+ (_b = handlers === null || handlers === void 0 ? void 0 : handlers.pointerleave) === null || _b === void 0 ? void 0 : _b.call(handlers, data);
1140
+ }
1141
+ }
1142
+ }
1143
+ }
1144
+ function pointerMissed(event, objects) {
1145
+ var _a, _b;
1146
+ for (let i = 0; i < objects.length; i++) {
1147
+ const instance = getLocalState(objects[i]);
1148
+ (_b = instance === null || instance === void 0 ? void 0 : (_a = instance.handlers).pointermissed) === null || _b === void 0 ? void 0 : _b.call(_a, event);
1149
+ }
1150
+ }
1151
+ function handlePointer(name) {
1152
+ // Deal with cancelation
1153
+ switch (name) {
1154
+ case 'pointerleave':
1155
+ case 'pointercancel':
1156
+ return () => cancelPointer([]);
1157
+ case 'lostpointercapture':
1158
+ return (event) => {
1159
+ const { internal } = store.get();
1160
+ if ('pointerId' in event && !internal.capturedMap.has(event.pointerId)) {
1161
+ // If the object event interface had onLostPointerCapture, we'd call it here on every
1162
+ // object that's getting removed.
1163
+ internal.capturedMap.delete(event.pointerId);
1164
+ cancelPointer([]);
1165
+ }
1166
+ };
1167
+ }
1168
+ // Any other pointer goes here ...
1169
+ return function handleEvent(event) {
1170
+ const { onPointerMissed, internal } = store.get();
1171
+ // prepareRay(event)
1172
+ internal.lastEvent = event;
1173
+ // Get fresh intersects
1174
+ const isPointerMove = name === 'pointermove';
1175
+ const isClickEvent = name === 'click' || name === 'contextmenu' || name === 'dblclick';
1176
+ const filter = isPointerMove ? filterPointerEvents : undefined;
1177
+ // const hits = patchIntersects(intersect(filter), event)
1178
+ const hits = intersect(event, filter);
1179
+ const delta = isClickEvent ? calculateDistance(event) : 0;
1180
+ // Save initial coordinates on pointer-down
1181
+ if (name === 'pointerdown') {
1182
+ internal.initialClick = [event.offsetX, event.offsetY];
1183
+ internal.initialHits = hits.map((hit) => hit.eventObject);
1184
+ }
1185
+ // If a click yields no results, pass it back to the user as a miss
1186
+ // Missed events have to come first in order to establish user-land side-effect clean up
1187
+ if (isClickEvent && !hits.length) {
1188
+ if (delta <= 2) {
1189
+ pointerMissed(event, internal.interaction);
1190
+ if (onPointerMissed)
1191
+ onPointerMissed(event);
1192
+ }
1193
+ }
1194
+ // Take care of unhover
1195
+ if (isPointerMove)
1196
+ cancelPointer(hits);
1197
+ function onIntersect(data) {
1198
+ var _a, _b, _c;
1199
+ const eventObject = data.eventObject;
1200
+ const instance = getLocalState(eventObject);
1201
+ const handlers = instance === null || instance === void 0 ? void 0 : instance.handlers;
1202
+ // Check presence of handlers
1203
+ if (!(instance === null || instance === void 0 ? void 0 : instance.eventCount))
1204
+ return;
1205
+ if (isPointerMove) {
1206
+ // Move event ...
1207
+ if ((handlers === null || handlers === void 0 ? void 0 : handlers.pointerover) ||
1208
+ (handlers === null || handlers === void 0 ? void 0 : handlers.pointerenter) ||
1209
+ (handlers === null || handlers === void 0 ? void 0 : handlers.pointerout) ||
1210
+ (handlers === null || handlers === void 0 ? void 0 : handlers.pointerleave)) {
1211
+ // When enter or out is present take care of hover-state
1212
+ const id = makeId(data);
1213
+ const hoveredItem = internal.hovered.get(id);
1214
+ if (!hoveredItem) {
1215
+ // If the object wasn't previously hovered, book it and call its handler
1216
+ internal.hovered.set(id, data);
1217
+ (_a = handlers.pointerover) === null || _a === void 0 ? void 0 : _a.call(handlers, data);
1218
+ (_b = handlers.pointerenter) === null || _b === void 0 ? void 0 : _b.call(handlers, data);
1219
+ }
1220
+ else if (hoveredItem.stopped) {
1221
+ // If the object was previously hovered and stopped, we shouldn't allow other items to proceed
1222
+ data.stopPropagation();
1223
+ }
1224
+ }
1225
+ // Call mouse move
1226
+ (_c = handlers === null || handlers === void 0 ? void 0 : handlers.pointermove) === null || _c === void 0 ? void 0 : _c.call(handlers, data);
1227
+ }
1228
+ else {
1229
+ // All other events ...
1230
+ const handler = handlers === null || handlers === void 0 ? void 0 : handlers[name];
1231
+ if (handler) {
1232
+ // Forward all events back to their respective handlers with the exception of click events,
1233
+ // which must use the initial target
1234
+ if (!isClickEvent || internal.initialHits.includes(eventObject)) {
1235
+ // Missed events have to come first
1236
+ pointerMissed(event, internal.interaction.filter((object) => !internal.initialHits.includes(object)));
1237
+ // Now call the handler
1238
+ handler(data);
1239
+ }
1240
+ }
1241
+ else {
1242
+ // Trigger onPointerMissed on all elements that have pointer over/out handlers, but not click and weren't hit
1243
+ if (isClickEvent && internal.initialHits.includes(eventObject)) {
1244
+ pointerMissed(event, internal.interaction.filter((object) => !internal.initialHits.includes(object)));
1245
+ }
1246
+ }
1247
+ }
1248
+ }
1249
+ handleIntersects(hits, event, delta, onIntersect);
1250
+ };
1251
+ }
1252
+ return { handlePointer };
1425
1253
  }
1426
1254
 
1427
- function mutate(object, value, paths = []) {
1255
+ function attach(object, value, paths = []) {
1428
1256
  const [base, ...remaining] = paths;
1429
1257
  if (!base)
1430
1258
  return;
@@ -1432,755 +1260,1152 @@ function mutate(object, value, paths = []) {
1432
1260
  applyProps(object, { [base]: value });
1433
1261
  }
1434
1262
  else {
1435
- // assign an empty object in order to spread object if undefined
1436
1263
  assignEmpty(object, base);
1437
- // recursion
1438
- mutate(object[base], value, remaining);
1264
+ attach(object[base], value, remaining);
1265
+ }
1266
+ }
1267
+ function detach(parent, child, attachProp) {
1268
+ const childLocalState = getLocalState(child);
1269
+ if (Array.isArray(attachProp)) {
1270
+ attach(parent, childLocalState.previousAttach, attachProp);
1271
+ }
1272
+ else {
1273
+ childLocalState.previousAttach();
1439
1274
  }
1440
1275
  }
1441
1276
  function assignEmpty(obj, base) {
1442
- if (
1443
- // @ts-ignore
1444
- (!Object.hasOwn(obj, base) && Reflect && !!Reflect.has && !Reflect.has(obj, base)) ||
1445
- obj[base] === undefined) {
1277
+ if ((!Object.hasOwn(obj, base) && Reflect && !!Reflect.has && !Reflect.has(obj, base)) || obj[base] === undefined) {
1446
1278
  obj[base] = {};
1447
1279
  }
1448
1280
  }
1449
1281
 
1450
- const NGT_PROXY_INSTANCE = Symbol.for('__ngt__proxy__instance__');
1451
- const NGT_INSTANCE_REF_FACTORY = new InjectionToken('NgtInstance[instanceRef] factory');
1452
- function provideInstanceRef(ctor, factory) {
1453
- return {
1454
- provide: NGT_INSTANCE_REF_FACTORY,
1455
- useFactory: (instance) => {
1456
- if (factory) {
1457
- return () => factory(instance);
1282
+ const SPECIAL_DOM_TAG = {
1283
+ NGT_PORTAL: 'ngt-portal',
1284
+ NGT_PRIMITIVE: 'ngt-primitive',
1285
+ NGT_VALUE: 'ngt-value',
1286
+ };
1287
+ const SPECIAL_PROPERTIES = {
1288
+ COMPOUND: 'ngtCompound',
1289
+ RENDER_PRIORITY: 'priority',
1290
+ ATTACH: 'attach',
1291
+ VALUE: 'rawValue',
1292
+ REF: 'ref',
1293
+ };
1294
+ const SPECIAL_EVENTS = {
1295
+ BEFORE_RENDER: 'beforeRender',
1296
+ AFTER_UPDATE: 'afterUpdate',
1297
+ AFTER_ATTACH: 'afterAttach',
1298
+ };
1299
+ function attachThreeChild(parent, child) {
1300
+ const pLS = getLocalState(parent);
1301
+ const cLS = getLocalState(child);
1302
+ if (!pLS || !cLS) {
1303
+ throw new Error(`[NGT] THREE instances need to be prepared with local state.`);
1304
+ }
1305
+ // whether the child is added to the parent with parent.add()
1306
+ let added = false;
1307
+ // assign store on child if not already exist
1308
+ if (!cLS.store) {
1309
+ cLS.store = pLS.store;
1310
+ }
1311
+ if (cLS.attach) {
1312
+ const attachProp = cLS.attach;
1313
+ if (typeof attachProp === 'function') {
1314
+ const attachCleanUp = attachProp(parent, child, cLS.store);
1315
+ if (attachCleanUp)
1316
+ cLS.previousAttach = attachCleanUp;
1317
+ }
1318
+ else {
1319
+ // we skip attach none if set explicitly
1320
+ if (attachProp[0] === 'none') {
1321
+ invalidateInstance(child);
1322
+ return;
1458
1323
  }
1459
- return () => instance['instanceRef'] || instance['instance']['instanceRef'];
1460
- },
1461
- deps: [ctor],
1324
+ // handle material array
1325
+ if (attachProp[0] === 'material' &&
1326
+ attachProp[1] &&
1327
+ typeof Number(attachProp[1]) === 'number' &&
1328
+ is.material(child) &&
1329
+ !Array.isArray(parent['material'])) {
1330
+ parent['material'] = [];
1331
+ }
1332
+ // attach
1333
+ if (cLS.isRaw) {
1334
+ cLS.parent = parent;
1335
+ // at this point we don't have rawValue yet, so we bail and wait until the Renderer recalls attach
1336
+ if (child.__ngt_renderer__[10 /* NgtRendererClassId.rawValue */] === undefined)
1337
+ return;
1338
+ attach(parent, child.__ngt_renderer__[10 /* NgtRendererClassId.rawValue */], attachProp);
1339
+ }
1340
+ else {
1341
+ attach(parent, child, attachProp);
1342
+ }
1343
+ // save value
1344
+ cLS.previousAttach = attachProp.reduce((value, property) => value[property], parent);
1345
+ }
1346
+ }
1347
+ else if (is.object3D(parent) && is.object3D(child)) {
1348
+ parent.add(child);
1349
+ added = true;
1350
+ }
1351
+ pLS.add(child, added ? 'objects' : 'nonObjects');
1352
+ cLS.parent = parent;
1353
+ if (cLS.afterAttach) {
1354
+ cLS.afterAttach.emit({ parent, node: child });
1355
+ }
1356
+ invalidateInstance(child);
1357
+ invalidateInstance(parent);
1358
+ }
1359
+ function removeThreeChild(parent, child, dispose) {
1360
+ var _a;
1361
+ const pLS = getLocalState(parent);
1362
+ const cLS = getLocalState(child);
1363
+ // clear parent ref
1364
+ cLS.parent = null;
1365
+ // remove child from parent
1366
+ if (pLS.objects) {
1367
+ pLS.remove(child, 'objects');
1368
+ }
1369
+ if (pLS.nonObjects) {
1370
+ pLS.remove(child, 'nonObjects');
1371
+ }
1372
+ if (cLS.attach) {
1373
+ detach(parent, child, cLS.attach);
1374
+ }
1375
+ else if (is.object3D(parent) && is.object3D(child)) {
1376
+ parent.remove(child);
1377
+ removeInteractivity(cLS.store || pLS.store, child);
1378
+ }
1379
+ const isPrimitive = cLS.primitive;
1380
+ if (!isPrimitive) {
1381
+ removeThreeRecursive(((_a = cLS.objects) === null || _a === void 0 ? void 0 : _a.value) || [], child, !!dispose);
1382
+ removeThreeRecursive(child.childre, child, !!dispose);
1383
+ }
1384
+ // dispose
1385
+ if (child['dispose'] && !is.scene(child)) {
1386
+ queueMicrotask(() => child['dispose']());
1387
+ }
1388
+ invalidateInstance(parent);
1389
+ }
1390
+ function removeThreeRecursive(array, parent, dispose) {
1391
+ if (array)
1392
+ [...array].forEach((child) => removeThreeChild(parent, child, dispose));
1393
+ }
1394
+ function processThreeEvent(instance, priority, eventName, callback, cdr) {
1395
+ var _a;
1396
+ const lS = getLocalState(instance);
1397
+ if (eventName === SPECIAL_EVENTS.BEFORE_RENDER) {
1398
+ return lS.store
1399
+ .get('internal')
1400
+ .subscribe((state) => callback({ state, object: instance }), priority || lS.priority || 0);
1401
+ }
1402
+ if (eventName === SPECIAL_EVENTS.AFTER_UPDATE || eventName === SPECIAL_EVENTS.AFTER_ATTACH) {
1403
+ if (!lS[eventName]) {
1404
+ lS[eventName] = new EventEmitter();
1405
+ }
1406
+ const sub = (_a = lS[eventName]) === null || _a === void 0 ? void 0 : _a.subscribe(callback);
1407
+ return sub.unsubscribe.bind(sub);
1408
+ }
1409
+ if (!lS.handlers) {
1410
+ lS.handlers = {};
1411
+ }
1412
+ // try to get the previous handler. compound might have one, the THREE object might also have one with the same name
1413
+ const previousHandler = lS.handlers[eventName];
1414
+ // readjust the callback
1415
+ const updatedCallback = (event) => {
1416
+ if (previousHandler)
1417
+ previousHandler(event);
1418
+ callback(event);
1419
+ };
1420
+ lS.handlers = Object.assign(Object.assign({}, lS.handlers), { [eventName]: eventToHandler(updatedCallback, cdr) });
1421
+ // increment the count everytime
1422
+ lS.eventCount += 1;
1423
+ // but only add the instance (target) to the interaction array (so that it is handled by the EventManager with Raycast)
1424
+ // the first time eventCount is incremented
1425
+ if (lS.eventCount === 1 && instance['raycast']) {
1426
+ lS.store.get('addInteraction')(instance);
1427
+ }
1428
+ // clean up the event listener by removing the target from the interaction array
1429
+ return () => {
1430
+ const localState = getLocalState(instance);
1431
+ if (localState && localState.eventCount) {
1432
+ localState.store.get('removeInteraction')(instance['uuid']);
1433
+ }
1462
1434
  };
1463
1435
  }
1464
- function injectInstanceRef(options = {}) {
1465
- return inject(NGT_INSTANCE_REF_FACTORY, options);
1436
+ function eventToHandler(callback, cdr) {
1437
+ return (event) => {
1438
+ callback(event);
1439
+ cdr.detectChanges();
1440
+ };
1466
1441
  }
1467
- function injectInstance(options = {}) {
1468
- return inject(NgtInstance, options);
1442
+ function kebabToPascal(str) {
1443
+ // split the string at each hyphen
1444
+ const parts = str.split('-');
1445
+ // map over the parts, capitalizing the first letter of each part
1446
+ const pascalParts = parts.map((part) => {
1447
+ return part.charAt(0).toUpperCase() + part.slice(1);
1448
+ });
1449
+ // join the parts together to create the final PascalCase string
1450
+ return pascalParts.join('');
1469
1451
  }
1470
- const supportedEvents = [
1471
- 'click',
1472
- 'contextmenu',
1473
- 'dblclick',
1474
- 'pointerup',
1475
- 'pointerdown',
1476
- 'pointerover',
1477
- 'pointerout',
1478
- 'pointerenter',
1479
- 'pointerleave',
1480
- 'pointermove',
1481
- 'pointermissed',
1482
- 'pointercancel',
1483
- 'wheel',
1484
- ];
1485
- class NgtInstance extends NgtComponentStore {
1486
- constructor() {
1487
- super(...arguments);
1488
- this.priority = 0;
1489
- this.click = new EventEmitter();
1490
- this.contextmenu = new EventEmitter();
1491
- this.dblclick = new EventEmitter();
1492
- this.pointerup = new EventEmitter();
1493
- this.pointerdown = new EventEmitter();
1494
- this.pointerover = new EventEmitter();
1495
- this.pointerout = new EventEmitter();
1496
- this.pointerenter = new EventEmitter();
1497
- this.pointerleave = new EventEmitter();
1498
- this.pointermove = new EventEmitter();
1499
- this.pointermissed = new EventEmitter();
1500
- this.pointercancel = new EventEmitter();
1501
- this.wheel = new EventEmitter();
1502
- this.zone = inject(NgZone);
1503
- this.store = inject(NgtStore);
1504
- this.parentRef = injectInstanceRef({ skipSelf: true, optional: true });
1505
- this._isRaw = false;
1506
- this.hasEmittedAlready = false;
1507
- this.instanceReady = this.effect(tapEffect(() => {
1508
- var _a, _b;
1509
- this.handleEvents();
1510
- let attachToParentSubscription;
1511
- if (this.parentRef) {
1512
- attachToParentSubscription = this.attachToParent(this.parent.pipe(filter((parent) => !!parent)));
1513
- const { noAttach, skipWrapper } = this.read();
1514
- if (!noAttach && !skipWrapper) {
1515
- const parentInstanceNode = getInstanceLocalState((_b = (_a = getInstanceLocalState(this.instanceValue)) === null || _a === void 0 ? void 0 : _a.parentRef) === null || _b === void 0 ? void 0 : _b.value);
1516
- if (parentInstanceNode) {
1517
- const collections = is.object3d(this.instanceValue)
1518
- ? parentInstanceNode.objectsRefs
1519
- : parentInstanceNode.instancesRefs;
1520
- collections.set((s) => [...s, this.instanceRef]);
1521
- }
1522
- }
1523
- }
1524
- let beforeRenderCleanUp;
1525
- if (this.beforeRender && is.object3d(this.instanceValue) && is.object3d(this.proxyInstance)) {
1526
- beforeRenderCleanUp = this.store
1527
- .read((s) => s.internal)
1528
- .subscribe((state, object) => this.beforeRender(state, object), this.priority, this.store.read, this.proxyInstance);
1529
- }
1530
- if (this.readyCallback)
1531
- this.readyCallback(this.instanceValue);
1532
- return () => {
1533
- beforeRenderCleanUp === null || beforeRenderCleanUp === void 0 ? void 0 : beforeRenderCleanUp();
1534
- attachToParentSubscription === null || attachToParentSubscription === void 0 ? void 0 : attachToParentSubscription.unsubscribe();
1535
- };
1536
- }));
1537
- this.handleEvents = this.effect(tapEffect(() => {
1538
- var _a;
1539
- if (this.instanceValue && is.object3d(this.instanceValue)) {
1540
- const observedEvents = supportedEvents.reduce((result, event) => {
1541
- const controllerEvent = this[event].observed ? this[event] : null;
1542
- if (controllerEvent) {
1543
- result.handlers[event] = this.eventNameToHandler(controllerEvent);
1544
- result.eventCount += 1;
1545
- }
1546
- return result;
1547
- }, { handlers: {}, eventCount: 0 });
1548
- // patch __ngt__ with events
1549
- applyProps(this.__ngt__, observedEvents);
1550
- // add as an interaction if there are events observed
1551
- if (observedEvents.eventCount > 0) {
1552
- (_a = getInstanceLocalState(this.instanceValue)) === null || _a === void 0 ? void 0 : _a.rootFactory().addInteraction(this.instanceValue);
1553
- }
1554
- }
1555
- return () => {
1556
- var _a;
1557
- if (is.object3d(this.instanceValue) && this.__ngt__.eventCount > 0) {
1558
- (_a = getInstanceLocalState(this.instanceValue)) === null || _a === void 0 ? void 0 : _a.rootFactory().removeInteraction(this.instanceValue.uuid);
1559
- }
1452
+
1453
+ class NgtRendererStore {
1454
+ constructor(root) {
1455
+ this.root = root;
1456
+ this.comments = [];
1457
+ this.portals = [];
1458
+ }
1459
+ createNode(type, node) {
1460
+ const state = [
1461
+ type,
1462
+ null,
1463
+ [],
1464
+ false,
1465
+ undefined,
1466
+ undefined,
1467
+ undefined,
1468
+ undefined,
1469
+ undefined,
1470
+ undefined,
1471
+ undefined,
1472
+ undefined,
1473
+ undefined,
1474
+ undefined,
1475
+ ];
1476
+ const rendererNode = Object.assign(node, { __ngt_renderer__: state });
1477
+ if (state[0 /* NgtRendererClassId.type */] === 'comment') {
1478
+ state[13 /* NgtRendererClassId.injectorFactory */] = () => getDebugNode(rendererNode).injector;
1479
+ // we attach an arrow function to the Comment node
1480
+ // In our directives, we can call this function to then start tracking the RendererNode
1481
+ rendererNode['__ngt_renderer_add_comment__'] = () => {
1482
+ this.comments.push(rendererNode);
1560
1483
  };
1561
- }));
1562
- this.attachToParent = this.effect(tap(() => {
1563
- var _a, _b, _c, _d;
1564
- const attach = this.read((s) => s.attach);
1565
- let parentInstanceRef = (_a = this.__ngt__) === null || _a === void 0 ? void 0 : _a.parentRef;
1566
- // if no parentInstance, try re-run the factory due to late init
1567
- if (!parentInstanceRef || !parentInstanceRef.value) {
1568
- // return early if failed to retrieve
1569
- if (!((_b = this.parent) === null || _b === void 0 ? void 0 : _b.value))
1570
- return;
1571
- // reassign on instance internal state
1572
- if (this.__ngt__) {
1573
- this.__ngt__.parentRef = this.parent;
1574
- }
1575
- parentInstanceRef = this.parent;
1576
- }
1577
- if (typeof attach === 'function') {
1578
- const attachCleanUp = attach(parentInstanceRef, this.instanceRef, this.store.read);
1579
- if (attachCleanUp) {
1580
- this.__ngt__.attach = attachCleanUp;
1581
- }
1484
+ return rendererNode;
1485
+ }
1486
+ if (state[0 /* NgtRendererClassId.type */] === 'portal') {
1487
+ state[13 /* NgtRendererClassId.injectorFactory */] = () => getDebugNode(rendererNode).injector;
1488
+ this.portals.push(rendererNode);
1489
+ return rendererNode;
1490
+ }
1491
+ if (state[0 /* NgtRendererClassId.type */] === 'compound') {
1492
+ state[7 /* NgtRendererClassId.queueOps */] = new Set();
1493
+ state[8 /* NgtRendererClassId.attributes */] = {};
1494
+ state[9 /* NgtRendererClassId.properties */] = {};
1495
+ return rendererNode;
1496
+ }
1497
+ return rendererNode;
1498
+ }
1499
+ setParent(node, parent) {
1500
+ if (!node.__ngt_renderer__[1 /* NgtRendererClassId.parent */]) {
1501
+ node.__ngt_renderer__[1 /* NgtRendererClassId.parent */] = parent;
1502
+ }
1503
+ }
1504
+ addChild(node, child) {
1505
+ if (!node.__ngt_renderer__[2 /* NgtRendererClassId.children */].includes(child)) {
1506
+ node.__ngt_renderer__[2 /* NgtRendererClassId.children */].push(child);
1507
+ }
1508
+ }
1509
+ removeChild(node, child) {
1510
+ const index = node.__ngt_renderer__[2 /* NgtRendererClassId.children */].findIndex((c) => child === c);
1511
+ if (index >= 0) {
1512
+ node.__ngt_renderer__[2 /* NgtRendererClassId.children */].splice(index, 1);
1513
+ }
1514
+ }
1515
+ setCompound(compound, instance) {
1516
+ compound.__ngt_renderer__[6 /* NgtRendererClassId.compounded */] = instance;
1517
+ const attributes = Object.keys(compound.__ngt_renderer__[8 /* NgtRendererClassId.attributes */]);
1518
+ const properties = Object.keys(compound.__ngt_renderer__[9 /* NgtRendererClassId.properties */]);
1519
+ if (attributes.length) {
1520
+ for (const key of attributes) {
1521
+ this.applyAttribute(instance, key, compound.__ngt_renderer__[8 /* NgtRendererClassId.attributes */][key]);
1582
1522
  }
1583
- else {
1584
- const propertyToAttach = [...attach];
1585
- // if propertyToAttach is empty
1586
- if (propertyToAttach.length === 0) {
1587
- // this might be the case where we are attaching an object3D to the parent object3D
1588
- if (is.object3d(this.instanceValue) &&
1589
- is.object3d(this.proxyInstance) &&
1590
- is.object3d((_c = this.parent) === null || _c === void 0 ? void 0 : _c.value)) {
1591
- (_d = this.parent) === null || _d === void 0 ? void 0 : _d.value.add(this.proxyInstance);
1592
- }
1593
- }
1594
- else {
1595
- // array material handling
1596
- if (propertyToAttach[0] === 'material' &&
1597
- propertyToAttach[1] &&
1598
- typeof Number(propertyToAttach[1]) === 'number' &&
1599
- is.material(this.instanceValue)) {
1600
- if (!Array.isArray(parentInstanceRef.value.material)) {
1601
- parentInstanceRef.value.material = [];
1602
- }
1603
- }
1604
- // retrieve the current value on the parentInstance, so we can reset it later
1605
- if (this.__ngt__) {
1606
- this.__ngt__.attachValue = propertyToAttach.reduce((value, property) => value[property], parentInstanceRef.value);
1607
- }
1608
- // attach the instance value on the parent
1609
- mutate(parentInstanceRef.value, this.proxyInstance, propertyToAttach);
1610
- }
1611
- // validate on the instance
1612
- invalidateInstance(this.instanceValue);
1613
- // validate on the parent
1614
- if (getInstanceLocalState(parentInstanceRef.value)) {
1615
- invalidateInstance(parentInstanceRef.value);
1616
- }
1617
- // save the attach
1618
- if (this.__ngt__) {
1619
- this.__ngt__.attach = propertyToAttach;
1620
- }
1621
- this.write({ attach: propertyToAttach });
1523
+ }
1524
+ if (properties.length) {
1525
+ for (const key of properties) {
1526
+ this.applyProperty(instance, key, compound.__ngt_renderer__[9 /* NgtRendererClassId.properties */][key]);
1622
1527
  }
1623
- }));
1528
+ }
1529
+ this.executeOperation(compound);
1624
1530
  }
1625
- set ref(instance) {
1626
- this.write({ instanceRef: is.ref(instance) ? instance : new NgtRef(instance) });
1531
+ queueOperation(node, op) {
1532
+ node.__ngt_renderer__[7 /* NgtRendererClassId.queueOps */].add(op);
1627
1533
  }
1628
- set skipWrapper(skipWrapper) {
1629
- this.write({ skipWrapper });
1630
- this.write({ skipWrapperExplicit: true });
1534
+ executeOperation(node, type = 'op') {
1535
+ var _a;
1536
+ if ((_a = node.__ngt_renderer__[7 /* NgtRendererClassId.queueOps */]) === null || _a === void 0 ? void 0 : _a.size) {
1537
+ node.__ngt_renderer__[7 /* NgtRendererClassId.queueOps */].forEach((op) => {
1538
+ if (op[0 /* NgtQueueOpClassId.type */] === type) {
1539
+ op[1 /* NgtQueueOpClassId.op */]();
1540
+ node.__ngt_renderer__[7 /* NgtRendererClassId.queueOps */].delete(op);
1541
+ }
1542
+ });
1543
+ }
1631
1544
  }
1632
- set skipInit(skipInit) {
1633
- this.write({ skipInit });
1634
- this.write({ skipInitExplicit: true });
1545
+ processPortalContainer(portal) {
1546
+ const injectorFactory = portal.__ngt_renderer__[13 /* NgtRendererClassId.injectorFactory */];
1547
+ const injector = injectorFactory === null || injectorFactory === void 0 ? void 0 : injectorFactory();
1548
+ if (!injector)
1549
+ return;
1550
+ const portalStore = injector.get(NgtStore, null);
1551
+ if (!portalStore)
1552
+ return;
1553
+ const portalContainer = portalStore.get('scene');
1554
+ if (!portalContainer)
1555
+ return;
1556
+ portal.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */] = this.createNode('three', portalContainer);
1635
1557
  }
1636
- set noAttach(noAttach) {
1637
- this.write({ noAttach });
1638
- this.write({ noAttachExplicit: true });
1558
+ applyAttribute(node, name, value) {
1559
+ if (node.__ngt_renderer__[3 /* NgtRendererClassId.destroyed */])
1560
+ return;
1561
+ if (name === SPECIAL_PROPERTIES.RENDER_PRIORITY) {
1562
+ // priority needs to be set as an attribute string so that they can be set as early as possible
1563
+ // we convert that string to a number. if it's invalid, 0
1564
+ let priority = Number(value);
1565
+ if (isNaN(priority)) {
1566
+ priority = 0;
1567
+ console.warn(`[NGT] "priority" is an invalid number, default to 0`);
1568
+ }
1569
+ getLocalState(node).priority = priority;
1570
+ }
1571
+ if (name === SPECIAL_PROPERTIES.COMPOUND) {
1572
+ // we set the compound property on instance node now so we know that this instance is being compounded
1573
+ node.__ngt_renderer__[4 /* NgtRendererClassId.compound */] = [value === '' || value === 'first', {}];
1574
+ return;
1575
+ }
1576
+ if (name === SPECIAL_PROPERTIES.ATTACH) {
1577
+ // handle attach as tring
1578
+ const paths = value.split('.');
1579
+ if (paths.length)
1580
+ getLocalState(node).attach = paths;
1581
+ return;
1582
+ }
1583
+ if (name === SPECIAL_PROPERTIES.VALUE) {
1584
+ // TODO the last time we tried this here, this didn't work
1585
+ // coercion
1586
+ let maybeCoerced = value;
1587
+ if (maybeCoerced === '' || maybeCoerced === 'true' || maybeCoerced === 'false') {
1588
+ maybeCoerced = maybeCoerced === 'true' || maybeCoerced === '';
1589
+ }
1590
+ else if (!isNaN(Number(maybeCoerced))) {
1591
+ maybeCoerced = Number(maybeCoerced);
1592
+ }
1593
+ node.__ngt_renderer__[10 /* NgtRendererClassId.rawValue */] = maybeCoerced;
1594
+ return;
1595
+ }
1596
+ applyProps(node, { [name]: value });
1639
1597
  }
1640
- set attach(value) {
1641
- if (value) {
1642
- const attach = typeof value === 'function'
1643
- ? value
1644
- : Array.isArray(value)
1645
- ? value.map((item) => (typeof item === 'number' ? item.toString() : item))
1646
- : [value];
1647
- this.write({ attach, attachExplicit: true });
1598
+ applyProperty(node, name, value) {
1599
+ if (node.__ngt_renderer__[3 /* NgtRendererClassId.destroyed */])
1600
+ return;
1601
+ // setup [ref] here
1602
+ if (name === SPECIAL_PROPERTIES.REF && is.ref(value)) {
1603
+ node.__ngt_renderer__[11 /* NgtRendererClassId.ref */] = value;
1604
+ value.nativeElement = node;
1605
+ return;
1606
+ }
1607
+ const parent = getLocalState(node).parent || node.__ngt_renderer__[1 /* NgtRendererClassId.parent */];
1608
+ // rawValue
1609
+ if (getLocalState(node).isRaw && name === SPECIAL_PROPERTIES.VALUE) {
1610
+ node.__ngt_renderer__[10 /* NgtRendererClassId.rawValue */] = value;
1611
+ attachThreeChild(parent, node);
1612
+ return;
1648
1613
  }
1614
+ // attach
1615
+ if (name === SPECIAL_PROPERTIES.ATTACH) {
1616
+ getLocalState(node).attach = Array.isArray(value) ? value.map((v) => v.toString()) : value;
1617
+ attachThreeChild(parent, node);
1618
+ return;
1619
+ }
1620
+ const compound = node.__ngt_renderer__[4 /* NgtRendererClassId.compound */];
1621
+ if ((compound === null || compound === void 0 ? void 0 : compound[1 /* NgtCompoundClassId.props */]) &&
1622
+ name in compound[1 /* NgtCompoundClassId.props */] &&
1623
+ !compound[0 /* NgtCompoundClassId.applyFirst */]) {
1624
+ value = compound[1 /* NgtCompoundClassId.props */][name];
1625
+ }
1626
+ applyProps(node, { [name]: value });
1649
1627
  }
1650
- set isRaw(val) {
1651
- this._isRaw = val;
1628
+ isCompound(name) {
1629
+ return this.root.compoundPrefixes.some((prefix) => name.startsWith(prefix));
1652
1630
  }
1653
- initialize() {
1654
- super.initialize();
1655
- this.write({
1656
- instanceRef: new NgtRef(null),
1657
- attach: [],
1658
- noAttach: false,
1659
- skipWrapper: false,
1660
- skipInit: false,
1661
- });
1631
+ get rootScene() {
1632
+ return this.root.store.get('scene');
1662
1633
  }
1663
- ngOnInit() {
1664
- this.zone.runOutsideAngular(() => {
1665
- this.store.onReady(() => {
1666
- this.instanceReady(this.instanceRef.pipe(filter((instance) => !!instance)));
1667
- });
1668
- });
1634
+ get rootCdr() {
1635
+ return this.root.cdr;
1669
1636
  }
1670
- get instanceRef() {
1671
- return this.read((s) => s.instanceRef);
1637
+ getClosestParentWithInstance(node) {
1638
+ let parent = node.__ngt_renderer__[1 /* NgtRendererClassId.parent */];
1639
+ while (parent && parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] !== 'three') {
1640
+ parent = parent.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */]
1641
+ ? parent.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */]
1642
+ : parent.__ngt_renderer__[1 /* NgtRendererClassId.parent */];
1643
+ }
1644
+ return parent;
1672
1645
  }
1673
- get instanceValue() {
1674
- var _a;
1675
- if (!this.instanceRef.value)
1676
- return this.instanceRef.value;
1677
- return this._isRaw ? (_a = this.instanceRef.value) === null || _a === void 0 ? void 0 : _a.valueOf() : this.instanceRef.value;
1646
+ getClosestParentWithCompound(node) {
1647
+ if (node.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */]) {
1648
+ return node.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */];
1649
+ }
1650
+ let parent = node.__ngt_renderer__[1 /* NgtRendererClassId.parent */];
1651
+ if (parent &&
1652
+ parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound' &&
1653
+ !parent.__ngt_renderer__[6 /* NgtRendererClassId.compounded */]) {
1654
+ return parent;
1655
+ }
1656
+ while (parent &&
1657
+ (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' ||
1658
+ !parent.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */] ||
1659
+ parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] !== 'compound')) {
1660
+ parent = parent.__ngt_renderer__[1 /* NgtRendererClassId.parent */];
1661
+ }
1662
+ if (!parent)
1663
+ return;
1664
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' &&
1665
+ parent.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */]) {
1666
+ return parent.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */];
1667
+ }
1668
+ if (!parent.__ngt_renderer__[6 /* NgtRendererClassId.compounded */]) {
1669
+ return parent;
1670
+ }
1671
+ return null;
1678
1672
  }
1679
- get proxyInstance() {
1673
+ getCreationState() {
1680
1674
  var _a;
1681
- return (_a = this.instanceValue) === null || _a === void 0 ? void 0 : _a[NGT_PROXY_INSTANCE];
1675
+ const injectedArgs = ((_a = this.firstNonInjectedDirective(NgtArgs)) === null || _a === void 0 ? void 0 : _a.args) || [];
1676
+ const store = this.tryGetPortalStore();
1677
+ return { injectedArgs, store };
1682
1678
  }
1683
- get __ngt__() {
1684
- return getInstanceLocalState(this._isRaw ? this.instanceRef.value : this.instanceValue);
1679
+ destroy(node, parent) {
1680
+ const state = node.__ngt_renderer__;
1681
+ if (state[3 /* NgtRendererClassId.destroyed */])
1682
+ return;
1683
+ if (state[0 /* NgtRendererClassId.type */] === 'three') {
1684
+ state[4 /* NgtRendererClassId.compound */] = undefined;
1685
+ state[5 /* NgtRendererClassId.compoundParent */] = undefined;
1686
+ const localState = getLocalState(node);
1687
+ if (localState.objects) {
1688
+ localState.objects.value.forEach((obj) => this.destroy(obj, parent));
1689
+ localState.objects.complete();
1690
+ }
1691
+ if (localState.nonObjects) {
1692
+ localState.nonObjects.value.forEach((obj) => this.destroy(obj, parent));
1693
+ localState.nonObjects.complete();
1694
+ }
1695
+ if (localState.afterUpdate)
1696
+ localState.afterUpdate.complete();
1697
+ if (localState.afterAttach)
1698
+ localState.afterAttach.complete();
1699
+ delete localState['objects'];
1700
+ delete localState['nonObjects'];
1701
+ delete localState['add'];
1702
+ delete localState['remove'];
1703
+ delete localState['afterUpdate'];
1704
+ delete localState['afterAttach'];
1705
+ delete localState['store'];
1706
+ delete localState['handlers'];
1707
+ if (!localState.primitive) {
1708
+ delete node['__ngt__'];
1709
+ }
1710
+ }
1711
+ if (state[0 /* NgtRendererClassId.type */] === 'comment') {
1712
+ state[13 /* NgtRendererClassId.injectorFactory */] = null;
1713
+ delete node['__ngt_renderer_add_comment__'];
1714
+ const index = this.comments.findIndex((comment) => comment === node);
1715
+ if (index > -1) {
1716
+ this.comments.splice(index, 1);
1717
+ }
1718
+ }
1719
+ if (state[0 /* NgtRendererClassId.type */] === 'portal') {
1720
+ state[13 /* NgtRendererClassId.injectorFactory */] = null;
1721
+ const index = this.portals.findIndex((portal) => portal === node);
1722
+ if (index > -1) {
1723
+ this.portals.splice(index, 1);
1724
+ }
1725
+ }
1726
+ if (state[0 /* NgtRendererClassId.type */] === 'compound') {
1727
+ state[6 /* NgtRendererClassId.compounded */] = undefined;
1728
+ state[8 /* NgtRendererClassId.attributes */] = null;
1729
+ state[9 /* NgtRendererClassId.properties */] = null;
1730
+ this.executeOperation(node, 'cleanUp');
1731
+ state[7 /* NgtRendererClassId.queueOps */].clear();
1732
+ state[7 /* NgtRendererClassId.queueOps */] = null;
1733
+ }
1734
+ if (state[11 /* NgtRendererClassId.ref */]) {
1735
+ // nullify ref
1736
+ state[11 /* NgtRendererClassId.ref */].nativeElement = null;
1737
+ state[11 /* NgtRendererClassId.ref */] = undefined;
1738
+ }
1739
+ // nullify parent
1740
+ state[1 /* NgtRendererClassId.parent */] = null;
1741
+ for (const renderChild of state[2 /* NgtRendererClassId.children */] || []) {
1742
+ if (renderChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' && parent) {
1743
+ removeThreeChild(parent, renderChild, true);
1744
+ }
1745
+ this.destroy(renderChild, parent);
1746
+ }
1747
+ state[2 /* NgtRendererClassId.children */] = [];
1748
+ state[3 /* NgtRendererClassId.destroyed */] = true;
1749
+ if (parent) {
1750
+ this.removeChild(parent, node);
1751
+ }
1685
1752
  }
1686
- get parent() {
1687
- var _a;
1688
- return (_a = this.parentRef) === null || _a === void 0 ? void 0 : _a.call(this);
1753
+ firstNonInjectedDirective(dir) {
1754
+ let directive;
1755
+ let i = this.comments.length - 1;
1756
+ while (i >= 0) {
1757
+ const comment = this.comments[i];
1758
+ if (comment.__ngt_renderer__[3 /* NgtRendererClassId.destroyed */]) {
1759
+ i--;
1760
+ continue;
1761
+ }
1762
+ const injector = comment.__ngt_renderer__[13 /* NgtRendererClassId.injectorFactory */]();
1763
+ if (!injector) {
1764
+ i--;
1765
+ continue;
1766
+ }
1767
+ const instance = injector.get(dir, null);
1768
+ if (instance && instance.validate()) {
1769
+ directive = instance;
1770
+ break;
1771
+ }
1772
+ i--;
1773
+ }
1774
+ return directive;
1775
+ }
1776
+ tryGetPortalStore() {
1777
+ let store;
1778
+ // we only care about the portal states because NgtStore only differs per Portal
1779
+ let i = this.portals.length - 1;
1780
+ while (i >= 0) {
1781
+ // loop through the portal state backwards to find the closest NgtStore
1782
+ const injector = this.portals[i].__ngt_renderer__[13 /* NgtRendererClassId.injectorFactory */]();
1783
+ if (!injector) {
1784
+ i--;
1785
+ continue;
1786
+ }
1787
+ const instance = injector.get(NgtStore, null);
1788
+ if (instance) {
1789
+ store = instance;
1790
+ break;
1791
+ }
1792
+ i--;
1793
+ }
1794
+ return store || this.root.store;
1689
1795
  }
1690
- ngOnDestroy() {
1691
- this.zone.runOutsideAngular(() => {
1692
- this.destroy();
1796
+ }
1797
+
1798
+ class NgtRendererFactory {
1799
+ constructor() {
1800
+ this.domRendererFactory = inject(ɵDomRendererFactory2);
1801
+ this.cdr = inject(ChangeDetectorRef);
1802
+ this.store = inject(NgtStore);
1803
+ this.catalogue = inject(NGT_CATALOGUE);
1804
+ this.compoundPrefixes = inject(NGT_COMPOUND_PREFIXES);
1805
+ this.rendererStore = new NgtRendererStore({
1806
+ store: this.store,
1807
+ cdr: this.cdr,
1808
+ compoundPrefixes: this.compoundPrefixes,
1693
1809
  });
1694
- super.ngOnDestroy();
1695
1810
  }
1696
- destroy() {
1697
- if (this.instanceValue) {
1698
- if (is.object3d(this.instanceValue)) {
1699
- const parentInstance = this.parent;
1700
- if (parentInstance && is.object3d(parentInstance.value)) {
1701
- removeInteractivity(this.__ngt__.stateFactory.bind(this.__ngt__), this.instanceValue);
1702
- parentInstance.value.remove(this.instanceValue);
1703
- invalidateInstance(parentInstance.value);
1704
- }
1705
- if (this.instanceValue.clear != null) {
1706
- this.instanceValue.clear();
1811
+ createRenderer(hostElement, type) {
1812
+ // TODO we might need to check on "type" to return DomRenderer for that particular type to support HTML
1813
+ if (!this.renderer) {
1814
+ const domRenderer = this.domRendererFactory.createRenderer(hostElement, type);
1815
+ this.renderer = new NgtRenderer(domRenderer, this.rendererStore, this.catalogue);
1816
+ }
1817
+ return this.renderer;
1818
+ }
1819
+ }
1820
+ NgtRendererFactory.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRendererFactory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1821
+ NgtRendererFactory.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRendererFactory });
1822
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRendererFactory, decorators: [{
1823
+ type: Injectable
1824
+ }] });
1825
+ class NgtRenderer {
1826
+ constructor(domRenderer, store, catalogue) {
1827
+ this.domRenderer = domRenderer;
1828
+ this.store = store;
1829
+ this.catalogue = catalogue;
1830
+ this.first = false;
1831
+ this.createText = this.domRenderer.createText.bind(this.domRenderer);
1832
+ this.destroy = this.domRenderer.destroy.bind(this.domRenderer);
1833
+ this.destroyNode = null;
1834
+ this.selectRootElement = this.domRenderer.selectRootElement.bind(this.domRenderer);
1835
+ this.nextSibling = this.domRenderer.nextSibling.bind(this.domRenderer);
1836
+ this.removeAttribute = this.domRenderer.removeAttribute.bind(this.domRenderer);
1837
+ this.addClass = this.domRenderer.addClass.bind(this.domRenderer);
1838
+ this.removeClass = this.domRenderer.removeClass.bind(this.domRenderer);
1839
+ this.setStyle = this.domRenderer.setStyle.bind(this.domRenderer);
1840
+ this.removeStyle = this.domRenderer.removeStyle.bind(this.domRenderer);
1841
+ this.setValue = this.domRenderer.setValue.bind(this.domRenderer);
1842
+ }
1843
+ createElement(name, namespace) {
1844
+ const element = this.domRenderer.createElement(name, namespace);
1845
+ // on first pass, we return the Root Scene as the root node
1846
+ if (!this.first) {
1847
+ this.first = true;
1848
+ return this.store.createNode('three', this.store.rootScene);
1849
+ }
1850
+ // handle compound
1851
+ if (this.store.isCompound(name))
1852
+ return this.store.createNode('compound', element);
1853
+ // handle portal
1854
+ if (name === SPECIAL_DOM_TAG.NGT_PORTAL) {
1855
+ return this.store.createNode('portal', element);
1856
+ }
1857
+ // handle raw value
1858
+ if (name === SPECIAL_DOM_TAG.NGT_VALUE) {
1859
+ return this.store.createNode('three', Object.assign({ __ngt_renderer__: { rawValue: undefined } }, { __ngt__: { isRaw: true } }));
1860
+ }
1861
+ const { injectedArgs, store } = this.store.getCreationState();
1862
+ // handle primitive
1863
+ if (name === SPECIAL_DOM_TAG.NGT_PRIMITIVE) {
1864
+ if (!injectedArgs[0])
1865
+ throw new Error(`[NGT] ngt-primitive without args is invalid`);
1866
+ const object = injectedArgs[0];
1867
+ let localState = getLocalState(object);
1868
+ if (!Object.keys(localState).length) {
1869
+ prepare(object, { store, args: injectedArgs, primitive: true });
1870
+ localState = getLocalState(object);
1871
+ }
1872
+ if (!localState.store)
1873
+ localState.store = store;
1874
+ return this.store.createNode('three', object);
1875
+ }
1876
+ const threeTag = name.startsWith('ngt') ? name.slice(4) : name;
1877
+ const threeName = kebabToPascal(threeTag);
1878
+ const threeTarget = this.catalogue[threeName];
1879
+ // we have the THREE constructor here, handle it
1880
+ if (threeTarget) {
1881
+ const instance = prepare(new threeTarget(...injectedArgs), { store, args: injectedArgs });
1882
+ const node = this.store.createNode('three', instance);
1883
+ const localState = getLocalState(instance);
1884
+ if (is.geometry(instance)) {
1885
+ localState.attach = ['geometry'];
1886
+ }
1887
+ else if (is.material(instance)) {
1888
+ localState.attach = ['material'];
1889
+ }
1890
+ return node;
1891
+ }
1892
+ return this.store.createNode('dom', element);
1893
+ }
1894
+ createComment(value) {
1895
+ const comment = this.domRenderer.createComment(value);
1896
+ return this.store.createNode('comment', comment);
1897
+ }
1898
+ appendChild(parent, newChild) {
1899
+ // TODO: just ignore text node for now
1900
+ if (newChild instanceof Text)
1901
+ return;
1902
+ if (newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'comment') {
1903
+ this.store.setParent(newChild, parent);
1904
+ return;
1905
+ }
1906
+ this.store.setParent(newChild, parent);
1907
+ this.store.addChild(parent, newChild);
1908
+ // if new chlid is a portal
1909
+ if (newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'portal') {
1910
+ this.store.processPortalContainer(newChild);
1911
+ if (newChild.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */]) {
1912
+ this.appendChild(parent, newChild.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */]);
1913
+ }
1914
+ return;
1915
+ }
1916
+ // if parent is a portal
1917
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'portal') {
1918
+ this.store.processPortalContainer(parent);
1919
+ if (parent.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */]) {
1920
+ this.appendChild(parent.__ngt_renderer__[12 /* NgtRendererClassId.portalContainer */], newChild);
1921
+ }
1922
+ return;
1923
+ }
1924
+ // if both are three instances, straightforward case
1925
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' &&
1926
+ newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
1927
+ attachThreeChild(parent, newChild);
1928
+ // here, we handle the special case of if the parent has a compoundParent, which means this child is part of a compound parent template
1929
+ if (!newChild.__ngt_renderer__[4 /* NgtRendererClassId.compound */])
1930
+ return;
1931
+ const closestGrandparentWithCompound = this.store.getClosestParentWithCompound(parent);
1932
+ if (!closestGrandparentWithCompound)
1933
+ return;
1934
+ this.appendChild(closestGrandparentWithCompound, newChild);
1935
+ return;
1936
+ }
1937
+ // if only the parent is the THREE instance
1938
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
1939
+ if (newChild.__ngt_renderer__[2 /* NgtRendererClassId.children */].length) {
1940
+ for (const renderChild of newChild.__ngt_renderer__[2 /* NgtRendererClassId.children */]) {
1941
+ this.appendChild(parent, renderChild);
1707
1942
  }
1708
1943
  }
1709
- else {
1710
- if (this.__ngt__) {
1711
- // non-scene objects
1712
- const previousAttach = this.__ngt__.attach;
1713
- if (previousAttach != null) {
1714
- if (typeof previousAttach === 'function') {
1715
- previousAttach();
1716
- }
1717
- else {
1718
- const previousAttachValue = this.__ngt__.attachValue;
1719
- if (this.__ngt__.parentRef && this.__ngt__.parentRef.value) {
1720
- mutate(this.__ngt__.parentRef.value, previousAttachValue, previousAttach);
1721
- }
1722
- }
1723
- if (this.__ngt__.parentRef && this.__ngt__.parentRef.value) {
1724
- invalidateInstance(this.__ngt__.parentRef.value);
1725
- }
1944
+ }
1945
+ // if parent is a compound
1946
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound') {
1947
+ // if compound doesn't have a THREE instance set yet
1948
+ if (!parent.__ngt_renderer__[6 /* NgtRendererClassId.compounded */] &&
1949
+ newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
1950
+ // if child is indeed an ngtCompound
1951
+ if (newChild.__ngt_renderer__[4 /* NgtRendererClassId.compound */]) {
1952
+ this.store.setCompound(parent, newChild);
1953
+ }
1954
+ else {
1955
+ // if not, we track the parent (that is supposedly the compound component) on this three instance
1956
+ if (!newChild.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */]) {
1957
+ newChild.__ngt_renderer__[5 /* NgtRendererClassId.compoundParent */] = parent;
1726
1958
  }
1727
1959
  }
1728
1960
  }
1729
- const dispose = this.instanceValue['dispose'];
1730
- if (dispose && typeof dispose === 'function') {
1731
- dispose.apply(this.instanceValue);
1961
+ // reset the compound if it's changed
1962
+ if (parent.__ngt_renderer__[6 /* NgtRendererClassId.compounded */] &&
1963
+ newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' &&
1964
+ newChild.__ngt_renderer__[4 /* NgtRendererClassId.compound */] &&
1965
+ parent.__ngt_renderer__[6 /* NgtRendererClassId.compounded */] !== newChild) {
1966
+ this.store.setCompound(parent, newChild);
1967
+ }
1968
+ }
1969
+ if (newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' && !getLocalState(newChild).parent) {
1970
+ // we'll try to get the grandparent instance here so that we can run appendChild with both instances
1971
+ const closestGrandparentInstance = this.store.getClosestParentWithInstance(parent);
1972
+ if (closestGrandparentInstance) {
1973
+ this.appendChild(closestGrandparentInstance, newChild);
1974
+ }
1975
+ return;
1976
+ }
1977
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'dom' &&
1978
+ newChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'dom') {
1979
+ const closestGrandparentInstance = this.store.getClosestParentWithInstance(parent);
1980
+ if (closestGrandparentInstance) {
1981
+ this.appendChild(closestGrandparentInstance, newChild);
1982
+ }
1983
+ }
1984
+ }
1985
+ insertBefore(parent, newChild
1986
+ // TODO we might need these?
1987
+ // refChild: NgtRendererNode,
1988
+ // isMove?: boolean | undefined
1989
+ ) {
1990
+ if (!parent.__ngt_renderer__)
1991
+ return;
1992
+ this.appendChild(parent, newChild);
1993
+ }
1994
+ removeChild(parent, oldChild, isHostElement) {
1995
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' &&
1996
+ oldChild.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
1997
+ removeThreeChild(parent, oldChild, true);
1998
+ this.store.destroy(oldChild, parent);
1999
+ return;
2000
+ }
2001
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound' &&
2002
+ parent.__ngt_renderer__[1 /* NgtRendererClassId.parent */]) {
2003
+ this.removeChild(parent.__ngt_renderer__[1 /* NgtRendererClassId.parent */], oldChild, isHostElement);
2004
+ return;
2005
+ }
2006
+ if (parent.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
2007
+ this.store.destroy(oldChild, parent);
2008
+ return;
2009
+ }
2010
+ const closestGrandparentInstance = this.store.getClosestParentWithInstance(parent);
2011
+ if (closestGrandparentInstance) {
2012
+ this.removeChild(closestGrandparentInstance, oldChild, isHostElement);
2013
+ }
2014
+ this.store.destroy(oldChild, closestGrandparentInstance);
2015
+ }
2016
+ parentNode(node) {
2017
+ var _a;
2018
+ if ((_a = node.__ngt_renderer__) === null || _a === void 0 ? void 0 : _a[1 /* NgtRendererClassId.parent */])
2019
+ return node.__ngt_renderer__[1 /* NgtRendererClassId.parent */];
2020
+ return this.domRenderer.parentNode(node);
2021
+ }
2022
+ setAttribute(el, name, value, namespace) {
2023
+ if (el.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound') {
2024
+ // we don't have the compound instance yet
2025
+ el.__ngt_renderer__[8 /* NgtRendererClassId.attributes */][name] = value;
2026
+ if (!el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */]) {
2027
+ this.store.queueOperation(el, ['op', () => this.setAttribute(el, name, value, namespace)]);
2028
+ return;
2029
+ }
2030
+ this.setAttribute(el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */], name, value, namespace);
2031
+ return;
2032
+ }
2033
+ if (el.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
2034
+ this.store.applyAttribute(el, name, value);
2035
+ }
2036
+ }
2037
+ setProperty(el, name, value) {
2038
+ if (el.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound') {
2039
+ // we don't have the compound instance yet
2040
+ el.__ngt_renderer__[9 /* NgtRendererClassId.properties */][name] = value;
2041
+ if (!el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */]) {
2042
+ this.store.queueOperation(el, ['op', () => this.setProperty(el, name, value)]);
2043
+ return;
2044
+ }
2045
+ if (el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */].__ngt_renderer__[4 /* NgtRendererClassId.compound */]) {
2046
+ Object.assign(el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */].__ngt_renderer__[4 /* NgtRendererClassId.compound */], {
2047
+ props: Object.assign(Object.assign({}, el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */].__ngt_renderer__[4 /* NgtRendererClassId.compound */]), { [name]: value }),
2048
+ });
1732
2049
  }
2050
+ this.setProperty(el.__ngt_renderer__[6 /* NgtRendererClassId.compounded */], name, value);
2051
+ return;
2052
+ }
2053
+ if (el.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three') {
2054
+ this.store.applyProperty(el, name, value);
1733
2055
  }
1734
- this.write({ attach: [] });
1735
- this.instanceRef.complete();
1736
2056
  }
1737
- eventNameToHandler(controllerEvent) {
1738
- return (event) => {
1739
- // go back into Angular Zone so that state updates on these events trigger CD
1740
- this.zone.run(() => {
1741
- controllerEvent.emit(event);
1742
- });
1743
- };
2057
+ listen(target, eventName, callback) {
2058
+ if (target.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'three' ||
2059
+ (target.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound' &&
2060
+ target.__ngt_renderer__[6 /* NgtRendererClassId.compounded */])) {
2061
+ const instance = target.__ngt_renderer__[6 /* NgtRendererClassId.compounded */] || target;
2062
+ const priority = getLocalState(target).priority;
2063
+ return processThreeEvent(instance, priority || 0, eventName, callback, this.store.rootCdr);
2064
+ }
2065
+ if (target.__ngt_renderer__[0 /* NgtRendererClassId.type */] === 'compound' &&
2066
+ !target.__ngt_renderer__[6 /* NgtRendererClassId.compounded */]) {
2067
+ this.store.queueOperation(target, [
2068
+ 'op',
2069
+ () => this.store.queueOperation(target, ['cleanUp', this.listen(target, eventName, callback)]),
2070
+ ]);
2071
+ }
2072
+ return () => { };
1744
2073
  }
1745
- }
1746
- NgtInstance.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtInstance, deps: null, target: i0.ɵɵFactoryTarget.Directive });
1747
- NgtInstance.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.0.0", type: NgtInstance, isStandalone: true, selector: "[ngtInstance]", inputs: { ref: "ref", skipWrapper: "skipWrapper", skipInit: "skipInit", noAttach: "noAttach", attach: "attach", priority: "priority", beforeRender: "beforeRender", readyCallback: "readyCallback", updateCallback: "updateCallback" }, outputs: { click: "click", contextmenu: "contextmenu", dblclick: "dblclick", pointerup: "pointerup", pointerdown: "pointerdown", pointerover: "pointerover", pointerout: "pointerout", pointerenter: "pointerenter", pointerleave: "pointerleave", pointermove: "pointermove", pointermissed: "pointermissed", pointercancel: "pointercancel", wheel: "wheel" }, exportAs: ["ngtInstance"], usesInheritance: true, ngImport: i0 });
1748
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtInstance, decorators: [{
1749
- type: Directive,
1750
- args: [{
1751
- selector: '[ngtInstance]',
1752
- exportAs: 'ngtInstance',
1753
- standalone: true,
1754
- }]
1755
- }], propDecorators: { ref: [{
1756
- type: Input
1757
- }], skipWrapper: [{
1758
- type: Input
1759
- }], skipInit: [{
1760
- type: Input
1761
- }], noAttach: [{
1762
- type: Input
1763
- }], attach: [{
1764
- type: Input
1765
- }], priority: [{
1766
- type: Input
1767
- }], beforeRender: [{
1768
- type: Input
1769
- }], readyCallback: [{
1770
- type: Input
1771
- }], updateCallback: [{
1772
- type: Input
1773
- }], click: [{
1774
- type: Output
1775
- }], contextmenu: [{
1776
- type: Output
1777
- }], dblclick: [{
1778
- type: Output
1779
- }], pointerup: [{
1780
- type: Output
1781
- }], pointerdown: [{
1782
- type: Output
1783
- }], pointerover: [{
1784
- type: Output
1785
- }], pointerout: [{
1786
- type: Output
1787
- }], pointerenter: [{
1788
- type: Output
1789
- }], pointerleave: [{
1790
- type: Output
1791
- }], pointermove: [{
1792
- type: Output
1793
- }], pointermissed: [{
1794
- type: Output
1795
- }], pointercancel: [{
1796
- type: Output
1797
- }], wheel: [{
1798
- type: Output
1799
- }] } });
1800
- const NGT_INSTANCE_INPUTS = [
1801
- 'ref',
1802
- 'attach',
1803
- 'skipWrapper',
1804
- 'skipInit',
1805
- 'noAttach',
1806
- 'beforeRender',
1807
- 'priority',
1808
- 'updateCallback',
1809
- 'readyCallback',
1810
- ];
1811
- const NGT_INSTANCE_OUTPUTS = [...supportedEvents];
1812
-
1813
- const defaultResizeOptions = {
1814
- box: 'content-box',
1815
- scroll: false,
1816
- offsetSize: false,
1817
- debounce: { scroll: 50, resize: 0 },
1818
- };
1819
- const [injectResizeOptions, provideResizeOptions] = createInjection('ngtResize Options', {
1820
- defaultValueOrFactory: defaultResizeOptions,
1821
- provideValueFactory: (value) => (Object.assign(Object.assign({}, defaultResizeOptions), value)),
1822
- });
1823
- const [injectResizeObserverSupport] = createInjection('Resize Observer API support', {
1824
- defaultValueOrFactory: () => {
1825
- const window = injectWindow();
1826
- return 'ResizeObserver' in window && window['ResizeObserver'] != null;
1827
- },
1828
- });
1829
-
1830
- class NgtResize extends Observable {
1831
- constructor() {
1832
- const { nativeElement } = inject(ElementRef);
1833
- const zone = inject(NgZone);
1834
- const document = inject(DOCUMENT);
1835
- const window = injectWindow();
1836
- const isSupport = injectResizeObserverSupport();
1837
- const { box, offsetSize, scroll, debounce } = injectResizeOptions();
1838
- let observer;
1839
- let lastBounds;
1840
- let lastEntries = [];
1841
- const torndown$ = new Subject();
1842
- const scrollContainers = findScrollContainers(nativeElement, document.body);
1843
- // set actual debounce values early, so effects know if they should react accordingly
1844
- const scrollDebounce = debounce ? (typeof debounce === 'number' ? debounce : debounce.scroll) : null;
1845
- const resizeDebounce = debounce ? (typeof debounce === 'number' ? debounce : debounce.resize) : null;
1846
- const debounceAndDestroy = (debounce) => {
1847
- return pipe(debounceTime(debounce !== null && debounce !== void 0 ? debounce : 0), takeUntil(torndown$));
1848
- };
1849
- super((subscriber) => {
1850
- if (!isSupport) {
1851
- subscriber.error('ResizeObserver is not supported in your browser. Please use a polyfill');
1852
- return;
1853
- }
1854
- zone.runOutsideAngular(() => {
1855
- const callback = (entries) => {
1856
- lastEntries = entries;
1857
- const { left, top, width, height, bottom, right, x, y } = nativeElement.getBoundingClientRect();
1858
- const size = {
1859
- left,
1860
- top,
1861
- width,
1862
- height,
1863
- bottom,
1864
- right,
1865
- x,
1866
- y,
1867
- };
1868
- if (nativeElement instanceof HTMLElement && offsetSize) {
1869
- size.height = nativeElement.offsetHeight;
1870
- size.width = nativeElement.offsetWidth;
1871
- }
1872
- Object.freeze(size);
1873
- subscriber.next(Object.assign({ entries, dpr: window.devicePixelRatio }, size));
1874
- if (!areBoundsEqual(lastBounds || {}, size)) {
1875
- lastBounds = size;
1876
- }
1877
- };
1878
- const boundEntriesCallback = () => {
1879
- callback(lastEntries);
1880
- };
1881
- observer = new ResizeObserver(callback);
1882
- observer.observe(nativeElement, { box });
1883
- if (scroll) {
1884
- if (scrollContainers) {
1885
- scrollContainers.forEach((scrollContainer) => {
1886
- fromEvent(scrollContainer, 'scroll', {
1887
- capture: true,
1888
- passive: true,
1889
- })
1890
- .pipe(debounceAndDestroy(scrollDebounce))
1891
- .subscribe(boundEntriesCallback);
1892
- });
1893
- }
1894
- fromEvent(window, 'scroll', {
1895
- capture: true,
1896
- passive: true,
1897
- })
1898
- .pipe(debounceAndDestroy(scrollDebounce))
1899
- .subscribe(boundEntriesCallback);
1900
- }
1901
- fromEvent(window, 'resize').pipe(debounceAndDestroy(resizeDebounce)).subscribe(boundEntriesCallback);
1902
- });
1903
- return () => {
1904
- if (observer) {
1905
- observer.unobserve(nativeElement);
1906
- observer.disconnect();
1907
- }
1908
- torndown$.next();
1909
- torndown$.complete();
1910
- };
1911
- });
1912
- return this.pipe(debounceTime(scrollDebounce || 0), share({
1913
- connector: () => new ReplaySubject(1),
1914
- resetOnRefCountZero: true,
1915
- resetOnComplete: true,
1916
- }));
2074
+ get data() {
2075
+ return this.domRenderer.data;
1917
2076
  }
1918
2077
  }
1919
- NgtResize.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtResize, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1920
- NgtResize.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtResize });
1921
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtResize, decorators: [{
1922
- type: Injectable
1923
- }], ctorParameters: function () { return []; } });
1924
- // Returns a list of scroll offsets
1925
- function findScrollContainers(element, documentBody) {
1926
- const result = [];
1927
- if (!element || element === documentBody)
1928
- return result;
1929
- const { overflow, overflowX, overflowY } = window.getComputedStyle(element);
1930
- if ([overflow, overflowX, overflowY].some((prop) => prop === 'auto' || prop === 'scroll'))
1931
- result.push(element);
1932
- return [...result, ...findScrollContainers(element.parentElement, documentBody)];
2078
+
2079
+ function provideNgtRenderer({ store, changeDetectorRef, compoundPrefixes = [] }) {
2080
+ if (!compoundPrefixes.includes('ngts')) {
2081
+ compoundPrefixes.push('ngts');
2082
+ }
2083
+ if (!compoundPrefixes.includes('ngtp')) {
2084
+ compoundPrefixes.push('ngtp');
2085
+ }
2086
+ return [
2087
+ { provide: RendererFactory2, useClass: NgtRendererFactory },
2088
+ { provide: NgtStore, useValue: store },
2089
+ { provide: ChangeDetectorRef, useValue: changeDetectorRef },
2090
+ { provide: NGT_COMPOUND_PREFIXES, useValue: compoundPrefixes },
2091
+ ];
1933
2092
  }
1934
- // Checks if element boundaries are equal
1935
- const keys = [
1936
- 'x',
1937
- 'y',
1938
- 'top',
1939
- 'bottom',
1940
- 'left',
1941
- 'right',
1942
- 'width',
1943
- 'height',
1944
- ];
1945
- const areBoundsEqual = (a, b) => keys.every((key) => a[key] === b[key]);
1946
2093
 
1947
- function buildGraph(object) {
1948
- const data = { nodes: {}, materials: {} };
1949
- if (object) {
1950
- object.traverse((obj) => {
1951
- if (obj.name)
1952
- data.nodes[obj.name] = obj;
1953
- if ('material' in obj && !data.materials[obj.material.name]) {
1954
- data.materials[obj.material.name] = obj
1955
- .material;
2094
+ const DOM_EVENTS = {
2095
+ click: false,
2096
+ contextmenu: false,
2097
+ dblclick: false,
2098
+ wheel: false,
2099
+ pointerdown: true,
2100
+ pointerup: true,
2101
+ pointerleave: true,
2102
+ pointermove: true,
2103
+ pointercancel: true,
2104
+ lostpointercapture: true,
2105
+ };
2106
+ const supportedEvents = [
2107
+ 'click',
2108
+ 'contextmenu',
2109
+ 'dblclick',
2110
+ 'pointerup',
2111
+ 'pointerdown',
2112
+ 'pointerover',
2113
+ 'pointerout',
2114
+ 'pointerenter',
2115
+ 'pointerleave',
2116
+ 'pointermove',
2117
+ 'pointermissed',
2118
+ 'pointercancel',
2119
+ 'wheel',
2120
+ ];
2121
+ function createPointerEvents(store) {
2122
+ const { handlePointer } = createEvents(store);
2123
+ return {
2124
+ priority: 1,
2125
+ enabled: true,
2126
+ compute: (event, root) => {
2127
+ const state = root.get();
2128
+ // https://github.com/pmndrs/react-three-fiber/pull/782
2129
+ // Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides
2130
+ state.pointer.set((event.offsetX / state.size.width) * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1);
2131
+ state.raycaster.setFromCamera(state.pointer, state.camera);
2132
+ },
2133
+ connected: undefined,
2134
+ handlers: Object.keys(DOM_EVENTS).reduce((handlers, supportedEventName) => {
2135
+ handlers[supportedEventName] = handlePointer(supportedEventName);
2136
+ return handlers;
2137
+ }, {}),
2138
+ connect: (target) => {
2139
+ var _a, _b, _c;
2140
+ const state = store.get();
2141
+ (_b = (_a = state.events).disconnect) === null || _b === void 0 ? void 0 : _b.call(_a);
2142
+ state.setEvents({ connected: target });
2143
+ Object.entries((_c = state.events.handlers) !== null && _c !== void 0 ? _c : {}).forEach(([eventName, eventHandler]) => {
2144
+ const passive = DOM_EVENTS[eventName];
2145
+ target.addEventListener(eventName, eventHandler, { passive });
2146
+ });
2147
+ },
2148
+ disconnect: () => {
2149
+ var _a;
2150
+ const { events, setEvents } = store.get();
2151
+ if (events.connected) {
2152
+ Object.entries((_a = events.handlers) !== null && _a !== void 0 ? _a : {}).forEach(([eventName, eventHandler]) => {
2153
+ if (events.connected instanceof HTMLElement) {
2154
+ events.connected.removeEventListener(eventName, eventHandler);
2155
+ }
2156
+ });
2157
+ setEvents({ connected: undefined });
1956
2158
  }
1957
- });
1958
- }
1959
- return data;
2159
+ },
2160
+ };
1960
2161
  }
1961
2162
 
1962
- class NgtLoader {
1963
- constructor() {
1964
- this.cached = new Map();
1965
- }
1966
- use(loadConstructor, input, extensions, onProgress) {
1967
- const urls = Array.isArray(input) ? input : [input];
1968
- const loader = new loadConstructor();
2163
+ const cached = new Map();
2164
+ function injectLoader(loaderConstructorFactory, input, extensions, onProgress) {
2165
+ const urls$ = isObservable(input) ? input : of(input);
2166
+ return urls$.pipe(map((inputs) => {
2167
+ const loaderConstructor = loaderConstructorFactory(inputs);
2168
+ const loader = new loaderConstructor();
1969
2169
  if (extensions) {
1970
2170
  extensions(loader);
1971
2171
  }
1972
- const observables$ = urls.map((url) => {
1973
- if (!this.cached.has(url)) {
1974
- this.cached.set(url, from(loader.loadAsync(url, onProgress)).pipe(tap((data) => {
1975
- if (data.scene) {
1976
- Object.assign(data, buildGraph(data.scene));
1977
- }
1978
- }), retry(2), catchError((err) => {
1979
- console.error(`[NgtLoader]: Error loading ${url}: ${err.message}`);
1980
- return of(null);
1981
- }), share({
1982
- connector: () => new ReplaySubject(1),
1983
- resetOnComplete: true,
1984
- resetOnRefCountZero: true,
1985
- resetOnError: true,
1986
- })));
1987
- }
1988
- return this.cached.get(url);
1989
- });
1990
- return forkJoin(observables$).pipe(map((results) => (Array.isArray(input) ? results : results[0])));
1991
- }
1992
- destroy() {
1993
- this.cached.clear();
1994
- }
2172
+ const urls = Array.isArray(inputs) ? inputs : typeof inputs === 'string' ? [inputs] : Object.values(inputs);
2173
+ return [
2174
+ urls.map((url) => {
2175
+ if (!cached.has(url)) {
2176
+ cached.set(url, from(loader.loadAsync(url, onProgress)).pipe(tap((data) => {
2177
+ if (data.scene) {
2178
+ Object.assign(data, makeObjectGraph(data.scene));
2179
+ }
2180
+ }), retry(2), catchError((err) => {
2181
+ console.error(`[NGT] Error loading ${url}: ${err.message}`);
2182
+ return of([]);
2183
+ }), share({
2184
+ connector: () => new ReplaySubject(1),
2185
+ resetOnComplete: true,
2186
+ resetOnError: true,
2187
+ resetOnRefCountZero: true,
2188
+ })));
2189
+ }
2190
+ return cached.get(url);
2191
+ }),
2192
+ inputs,
2193
+ ];
2194
+ }), switchMap(([observables$, inputs]) => {
2195
+ return forkJoin(observables$).pipe(map((results) => {
2196
+ if (Array.isArray(inputs))
2197
+ return results;
2198
+ if (typeof inputs === 'string')
2199
+ return results[0];
2200
+ const keys = Object.keys(inputs);
2201
+ return keys.reduce((result, key) => {
2202
+ result[key] = results[keys.indexOf(key)];
2203
+ return result;
2204
+ }, {});
2205
+ }));
2206
+ }));
1995
2207
  }
1996
- NgtLoader.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1997
- NgtLoader.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtLoader, providedIn: 'root' });
1998
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtLoader, decorators: [{
1999
- type: Injectable,
2000
- args: [{ providedIn: 'root' }]
2001
- }] });
2208
+ injectLoader.destroy = () => {
2209
+ cached.clear();
2210
+ };
2211
+ injectLoader.preLoad = (loaderConstructorFactory, inputs, extensions) => {
2212
+ injectLoader(loaderConstructorFactory, inputs, extensions).pipe(take(1)).subscribe();
2213
+ };
2214
+ const injectNgtLoader = injectLoader;
2002
2215
 
2003
2216
  class NgtCanvasContainer {
2004
2217
  constructor() {
2005
- this.resize = inject(NgtResize);
2218
+ this.canvasResize = injectNgxResize();
2006
2219
  }
2007
2220
  }
2008
- NgtCanvasContainer.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtCanvasContainer, deps: [], target: i0.ɵɵFactoryTarget.Component });
2009
- NgtCanvasContainer.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.0.0", type: NgtCanvasContainer, isStandalone: true, selector: "ngt-canvas-container", outputs: { resize: "resize" }, providers: [NgtResize], ngImport: i0, template: '<ng-content></ng-content>', isInline: true, styles: [":host{display:block;height:100%;width:100%}\n"] });
2010
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtCanvasContainer, decorators: [{
2221
+ NgtCanvasContainer.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtCanvasContainer, deps: [], target: i0.ɵɵFactoryTarget.Component });
2222
+ NgtCanvasContainer.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.1.1", type: NgtCanvasContainer, isStandalone: true, selector: "ngt-canvas-container", outputs: { canvasResize: "canvasResize" }, providers: [provideNgxResizeOptions({ emitInZone: false })], ngImport: i0, template: '<ng-content />', isInline: true, styles: [":host{display:block;width:100%;height:100%}\n"] });
2223
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtCanvasContainer, decorators: [{
2011
2224
  type: Component,
2012
- args: [{ selector: 'ngt-canvas-container', standalone: true, template: '<ng-content></ng-content>', providers: [NgtResize], styles: [":host{display:block;height:100%;width:100%}\n"] }]
2013
- }], propDecorators: { resize: [{
2225
+ args: [{ selector: 'ngt-canvas-container', standalone: true, template: '<ng-content />', providers: [provideNgxResizeOptions({ emitInZone: false })], styles: [":host{display:block;width:100%;height:100%}\n"] }]
2226
+ }], propDecorators: { canvasResize: [{
2014
2227
  type: Output
2015
2228
  }] } });
2016
- class NgtCanvas extends NgtComponentStore {
2229
+ class NgtCanvas extends NgtRxStore {
2017
2230
  constructor() {
2018
2231
  super(...arguments);
2232
+ this.cdr = inject(ChangeDetectorRef);
2233
+ this.envInjector = inject(EnvironmentInjector);
2234
+ this.host = inject(ElementRef);
2235
+ this.store = inject(NgtStore);
2019
2236
  this.hostClass = true;
2237
+ this.compoundPrefixes = [];
2020
2238
  this.created = new EventEmitter();
2021
- this.canvasPointerMissed = new EventEmitter();
2022
- this.zone = inject(NgZone);
2023
- this.loader = inject(NgtLoader);
2024
- this.store = inject(NgtStore, { self: true });
2025
- this.host = inject(ElementRef);
2239
+ this.pointerMissed = new EventEmitter();
2240
+ }
2241
+ initialize() {
2242
+ super.initialize();
2243
+ this.set({
2244
+ shadows: false,
2245
+ linear: false,
2246
+ flat: false,
2247
+ legacy: false,
2248
+ orthographic: false,
2249
+ frameloop: 'always',
2250
+ dpr: [1, 2],
2251
+ events: createPointerEvents,
2252
+ });
2026
2253
  }
2027
2254
  get pointerEvents() {
2028
- return this.read((s) => s.eventSource) !== this.host.nativeElement ? 'none' : 'auto';
2255
+ return this.get('eventSource') !== this.host.nativeElement ? 'none' : 'auto';
2029
2256
  }
2030
2257
  set linear(linear) {
2031
- this.write({ linear });
2258
+ this.set({ linear });
2032
2259
  }
2033
2260
  set legacy(legacy) {
2034
- this.write({ legacy });
2261
+ this.set({ legacy });
2035
2262
  }
2036
2263
  set flat(flat) {
2037
- this.write({ flat });
2264
+ this.set({ flat });
2038
2265
  }
2039
2266
  set orthographic(orthographic) {
2040
- this.write({ orthographic });
2267
+ this.set({ orthographic });
2041
2268
  }
2042
2269
  set frameloop(frameloop) {
2043
- this.write({ frameloop });
2270
+ this.set({ frameloop });
2044
2271
  }
2045
2272
  set dpr(dpr) {
2046
- this.write({ dpr });
2273
+ this.set({ dpr });
2047
2274
  }
2048
2275
  set raycaster(raycaster) {
2049
- this.write({ raycaster });
2276
+ this.set({ raycaster });
2050
2277
  }
2051
2278
  set shadows(shadows) {
2052
- this.write({
2279
+ this.set({
2053
2280
  shadows: typeof shadows === 'object' ? shadows : shadows,
2054
2281
  });
2055
2282
  }
2056
2283
  set camera(camera) {
2057
- this.write({ camera });
2284
+ this.set({ camera });
2058
2285
  }
2059
2286
  set gl(gl) {
2060
- this.write({ gl });
2287
+ this.set({ gl });
2061
2288
  }
2062
2289
  set eventSource(eventSource) {
2063
- this.write({ eventSource });
2290
+ this.set({ eventSource });
2064
2291
  }
2065
2292
  set eventPrefix(eventPrefix) {
2066
- this.write({ eventPrefix });
2293
+ this.set({ eventPrefix });
2067
2294
  }
2068
2295
  set lookAt(lookAt) {
2069
- this.write({ lookAt });
2296
+ this.set({ lookAt });
2070
2297
  }
2071
2298
  set performance(performance) {
2072
- this.write({ performance });
2073
- }
2074
- get sceneRef() {
2075
- return this.store.read((s) => s.sceneRef);
2076
- }
2077
- get isConfigured() {
2078
- return this.store.isConfigured;
2079
- }
2080
- initialize() {
2081
- super.initialize();
2082
- this.write({
2083
- shadows: false,
2084
- linear: false,
2085
- flat: false,
2086
- legacy: false,
2087
- orthographic: false,
2088
- frameloop: 'always',
2089
- dpr: [1, 2],
2090
- events: createPointerEvents,
2091
- });
2299
+ this.set({ performance });
2092
2300
  }
2093
2301
  ngOnInit() {
2094
- this.zone.runOutsideAngular(() => {
2095
- if (!this.eventSource) {
2096
- this.eventSource = this.host.nativeElement;
2097
- }
2098
- if (this.canvasPointerMissed.observed) {
2099
- // update pointerMissed event
2100
- this.store.write({
2101
- onPointerMissed: (event) => {
2102
- // go back into angular zone
2103
- this.zone.run(() => {
2104
- this.canvasPointerMissed.emit(event);
2105
- });
2106
- },
2107
- });
2108
- }
2109
- // set rootStateMap
2110
- rootStateMap.set(this.glCanvas.nativeElement, this.store.read);
2111
- // setup canvas state
2112
- this.store.init();
2113
- this.store.onReady(() => {
2114
- var _a, _b;
2115
- const state = this.store.read();
2116
- const inputs = this.read();
2117
- // canvas is ready
2118
- this.store.write((s) => ({ internal: Object.assign(Object.assign({}, s.internal), { active: true }) }));
2119
- // Connect to eventsource
2120
- (_b = (_a = state.events).connect) === null || _b === void 0 ? void 0 : _b.call(_a, inputs.eventSource instanceof ElementRef ? inputs.eventSource.nativeElement : inputs.eventSource);
2121
- // Set up compute function
2122
- if (inputs.eventPrefix) {
2123
- state.setEvents({
2124
- compute: (event, stateGetter) => {
2125
- const innerState = stateGetter();
2126
- const x = event[(inputs.eventPrefix + 'X')];
2127
- const y = event[(inputs.eventPrefix + 'Y')];
2128
- innerState.pointer.set((x / innerState.size.width) * 2 - 1, -(y / innerState.size.height) * 2 + 1);
2129
- innerState.raycaster.setFromCamera(innerState.pointer, innerState.camera);
2130
- },
2131
- });
2132
- }
2133
- if (this.created.observed) {
2134
- this.zone.run(() => {
2135
- requestAnimationFrame(() => {
2136
- this.created.emit(this.store.read());
2137
- });
2138
- });
2139
- }
2302
+ if (!this.get('eventSource')) {
2303
+ // set default event source to the host element
2304
+ this.eventSource = this.host.nativeElement;
2305
+ }
2306
+ if (this.pointerMissed.observed) {
2307
+ this.store.set({
2308
+ onPointerMissed: (event) => {
2309
+ this.pointerMissed.emit(event);
2310
+ this.cdr.detectChanges();
2311
+ },
2140
2312
  });
2313
+ }
2314
+ // setup NgtStore
2315
+ this.store.init();
2316
+ // set rootStateMap
2317
+ rootStateMap.set(this.glCanvas.nativeElement, this.store);
2318
+ // subscribe to store to listen for ready state
2319
+ this.hold(this.store.select('ready').pipe(filter((ready) => ready)), () => {
2320
+ this.storeReady();
2141
2321
  });
2142
2322
  }
2143
- onResize(resizeResult) {
2144
- this.zone.runOutsideAngular(() => {
2145
- const { width, height } = resizeResult;
2146
- if (width > 0 && height > 0) {
2147
- if (!this.store.isInit) {
2148
- this.store.init();
2149
- }
2150
- this.store.configure(this.read(), this.glCanvas.nativeElement);
2151
- }
2323
+ onResize({ width, height }) {
2324
+ if (width > 0 && height > 0) {
2325
+ if (!this.store.isInit)
2326
+ this.store.init();
2327
+ this.store.configure(this.get(), this.glCanvas.nativeElement);
2328
+ }
2329
+ }
2330
+ storeReady() {
2331
+ var _a, _b;
2332
+ // canvas is ready, let's activate the loop
2333
+ this.store.set((state) => ({ internal: Object.assign(Object.assign({}, state.internal), { active: true }) }));
2334
+ const inputs = this.get();
2335
+ const state = this.store.get();
2336
+ // connect to event source
2337
+ (_b = (_a = state.events).connect) === null || _b === void 0 ? void 0 : _b.call(_a, is.ref(inputs.eventSource) ? inputs.eventSource.nativeElement : inputs.eventSource);
2338
+ // setup compute function for events
2339
+ if (inputs.eventPrefix) {
2340
+ state.setEvents({
2341
+ compute: (event, store) => {
2342
+ const innerState = store.get();
2343
+ const x = event[(inputs.eventPrefix + 'X')];
2344
+ const y = event[(inputs.eventPrefix + 'Y')];
2345
+ innerState.pointer.set((x / innerState.size.width) * 2 - 1, -(y / innerState.size.height) * 2 + 1);
2346
+ innerState.raycaster.setFromCamera(innerState.pointer, innerState.camera);
2347
+ },
2348
+ });
2349
+ }
2350
+ // emit created event if observed
2351
+ if (this.created.observed) {
2352
+ this.created.emit(this.store.get());
2353
+ this.cdr.detectChanges();
2354
+ }
2355
+ // render
2356
+ if (this.glRef) {
2357
+ this.glRef.destroy();
2358
+ }
2359
+ requestAnimationFrame(() => {
2360
+ this.glEnvInjector = createEnvironmentInjector([
2361
+ provideNgtRenderer({
2362
+ store: this.store,
2363
+ changeDetectorRef: this.cdr,
2364
+ compoundPrefixes: this.compoundPrefixes,
2365
+ }),
2366
+ ], this.envInjector);
2367
+ this.glRef = this.glAnchor.createComponent(this.scene, { environmentInjector: this.glEnvInjector });
2368
+ this.glRef.changeDetectorRef.detectChanges();
2369
+ this.glRef.changeDetectorRef.detach();
2370
+ this.cdr.detectChanges();
2152
2371
  });
2153
2372
  }
2154
2373
  ngOnDestroy() {
2155
- this.loader.destroy();
2374
+ if (this.glRef) {
2375
+ this.glRef.destroy();
2376
+ }
2377
+ if (this.glEnvInjector) {
2378
+ this.glEnvInjector.destroy();
2379
+ }
2380
+ injectNgtLoader.destroy();
2156
2381
  super.ngOnDestroy();
2157
2382
  }
2158
2383
  }
2159
- NgtCanvas.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtCanvas, deps: null, target: i0.ɵɵFactoryTarget.Component });
2160
- NgtCanvas.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.0.0", type: NgtCanvas, isStandalone: true, selector: "ngt-canvas", inputs: { linear: "linear", legacy: "legacy", flat: "flat", orthographic: "orthographic", frameloop: "frameloop", dpr: "dpr", raycaster: "raycaster", shadows: "shadows", camera: "camera", gl: "gl", eventSource: "eventSource", eventPrefix: "eventPrefix", lookAt: "lookAt", performance: "performance" }, outputs: { created: "created", canvasPointerMissed: "canvasPointerMissed" }, host: { properties: { "class.ngt-canvas": "this.hostClass", "style.pointerEvents": "this.pointerEvents" } }, providers: [NgtStore, provideInstanceRef(NgtCanvas, (canvas) => canvas.sceneRef)], queries: [{ propertyName: "canvasContent", first: true, predicate: TemplateRef, descendants: true, static: true }], viewQueries: [{ propertyName: "glCanvas", first: true, predicate: ["glCanvas"], descendants: true, static: true }], usesInheritance: true, ngImport: i0, template: `
2161
- <ngt-canvas-container (resize)="onResize($event)">
2162
- <canvas #glCanvas style="display: block">
2163
- <ng-container *ngIf="isConfigured" [ngTemplateOutlet]="canvasContent"></ng-container>
2164
- <ng-content></ng-content>
2165
- </canvas>
2384
+ NgtCanvas.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtCanvas, deps: null, target: i0.ɵɵFactoryTarget.Component });
2385
+ NgtCanvas.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "15.1.1", type: NgtCanvas, isStandalone: true, selector: "ngt-canvas", inputs: { scene: "scene", compoundPrefixes: "compoundPrefixes", linear: "linear", legacy: "legacy", flat: "flat", orthographic: "orthographic", frameloop: "frameloop", dpr: "dpr", raycaster: "raycaster", shadows: "shadows", camera: "camera", gl: "gl", eventSource: "eventSource", eventPrefix: "eventPrefix", lookAt: "lookAt", performance: "performance" }, outputs: { created: "created", pointerMissed: "pointerMissed" }, host: { properties: { "class.ngt-canvas": "this.hostClass", "style.pointerEvents": "this.pointerEvents" } }, providers: [NgtStore], viewQueries: [{ propertyName: "glCanvas", first: true, predicate: ["glCanvas"], descendants: true, static: true }, { propertyName: "glAnchor", first: true, predicate: ["glAnchor"], descendants: true, read: ViewContainerRef, static: true }], usesInheritance: true, ngImport: i0, template: `
2386
+ <ngt-canvas-container (canvasResize)="onResize($event)">
2387
+ <canvas #glCanvas style="display: block;"></canvas>
2388
+ <ng-container #glAnchor />
2166
2389
  </ngt-canvas-container>
2167
- `, isInline: true, styles: [":host{display:block;position:relative;width:100%;height:100%;overflow:hidden}\n"], dependencies: [{ kind: "component", type: NgtCanvasContainer, selector: "ngt-canvas-container", outputs: ["resize"] }, { kind: "directive", type: NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
2168
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtCanvas, decorators: [{
2390
+ `, isInline: true, styles: [":host{display:block;position:relative;width:100%;height:100%;overflow:hidden}\n"], dependencies: [{ kind: "component", type: NgtCanvasContainer, selector: "ngt-canvas-container", outputs: ["canvasResize"] }] });
2391
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtCanvas, decorators: [{
2169
2392
  type: Component,
2170
2393
  args: [{ selector: 'ngt-canvas', standalone: true, template: `
2171
- <ngt-canvas-container (resize)="onResize($event)">
2172
- <canvas #glCanvas style="display: block">
2173
- <ng-container *ngIf="isConfigured" [ngTemplateOutlet]="canvasContent"></ng-container>
2174
- <ng-content></ng-content>
2175
- </canvas>
2394
+ <ngt-canvas-container (canvasResize)="onResize($event)">
2395
+ <canvas #glCanvas style="display: block;"></canvas>
2396
+ <ng-container #glAnchor />
2176
2397
  </ngt-canvas-container>
2177
- `, changeDetection: ChangeDetectionStrategy.OnPush, imports: [NgtCanvasContainer, NgIf, NgTemplateOutlet, AsyncPipe], providers: [NgtStore, provideInstanceRef(NgtCanvas, (canvas) => canvas.sceneRef)], styles: [":host{display:block;position:relative;width:100%;height:100%;overflow:hidden}\n"] }]
2398
+ `, imports: [NgtCanvasContainer], providers: [NgtStore], styles: [":host{display:block;position:relative;width:100%;height:100%;overflow:hidden}\n"] }]
2178
2399
  }], propDecorators: { hostClass: [{
2179
2400
  type: HostBinding,
2180
2401
  args: ['class.ngt-canvas']
2181
2402
  }], pointerEvents: [{
2182
2403
  type: HostBinding,
2183
2404
  args: ['style.pointerEvents']
2405
+ }], scene: [{
2406
+ type: Input
2407
+ }], compoundPrefixes: [{
2408
+ type: Input
2184
2409
  }], linear: [{
2185
2410
  type: Input
2186
2411
  }], legacy: [{
@@ -2211,251 +2436,33 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImpor
2211
2436
  type: Input
2212
2437
  }], created: [{
2213
2438
  type: Output
2214
- }], canvasPointerMissed: [{
2439
+ }], pointerMissed: [{
2215
2440
  type: Output
2216
2441
  }], glCanvas: [{
2217
2442
  type: ViewChild,
2218
2443
  args: ['glCanvas', { static: true }]
2219
- }], canvasContent: [{
2220
- type: ContentChild,
2221
- args: [TemplateRef, { static: true }]
2222
- }] } });
2223
-
2224
- const NGT_ARGS = new InjectionToken('NgtArgs');
2225
- function injectArgs(options = {}) {
2226
- return inject(NGT_ARGS, options);
2227
- }
2228
- class NgtArgs {
2229
- constructor() {
2230
- this.templateRef = inject(TemplateRef);
2231
- this.vcr = inject(ViewContainerRef);
2232
- }
2233
- set args(args) {
2234
- if (this.view) {
2235
- this.view.destroy();
2236
- }
2237
- this.view = this.vcr.createEmbeddedView(this.templateRef, {}, { injector: Injector.create({ providers: [{ provide: NGT_ARGS, useValue: args }] }) });
2238
- }
2239
- }
2240
- NgtArgs.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtArgs, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2241
- NgtArgs.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.0.0", type: NgtArgs, isStandalone: true, selector: "[args]", inputs: { args: "args" }, ngImport: i0 });
2242
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtArgs, decorators: [{
2243
- type: Directive,
2244
- args: [{
2245
- selector: '[args]',
2246
- standalone: true,
2247
- }]
2248
- }], propDecorators: { args: [{
2249
- type: Input
2444
+ }], glAnchor: [{
2445
+ type: ViewChild,
2446
+ args: ['glAnchor', { static: true, read: ViewContainerRef }]
2250
2447
  }] } });
2251
2448
 
2252
- class NgtCursor {
2253
- constructor(instance, document) {
2254
- if (!instance)
2255
- return;
2256
- merge(instance.pointerover.pipe(map(() => true)), instance.pointerout.pipe(map(() => false)))
2257
- .pipe(takeUntil(instance.destroy$))
2258
- .subscribe((hovered) => {
2259
- document.body.style.cursor = hovered ? 'pointer' : 'auto';
2260
- });
2261
- }
2262
- }
2263
- NgtCursor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtCursor, deps: [{ token: NgtInstance, optional: true, self: true }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Directive });
2264
- NgtCursor.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.0.0", type: NgtCursor, isStandalone: true, selector: "[ngtCursor]", exportAs: ["ngtCursor"], ngImport: i0 });
2265
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtCursor, decorators: [{
2266
- type: Directive,
2267
- args: [{
2268
- selector: '[ngtCursor]',
2269
- standalone: true,
2270
- exportAs: 'ngtCursor',
2271
- }]
2272
- }], ctorParameters: function () {
2273
- return [{ type: NgtInstance, decorators: [{
2274
- type: Optional
2275
- }, {
2276
- type: Self
2277
- }] }, { type: Document, decorators: [{
2278
- type: Inject,
2279
- args: [DOCUMENT]
2280
- }] }];
2281
- } });
2282
-
2283
2449
  class NgtRepeat extends NgForOf {
2284
2450
  set ngForRepeat(count) {
2285
2451
  this.ngForOf = Number.isInteger(count) ? Array.from({ length: count }, (_, i) => i) : [];
2286
2452
  }
2287
2453
  }
2288
- NgtRepeat.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtRepeat, deps: null, target: i0.ɵɵFactoryTarget.Directive });
2289
- NgtRepeat.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.0.0", type: NgtRepeat, isStandalone: true, selector: "[ngFor][ngForRepeat]", inputs: { ngForRepeat: "ngForRepeat" }, usesInheritance: true, ngImport: i0 });
2290
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtRepeat, decorators: [{
2454
+ NgtRepeat.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRepeat, deps: null, target: i0.ɵɵFactoryTarget.Directive });
2455
+ NgtRepeat.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "15.1.1", type: NgtRepeat, isStandalone: true, selector: "[ngFor][ngForRepeat]", inputs: { ngForRepeat: "ngForRepeat" }, usesInheritance: true, ngImport: i0 });
2456
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.1.1", ngImport: i0, type: NgtRepeat, decorators: [{
2291
2457
  type: Directive,
2292
- args: [{
2293
- selector: '[ngFor][ngForRepeat]',
2294
- standalone: true,
2295
- }]
2458
+ args: [{ selector: '[ngFor][ngForRepeat]', standalone: true }]
2296
2459
  }], propDecorators: { ngForRepeat: [{
2297
2460
  type: Input
2298
2461
  }] } });
2299
2462
 
2300
- class NgtPiPipe {
2301
- transform(value) {
2302
- return value * Math.PI;
2303
- }
2304
- }
2305
- NgtPiPipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtPiPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
2306
- NgtPiPipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.0.0", ngImport: i0, type: NgtPiPipe, isStandalone: true, name: "pi" });
2307
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtPiPipe, decorators: [{
2308
- type: Pipe,
2309
- args: [{ name: 'pi', standalone: true }]
2310
- }] });
2311
-
2312
- class NgtMathPipe {
2313
- transform(value, keyOfMath) {
2314
- const params = Array.isArray(value) ? value : [value];
2315
- return Math[keyOfMath](...params);
2316
- }
2317
- }
2318
- NgtMathPipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtMathPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
2319
- NgtMathPipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.0.0", ngImport: i0, type: NgtMathPipe, isStandalone: true, name: "math" });
2320
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtMathPipe, decorators: [{
2321
- type: Pipe,
2322
- args: [{ name: 'math', standalone: true }]
2323
- }] });
2324
-
2325
- class NgtRadianPipe {
2326
- transform(degree) {
2327
- return (degree * Math.PI) / 180;
2328
- }
2329
- }
2330
- NgtRadianPipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtRadianPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
2331
- NgtRadianPipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.0.0", ngImport: i0, type: NgtRadianPipe, isStandalone: true, name: "radian" });
2332
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtRadianPipe, decorators: [{
2333
- type: Pipe,
2334
- args: [{ name: 'radian', standalone: true }]
2335
- }] });
2336
-
2337
- class NgtSidePipe {
2338
- transform(side) {
2339
- switch (side) {
2340
- case 'front':
2341
- return THREE.FrontSide;
2342
- case 'back':
2343
- return THREE.BackSide;
2344
- case 'double':
2345
- return THREE.DoubleSide;
2346
- }
2347
- }
2348
- }
2349
- NgtSidePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtSidePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
2350
- NgtSidePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "15.0.0", ngImport: i0, type: NgtSidePipe, isStandalone: true, name: "side" });
2351
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "15.0.0", ngImport: i0, type: NgtSidePipe, decorators: [{
2352
- type: Pipe,
2353
- args: [{ name: 'side', standalone: true }]
2354
- }] });
2355
-
2356
- function capitalize(str) {
2357
- return str.charAt(0).toUpperCase() + str.slice(1);
2358
- }
2359
-
2360
- function proxify(instance, proxifyOptions = {}) {
2361
- const ngtInstance = injectInstance({ host: true });
2362
- const store = inject(NgtStore);
2363
- const zone = inject(NgZone);
2364
- const parentInstance = injectInstanceRef({ skipSelf: true, optional: true });
2365
- return zone.runOutsideAngular(() => {
2366
- // prep the instance w/ local state
2367
- instance = prepare(instance, store.read, store.rootStateFactory, parentInstance === null || parentInstance === void 0 ? void 0 : parentInstance(), ngtInstance.instanceValue ? ngtInstance.instanceRef : undefined, !!proxifyOptions.primitive);
2368
- let storeReadySubscription;
2369
- const newValueSubscriptionMap = new Map();
2370
- function setProp(obj, prop, newValue) {
2371
- const capitalizedProp = `set${capitalize(prop)}`;
2372
- if (isObservable(newValue)) {
2373
- const sub = newValue.subscribe((val) => {
2374
- if (obj[capitalizedProp] && typeof obj[capitalizedProp] === 'function') {
2375
- obj[capitalizedProp](val);
2376
- }
2377
- else {
2378
- applyProps(obj, { [prop]: val });
2379
- }
2380
- ngtInstance.write({ [prop]: val });
2381
- });
2382
- return () => sub.unsubscribe();
2383
- }
2384
- if (obj[capitalizedProp] && typeof obj[capitalizedProp] === 'function') {
2385
- obj[capitalizedProp](newValue);
2386
- }
2387
- else {
2388
- applyProps(obj, { [prop]: newValue });
2389
- }
2390
- ngtInstance.write({ [prop]: newValue });
2391
- return;
2392
- }
2393
- const handler = {
2394
- get(target, p, receiver) {
2395
- if (p === 'instanceRef')
2396
- return ngtInstance.instanceRef;
2397
- if (p === 'instance')
2398
- return ngtInstance;
2399
- if (p === NGT_PROXY_INSTANCE)
2400
- return target;
2401
- const capitalizedProp = `get${capitalize(p)}`;
2402
- if (target[capitalizedProp] && typeof target[capitalizedProp] === 'function') {
2403
- return target[capitalizedProp]();
2404
- }
2405
- return Reflect.get(target, p, receiver);
2406
- },
2407
- set(target, p, newValue, receiver) {
2408
- const prop = p;
2409
- if (storeReadySubscription)
2410
- storeReadySubscription.unsubscribe();
2411
- if (newValueSubscriptionMap.has(prop))
2412
- newValueSubscriptionMap.get(prop)();
2413
- // Angular sets this property
2414
- if (p === '__ngContext__')
2415
- return Reflect.set(target, p, newValue, receiver);
2416
- return zone.runOutsideAngular(() => {
2417
- // TODO: figure out what else we need to handle
2418
- // we should handle if newValue is an Observable as well
2419
- if (store.read((s) => s.ready)) {
2420
- const cleanUp = setProp(instance, prop, newValue);
2421
- if (cleanUp)
2422
- newValueSubscriptionMap.set(prop, cleanUp);
2423
- }
2424
- else {
2425
- storeReadySubscription = store.onReady(() => setProp(instance, prop, newValue));
2426
- }
2427
- // schedule updateCallback on next event loop
2428
- queueMicrotask(() => {
2429
- if (ngtInstance.updateCallback)
2430
- ngtInstance.updateCallback(instance);
2431
- });
2432
- return true;
2433
- });
2434
- },
2435
- };
2436
- ngtInstance.effect(tapEffect(() => () => {
2437
- if (storeReadySubscription)
2438
- storeReadySubscription.unsubscribe();
2439
- newValueSubscriptionMap.forEach((cleanUp) => cleanUp());
2440
- }))();
2441
- const proxied = new Proxy(instance, handler);
2442
- if (proxifyOptions.attach)
2443
- ngtInstance.attach = proxifyOptions.attach;
2444
- if (proxifyOptions.created)
2445
- proxifyOptions.created(proxied, store.read, ngtInstance);
2446
- ngtInstance.instanceRef.set(proxied);
2447
- return proxied;
2448
- });
2449
- }
2450
-
2451
- /**
2452
- * main exports
2453
- */
2454
-
2455
2463
  /**
2456
2464
  * Generated bundle index. Do not edit.
2457
2465
  */
2458
2466
 
2459
- export { NGT_ARGS, NGT_INSTANCE_INPUTS, NGT_INSTANCE_OUTPUTS, NGT_INSTANCE_REF_FACTORY, NGT_PROXY_INSTANCE, NgtArgs, NgtCanvas, NgtCanvasContainer, NgtComponentStore, NgtCursor, NgtInstance, NgtLoader, NgtMathPipe, NgtPiPipe, NgtRadianPipe, NgtRepeat, NgtResize, NgtSidePipe, NgtStore, addAfterEffect, addEffect, addTail, createLoop, defaultProjector, defaultResizeOptions, flushGlobalEffects, injectArgs, injectInstance, injectInstanceRef, injectResizeObserverSupport, injectResizeOptions, provideInstanceRef, provideResizeOptions, proxify, rootStateMap, skipFirstUndefined, tapEffect };
2460
- //# sourceMappingURL=angular-three.mjs.map
2467
+ export { NGT_CATALOGUE, NgtArgs, NgtCanvas, NgtCanvasContainer, NgtRepeat, extend };
2461
2468
  //# sourceMappingURL=angular-three.mjs.map