Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

aframe-with-encantar.js 25KB

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