Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

demo.js 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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.Image();
  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. * Preload resources before starting the AR session
  135. * @returns {Promise<void>}
  136. */
  137. async preload()
  138. {
  139. // preload meshes
  140. const [ mage, cat ] = await Promise.all([
  141. Utils.loadGLTF('../assets/mage.glb'),
  142. Utils.loadGLTF('../assets/cat.glb')
  143. ]);
  144. // save references
  145. this._objects.gltf = { mage, cat };
  146. }
  147. /**
  148. * Initialization
  149. * @param {ARSystem} ar
  150. * @returns {void}
  151. */
  152. init(ar)
  153. {
  154. // Change the point of view. All virtual objects are descendants of
  155. // ar.root, a node that is automatically aligned to the physical scene.
  156. // Adjusting ar.root will adjust all virtual objects.
  157. Utils.switchToFrontView(ar);
  158. ar.root.position.set(0, -0.8, 0);
  159. // Initialize objects
  160. this._initLight(ar);
  161. this._initText(ar);
  162. this._initMagicCircle(ar);
  163. this._initMage(ar);
  164. this._initCat(ar);
  165. // done!
  166. this._initialized = true;
  167. }
  168. /**
  169. * Animation loop
  170. * @param {ARSystem} ar
  171. * @returns {void}
  172. */
  173. update(ar)
  174. {
  175. const delta = ar.session.time.delta; // given in seconds
  176. // animate the objects of the scene
  177. this._animateMagicCircle(delta);
  178. this._animateMage(delta);
  179. this._animateCat(delta);
  180. }
  181. // ------------------------------------------------------------------------
  182. _initLight(ar)
  183. {
  184. const ambientLight = new THREE.AmbientLight(0xffffff);
  185. ambientLight.intensity = 1.5;
  186. ar.scene.add(ambientLight);
  187. }
  188. _initMagicCircle(ar)
  189. {
  190. // create a magic circle
  191. const magicCircle = Utils.createImagePlane('../assets/magic-circle.png');
  192. magicCircle.material.transparent = true;
  193. magicCircle.material.opacity = 1;
  194. magicCircle.scale.set(4, 4, 1);
  195. // make it a child of ar.root
  196. ar.root.add(magicCircle);
  197. // save a reference
  198. this._objects.magicCircle = magicCircle;
  199. }
  200. _initText(ar)
  201. {
  202. const text = Utils.createImagePlane('../assets/it-works.png');
  203. text.material.transparent = true;
  204. text.material.opacity = 1;
  205. text.position.set(0, -0.5, 2);
  206. text.scale.set(3, 1.5, 1);
  207. text.rotateX(Math.PI / 2);
  208. ar.root.add(text);
  209. this._objects.text = text;
  210. }
  211. _initMage(ar)
  212. {
  213. // load the mage
  214. const gltf = this._objects.gltf.mage;
  215. const mage = gltf.scene;
  216. mage.scale.set(0.7, 0.7, 0.7);
  217. // prepare the animation of the mage
  218. const mageAction = Utils.createAnimationAction(gltf, 'Idle');
  219. mageAction.play();
  220. // make the mage a child of ar.root
  221. ar.root.add(mage);
  222. // save references
  223. this._objects.mage = mage;
  224. this._objects.mageAction = mageAction;
  225. }
  226. _initCat(ar)
  227. {
  228. const gltf = this._objects.gltf.cat;
  229. const cat = gltf.scene;
  230. cat.scale.set(0.7, 0.7, 0.7);
  231. const catAction = Utils.createAnimationAction(gltf, 'Cheer');
  232. catAction.play();
  233. ar.root.add(cat);
  234. this._objects.cat = cat;
  235. this._objects.catAction = catAction;
  236. }
  237. _animate(action, delta)
  238. {
  239. const mixer = action.getMixer();
  240. mixer.update(delta);
  241. }
  242. _animateMage(delta)
  243. {
  244. this._animate(this._objects.mageAction, delta);
  245. }
  246. _animateCat(delta)
  247. {
  248. this._animate(this._objects.catAction, delta);
  249. }
  250. _animateMagicCircle(delta)
  251. {
  252. const TWO_PI = 2.0 * Math.PI;
  253. const ROTATIONS_PER_SECOND = 1.0 / 8.0;
  254. this._objects.magicCircle.rotateZ(-TWO_PI * ROTATIONS_PER_SECOND * delta);
  255. }
  256. _onTargetFound(referenceImage)
  257. {
  258. // make sure that the scene is initialized
  259. if(!this._initialized) {
  260. alert(`Target \"${referenceImage.name}\" was found, but the 3D scene is not yet initialized!`);
  261. return;
  262. }
  263. // change the scene based on the tracked image
  264. switch(referenceImage.name) {
  265. case 'mage':
  266. this._objects.mage.visible = true;
  267. this._objects.cat.visible = false;
  268. this._objects.text.visible = false;
  269. this._objects.magicCircle.material.color.set(0xbeefff);
  270. break;
  271. case 'cat':
  272. this._objects.mage.visible = false;
  273. this._objects.cat.visible = true;
  274. this._objects.text.visible = true;
  275. this._objects.magicCircle.material.color.set(0xffffaa);
  276. break;
  277. }
  278. }
  279. _onTargetLost(referenceImage)
  280. {
  281. }
  282. }
  283. /**
  284. * Start the Demo
  285. * @returns {void}
  286. */
  287. function main()
  288. {
  289. const demo = new EnchantedDemo();
  290. if(typeof encantar === 'undefined')
  291. throw new Error(`Can't find the three.js plugin for encantar.js`);
  292. encantar(demo).catch(error => {
  293. alert(error.message);
  294. });
  295. }
  296. document.addEventListener('DOMContentLoaded', main);
  297. })();