Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

demo.js 9.1KB

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