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 27KB

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