Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

demo.js 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. /**
  7. * Utilities for the Demo
  8. */
  9. class Utils
  10. {
  11. static async loadGLTF(filepath, yAxisIsUp = true)
  12. {
  13. const loader = new THREE.GLTFLoader();
  14. const gltf = await loader.loadAsync(filepath);
  15. // glTF defines +y as up. We expect +z to be up (when XY is the ground plane)
  16. if(yAxisIsUp)
  17. gltf.scene.rotateX(Math.PI / 2);
  18. return gltf;
  19. }
  20. static createAnimationAction(gltf, name = null, loop = THREE.LoopRepeat)
  21. {
  22. const mixer = new THREE.AnimationMixer(gltf.scene);
  23. const clips = gltf.animations;
  24. if(clips.length == 0)
  25. throw new Error('No animation clips');
  26. if(name === null) {
  27. const sortedNames = clips.map(clip => clip.name).sort();
  28. name = sortedNames[0];
  29. }
  30. const clip = THREE.AnimationClip.findByName(clips, name);
  31. const action = mixer.clipAction(clip);
  32. action.loop = loop;
  33. return action;
  34. }
  35. static createImagePlane(imagepath)
  36. {
  37. const texture = new THREE.TextureLoader().load(imagepath);
  38. const geometry = new THREE.PlaneGeometry(1, 1);
  39. const material = new THREE.MeshBasicMaterial({
  40. map: texture,
  41. side: THREE.DoubleSide,
  42. });
  43. const mesh = new THREE.Mesh(geometry, material);
  44. return mesh;
  45. }
  46. static switchToFrontView(ar)
  47. {
  48. // top view is the default
  49. ar.root.rotation.set(-Math.PI / 2, 0, 0);
  50. }
  51. static referenceImageName(ar)
  52. {
  53. if(ar.frame === null)
  54. return null;
  55. for(const result of ar.frame.results) {
  56. if(result.tracker.type == 'image-tracker') {
  57. if(result.trackables.length > 0) {
  58. const trackable = result.trackables[0];
  59. return trackable.referenceImage.name;
  60. }
  61. }
  62. }
  63. return null;
  64. }
  65. }
  66. /**
  67. * Augmented Reality Demo
  68. */
  69. class EnchantedDemo extends ARDemo
  70. {
  71. /**
  72. * Constructor
  73. */
  74. constructor()
  75. {
  76. super();
  77. this._objects = { };
  78. this._initialized = false;
  79. }
  80. /**
  81. * Start the AR session
  82. * @returns {Promise<Session>}
  83. */
  84. async startSession()
  85. {
  86. if(!AR.isSupported()) {
  87. throw new Error(
  88. 'This device is not compatible with this AR experience.\n\n' +
  89. 'User agent: ' + navigator.userAgent
  90. );
  91. }
  92. const tracker = AR.Tracker.ImageTracker();
  93. await tracker.database.add([
  94. {
  95. name: 'mage',
  96. image: document.getElementById('mage')
  97. },
  98. {
  99. name: 'cat',
  100. image: document.getElementById('cat')
  101. }
  102. ]);
  103. const viewport = AR.Viewport({
  104. container: document.getElementById('ar-viewport'),
  105. hudContainer: document.getElementById('ar-hud')
  106. });
  107. const video = document.getElementById('my-video');
  108. const useWebcam = (video === null);
  109. const source = useWebcam ? AR.Source.Camera() : AR.Source.Video(video);
  110. const session = await AR.startSession({
  111. mode: 'immersive',
  112. viewport: viewport,
  113. trackers: [ tracker ],
  114. sources: [ source ],
  115. stats: true,
  116. gizmos: true,
  117. });
  118. const scan = document.getElementById('scan');
  119. tracker.addEventListener('targetfound', event => {
  120. session.gizmos.visible = false;
  121. if(scan)
  122. scan.hidden = true;
  123. this._onTargetFound(event.referenceImage);
  124. });
  125. tracker.addEventListener('targetlost', event => {
  126. session.gizmos.visible = true;
  127. if(scan)
  128. scan.hidden = false;
  129. this._onTargetLost(event.referenceImage);
  130. });
  131. return session;
  132. }
  133. /**
  134. * Initialization
  135. * @param {ARSystem} ar
  136. * @returns {Promise<void>}
  137. */
  138. async init(ar)
  139. {
  140. // Change the point of view. All virtual objects are descendants of
  141. // ar.root, a node that is automatically aligned to the physical scene.
  142. // Adjusting ar.root will adjust all virtual objects.
  143. Utils.switchToFrontView(ar);
  144. ar.root.position.set(0, -0.8, 0);
  145. // Initialize objects
  146. this._initLight(ar);
  147. this._initText(ar);
  148. this._initMagicCircle(ar);
  149. await Promise.all([
  150. this._initMage(ar),
  151. this._initCat(ar),
  152. ]);
  153. // done!
  154. this._initialized = true;
  155. }
  156. /**
  157. * Animation loop
  158. * @param {ARSystem} ar
  159. * @returns {void}
  160. */
  161. update(ar)
  162. {
  163. const delta = ar.session.time.delta; // given in seconds
  164. // animate the objects of the scene
  165. this._animateMagicCircle(delta);
  166. this._animateMage(delta);
  167. this._animateCat(delta);
  168. }
  169. // ------------------------------------------------------------------------
  170. _initLight(ar)
  171. {
  172. const ambientLight = new THREE.AmbientLight(0xffffff);
  173. ambientLight.intensity = 1.5;
  174. ar.scene.add(ambientLight);
  175. }
  176. _initMagicCircle(ar)
  177. {
  178. // create a magic circle
  179. const magicCircle = Utils.createImagePlane('../assets/magic-circle.png');
  180. magicCircle.material.transparent = true;
  181. magicCircle.material.opacity = 1;
  182. magicCircle.scale.set(4, 4, 1);
  183. // make it a child of ar.root
  184. ar.root.add(magicCircle);
  185. // save a reference
  186. this._objects.magicCircle = magicCircle;
  187. }
  188. _initText(ar)
  189. {
  190. const text = Utils.createImagePlane('../assets/it-works.png');
  191. text.material.transparent = true;
  192. text.material.opacity = 1;
  193. text.position.set(0, -0.5, 2);
  194. text.scale.set(3, 1.5, 1);
  195. text.rotateX(Math.PI / 2);
  196. ar.root.add(text);
  197. this._objects.text = text;
  198. }
  199. async _initMage(ar)
  200. {
  201. // load the mage
  202. const gltf = await Utils.loadGLTF('../assets/mage.glb');
  203. const mage = gltf.scene;
  204. mage.scale.set(0.7, 0.7, 0.7);
  205. // prepare the animation of the mage
  206. const mageAction = Utils.createAnimationAction(gltf, 'Idle');
  207. mageAction.play();
  208. // make the mage a child of ar.root
  209. ar.root.add(mage);
  210. // save references
  211. this._objects.mage = mage;
  212. this._objects.mageAction = mageAction;
  213. }
  214. async _initCat(ar)
  215. {
  216. const gltf = await Utils.loadGLTF('../assets/cat.glb');
  217. const cat = gltf.scene;
  218. cat.scale.set(0.7, 0.7, 0.7);
  219. const catAction = Utils.createAnimationAction(gltf, 'Cheer');
  220. catAction.play();
  221. ar.root.add(cat);
  222. this._objects.cat = cat;
  223. this._objects.catAction = catAction;
  224. }
  225. _animate(action, delta)
  226. {
  227. const mixer = action.getMixer();
  228. mixer.update(delta);
  229. }
  230. _animateMage(delta)
  231. {
  232. this._animate(this._objects.mageAction, delta);
  233. }
  234. _animateCat(delta)
  235. {
  236. this._animate(this._objects.catAction, delta);
  237. }
  238. _animateMagicCircle(delta)
  239. {
  240. const TWO_PI = 2.0 * Math.PI;
  241. const ROTATIONS_PER_SECOND = 1.0 / 8.0;
  242. this._objects.magicCircle.rotateZ(-TWO_PI * ROTATIONS_PER_SECOND * delta);
  243. }
  244. _onTargetFound(referenceImage)
  245. {
  246. // make sure that the scene is initialized
  247. if(!this._initialized) {
  248. alert(`Target \"${referenceImage.name}\" was found, but the 3D scene is not yet initialized!`);
  249. return;
  250. }
  251. // change the scene based on the tracked image
  252. switch(referenceImage.name) {
  253. case 'mage':
  254. this._objects.mage.visible = true;
  255. this._objects.cat.visible = false;
  256. this._objects.text.visible = false;
  257. this._objects.magicCircle.material.color.set(0xbeefff);
  258. break;
  259. case 'cat':
  260. this._objects.mage.visible = false;
  261. this._objects.cat.visible = true;
  262. this._objects.text.visible = true;
  263. this._objects.magicCircle.material.color.set(0xffffaa);
  264. break;
  265. }
  266. }
  267. _onTargetLost(referenceImage)
  268. {
  269. }
  270. }
  271. /**
  272. * Start the Demo
  273. * @returns {void}
  274. */
  275. function main()
  276. {
  277. const demo = new EnchantedDemo();
  278. if(typeof encantar === 'undefined')
  279. throw new Error(`Can't find the three.js plugin for encantar.js`);
  280. encantar(demo).catch(error => {
  281. alert(error.message);
  282. });
  283. }
  284. document.addEventListener('DOMContentLoaded', main);
  285. })();