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

aframe-with-encantar.js 27KB

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