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.

three-with-encantar.js 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /**
  2. * three.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. 'three.js': { version: '147' }
  10. });
  11. /**
  12. * Base class for Augmented Reality experiences
  13. */
  14. class ARDemo
  15. {
  16. /**
  17. * Start the AR session
  18. * @returns {Promise<Session> | SpeedyPromise<Session>}
  19. * @abstract
  20. */
  21. startSession()
  22. {
  23. throw new Error('Abstract method');
  24. }
  25. /**
  26. * Initialization
  27. * @returns {void | Promise<void> | SpeedyPromise<void>}
  28. */
  29. init()
  30. {
  31. return Promise.resolve();
  32. }
  33. /**
  34. * Animation step
  35. * @returns {void}
  36. */
  37. update()
  38. {
  39. }
  40. /**
  41. * Release resources
  42. * @returns {void}
  43. */
  44. release()
  45. {
  46. }
  47. /**
  48. * Preload resources before starting the AR session
  49. * @returns {Promise<void> | SpeedyPromise<void>}
  50. */
  51. preload()
  52. {
  53. return Promise.resolve();
  54. }
  55. /**
  56. * A reference to the ARSystem
  57. * @returns {ARSystem | null}
  58. */
  59. get ar()
  60. {
  61. return this._ar;
  62. }
  63. /**
  64. * Constructor
  65. */
  66. constructor()
  67. {
  68. this._ar = null;
  69. }
  70. }
  71. /**
  72. * AR Utilities
  73. */
  74. class ARUtils
  75. {
  76. /**
  77. * Convert an AR Vector2 to a THREE Vector2
  78. * @param {Vector2} v
  79. * @returns {THREE.Vector2}
  80. */
  81. convertVector2(v)
  82. {
  83. return new THREE.Vector2(v.x, v.y);
  84. }
  85. /**
  86. * Convert an AR Vector3 to a THREE Vector3
  87. * @param {Vector3} v
  88. * @returns {THREE.Vector3}
  89. */
  90. convertVector3(v)
  91. {
  92. return new THREE.Vector3(v.x, v.y, v.z);
  93. }
  94. /**
  95. * Convert an AR Quaternion to a THREE Quaternion
  96. * @param {Quaternion} q
  97. * @returns {THREE.Quaternion}
  98. */
  99. convertQuaternion(q)
  100. {
  101. return new THREE.Quaternion(q.x, q.y, q.z, q.w);
  102. }
  103. /**
  104. * Convert an AR Ray to a THREE Ray
  105. * @param {Ray} r
  106. * @returns {THREE.Ray}
  107. */
  108. convertRay(r)
  109. {
  110. const origin = this.convertVector3(r.origin);
  111. const direction = this.convertVector3(r.direction);
  112. return new THREE.Ray(origin, direction);
  113. }
  114. }
  115. /**
  116. * Helper for creating Augmented Reality experiences
  117. */
  118. class ARSystem
  119. {
  120. /**
  121. * AR Session
  122. * @returns {Session}
  123. */
  124. get session()
  125. {
  126. return this._session;
  127. }
  128. /**
  129. * Current frame: an object holding data to augment the physical scene.
  130. * If the AR scene is not initialized, this will be null.
  131. * @returns {Frame | null}
  132. */
  133. get frame()
  134. {
  135. return this._frame;
  136. }
  137. /**
  138. * AR Viewer
  139. * @returns {Viewer | null}
  140. */
  141. get viewer()
  142. {
  143. return this._viewer;
  144. }
  145. /**
  146. * Pointer-based input (current frame)
  147. * Make sure to add a PointerTracker to your session in order to use these
  148. * @returns {TrackablePointer[]}
  149. */
  150. get pointers()
  151. {
  152. return this._pointers;
  153. }
  154. /**
  155. * The root is a node that is automatically aligned to the physical scene.
  156. * Objects of your virtual scene should be descendants of this node.
  157. * @returns {THREE.Group}
  158. */
  159. get root()
  160. {
  161. return this._root;
  162. }
  163. /**
  164. * The three.js scene
  165. * @returns {THREE.Scene}
  166. */
  167. get scene()
  168. {
  169. return this._scene;
  170. }
  171. /**
  172. * A camera that is automatically adjusted for AR
  173. * @returns {THREE.Camera}
  174. */
  175. get camera()
  176. {
  177. return this._camera;
  178. }
  179. /**
  180. * The three.js renderer
  181. * @returns {THREE.WebGLRenderer}
  182. */
  183. get renderer()
  184. {
  185. return this._renderer;
  186. }
  187. /**
  188. * AR Utilities
  189. * @returns {ARUtils}
  190. */
  191. get utils()
  192. {
  193. return this._utils;
  194. }
  195. /**
  196. * Constructor
  197. */
  198. constructor()
  199. {
  200. this._session = null;
  201. this._frame = null;
  202. this._viewer = null;
  203. this._pointers = [];
  204. this._origin = null;
  205. this._root = null;
  206. this._scene = null;
  207. this._camera = null;
  208. this._renderer = null;
  209. this._utils = new ARUtils();
  210. }
  211. }
  212. /**
  213. * Enchant three.js with encantar.js!
  214. * @param {ARDemo} demo
  215. * @returns {Promise<ARSystem>}
  216. */
  217. function encantar(demo)
  218. {
  219. const ar = new ARSystem();
  220. function animate(time, frame)
  221. {
  222. ar._frame = frame;
  223. mix(frame);
  224. demo.update();
  225. ar._renderer.render(ar._scene, ar._camera);
  226. ar._session.requestAnimationFrame(animate);
  227. }
  228. function mix(frame)
  229. {
  230. let found = false;
  231. ar._viewer = null;
  232. ar._pointers.length = 0;
  233. for(const result of frame.results) {
  234. if(result.tracker.type == 'image-tracker') {
  235. if(result.trackables.length > 0) {
  236. const trackable = result.trackables[0];
  237. const projectionMatrix = result.viewer.view.projectionMatrix;
  238. const viewMatrixInverse = result.viewer.pose.transform.matrix;
  239. const modelMatrix = trackable.pose.transform.matrix;
  240. align(projectionMatrix, viewMatrixInverse, modelMatrix);
  241. ar._origin.visible = true;
  242. ar._viewer = result.viewer;
  243. found = true;
  244. }
  245. }
  246. else if(result.tracker.type == 'pointer-tracker') {
  247. if(result.trackables.length > 0)
  248. ar._pointers.push.apply(ar._pointers, result.trackables);
  249. }
  250. }
  251. if(!found)
  252. ar._origin.visible = false;
  253. }
  254. function align(projectionMatrix, viewMatrixInverse, modelMatrix)
  255. {
  256. ar._camera.projectionMatrix.fromArray(projectionMatrix.read());
  257. ar._camera.projectionMatrixInverse.copy(ar._camera.projectionMatrix).invert();
  258. ar._camera.matrix.fromArray(viewMatrixInverse.read());
  259. ar._camera.updateMatrixWorld(true);
  260. ar._origin.matrix.fromArray(modelMatrix.read());
  261. ar._origin.updateMatrixWorld(true);
  262. }
  263. return Promise.resolve()
  264. .then(() => demo.preload())
  265. .then(() => demo.startSession()) // Promise or SpeedyPromise
  266. .then(session => {
  267. demo._ar = ar;
  268. ar._session = session;
  269. ar._scene = new THREE.Scene();
  270. ar._origin = new THREE.Group();
  271. ar._origin.matrixAutoUpdate = false;
  272. ar._origin.visible = false;
  273. ar._scene.add(ar._origin);
  274. ar._root = new THREE.Group();
  275. ar._origin.add(ar._root);
  276. ar._camera = new THREE.PerspectiveCamera();
  277. ar._camera.matrixAutoUpdate = false;
  278. ar._renderer = new THREE.WebGLRenderer({
  279. canvas: session.viewport.canvas,
  280. alpha: true,
  281. });
  282. session.addEventListener('end', event => {
  283. ar._origin.visible = false;
  284. ar._viewer = null;
  285. ar._frame = null;
  286. ar._pointers.length = 0;
  287. });
  288. session.viewport.addEventListener('resize', event => {
  289. const size = session.viewport.virtualSize;
  290. ar._renderer.setPixelRatio(1.0);
  291. ar._renderer.setSize(size.width, size.height, false);
  292. });
  293. return Promise.resolve()
  294. .then(() => {
  295. return demo.init();
  296. })
  297. .then(() => {
  298. session.addEventListener('end', event => { demo.release(); });
  299. session.requestAnimationFrame(animate);
  300. return ar;
  301. })
  302. .catch(error => {
  303. session.end();
  304. throw error;
  305. });
  306. })
  307. .catch(error => {
  308. console.error(error);
  309. throw error;
  310. });
  311. }
  312. /**
  313. * Version check
  314. * @param {object} libs
  315. */
  316. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  317. {
  318. window.addEventListener('load', () => {
  319. try { AR, __THREE__;
  320. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'three.js': __THREE__ };
  321. 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;
  322. for(const [lib, expected] of Object.entries(libs))
  323. check(lib, expected.version, versionOf[lib]);
  324. }
  325. catch(e) {
  326. alert(e.message);
  327. }
  328. });
  329. }