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

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