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 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. * AR Utilities
  57. */
  58. class ARUtils
  59. {
  60. /**
  61. * Convert an AR Vector2 to a BABYLON Vector2
  62. * @param {Vector2} v
  63. * @returns {BABYLON.Vector2}
  64. */
  65. convertVector2(v)
  66. {
  67. return new BABYLON.Vector2(v.x, v.y);
  68. }
  69. /**
  70. * Convert an AR Vector3 to a BABYLON Vector3
  71. * @param {Vector3} v
  72. * @returns {BABYLON.Vector3}
  73. */
  74. convertVector3(v)
  75. {
  76. return new BABYLON.Vector3(v.x, v.y, v.z);
  77. }
  78. /**
  79. * Convert an AR Quaternion to a BABYLON Quaternion
  80. * @param {Quaternion} q
  81. * @returns {BABYLON.Quaternion}
  82. */
  83. convertQuaternion(q)
  84. {
  85. return new BABYLON.Quaternion(q.x, q.y, q.z, q.w);
  86. }
  87. /**
  88. * Convert an AR Ray to a BABYLON Ray
  89. * @param {Ray} r
  90. * @returns {BABYLON.Ray}
  91. */
  92. convertRay(r)
  93. {
  94. const origin = this.convertVector3(r.origin);
  95. const direction = this.convertVector3(r.direction);
  96. return new BABYLON.Ray(origin, direction);
  97. }
  98. }
  99. /**
  100. * Helper for creating Augmented Reality experiences
  101. */
  102. class ARSystem
  103. {
  104. /**
  105. * AR Session
  106. * @returns {Session}
  107. */
  108. get session()
  109. {
  110. return this._session;
  111. }
  112. /**
  113. * Current frame: an object holding data to augment the physical scene.
  114. * If the AR scene is not initialized, this will be null.
  115. * @returns {Frame | null}
  116. */
  117. get frame()
  118. {
  119. return this._frame;
  120. }
  121. /**
  122. * AR Viewer
  123. * @returns {Viewer | null}
  124. */
  125. get viewer()
  126. {
  127. return this._viewer;
  128. }
  129. /**
  130. * Pointer-based input (current frame)
  131. * Make sure to add a PointerTracker to your session in order to use these
  132. * @returns {TrackablePointer[]}
  133. */
  134. get pointers()
  135. {
  136. return this._pointers;
  137. }
  138. /**
  139. * The root is a node that is automatically aligned to the physical scene.
  140. * Objects of your virtual scene should be descendants of this node.
  141. * @returns {BABYLON.TransformNode}
  142. */
  143. get root()
  144. {
  145. return this._root;
  146. }
  147. /**
  148. * The babylon.js scene
  149. * @returns {BABYLON.Scene}
  150. */
  151. get scene()
  152. {
  153. return this._scene;
  154. }
  155. /**
  156. * A camera that is automatically adjusted for AR
  157. * @returns {BABYLON.Camera}
  158. */
  159. get camera()
  160. {
  161. return this._camera;
  162. }
  163. /**
  164. * The babylon.js engine
  165. * @returns {BABYLON.Engine}
  166. */
  167. get engine()
  168. {
  169. return this._engine;
  170. }
  171. /**
  172. * AR Utilities
  173. * @returns {ARUtils}
  174. */
  175. get utils()
  176. {
  177. return this._utils;
  178. }
  179. /**
  180. * Constructor
  181. */
  182. constructor()
  183. {
  184. this._session = null;
  185. this._frame = null;
  186. this._viewer = null;
  187. this._pointers = [];
  188. this._origin = null;
  189. this._root = null;
  190. this._scene = null;
  191. this._camera = null;
  192. this._engine = null;
  193. this._utils = new ARUtils();
  194. }
  195. }
  196. /**
  197. * Enchant babylon.js with encantar.js!
  198. * @param {ARDemo} demo
  199. * @returns {Promise<ARSystem>}
  200. */
  201. function encantar(demo)
  202. {
  203. const ar = new ARSystem();
  204. const flipZAxis = new BABYLON.Matrix().copyFromFloats(
  205. 1, 0, 0, 0,
  206. 0, 1, 0, 0,
  207. 0, 0,-1, 0,
  208. 0, 0, 0, 1
  209. );
  210. function animate(time, frame)
  211. {
  212. ar._frame = frame;
  213. mix(frame);
  214. demo.update(ar);
  215. ar._scene.render(false);
  216. ar._session.requestAnimationFrame(animate);
  217. }
  218. function mix(frame)
  219. {
  220. let found = false;
  221. ar._viewer = null;
  222. ar._pointers.length = 0;
  223. for(const result of frame.results) {
  224. if(result.tracker.type == 'image-tracker') {
  225. if(result.trackables.length > 0) {
  226. const trackable = result.trackables[0];
  227. const projectionMatrix = result.viewer.view.projectionMatrix;
  228. const viewMatrix = result.viewer.pose.viewMatrix;
  229. const modelMatrix = trackable.pose.transform.matrix;
  230. align(projectionMatrix, viewMatrix, modelMatrix);
  231. ar._origin.setEnabled(true);
  232. ar._viewer = result.viewer;
  233. found = true;
  234. }
  235. }
  236. else if(result.tracker.type == 'pointer-tracker') {
  237. if(result.trackables.length > 0)
  238. ar._pointers.push.apply(ar._pointers, result.trackables);
  239. }
  240. }
  241. if(!found)
  242. ar._origin.setEnabled(false);
  243. }
  244. function align(projectionMatrix, viewMatrix, modelMatrix)
  245. {
  246. if(ar._scene.useRightHandedSystem)
  247. ar._camera.freezeProjectionMatrix(convert(projectionMatrix));
  248. else
  249. ar._camera.freezeProjectionMatrix(convert(projectionMatrix).multiply(flipZAxis));
  250. ar._camera.setViewMatrix(convert(viewMatrix));
  251. convert(modelMatrix).decomposeToTransformNode(ar._origin);
  252. }
  253. function convert(matrix)
  254. {
  255. // encantar.js uses column vectors stored in column-major format,
  256. // whereas babylon.js uses row vectors stored in row-major format
  257. // (y = Ax vs y = xA). So, we return the transpose of the transpose.
  258. return new BABYLON.Matrix().fromArray(matrix.read());
  259. }
  260. return Promise.resolve()
  261. .then(() => {
  262. return demo.startSession(); // Promise or SpeedyPromise
  263. })
  264. .then(session => {
  265. ar._session = session;
  266. ar._engine = new BABYLON.Engine(session.viewport.canvas, false, {
  267. premultipliedAlpha: true
  268. });
  269. ar._engine.resize = function(forceSetSize = false) {
  270. // make babylon.js respect the resolution of the viewport
  271. const size = session.viewport.virtualSize;
  272. this.setSize(size.width, size.height, forceSetSize);
  273. };
  274. ar._scene = new BABYLON.Scene(ar._engine);
  275. ar._scene.useRightHandedSystem = true;
  276. ar._scene.clearColor.set(0, 0, 0, 0);
  277. ar._origin = new BABYLON.TransformNode('ar-origin', ar._scene);
  278. ar._root = new BABYLON.TransformNode('ar-root', ar._scene);
  279. ar._root.parent = ar._origin;
  280. ar._origin.setEnabled(false);
  281. ar._camera = new BABYLON.Camera('ar-camera', BABYLON.Vector3.Zero(), ar._scene);
  282. ar._camera._tmpQuaternion = BABYLON.Quaternion.Identity();
  283. ar._camera._customViewMatrix = BABYLON.Matrix.Identity();
  284. ar._camera._getViewMatrix = function() { return this._customViewMatrix; };
  285. ar._camera.setViewMatrix = function(matrix) {
  286. this._customViewMatrix = matrix;
  287. this.getViewMatrix(true);
  288. this.getWorldMatrix().decompose(undefined, this._tmpQuaternion, this.position);
  289. BABYLON.Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
  290. this._globalPosition.copyFrom(this.position);
  291. };
  292. session.addEventListener('end', event => {
  293. ar._origin.setEnabled(false);
  294. ar._viewer = null;
  295. ar._frame = null;
  296. ar._pointers.length = 0;
  297. });
  298. session.viewport.addEventListener('resize', event => {
  299. ar._engine.resize();
  300. });
  301. return Promise.resolve()
  302. .then(() => {
  303. return demo.init(ar);
  304. })
  305. .then(() => {
  306. session.addEventListener('end', event => { demo.release(ar); });
  307. session.requestAnimationFrame(animate);
  308. return ar;
  309. })
  310. .catch(error => {
  311. session.end();
  312. throw error;
  313. });
  314. })
  315. .catch(error => {
  316. console.error(error);
  317. throw error;
  318. });
  319. }
  320. /**
  321. * Version check
  322. * @param {object} libs
  323. */
  324. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  325. {
  326. window.addEventListener('load', () => {
  327. try { AR, BABYLON;
  328. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'babylon.js': BABYLON.Engine.Version };
  329. 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;
  330. for(const [lib, expected] of Object.entries(libs))
  331. check(lib, expected.version, versionOf[lib]);
  332. }
  333. catch(e) {
  334. alert(e.message);
  335. }
  336. });
  337. }