You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

demo.js 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /**
  2. * Augmented Reality demo using the three.js plugin for encantar.js
  3. * @author Alexandre Martins <alemartf(at)gmail.com> (https://github.com/alemart/encantar-js)
  4. */
  5. (function() {
  6. // Validate
  7. if(typeof encantar === 'undefined')
  8. throw new Error(`Can't find the three.js plugin for encantar.js`);
  9. /**
  10. * Utilities for the Demo scene
  11. */
  12. class DemoUtils
  13. {
  14. async loadGLTF(filepath, yAxisIsUp = true)
  15. {
  16. const loader = new THREE.GLTFLoader();
  17. const gltf = await loader.loadAsync(filepath);
  18. // glTF defines +y as up. We expect +z to be up.
  19. if(yAxisIsUp)
  20. gltf.scene.rotateX(Math.PI / 2);
  21. return gltf;
  22. }
  23. createAnimationAction(gltf, name = null)
  24. {
  25. const mixer = new THREE.AnimationMixer(gltf.scene);
  26. const clips = gltf.animations;
  27. if(clips.length == 0)
  28. throw new Error('No animation clips');
  29. if(name === null) {
  30. const sortedNames = clips.map(clip => clip.name).sort();
  31. name = sortedNames[0];
  32. }
  33. const clip = THREE.AnimationClip.findByName(clips, name);
  34. const action = mixer.clipAction(clip);
  35. return action;
  36. }
  37. createImagePlane(imagepath)
  38. {
  39. const texture = new THREE.TextureLoader().load(imagepath);
  40. const geometry = new THREE.PlaneGeometry(1, 1);
  41. const material = new THREE.MeshBasicMaterial({
  42. map: texture,
  43. side: THREE.DoubleSide,
  44. });
  45. const mesh = new THREE.Mesh(geometry, material);
  46. return mesh;
  47. }
  48. switchToFrontView(ar)
  49. {
  50. // top view is the default
  51. ar.root.rotation.set(-Math.PI / 2, 0, 0);
  52. }
  53. referenceImage(ar)
  54. {
  55. if(ar.frame === null)
  56. return null;
  57. for(const result of ar.frame.results) {
  58. if(result.tracker.type == 'image-tracker') {
  59. if(result.trackables.length > 0) {
  60. const trackable = result.trackables[0];
  61. return trackable.referenceImage;
  62. }
  63. }
  64. }
  65. return null;
  66. }
  67. }
  68. /**
  69. * Demo scene
  70. */
  71. class DemoScene extends ARScene
  72. {
  73. /**
  74. * Constructor
  75. */
  76. constructor()
  77. {
  78. super();
  79. this._utils = new DemoUtils();
  80. this._objects = { };
  81. }
  82. /**
  83. * Start the AR session
  84. * @returns {Promise<Session>}
  85. */
  86. async startSession()
  87. {
  88. if(!AR.isSupported()) {
  89. throw new Error(
  90. 'This device is not compatible with this AR experience.\n\n' +
  91. 'User agent: ' + navigator.userAgent
  92. );
  93. }
  94. const tracker = AR.Tracker.ImageTracker();
  95. await tracker.database.add([{
  96. name: 'my-reference-image',
  97. image: document.getElementById('my-reference-image')
  98. }]);
  99. const viewport = AR.Viewport({
  100. container: document.getElementById('ar-viewport'),
  101. hudContainer: document.getElementById('ar-hud')
  102. });
  103. const video = document.getElementById('my-video');
  104. const useWebcam = (video === null);
  105. const source = useWebcam ?
  106. AR.Source.Camera({ resolution: 'md' }) :
  107. AR.Source.Video(video);
  108. const session = await AR.startSession({
  109. mode: 'immersive',
  110. viewport: viewport,
  111. trackers: [ tracker ],
  112. sources: [ source ],
  113. stats: true,
  114. gizmos: true,
  115. });
  116. const scan = document.getElementById('scan');
  117. tracker.addEventListener('targetfound', event => {
  118. session.gizmos.visible = false;
  119. if(scan)
  120. scan.hidden = true;
  121. });
  122. tracker.addEventListener('targetlost', event => {
  123. session.gizmos.visible = true;
  124. if(scan)
  125. scan.hidden = false;
  126. });
  127. return session;
  128. }
  129. /**
  130. * Initialize the augmented scene
  131. * @param {ARSystem} ar
  132. * @returns {Promise<void>}
  133. */
  134. async init(ar)
  135. {
  136. // Change the point of view. All virtual objects are descendants of
  137. // ar.root, a node that is automatically aligned to the physical scene.
  138. // Adjusting ar.root will adjust all virtual objects.
  139. this._utils.switchToFrontView(ar);
  140. ar.root.position.set(0, -0.5, 0);
  141. ar.root.scale.set(0.7, 0.7, 0.7);
  142. // add light
  143. const ambientLight = new THREE.AmbientLight(0xffffff);
  144. ambientLight.intensity = 1.4;
  145. ar.scene.add(ambientLight);
  146. // create the magic circle
  147. const magicCircle = this._utils.createImagePlane('../assets/magic-circle.png');
  148. magicCircle.material.color = new THREE.Color(0xbeefff);
  149. magicCircle.material.transparent = true;
  150. magicCircle.material.opacity = 1;
  151. magicCircle.scale.set(6, 6, 1);
  152. ar.root.add(magicCircle);
  153. // load the mage
  154. const gltf = await this._utils.loadGLTF('../assets/mage.glb');
  155. const mage = gltf.scene;
  156. ar.root.add(mage);
  157. // prepare the animation of the mage
  158. const animationAction = this._utils.createAnimationAction(gltf, 'Idle');
  159. animationAction.loop = THREE.LoopRepeat;
  160. animationAction.play();
  161. // save objects
  162. this._objects.mage = mage;
  163. this._objects.magicCircle = magicCircle;
  164. this._objects.animationAction = animationAction;
  165. }
  166. /**
  167. * Update / animate the augmented scene
  168. * @param {ARSystem} ar
  169. * @returns {void}
  170. */
  171. update(ar)
  172. {
  173. const TWO_PI = 2.0 * Math.PI;
  174. const ROTATIONS_PER_SECOND = 0.25;
  175. const delta = ar.session.time.delta; // given in seconds
  176. // animate the mage
  177. const animationAction = this._objects.animationAction;
  178. const mixer = animationAction.getMixer();
  179. mixer.update(delta);
  180. // animate the magic circle
  181. const magicCircle = this._objects.magicCircle;
  182. magicCircle.rotateZ(-TWO_PI * ROTATIONS_PER_SECOND * delta);
  183. }
  184. }
  185. /**
  186. * Enchant the scene
  187. * @returns {void}
  188. */
  189. function main()
  190. {
  191. const scene = new DemoScene();
  192. encantar(scene).catch(error => {
  193. alert(error.message);
  194. });
  195. }
  196. document.addEventListener('DOMContentLoaded', main);
  197. })();