您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

demo.js 6.2KB

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