Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

aframe-with-encantar.js 26KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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.1' },
  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('encantar')) {
  150. scene.setAttribute('encantar', {}); // use a default encantar
  151. //throw new Error('Missing encantar 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['encantar'];
  334. if(sessionComponent === undefined)
  335. throw new Error('Missing encantar 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. * The encantar component enchants an a-scene with AR
  379. * Parameters of the AR scene are set in this component
  380. */
  381. AFRAME.registerComponent('encantar', ARComponent({
  382. schema: {
  383. /** session mode: "immersive" | "inline" */
  384. 'mode': { type: 'string', default: 'immersive' },
  385. /** show stats panel? */
  386. 'stats': { type: 'boolean', default: false },
  387. /** show gizmos? */
  388. 'gizmos': { type: 'boolean', default: false },
  389. /** start the session automatically? */
  390. 'autoplay': { type: 'boolean', default: true },
  391. },
  392. sceneOnly: true,
  393. _started: false,
  394. init()
  395. {
  396. this._started = false;
  397. },
  398. play()
  399. {
  400. // start the session (run once)
  401. if(!this._started) {
  402. this._started = true;
  403. if(this.data.autoplay)
  404. this.startSession();
  405. }
  406. },
  407. remove()
  408. {
  409. // end the session
  410. if(this.ar.session !== null)
  411. this.ar.session.end();
  412. },
  413. preferences()
  414. {
  415. return {
  416. mode: this.data.mode,
  417. stats: this.data.stats,
  418. gizmos: this.data.gizmos
  419. };
  420. },
  421. startSession()
  422. {
  423. return this.ar.startSession();
  424. },
  425. }));
  426. /* ========================================================================= */
  427. /**
  428. * AR Camera
  429. */
  430. AFRAME.registerComponent('ar-camera', ARComponent({
  431. dependencies: ['camera'],
  432. init()
  433. {
  434. const el = this.el;
  435. el.setAttribute('camera', { active: true });
  436. el.setAttribute('wasd-controls', { enabled: false });
  437. el.setAttribute('look-controls', { enabled: false });
  438. el.setAttribute('position', { x: 0, y: 0, z: 0 }); // A-Frame sets y = 1.6m for VR
  439. const camera = el.getObject3D('camera');
  440. camera.matrixAutoUpdate = false;
  441. },
  442. tick()
  443. {
  444. const ar = this.ar;
  445. const el = this.el;
  446. const tracked = ar._utils.findTrackedImage(ar.frame);
  447. if(tracked === null)
  448. return;
  449. const camera = el.getObject3D('camera');
  450. camera.projectionMatrix.fromArray(tracked.projectionMatrix.read());
  451. camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
  452. camera.matrix.fromArray(tracked.viewMatrixInverse.read());
  453. camera.updateMatrixWorld(true);
  454. //console.log('projectionMatrix', tracked.projectionMatrix.read());
  455. //console.log('viewMatrixInverse', tracked.viewMatrixInverse.read());
  456. },
  457. validate()
  458. {
  459. if(!this.el.getAttribute('camera'))
  460. throw new Error('Incorrect ar-camera');
  461. if(this.el.parentNode !== this.el.sceneEl)
  462. throw new Error('ar-camera must be a direct child of a-scene');
  463. },
  464. }));
  465. AFRAME.registerPrimitive('ar-camera', {
  466. defaultComponents: {
  467. 'ar-camera': {},
  468. 'camera': {}
  469. }
  470. });
  471. /**
  472. * AR Root node
  473. */
  474. AFRAME.registerComponent('ar-root', ARComponent({
  475. schema: {
  476. /** the name of a reference image (target) or the empty string (to match any target) */
  477. 'referenceImage': { type: 'string', default: '' },
  478. },
  479. _origin: null,
  480. _firstRun: true,
  481. init()
  482. {
  483. const origin = new THREE.Group();
  484. origin.matrixAutoUpdate = false;
  485. const root = this.el.object3D;
  486. root.parent.add(origin);
  487. origin.add(root);
  488. this._origin = origin;
  489. this._firstRun = true;
  490. this.ar.registerRoot(this);
  491. },
  492. remove()
  493. {
  494. const origin = this._origin;
  495. const root = this.el.object3D;
  496. origin.parent.add(root);
  497. origin.removeFromParent();
  498. this._origin = null;
  499. this.ar.unregisterRoot(this);
  500. },
  501. play()
  502. {
  503. const origin = this._origin;
  504. origin.visible = true;
  505. if(this._firstRun) {
  506. this._firstRun = false;
  507. origin.visible = false;
  508. this.el.pause();
  509. }
  510. },
  511. pause()
  512. {
  513. const origin = this._origin;
  514. origin.visible = false;
  515. },
  516. teek()
  517. {
  518. const ar = this.ar;
  519. const targetName = this.data.referenceImage;
  520. const tracked = ar._utils.findTrackedImage(ar.frame, targetName);
  521. if(tracked === null) {
  522. this.el.pause();
  523. return;
  524. }
  525. const origin = this._origin;
  526. origin.matrix.fromArray(tracked.modelMatrix.read());
  527. origin.updateMatrixWorld(true);
  528. this.el.play();
  529. //console.log('modelMatrix', tracked.modelMatrix.toString());
  530. },
  531. validate()
  532. {
  533. if(this.el.parentNode !== this.el.sceneEl)
  534. throw new Error('ar-root must be a direct child of a-scene');
  535. },
  536. }));
  537. AFRAME.registerPrimitive('ar-root', {
  538. defaultComponents: {
  539. 'ar-root': {}
  540. },
  541. mappings: {
  542. 'reference-image': 'ar-root.referenceImage'
  543. }
  544. });
  545. /* ========================================================================= */
  546. /**
  547. * AR Sources
  548. */
  549. AFRAME.registerComponent('ar-sources', ARComponent({
  550. validate()
  551. {
  552. if(this.el.parentNode !== this.el.sceneEl)
  553. throw new Error('ar-sources must be a direct child of a-scene');
  554. },
  555. sources()
  556. {
  557. const sources = [];
  558. for(const child of this.el.children) {
  559. if(child.components !== undefined) {
  560. for(const name in child.components) {
  561. const component = child.components[name];
  562. if(component.ar === this.ar && typeof component.source == 'function')
  563. sources.push(component.source());
  564. }
  565. }
  566. }
  567. return sources;
  568. },
  569. }));
  570. AFRAME.registerPrimitive('ar-sources', {
  571. defaultComponents: {
  572. 'ar-sources': {}
  573. }
  574. });
  575. /**
  576. * AR Camera Source
  577. */
  578. AFRAME.registerComponent('ar-camera-source', ARComponent({
  579. schema: {
  580. /** video resolution */
  581. 'resolution': { type: 'string', default: 'md' },
  582. /** facing mode: "environment" | "user" */
  583. 'facingMode': { type: 'string', default: 'environment' },
  584. },
  585. validate()
  586. {
  587. if(!this.el.parentNode.getAttribute('ar-sources'))
  588. throw new Error('ar-camera-source must be a direct child of ar-sources');
  589. },
  590. source()
  591. {
  592. return AR.Source.Camera({
  593. resolution: this.data.resolution,
  594. constraints: {
  595. facingMode: this.data.facingMode
  596. }
  597. });
  598. },
  599. }));
  600. AFRAME.registerPrimitive('ar-camera-source', {
  601. defaultComponents: {
  602. 'ar-camera-source': {}
  603. },
  604. mappings: {
  605. 'resolution': 'ar-camera-source.resolution',
  606. 'facing-mode': 'ar-camera-source.facingMode',
  607. }
  608. });
  609. /**
  610. * AR Video Source
  611. */
  612. AFRAME.registerComponent('ar-video-source', ARComponent({
  613. schema: {
  614. /** selector for a <video> element */
  615. 'video': { type: 'selector' },
  616. },
  617. validate()
  618. {
  619. if(!this.el.parentNode.getAttribute('ar-sources'))
  620. throw new Error('ar-video-source must be a direct child of ar-sources');
  621. },
  622. source()
  623. {
  624. return AR.Source.Video(this.data.video);
  625. },
  626. }));
  627. AFRAME.registerPrimitive('ar-video-source', {
  628. defaultComponents: {
  629. 'ar-video-source': {}
  630. },
  631. mappings: {
  632. 'video': 'ar-video-source.video'
  633. }
  634. });
  635. /**
  636. * AR Canvas Source
  637. */
  638. AFRAME.registerComponent('ar-canvas-source', ARComponent({
  639. schema: {
  640. /** selector for a <canvas> element */
  641. 'canvas': { type: 'selector' },
  642. },
  643. validate()
  644. {
  645. if(!this.el.parentNode.getAttribute('ar-sources'))
  646. throw new Error('ar-canvas-source must be a direct child of ar-sources');
  647. },
  648. source()
  649. {
  650. return AR.Source.Canvas(this.data.canvas);
  651. },
  652. }));
  653. AFRAME.registerPrimitive('ar-canvas-source', {
  654. defaultComponents: {
  655. 'ar-canvas-source': {}
  656. },
  657. mappings: {
  658. 'canvas': 'ar-canvas-source.canvas'
  659. }
  660. });
  661. /**
  662. * AR Pointer Source
  663. */
  664. AFRAME.registerComponent('ar-pointer-source', ARComponent({
  665. schema: {
  666. },
  667. validate()
  668. {
  669. if(!this.el.parentNode.getAttribute('ar-sources'))
  670. throw new Error('ar-pointer-source must be a direct child of ar-sources');
  671. },
  672. source()
  673. {
  674. return AR.Source.Pointer();
  675. },
  676. }));
  677. AFRAME.registerPrimitive('ar-pointer-source', {
  678. defaultComponents: {
  679. 'ar-pointer-source': {}
  680. },
  681. mappings: {
  682. }
  683. });
  684. /* ========================================================================= */
  685. /**
  686. * AR Trackers
  687. */
  688. AFRAME.registerComponent('ar-trackers', ARComponent({
  689. validate()
  690. {
  691. if(this.el.parentNode !== this.el.sceneEl)
  692. throw new Error('ar-trackers must be a direct child of a-scene');
  693. },
  694. /* async */ trackers()
  695. {
  696. const trackers = [];
  697. for(const child of this.el.children) {
  698. if(child.components !== undefined) {
  699. for(const name in child.components) {
  700. const component = child.components[name];
  701. if(component.ar === this.ar && typeof component.tracker == 'function')
  702. trackers.push(component.tracker());
  703. }
  704. }
  705. }
  706. return Speedy.Promise.all(trackers);
  707. },
  708. }));
  709. AFRAME.registerPrimitive('ar-trackers', {
  710. defaultComponents: {
  711. 'ar-trackers': {}
  712. }
  713. });
  714. /**
  715. * AR Image Tracker
  716. */
  717. AFRAME.registerComponent('ar-image-tracker', ARComponent({
  718. schema: {
  719. /** resolution of the tracker */
  720. 'resolution': { type: 'string', default: 'sm' },
  721. },
  722. validate()
  723. {
  724. if(!this.el.parentNode.getAttribute('ar-trackers'))
  725. throw new Error('ar-image-tracker must be a direct child of ar-trackers');
  726. },
  727. /* async */ tracker()
  728. {
  729. const tracker = AR.Tracker.Image();
  730. const referenceImages = [];
  731. tracker.resolution = this.data.resolution;
  732. for(const child of this.el.children) {
  733. if(child.components !== undefined) {
  734. for(const name in child.components) {
  735. const component = child.components[name];
  736. if(component.ar === this.ar && typeof component.referenceImage == 'function')
  737. referenceImages.push(component.referenceImage());
  738. }
  739. }
  740. }
  741. return tracker.database.add(referenceImages).then(() => tracker);
  742. },
  743. }));
  744. AFRAME.registerPrimitive('ar-image-tracker', {
  745. defaultComponents: {
  746. 'ar-image-tracker': {}
  747. }
  748. });
  749. /**
  750. * AR Reference Image
  751. */
  752. AFRAME.registerComponent('ar-reference-image', ARComponent({
  753. schema: {
  754. /** the name of the reference image */
  755. 'name': { type: 'string', default: '' },
  756. /** URL of an image */
  757. 'src': { type: 'string', default: '' }
  758. },
  759. validate()
  760. {
  761. if(!this.el.parentNode.getAttribute('ar-image-tracker'))
  762. throw new Error('ar-reference-image must be a direct child of ar-image-tracker');
  763. },
  764. referenceImage()
  765. {
  766. if(this.data.src == '')
  767. throw new Error('Unspecified src attribute of ar-reference-image');
  768. const img = new Image();
  769. img.src = this.data.src;
  770. return {
  771. name: this.data.name != '' ? this.data.name : undefined,
  772. image: img
  773. };
  774. }
  775. }));
  776. AFRAME.registerPrimitive('ar-reference-image', {
  777. defaultComponents: {
  778. 'ar-reference-image': {}
  779. },
  780. mappings: {
  781. 'name': 'ar-reference-image.name',
  782. 'src': 'ar-reference-image.src'
  783. }
  784. });
  785. /**
  786. * AR Pointer Tracker
  787. */
  788. AFRAME.registerComponent('ar-pointer-tracker', ARComponent({
  789. schema: {
  790. /** the space in which pointers will be located */
  791. 'space': { type: 'string', default: 'normalized' },
  792. },
  793. validate()
  794. {
  795. if(!this.el.parentNode.getAttribute('ar-trackers'))
  796. throw new Error('ar-pointer-tracker must be a direct child of ar-trackers');
  797. },
  798. tracker()
  799. {
  800. return AR.Tracker.Pointer({
  801. space: this.data.space
  802. });
  803. },
  804. }));
  805. AFRAME.registerPrimitive('ar-pointer-tracker', {
  806. defaultComponents: {
  807. 'ar-pointer-tracker': {}
  808. },
  809. mappings: {
  810. 'space': 'ar-pointer-tracker.space'
  811. }
  812. });
  813. /* ========================================================================= */
  814. /**
  815. * AR Viewport
  816. */
  817. AFRAME.registerComponent('ar-viewport', ARComponent({
  818. schema: {
  819. /** viewport resolution */
  820. 'resolution': { type: 'string', default: 'lg' },
  821. /** viewport style: "best-fit" | "stretch" | "inline" */
  822. 'style': { type: 'string', default: 'best-fit' },
  823. },
  824. validate()
  825. {
  826. if(this.el.parentNode !== this.el.sceneEl)
  827. throw new Error('ar-viewport must be a direct child of a-scene');
  828. },
  829. viewport()
  830. {
  831. const scene = this.el.sceneEl;
  832. const huds = [];
  833. const fullscreenUI = this.el.components['ar-viewport-fullscreen-ui'];
  834. for(const child of this.el.children) {
  835. if(child.components !== undefined) {
  836. for(const name in child.components) {
  837. const component = child.components[name];
  838. if(component.ar === this.ar && typeof component.hudContainer == 'function')
  839. huds.push(component.hudContainer());
  840. }
  841. }
  842. }
  843. if(huds.length > 1)
  844. throw new Error('Can\'t define multiple ar-hud\'s in an ar-viewport');
  845. else if(huds.length == 0)
  846. huds.push(undefined);
  847. return AR.Viewport(Object.assign(
  848. {
  849. container: this.el,
  850. hudContainer: huds[0],
  851. canvas: scene.canvas,
  852. resolution: this.data.resolution,
  853. style: this.data.style,
  854. },
  855. !fullscreenUI ? {} : { fullscreenUI: fullscreenUI.data.enabled }
  856. ));
  857. },
  858. }));
  859. AFRAME.registerPrimitive('ar-viewport', {
  860. defaultComponents: {
  861. 'ar-viewport': {}
  862. },
  863. mappings: {
  864. 'resolution': 'ar-viewport.resolution',
  865. 'style': 'ar-viewport.style',
  866. 'fullscreen-ui': 'ar-viewport-fullscreen-ui'
  867. }
  868. });
  869. AFRAME.registerComponent('ar-viewport-fullscreen-ui', ARComponent({
  870. schema: {
  871. /** whether or not to include the built-in fullscreen button */
  872. 'enabled': { type: 'boolean', default: true },
  873. }
  874. }));
  875. /**
  876. * AR Heads-Up Display
  877. */
  878. let hudStyle = (function() { // hide on page load
  879. const style = document.createElement('style');
  880. style.textContent = 'ar-hud, [ar-hud] { display: none; }';
  881. document.head.appendChild(style);
  882. return style;
  883. })();
  884. AFRAME.registerComponent('ar-hud', ARComponent({
  885. init()
  886. {
  887. if(hudStyle !== null) {
  888. document.head.removeChild(hudStyle);
  889. hudStyle = null;
  890. }
  891. this.el.hidden = true;
  892. },
  893. validate()
  894. {
  895. if(!this.el.parentNode.getAttribute('ar-viewport'))
  896. throw new Error('ar-hud must be a direct child of ar-viewport');
  897. },
  898. hudContainer()
  899. {
  900. return this.el;
  901. },
  902. }));
  903. AFRAME.registerPrimitive('ar-hud', {
  904. defaultComponents: {
  905. 'ar-hud': {}
  906. }
  907. });
  908. /* ========================================================================= */
  909. /**
  910. * Version check
  911. * @param {object} libs
  912. */
  913. function __THIS_PLUGIN_HAS_BEEN_TESTED_WITH__(libs)
  914. {
  915. window.addEventListener('load', () => {
  916. try { AR, AFRAME;
  917. const versionOf = { 'encantar.js': AR.version.replace(/-.*$/, ''), 'A-Frame': AFRAME.version };
  918. 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;
  919. for(const [lib, expected] of Object.entries(libs))
  920. check(lib, expected.version, versionOf[lib]);
  921. }
  922. catch(e) {
  923. alert(e.message);
  924. }
  925. });
  926. }
  927. })();