Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

babylon-with-encantar.js 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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.4.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. * Pointer-based input in the current frame (touch, mouse, pen...)
  79. * You need a PointerTracker in your session in order to use these
  80. * @returns {TrackablePointer[]}
  81. */
  82. get pointers()
  83. {
  84. return this._pointers;
  85. }
  86. /**
  87. * The root is a node that is automatically aligned to the physical scene.
  88. * Objects of your virtual scene should be descendants of this node.
  89. * @returns {BABYLON.TransformNode}
  90. */
  91. get root()
  92. {
  93. return this._root;
  94. }
  95. /**
  96. * The babylon.js scene
  97. * @returns {BABYLON.Scene}
  98. */
  99. get scene()
  100. {
  101. return this._scene;
  102. }
  103. /**
  104. * A camera that is automatically adjusted for AR
  105. * @returns {BABYLON.Camera}
  106. */
  107. get camera()
  108. {
  109. return this._camera;
  110. }
  111. /**
  112. * The babylon.js engine
  113. * @returns {BABYLON.Engine}
  114. */
  115. get engine()
  116. {
  117. return this._engine;
  118. }
  119. /**
  120. * Constructor
  121. */
  122. constructor()
  123. {
  124. this._session = null;
  125. this._frame = null;
  126. this._pointers = [];
  127. this._origin = null;
  128. this._root = null;
  129. this._scene = null;
  130. this._camera = null;
  131. this._engine = null;
  132. }
  133. }
  134. /**
  135. * Enchant babylon.js with encantar.js!
  136. * @param {ARDemo} demo
  137. * @returns {Promise<ARSystem>}
  138. */
  139. function encantar(demo)
  140. {
  141. const ar = new ARSystem();
  142. const flipZAxis = new BABYLON.Matrix().copyFromFloats(
  143. 1, 0, 0, 0,
  144. 0, 1, 0, 0,
  145. 0, 0,-1, 0,
  146. 0, 0, 0, 1
  147. );
  148. function animate(time, frame)
  149. {
  150. ar._frame = frame;
  151. mix(frame);
  152. demo.update(ar);
  153. ar._scene.render(false);
  154. ar._session.requestAnimationFrame(animate);
  155. }
  156. function mix(frame)
  157. {
  158. let found = false;
  159. ar._pointers.length = 0;
  160. for(const result of frame.results) {
  161. if(result.tracker.type == 'image-tracker') {
  162. if(result.trackables.length > 0) {
  163. const trackable = result.trackables[0];
  164. const projectionMatrix = result.viewer.view.projectionMatrix;
  165. const viewMatrix = result.viewer.pose.viewMatrix;
  166. const modelMatrix = trackable.pose.transform.matrix;
  167. align(projectionMatrix, viewMatrix, modelMatrix);
  168. ar._origin.setEnabled(true);
  169. found = true;
  170. }
  171. }
  172. else if(result.tracker.type == 'pointer-tracker') {
  173. if(result.trackables.length > 0)
  174. ar._pointers.push.apply(ar._pointers, result.trackables);
  175. }
  176. }
  177. if(!found)
  178. ar._origin.setEnabled(false);
  179. }
  180. function align(projectionMatrix, viewMatrix, modelMatrix)
  181. {
  182. if(ar._scene.useRightHandedSystem)
  183. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  184. else
  185. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZAxis));
  186. ar._camera.setViewMatrix(convert(viewMatrix));
  187. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  188. }
  189. function convert(matrix)
  190. {
  191. // encantar.js uses column vectors stored in column-major format,
  192. // whereas babylon.js uses row vectors stored in row-major format
  193. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  194. return new BABYLON.Matrix().fromArray(matrix.read());
  195. }
  196. return Promise.resolve()
  197. .then(() => {
  198. return demo.startSession(); // Promise or SpeedyPromise
  199. })
  200. .then(session => {
  201. ar._session = session;
  202. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  203. premultipliedAlpha: true
  204. });
  205. ar._engine.resize = function(forceSetSize = false) {
  206. // make babylon.js respect the resolution of the viewport
  207. const size = session.viewport.virtualSize;
  208. this.setSize(size.width, size.height, forceSetSize);
  209. };
  210. ar._scene = new BABYLON.Scene(ar._engine);
  211. ar._scene.useRightHandedSystem = true;
  212. ar._scene.clearColor.set(0, 0, 0, 0);
  213. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  214. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  215. ar._root.parent = ar._origin;
  216. ar._origin.setEnabled(false);
  217. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  218. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  219. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  220. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  221. ar._camera.setViewMatrix = function(matrix) {
  222. this._customViewMatrix = matrix;
  223. this.getViewMatrix(true);
  224. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  225. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  226. this._globalPosition.copyFrom(this.position);
  227. };
  228. session.addEventListener('end', event => {
  229. ar._origin.setEnabled(false);
  230. ar._frame = null;
  231. });
  232. session.viewport.addEventListener('resize', event => {
  233. ar._engine.resize();
  234. });
  235. return Promise.resolve()
  236. .then(() => {
  237. return demo.init(ar);
  238. })
  239. .then(() => {
  240. session.addEventListener('end', event => { demo.release(ar); });
  241. session.requestAnimationFrame(animate);
  242. return ar;
  243. })
  244. .catch(error => {
  245. session.end();
  246. throw error;
  247. });
  248. })
  249. .catch(error => {
  250. console.error(error);
  251. throw error;
  252. });
  253. }
  254. /**
  255. * Version check
  256. * @param {object} libs
  257. */
  258. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  259. {
  260. window.addEventListener('load', () => {
  261. try { AR, BABYLON;
  262. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  263. 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;
  264. for(const [lib, expected] of Object.entries(libs))
  265. check(lib, expected.version, versionOf[lib]);
  266. }
  267. catch(e) {
  268. alert(e.message);
  269. }
  270. });
  271. }