You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

aframe-with-encantar.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. /**
  2. * A-Frame 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. (function() {
  7. /* Usage of the indicated versions is encouraged */
  8. __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__({
  9. 'encantar.js': { version: '0.4.0' },
  10. 'A-Frame': { version: '1.4.2' }
  11. });
  12. /**
  13. * AR Base System
  14. * @mixin ARBaseSystem
  15. */
  16. const ARBaseSystem = () => ({
  17. /**
  18. * AR Session
  19. * @type {Session | null}
  20. */
  21. session: null,
  22. /**
  23. * Current frame: an object holding data to augment the physical scene.
  24. * If the AR scene is not initialized, this will be null.
  25. * @type {Frame | null}
  26. */
  27. frame: null,
  28. /**
  29. * AR Viewer
  30. * @type {Viewer | null}
  31. */
  32. viewer: null,
  33. /**
  34. * Pointer-based input (current frame)
  35. * Make sure to add a PointerTracker to your session in order to use these
  36. * @type {TrackablePointer[]}
  37. */
  38. pointers: [],
  39. /**
  40. * AR Utilities
  41. * @type {object}
  42. */
  43. utils: {
  44. /**
  45. * Convert an AR Vector2 to a THREE Vector2
  46. * @param {Vector2} v
  47. * @returns {THREE.Vector2}
  48. */
  49. convertVector2(v)
  50. {
  51. return new THREE.Vector2(v.x, v.y);
  52. },
  53. /**
  54. * Convert an AR Vector3 to a THREE Vector3
  55. * @param {Vector3} v
  56. * @returns {THREE.Vector3}
  57. */
  58. convertVector3(v)
  59. {
  60. return new THREE.Vector3(v.x, v.y, v.z);
  61. },
  62. /**
  63. * Convert an AR Quaternion to a THREE Quaternion
  64. * @param {Quaternion} q
  65. * @returns {THREE.Quaternion}
  66. */
  67. convertQuaternion(q)
  68. {
  69. return new THREE.Quaternion(q.x, q.y, q.z, q.w);
  70. },
  71. /**
  72. * Convert an AR Ray to a THREE Ray
  73. * @param {Ray} r
  74. * @returns {THREE.Ray}
  75. */
  76. convertRay(r)
  77. {
  78. const origin = this.convertVector3(r.origin);
  79. const direction = this.convertVector3(r.direction);
  80. return new THREE.Ray(origin, direction);
  81. },
  82. }
  83. });
  84. /**
  85. * Internal Utilities
  86. */
  87. const Utils = () => ({
  88. findTrackedImage(frame, name = '')
  89. {
  90. if(frame === null)
  91. return null;
  92. for(const result of frame.results) {
  93. if(result.tracker.type == 'image-tracker') {
  94. for(const trackable of result.trackables) {
  95. if(name === '' || name === trackable.referenceImage.name) {
  96. return {
  97. projectionMatrix: result.viewer.view.projectionMatrix,
  98. viewMatrixInverse: result.viewer.pose.transform.matrix,
  99. modelMatrix: trackable.pose.transform.matrix,
  100. };
  101. }
  102. }
  103. }
  104. }
  105. return null;
  106. },
  107. findViewer(frame)
  108. {
  109. if(frame === null)
  110. return null;
  111. for(const result of frame.results) {
  112. if(result.tracker.type == 'image-tracker') {
  113. if(result.trackables.length > 0)
  114. return result.viewer;
  115. }
  116. }
  117. return null;
  118. },
  119. findTrackablePointers(frame)
  120. {
  121. if(frame === null)
  122. return [];
  123. for(const result of frame.results) {
  124. if(result.tracker.type == 'pointer-tracker')
  125. return result.trackables;
  126. }
  127. return [];
  128. },
  129. });
  130. /* ========================================================================= */
  131. /**
  132. * AR System
  133. * @name ARSystem
  134. * @type {object}
  135. * @mixes ARBaseSystem
  136. */
  137. AFRAME.registerSystem('ar', Object.assign(ARBaseSystem(), {
  138. // el;
  139. // data;
  140. // schema;
  141. _utils: Utils(),
  142. _started: false,
  143. _components: [],
  144. _roots: [],
  145. init()
  146. {
  147. const scene = this.el;
  148. // validate
  149. if(!scene.getAttribute('ar-session')) {
  150. scene.setAttribute('ar-session', {}); // use a default ar-session
  151. //throw new Error('Missing ar-session in a-scene'); // other errors will appear
  152. }
  153. // initial setup
  154. scene.setAttribute('vr-mode-ui', { enabled: false });
  155. scene.setAttribute('embedded', true);
  156. scene.setAttribute('renderer', { alpha: true });
  157. // pause the scene until we're ready
  158. scene.addEventListener('ar-started', () => {
  159. scene.play();
  160. });
  161. scene.addEventListener('loaded', () => {
  162. //scene.pause();
  163. Promise.resolve().then(() => scene.pause());
  164. });
  165. /*
  166. // we take control of the rendering
  167. scene.addEventListener('loaded', () => {
  168. scene.renderer.setAnimationLoop(null);
  169. });
  170. */
  171. },
  172. tick()
  173. {
  174. const scene = this.el;
  175. // we take control of the rendering
  176. scene.renderer.setAnimationLoop(null);
  177. // manually update the roots
  178. for(let i = 0; i < this._roots.length; i++)
  179. this._roots[i].teek();
  180. },
  181. startSession()
  182. {
  183. if(this._started)
  184. throw new Error('Can\'t start an AR session twice');
  185. this._started = true;
  186. for(const component of this._components)
  187. component.validate();
  188. return Speedy.Promise.all([
  189. this._loadSources(),
  190. this._loadTrackers(),
  191. this._loadViewport(),
  192. this._loadPreferences(),
  193. ])
  194. .then(([
  195. sources,
  196. trackers,
  197. viewport,
  198. preferences,
  199. ]) => AR.startSession(
  200. Object.assign({}, preferences, {
  201. sources,
  202. trackers,
  203. viewport
  204. })
  205. ))
  206. .then(session => {
  207. // setup
  208. this.session = session;
  209. this._configureSession();
  210. this._startAnimationLoop();
  211. // we're done!
  212. const scene = this.el;
  213. scene.emit('ar-started', { ar: this });
  214. return session;
  215. })
  216. .catch(error => {
  217. console.error(error);
  218. throw error;
  219. });
  220. },
  221. register(component)
  222. {
  223. this._register(this._components, component);
  224. },
  225. unregister(component)
  226. {
  227. this._unregister(this._components, component);
  228. },
  229. registerRoot(component)
  230. {
  231. this._register(this._roots, component);
  232. },
  233. unregisterRoot(component)
  234. {
  235. this._unregister(this._roots, component);
  236. },
  237. _register(arr, component)
  238. {
  239. const j = arr.indexOf(component);
  240. if(j < 0)
  241. arr.push(component);
  242. },
  243. _unregister(arr, component)
  244. {
  245. const j = arr.indexOf(component);
  246. if(j >= 0)
  247. arr.splice(j, 1);
  248. },
  249. _configureSession()
  250. {
  251. const scene = this.el;
  252. const session = this.session;
  253. if(session.viewport.canvas !== scene.canvas) {
  254. session.end();
  255. throw new Error('Invalid A-Frame canvas');
  256. }
  257. session.addEventListener('end', () => {
  258. this.viewer = null;
  259. this.frame = null;
  260. this.pointers.length = 0;
  261. });
  262. session.viewport.addEventListener('resize', () => {
  263. // timeout : internals of aframe (a-scene.js)
  264. setTimeout(() => this._resize(), 200);
  265. this._resize();
  266. });
  267. this._resize(); // initial setup
  268. },
  269. _startAnimationLoop()
  270. {
  271. const scene = this.el;
  272. const session = this.session;
  273. scene.object3D.background = null;
  274. // animation loop
  275. const animate = (time, frame) => {
  276. this.frame = frame;
  277. this.viewer = this._utils.findViewer(frame);
  278. this._updateTrackablePointers();
  279. scene.render();
  280. session.requestAnimationFrame(animate);
  281. };
  282. session.requestAnimationFrame(animate);
  283. },
  284. _resize()
  285. {
  286. const scene = this.el;
  287. const size = this.session.viewport.virtualSize;
  288. scene.renderer.setPixelRatio(1.0);
  289. scene.renderer.setSize(size.width, size.height, false);
  290. },
  291. _loadTrackers()
  292. {
  293. const scene = this.el;
  294. const groups = Array.from(
  295. scene.querySelectorAll('[ar-trackers]'),
  296. el => el.components['ar-trackers']
  297. );
  298. if(groups.length > 1)
  299. throw new Error('Can\'t define multiple groups of ar-trackers');
  300. else if(groups.length == 0)
  301. throw new Error('Missing ar-trackers');
  302. return groups[0].trackers();
  303. },
  304. _loadSources()
  305. {
  306. const scene = this.el;
  307. const groups = Array.from(
  308. scene.querySelectorAll('[ar-sources]'),
  309. el => el.components['ar-sources']
  310. );
  311. if(groups.length > 1)
  312. throw new Error('Can\'t define multiple groups of ar-sources');
  313. else if(groups.length == 0)
  314. throw new Error('Missing ar-sources');
  315. return groups[0].sources();
  316. },
  317. _loadViewport()
  318. {
  319. const scene = this.el;
  320. const viewports = Array.from(
  321. scene.querySelectorAll('[ar-viewport]'),
  322. el => el.components['ar-viewport']
  323. );
  324. if(viewports.length > 1)
  325. throw new Error('Can\'t define multiple ar-viewport\'s');
  326. else if(viewports.length == 0)
  327. throw new Error('Missing ar-viewport');
  328. return viewports[0].viewport();
  329. },
  330. _loadPreferences()
  331. {
  332. const scene = this.el;
  333. const sessionComponent = scene.components['ar-session'];
  334. if(sessionComponent === undefined)
  335. throw new Error('Missing ar-session in a-scene');
  336. return sessionComponent.preferences();
  337. },
  338. _updateTrackablePointers()
  339. {
  340. this.pointers.length = 0;
  341. const newPointers = this._utils.findTrackablePointers(this.frame);
  342. if(newPointers.length > 0)
  343. this.pointers.push.apply(this.pointers, newPointers);
  344. },
  345. }));
  346. /**
  347. * AR Component
  348. * @mixin ARComponent
  349. */
  350. const ARComponent = obj => Object.assign({}, obj, {
  351. // el;
  352. // data;
  353. // id;
  354. init()
  355. {
  356. Object.defineProperty(this, 'ar', {
  357. get: function() { return this.el.sceneEl.systems.ar; }
  358. });
  359. this.ar.register(this);
  360. if(obj.init !== undefined)
  361. obj.init.call(this);
  362. if(this.el.sceneEl.hasLoaded)
  363. this.validate();
  364. },
  365. remove()
  366. {
  367. if(obj.remove !== undefined)
  368. obj.remove.call(this);
  369. this.ar.unregister(this);
  370. },
  371. validate()
  372. {
  373. if(obj.validate !== undefined)
  374. obj.validate.call(this);
  375. }
  376. });
  377. /**
  378. * AR Session
  379. */
  380. AFRAME.registerComponent('ar-session', ARComponent({
  381. schema: {
  382. /** session mode: "immersive" | "inline" */
  383. 'mode': { type: 'string', default: 'immersive' },
  384. /** show stats panel? */
  385. 'stats': { type: 'boolean', default: false },
  386. /** show gizmos? */
  387. 'gizmos': { type: 'boolean', default: false },
  388. /** start the session automatically? */
  389. 'autoplay': { type: 'boolean', default: true },
  390. },
  391. sceneOnly: true,
  392. _started: false,
  393. init()
  394. {
  395. this._started = false;
  396. },
  397. play()
  398. {
  399. // start the session (run once)
  400. if(!this._started) {
  401. this._started = true;
  402. if(this.data.autoplay)
  403. this.startSession();
  404. }
  405. },
  406. remove()
  407. {
  408. // end the session
  409. if(this.ar.session !== null)
  410. this.ar.session.end();
  411. },
  412. preferences()
  413. {
  414. return {
  415. mode: this.data.mode,
  416. stats: this.data.stats,
  417. gizmos: this.data.gizmos
  418. };
  419. },
  420. startSession()
  421. {
  422. return this.ar.startSession();
  423. },
  424. }));
  425. /* ========================================================================= */
  426. /**
  427. * AR Camera
  428. */
  429. AFRAME.registerComponent('ar-camera', ARComponent({
  430. dependencies: ['camera'],
  431. init()
  432. {
  433. const el = this.el;
  434. el.setAttribute('camera', { active: true });
  435. el.setAttribute('wasd-controls', { enabled: false });
  436. el.setAttribute('look-controls', { enabled: false });
  437. el.setAttribute('position', { x: 0, y: 0, z: 0 }); // A-Frame sets y = 1.6m for VR
  438. const camera = el.getObject3D('camera');
  439. camera.matrixAutoUpdate = false;
  440. },
  441. tick()
  442. {
  443. const ar = this.ar;
  444. const el = this.el;
  445. const tracked = ar._utils.findTrackedImage(ar.frame);
  446. if(tracked === null)
  447. return;
  448. const camera = el.getObject3D('camera');
  449. camera.projectionMatrix.fromArray(tracked.projectionMatrix.read());
  450. camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
  451. camera.matrix.fromArray(tracked.viewMatrixInverse.read());
  452. camera.updateMatrixWorld(true);
  453. //console.log('projectionMatrix', tracked.projectionMatrix.read());
  454. //console.log('viewMatrixInverse', tracked.viewMatrixInverse.read());
  455. },
  456. validate()
  457. {
  458. if(!this.el.getAttribute('camera'))
  459. throw new Error('Incorrect ar-camera');
  460. if(this.el.parentNode !== this.el.sceneEl)
  461. throw new Error('ar-camera must be a direct child of a-scene');
  462. },
  463. }));
  464. AFRAME.registerPrimitive('ar-camera', {
  465. defaultComponents: {
  466. 'ar-camera': {},
  467. 'camera': {}
  468. }
  469. });
  470. /**
  471. * AR Root node
  472. */
  473. AFRAME.registerComponent('ar-root', ARComponent({
  474. schema: {
  475. /** the name of a reference image (target) or the empty string (to match any target) */
  476. 'referenceImage': { type: 'string', default: '' },
  477. },
  478. _origin: null,
  479. _firstRun: true,
  480. init()
  481. {
  482. const origin = new THREE.Group();
  483. origin.matrixAutoUpdate = false;
  484. const root = this.el.object3D;
  485. root.parent.add(origin);
  486. origin.add(root);
  487. this._origin = origin;
  488. this._firstRun = true;
  489. this.ar.registerRoot(this);
  490. },
  491. remove()
  492. {
  493. const origin = this._origin;
  494. const root = this.el.object3D;
  495. origin.parent.add(root);
  496. origin.removeFromParent();
  497. this._origin = null;
  498. this.ar.unregisterRoot(this);
  499. },
  500. play()
  501. {
  502. const origin = this._origin;
  503. origin.visible = true;
  504. if(this._firstRun) {
  505. this._firstRun = false;
  506. origin.visible = false;
  507. this.el.pause();
  508. }
  509. },
  510. pause()
  511. {
  512. const origin = this._origin;
  513. origin.visible = false;
  514. },
  515. teek()
  516. {
  517. const ar = this.ar;
  518. const targetName = this.data.referenceImage;
  519. const tracked = ar._utils.findTrackedImage(ar.frame, targetName);
  520. if(tracked === null) {
  521. this.el.pause();
  522. return;
  523. }
  524. const origin = this._origin;
  525. origin.matrix.fromArray(tracked.modelMatrix.read());
  526. origin.updateMatrixWorld(true);
  527. this.el.play();
  528. //console.log('modelMatrix', tracked.modelMatrix.toString());
  529. },
  530. validate()
  531. {
  532. if(this.el.parentNode !== this.el.sceneEl)
  533. throw new Error('ar-root must be a direct child of a-scene');
  534. },
  535. }));
  536. AFRAME.registerPrimitive('ar-root', {
  537. defaultComponents: {
  538. 'ar-root': {}
  539. },
  540. mappings: {
  541. 'reference-image': 'ar-root.referenceImage'
  542. }
  543. });
  544. /* ========================================================================= */
  545. /**
  546. * AR Sources
  547. */
  548. AFRAME.registerComponent('ar-sources', ARComponent({
  549. validate()
  550. {
  551. if(this.el.parentNode !== this.el.sceneEl)
  552. throw new Error('ar-sources must be a direct child of a-scene');
  553. },
  554. sources()
  555. {
  556. const sources = [];
  557. for(const child of this.el.children) {
  558. if(child.components !== undefined) {
  559. for(const name in child.components) {
  560. const component = child.components[name];
  561. if(component.ar === this.ar && typeof component.source == 'function')
  562. sources.push(component.source());
  563. }
  564. }
  565. }
  566. return sources;
  567. },
  568. }));
  569. AFRAME.registerPrimitive('ar-sources', {
  570. defaultComponents: {
  571. 'ar-sources': {}
  572. }
  573. });
  574. /**
  575. * AR Camera Source
  576. */
  577. AFRAME.registerComponent('ar-camera-source', ARComponent({
  578. schema: {
  579. /** video resolution */
  580. 'resolution': { type: 'string', default: 'md' },
  581. /** facing mode: "environment" | "user" */
  582. 'facingMode': { type: 'string', default: 'environment' },
  583. },
  584. validate()
  585. {
  586. if(!this.el.parentNode.getAttribute('ar-sources'))
  587. throw new Error('ar-camera-source must be a direct child of ar-sources');
  588. },
  589. source()
  590. {
  591. return AR.Source.Camera({
  592. resolution: this.data.resolution,
  593. constraints: {
  594. facingMode: this.data.facingMode
  595. }
  596. });
  597. },
  598. }));
  599. AFRAME.registerPrimitive('ar-camera-source', {
  600. defaultComponents: {
  601. 'ar-camera-source': {}
  602. },
  603. mappings: {
  604. 'resolution': 'ar-camera-source.resolution',
  605. 'facing-mode': 'ar-camera-source.facingMode',
  606. }
  607. });
  608. /**
  609. * AR Video Source
  610. */
  611. AFRAME.registerComponent('ar-video-source', ARComponent({
  612. schema: {
  613. /** selector for a <video> element */
  614. 'video': { type: 'selector' },
  615. },
  616. validate()
  617. {
  618. if(!this.el.parentNode.getAttribute('ar-sources'))
  619. throw new Error('ar-video-source must be a direct child of ar-sources');
  620. },
  621. source()
  622. {
  623. return AR.Source.Video(this.data.video);
  624. },
  625. }));
  626. AFRAME.registerPrimitive('ar-video-source', {
  627. defaultComponents: {
  628. 'ar-video-source': {}
  629. },
  630. mappings: {
  631. 'video': 'ar-video-source.video'
  632. }
  633. });
  634. /**
  635. * AR Canvas Source
  636. */
  637. AFRAME.registerComponent('ar-canvas-source', ARComponent({
  638. schema: {
  639. /** selector for a <canvas> element */
  640. 'canvas': { type: 'selector' },
  641. },
  642. validate()
  643. {
  644. if(!this.el.parentNode.getAttribute('ar-sources'))
  645. throw new Error('ar-canvas-source must be a direct child of ar-sources');
  646. },
  647. source()
  648. {
  649. return AR.Source.Canvas(this.data.canvas);
  650. },
  651. }));
  652. AFRAME.registerPrimitive('ar-canvas-source', {
  653. defaultComponents: {
  654. 'ar-canvas-source': {}
  655. },
  656. mappings: {
  657. 'canvas': 'ar-canvas-source.canvas'
  658. }
  659. });
  660. /**
  661. * AR Pointer Source
  662. */
  663. AFRAME.registerComponent('ar-pointer-source', ARComponent({
  664. schema: {
  665. },
  666. validate()
  667. {
  668. if(!this.el.parentNode.getAttribute('ar-sources'))
  669. throw new Error('ar-pointer-source must be a direct child of ar-sources');
  670. },
  671. source()
  672. {
  673. return AR.Source.Pointer();
  674. },
  675. }));
  676. AFRAME.registerPrimitive('ar-pointer-source', {
  677. defaultComponents: {
  678. 'ar-pointer-source': {}
  679. },
  680. mappings: {
  681. }
  682. });
  683. /* ========================================================================= */
  684. /**
  685. * AR Trackers
  686. */
  687. AFRAME.registerComponent('ar-trackers', ARComponent({
  688. validate()
  689. {
  690. if(this.el.parentNode !== this.el.sceneEl)
  691. throw new Error('ar-trackers must be a direct child of a-scene');
  692. },
  693. /* async */ trackers()
  694. {
  695. const trackers = [];
  696. for(const child of this.el.children) {
  697. if(child.components !== undefined) {
  698. for(const name in child.components) {
  699. const component = child.components[name];
  700. if(component.ar === this.ar && typeof component.tracker == 'function')
  701. trackers.push(component.tracker());
  702. }
  703. }
  704. }
  705. return Speedy.Promise.all(trackers);
  706. },
  707. }));
  708. AFRAME.registerPrimitive('ar-trackers', {
  709. defaultComponents: {
  710. 'ar-trackers': {}
  711. }
  712. });
  713. /**
  714. * AR Image Tracker
  715. */
  716. AFRAME.registerComponent('ar-image-tracker', ARComponent({
  717. schema: {
  718. /** resolution of the tracker */
  719. 'resolution': { type: 'string', default: 'sm' },
  720. },
  721. validate()
  722. {
  723. if(!this.el.parentNode.getAttribute('ar-trackers'))
  724. throw new Error('ar-image-tracker must be a direct child of ar-trackers');
  725. },
  726. /* async */ tracker()
  727. {
  728. const tracker = AR.Tracker.ImageTracker();
  729. const referenceImages = [];
  730. tracker.resolution = this.data.resolution;
  731. for(const child of this.el.children) {
  732. if(child.components !== undefined) {
  733. for(const name in child.components) {
  734. const component = child.components[name];
  735. if(component.ar === this.ar && typeof component.referenceImage == 'function')
  736. referenceImages.push(component.referenceImage());
  737. }
  738. }
  739. }
  740. return tracker.database.add(referenceImages).then(() => tracker);
  741. },
  742. }));
  743. AFRAME.registerPrimitive('ar-image-tracker', {
  744. defaultComponents: {
  745. 'ar-image-tracker': {}
  746. }
  747. });
  748. /**
  749. * AR Reference Image
  750. */
  751. AFRAME.registerComponent('ar-reference-image', ARComponent({
  752. schema: {
  753. /** the name of the reference image */
  754. 'name': { type: 'string', default: '' },
  755. /** URL of an image */
  756. 'src': { type: 'string', default: '' }
  757. },
  758. validate()
  759. {
  760. if(!this.el.parentNode.getAttribute('ar-image-tracker'))
  761. throw new Error('ar-reference-image must be a direct child of ar-image-tracker');
  762. },
  763. referenceImage()
  764. {
  765. if(this.data.src == '')
  766. throw new Error('Unspecified src attribute of ar-reference-image');
  767. const img = new Image();
  768. img.src = this.data.src;
  769. return {
  770. name: this.data.name != '' ? this.data.name : undefined,
  771. image: img
  772. };
  773. }
  774. }));
  775. AFRAME.registerPrimitive('ar-reference-image', {
  776. defaultComponents: {
  777. 'ar-reference-image': {}
  778. },
  779. mappings: {
  780. 'name': 'ar-reference-image.name',
  781. 'src': 'ar-reference-image.src'
  782. }
  783. });
  784. /**
  785. * AR Pointer Tracker
  786. */
  787. AFRAME.registerComponent('ar-pointer-tracker', ARComponent({
  788. schema: {
  789. },
  790. validate()
  791. {
  792. if(!this.el.parentNode.getAttribute('ar-trackers'))
  793. throw new Error('ar-pointer-tracker must be a direct child of ar-trackers');
  794. },
  795. tracker()
  796. {
  797. return AR.Tracker.Pointer();
  798. },
  799. }));
  800. AFRAME.registerPrimitive('ar-pointer-tracker', {
  801. defaultComponents: {
  802. 'ar-pointer-tracker': {}
  803. }
  804. });
  805. /* ========================================================================= */
  806. /**
  807. * AR Viewport
  808. */
  809. AFRAME.registerComponent('ar-viewport', ARComponent({
  810. schema: {
  811. /** viewport resolution */
  812. 'resolution': { type: 'string', default: 'lg' },
  813. /** viewport style: "best-fit" | "stretch" | "inline" */
  814. 'style': { type: 'string', default: 'best-fit' },
  815. },
  816. validate()
  817. {
  818. if(this.el.parentNode !== this.el.sceneEl)
  819. throw new Error('ar-viewport must be a direct child of a-scene');
  820. },
  821. viewport()
  822. {
  823. const scene = this.el.sceneEl;
  824. const huds = [];
  825. const fullscreenUI = this.el.components['ar-viewport-fullscreen-ui'];
  826. for(const child of this.el.children) {
  827. if(child.components !== undefined) {
  828. for(const name in child.components) {
  829. const component = child.components[name];
  830. if(component.ar === this.ar && typeof component.hudContainer == 'function')
  831. huds.push(component.hudContainer());
  832. }
  833. }
  834. }
  835. if(huds.length > 1)
  836. throw new Error('Can\'t define multiple ar-hud\'s in an ar-viewport');
  837. else if(huds.length == 0)
  838. huds.push(undefined);
  839. return AR.Viewport(Object.assign(
  840. {
  841. container: this.el,
  842. hudContainer: huds[0],
  843. canvas: scene.canvas,
  844. resolution: this.data.resolution,
  845. style: this.data.style,
  846. },
  847. !fullscreenUI ? {} : { fullscreenUI: fullscreenUI.data.enabled }
  848. ));
  849. },
  850. }));
  851. AFRAME.registerPrimitive('ar-viewport', {
  852. defaultComponents: {
  853. 'ar-viewport': {}
  854. },
  855. mappings: {
  856. 'resolution': 'ar-viewport.resolution',
  857. 'style': 'ar-viewport.style',
  858. 'fullscreen-ui': 'ar-viewport-fullscreen-ui'
  859. }
  860. });
  861. AFRAME.registerComponent('ar-viewport-fullscreen-ui', ARComponent({
  862. schema: {
  863. /** whether or not to include the built-in fullscreen button */
  864. 'enabled': { type: 'boolean', default: true },
  865. }
  866. }));
  867. /**
  868. * AR Heads-Up Display
  869. */
  870. let hudStyle = (function() { // hide on page load
  871. const style = document.createElement('style');
  872. style.textContent = 'ar-hud, [ar-hud] { display: none; }';
  873. document.head.appendChild(style);
  874. return style;
  875. })();
  876. AFRAME.registerComponent('ar-hud', ARComponent({
  877. init()
  878. {
  879. if(hudStyle !== null) {
  880. document.head.removeChild(hudStyle);
  881. hudStyle = null;
  882. }
  883. this.el.hidden = true;
  884. },
  885. validate()
  886. {
  887. if(!this.el.parentNode.getAttribute('ar-viewport'))
  888. throw new Error('ar-hud must be a direct child of ar-viewport');
  889. },
  890. hudContainer()
  891. {
  892. return this.el;
  893. },
  894. }));
  895. AFRAME.registerPrimitive('ar-hud', {
  896. defaultComponents: {
  897. 'ar-hud': {}
  898. }
  899. });
  900. /* ========================================================================= */
  901. /**
  902. * Version check
  903. * @param {object} libs
  904. */
  905. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  906. {
  907. window.addEventListener('load', () => {
  908. try { AR, AFRAME;
  909. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'A-Frame': AFRAME.version };
  910. 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;
  911. for(const [lib, expected] of Object.entries(libs))
  912. check(lib, expected.version, versionOf[lib]);
  913. }
  914. catch(e) {
  915. alert(e.message);
  916. }
  917. });
  918. }
  919. })();