Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

aframe-with-encantar.js 27KB

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