Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

babylon-with-encantar.js 8.3KB

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