選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

babylon-with-encantar.js 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /**
  2. * babylon.js plugin for encantar.js
  3. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  4. * @license LGPL-3.0-or-later
  5. */
  6. /* Usage of the indicated versions is encouraged */
  7. __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__({
  8. 'encantar.js': { version: '0.3.0' },
  9. 'babylon.js': { version: '7.29.0' }
  10. });
  11. /**
  12. * Base class for Augmented Reality experiences
  13. */
  14. class ARDemo
  15. {
  16. /**
  17. * Start the AR session
  18. * @abstract
  19. * @returns {Promise<Session> | SpeedyPromise<Session>}
  20. */
  21. startSession()
  22. {
  23. throw new Error('Abstract method');
  24. }
  25. /**
  26. * Initialization
  27. * @abstract
  28. * @param {ARSystem} ar
  29. * @returns {void | Promise<void> | SpeedyPromise<void>}
  30. */
  31. init(ar)
  32. {
  33. throw new Error('Abstract method');
  34. }
  35. /**
  36. * Animation loop
  37. * @abstract
  38. * @param {ARSystem} ar
  39. * @returns {void}
  40. */
  41. update(ar)
  42. {
  43. throw new Error('Abstract method');
  44. }
  45. /**
  46. * Release resources
  47. * @param {ARSystem} ar
  48. * @returns {void}
  49. */
  50. release(ar)
  51. {
  52. // optional implementation
  53. }
  54. }
  55. /**
  56. * Helper for creating Augmented Reality experiences
  57. */
  58. class ARSystem
  59. {
  60. /**
  61. * AR Session
  62. * @returns {Session}
  63. */
  64. get session()
  65. {
  66. return this._session;
  67. }
  68. /**
  69. * Current frame: an object holding data to augment the physical scene.
  70. * If the AR scene is not initialized, this will be null.
  71. * @returns {Frame | null}
  72. */
  73. get frame()
  74. {
  75. return this._frame;
  76. }
  77. /**
  78. * The root is a node that is automatically aligned to the physical scene.
  79. * Objects of your virtual scene should be descendants of this node.
  80. * @returns {BABYLON.TransformNode}
  81. */
  82. get root()
  83. {
  84. return this._root;
  85. }
  86. /**
  87. * The babylon.js scene
  88. * @returns {BABYLON.Scene}
  89. */
  90. get scene()
  91. {
  92. return this._scene;
  93. }
  94. /**
  95. * A camera that is automatically adjusted for AR
  96. * @returns {BABYLON.Camera}
  97. */
  98. get camera()
  99. {
  100. return this._camera;
  101. }
  102. /**
  103. * The babylon.js engine
  104. * @returns {BABYLON.Engine}
  105. */
  106. get engine()
  107. {
  108. return this._engine;
  109. }
  110. /**
  111. * Constructor
  112. */
  113. constructor()
  114. {
  115. this._session = null;
  116. this._frame = null;
  117. this._origin = null;
  118. this._root = null;
  119. this._scene = null;
  120. this._camera = null;
  121. this._engine = null;
  122. }
  123. }
  124. /**
  125. * Enchant babylon.js with encantar.js!
  126. * @param {ARDemo} demo
  127. * @returns {Promise<ARSystem>}
  128. */
  129. function encantar(demo)
  130. {
  131. const ar = new ARSystem();
  132. const flipZAxis = new BABYLON.Matrix().copyFromFloats(
  133. 1, 0, 0, 0,
  134. 0, 1, 0, 0,
  135. 0, 0,-1, 0,
  136. 0, 0, 0, 1
  137. );
  138. function animate(time, frame)
  139. {
  140. ar._frame = frame;
  141. mix(frame);
  142. demo.update(ar);
  143. ar._scene.render(false);
  144. ar._session.requestAnimationFrame(animate);
  145. }
  146. function mix(frame)
  147. {
  148. for(const result of frame.results) {
  149. if(result.tracker.type == 'image-tracker') {
  150. if(result.trackables.length > 0) {
  151. const trackable = result.trackables[0];
  152. const projectionMatrix = result.viewer.view.projectionMatrix;
  153. const viewMatrix = result.viewer.pose.viewMatrix;
  154. const modelMatrix = trackable.pose.transform.matrix;
  155. align(projectionMatrix, viewMatrix, modelMatrix);
  156. ar._origin.setEnabled(true);
  157. return;
  158. }
  159. }
  160. }
  161. ar._origin.setEnabled(false);
  162. }
  163. function align(projectionMatrix, viewMatrix, modelMatrix)
  164. {
  165. if(ar._scene.useRightHandedSystem)
  166. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  167. else
  168. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZAxis));
  169. ar._camera.setViewMatrix(convert(viewMatrix));
  170. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  171. }
  172. function convert(matrix)
  173. {
  174. // encantar.js uses column vectors stored in column-major format,
  175. // whereas babylon.js uses row vectors stored in row-major format
  176. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  177. return new BABYLON.Matrix().fromArray(matrix.read());
  178. }
  179. return Promise.resolve()
  180. .then(() => {
  181. return demo.startSession(); // Promise or SpeedyPromise
  182. })
  183. .then(session => {
  184. ar._session = session;
  185. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  186. premultipliedAlpha: true
  187. });
  188. ar._engine.resize = function(forceSetSize = false) {
  189. // make babylon.js respect the resolution of the viewport
  190. const size = session.viewport.virtualSize;
  191. this.setSize(size.width, size.height, forceSetSize);
  192. };
  193. ar._scene = new BABYLON.Scene(ar._engine);
  194. ar._scene.useRightHandedSystem = true;
  195. ar._scene.clearColor.set(0, 0, 0, 0);
  196. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  197. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  198. ar._root.parent = ar._origin;
  199. ar._origin.setEnabled(false);
  200. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  201. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  202. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  203. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  204. ar._camera.setViewMatrix = function(matrix) {
  205. this._customViewMatrix = matrix;
  206. this.getViewMatrix(true);
  207. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  208. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  209. this._globalPosition.copyFrom(this.position);
  210. };
  211. session.addEventListener('end', event => {
  212. ar._origin.setEnabled(false);
  213. ar._frame = null;
  214. });
  215. session.viewport.addEventListener('resize', event => {
  216. ar._engine.resize();
  217. });
  218. return Promise.resolve()
  219. .then(() => {
  220. return demo.init(ar);
  221. })
  222. .then(() => {
  223. session.addEventListener('end', event => { demo.release(ar); });
  224. session.requestAnimationFrame(animate);
  225. return ar;
  226. })
  227. .catch(error => {
  228. session.end();
  229. throw error;
  230. });
  231. })
  232. .catch(error => {
  233. console.error(error);
  234. throw error;
  235. });
  236. }
  237. /**
  238. * Version check
  239. * @param {object} libs
  240. */
  241. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  242. {
  243. window.addEventListener('load', () => {
  244. try { AR, BABYLON;
  245. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  246. const check = (x,v,w) => v != w ? console.warn(`\n\n\nWARNING\n\nThis plugin has been tested with ${x} version ${v}. The version in use is ${w}. Usage of ${x} version ${v} is recommended instead.\n\n\n`) : void 0;
  247. for(const [lib, expected] of Object.entries(libs))
  248. check(lib, expected.version, versionOf[lib]);
  249. }
  250. catch(e) {
  251. alert(e.message);
  252. }
  253. });
  254. }