aframe-components.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2018 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. */
  5. if (typeof AFRAME === 'undefined') {
  6. throw new Error('Component attempted to register before AFRAME was available.');
  7. }
  8. AFRAME.registerComponent('avatar', {
  9. init: function () {
  10. },
  11. tick: function () {
  12. }
  13. })
  14. AFRAME.registerComponent('scene-utils', {
  15. init: function () {
  16. this.mirrors = {};
  17. //this.setCameraControl();
  18. const sceneEnterVR = (e) => {
  19. let driver = vwf.views["vwf/view/aframe"];
  20. // let avatarEl = document.querySelector('#avatarControlParent');
  21. let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  22. driver.hmd = true;
  23. if (driver.threeDoFMobile || _app.config.d3DoF ) {
  24. driver.threeDoF = true;
  25. vwf_view.kernel.callMethod(avatarID, "updateYPositionForXR", [0.0]);
  26. } else if (driver.sixDoFMobile || driver.sixDoFDesktop || _app.config.d6DoF ) {
  27. driver.sixDoF = true;
  28. }
  29. }
  30. const sceneExitVR = (e) => {
  31. let driver = vwf.views["vwf/view/aframe"];
  32. let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  33. driver.hmd = false;
  34. if (driver.threeDoFMobile || _app.config.d3DoF ) {
  35. driver.threeDoF = false;
  36. vwf_view.kernel.callMethod(avatarID, "updateYPositionForXR", [-1.6]);
  37. } else if (driver.sixDoFMobile || driver.sixDoFDesktop || _app.config.d6DoF ) {
  38. driver.sixDoF = false;
  39. }
  40. }
  41. this.el.sceneEl.addEventListener('enter-vr', sceneEnterVR);
  42. this.el.sceneEl.addEventListener('exit-vr', sceneExitVR);
  43. },
  44. setCameraControl(){
  45. let avatarEl = document.querySelector('#avatarControl');
  46. document.addEventListener('keydown', (event) => {
  47. const keyName = event.key;
  48. if (keyName === 'Alt') {
  49. // do not alert when only Control key is pressed.
  50. console.log(keyName, ' pressed');
  51. avatarEl.setAttribute('look-controls', 'enabled', true)
  52. return;
  53. }
  54. })
  55. document.addEventListener('keyup', (event) => {
  56. const keyName = event.key;
  57. if (keyName === 'Alt') {
  58. // do not alert when only Control key is pressed.
  59. console.log(keyName, ' released');
  60. avatarEl.setAttribute('look-controls', 'enabled', false)
  61. return;
  62. }
  63. })
  64. },
  65. update: function () {
  66. },
  67. tick: function (t) {
  68. Object.values(this.mirrors).forEach(el => {
  69. el.mirrorTick.call(el)
  70. })
  71. }
  72. })
  73. AFRAME.registerComponent('linepath', {
  74. schema: {
  75. color: { default: '#000' },
  76. width: { default: 0.01 },
  77. path: {
  78. default: [
  79. { x: -0.5, y: 0, z: 0 },
  80. { x: 0.5, y: 0, z: 0 }
  81. ]
  82. // Deserialize path in the form of comma-separated vec3s: `0 0 0, 1 1 1, 2 0 3`.
  83. // parse: function (value) {
  84. // return value.split(',').map(coordinates.parse);
  85. // },
  86. // Serialize array of vec3s in case someone does setAttribute('line', 'path', [...]).
  87. // stringify: function (data) {
  88. // return data.map(coordinates.stringify).join(',');
  89. // }
  90. }
  91. },
  92. update: function () {
  93. var material = new MeshLineMaterial({
  94. color: new THREE.Color(this.data.color), //this.data.color
  95. lineWidth: this.data.width
  96. });
  97. var geometry = new THREE.Geometry();
  98. this.data.path.forEach(function (vec3) {
  99. geometry.vertices.push(
  100. new THREE.Vector3(vec3.x, vec3.y, vec3.z)
  101. );
  102. });
  103. let line = new MeshLine();
  104. line.setGeometry(geometry);
  105. //new THREE.Line(geometry, material)
  106. this.el.setObject3D('mesh', new THREE.Mesh(line.geometry, material));
  107. },
  108. remove: function () {
  109. this.el.removeObject3D('mesh');
  110. }
  111. });
  112. AFRAME.registerComponent('gizmo', {
  113. schema: {
  114. mode: { default: 'translate' }
  115. },
  116. update: function (old) {
  117. let modes = ['translate', 'rotate', 'scale'];
  118. if (!this.gizmo) {
  119. let newMode = modes.filter(el => {
  120. return el == this.data.mode
  121. })
  122. if (newMode.length !== 0) {
  123. this.mode = this.data.mode
  124. this.transformControls.setMode(this.mode)
  125. }
  126. }
  127. },
  128. init: function () {
  129. let self = this
  130. this.mode = this.data.mode
  131. let activeCamera = document.querySelector('#avatarControl').getObject3D('camera');
  132. let renderer = this.el.sceneEl.renderer;
  133. this.transformControls = new THREE.TransformControls(activeCamera, renderer.domElement);
  134. this.transformControls.attach(this.el.object3D);
  135. this.el.sceneEl.setObject3D('control-' + this.el.id, this.transformControls);
  136. this.transformControls.addEventListener('change', function (evt) {
  137. // console.log('changed');
  138. var object = self.transformControls.object;
  139. if (object === undefined) {
  140. return;
  141. }
  142. var transformMode = self.transformControls.getMode();
  143. switch (transformMode) {
  144. case 'translate':
  145. vwf_view.kernel.setProperty(object.el.id, 'position',
  146. [object.position.x, object.position.y, object.position.z])
  147. break;
  148. case 'rotate':
  149. // let q = (new THREE.Quaternion()).setFromEuler(new THREE.Euler(
  150. // (object.rotation.x),
  151. // (object.rotation.y),
  152. // (object.rotation.z), 'XYZ'
  153. // ));
  154. // let angle = (new THREE.Euler()).setFromQuaternion(q, 'YXZ');
  155. // vwf_view.kernel.setProperty(object.el.id, 'rotation', [THREE.Math.radToDeg(angle.x), THREE.Math.radToDeg(angle.y), THREE.Math.radToDeg(angle.z)])
  156. vwf_view.kernel.setProperty(object.el.id, 'rotation',
  157. [THREE.Math.radToDeg(object.rotation.x), THREE.Math.radToDeg(object.rotation.y), THREE.Math.radToDeg(object.rotation.z)])
  158. break;
  159. case 'scale':
  160. vwf_view.kernel.setProperty(object.el.id, 'scale',
  161. [object.scale.x, object.scale.y, object.scale.z])
  162. break;
  163. }
  164. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  165. });
  166. },
  167. remove: function () {
  168. this.transformControls.detach();
  169. this.el.sceneEl.removeObject3D('control-' + this.el.id);
  170. },
  171. // tick: function (t) {
  172. // // this.transformControls.update();
  173. // }
  174. });
  175. AFRAME.registerComponent('cursor-listener', {
  176. init: function () {
  177. this.el.addEventListener('click', function (evt) {
  178. console.log('I was clicked at: ', evt.detail.intersection.point);
  179. let cursorID = 'cursor-avatar-' + vwf_view.kernel.moniker();
  180. if (evt.detail.cursorEl.id.includes(vwf_view.kernel.moniker())) {
  181. vwf_view.kernel.fireEvent(evt.detail.intersection.object.el.id, "clickEvent", [vwf_view.kernel.moniker()])
  182. }
  183. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  184. });
  185. }
  186. });
  187. AFRAME.registerComponent('aabb-collider-listener', {
  188. // If the target collidable object is moving, set <a-entity data-aabb-collider-dynamic> on the target. By default, collidable objects are presumed to be static for performance purposes.
  189. init: function () {
  190. // let self = this;
  191. // this.me = vwf_view.kernel.moniker();
  192. this.el.addEventListener('hitstart', function (evt) {
  193. vwf_view.kernel.fireEvent(evt.target.id, "hitstartEvent");
  194. })
  195. this.el.addEventListener('hitend', function (evt) {
  196. vwf_view.kernel.fireEvent(evt.target.id, "hitendEvent");
  197. })
  198. }
  199. });
  200. AFRAME.registerComponent('raycaster-listener', {
  201. init: function () {
  202. let self = this;
  203. this.intersected = false;
  204. this.casters = {}
  205. this.me = vwf_view.kernel.moniker();
  206. this.driver = vwf.views["vwf/view/aframe"];
  207. this.el.addEventListener('raycaster-intersected', function (evt) {
  208. if (evt.detail.el.nodeName == 'A-CURSOR') {
  209. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  210. } else {
  211. if (self.intersected) {
  212. } else {
  213. console.log('I was intersected at: ', evt.target);//evt.detail.getIntersection().point);
  214. vwf_view.kernel.fireEvent(evt.target.id, "intersectEvent");
  215. }
  216. self.casters[evt.target.id] = evt.target;
  217. self.intersected = true;
  218. }
  219. });
  220. this.el.addEventListener('raycaster-intersected-cleared', function (evt) {
  221. if (evt.detail.el.nodeName == 'A-CURSOR') {
  222. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  223. } else {
  224. if (self.intersected) {
  225. console.log('Clear intersection');
  226. if (Object.entries(self.casters).length == 1 && (self.casters[evt.target.id] !== undefined)) {
  227. vwf_view.kernel.fireEvent(evt.target.id, "clearIntersectEvent")
  228. }
  229. delete self.casters[evt.target.id]
  230. } else { }
  231. self.intersected = false;
  232. }
  233. });
  234. }
  235. });
  236. AFRAME.registerComponent('envmap', {
  237. /**
  238. * Creates a new THREE.ShaderMaterial using the two shaders defined
  239. * in vertex.glsl and fragment.glsl.
  240. */
  241. init: function () {
  242. const data = this.data;
  243. //this.applyToMesh();
  244. this.el.addEventListener('model-loaded', () => this.applyToMesh());
  245. },
  246. /**
  247. * Update the ShaderMaterial when component data changes.
  248. */
  249. update: function () {
  250. },
  251. getEnvMap: function () {
  252. var path = './assets/textures/skybox2/';
  253. var format = '.jpg';
  254. var urls = [
  255. path + 'px' + format, path + 'nx' + format,
  256. path + 'py' + format, path + 'ny' + format,
  257. path + 'pz' + format, path + 'nz' + format
  258. ];
  259. envMap = new THREE.CubeTextureLoader().load(urls);
  260. envMap.format = THREE.RGBFormat;
  261. return envMap;
  262. },
  263. /**
  264. * Apply the material to the current entity.
  265. */
  266. applyToMesh: function () {
  267. const mesh = this.el.getObject3D('mesh');
  268. //var scene = mesh;
  269. var envMap = this.getEnvMap();
  270. mesh.traverse(function (node) {
  271. if (node.material) {
  272. node.material.side = THREE.BackSide;
  273. node.material.needsUpdate = true;
  274. //side = THREE.DoubleSide; break;
  275. }
  276. });
  277. mesh.traverse(function (node) {
  278. if (node.material && (node.material.isMeshStandardMaterial ||
  279. (node.material.isShaderMaterial && node.material.envMap !== undefined))) {
  280. node.material.envMap = envMap;
  281. node.material.needsUpdate = true;
  282. }
  283. });
  284. // const mesh = this.el.getObject3D('mesh');
  285. // if (mesh) {
  286. // mesh.material = this.material;
  287. // }
  288. },
  289. /**
  290. * On each frame, update the 'time' uniform in the shaders.
  291. */
  292. // tick: function (t) {
  293. // }
  294. })
  295. //https://threejs.org/examples/webgl_shaders_sky.html
  296. AFRAME.registerComponent('skyshader', {
  297. makeSun: function () {
  298. let sunSphere = new THREE.Mesh(
  299. new THREE.SphereBufferGeometry(20000, 16, 8),
  300. new THREE.MeshBasicMaterial({ color: 0xffffff })
  301. );
  302. sunSphere.position.y = - 700000;
  303. sunSphere.visible = true;
  304. let scene = this.el.sceneEl;
  305. this.el.sceneEl.setObject3D('sun', sunSphere);
  306. },
  307. init: function () {
  308. //let sunSphereEl = document.querySelector('a-scene').querySelector('#sun');
  309. //this.sunSphere = sunSphereEl.object3D;
  310. this.makeSun();
  311. this.sunSphere = this.el.sceneEl.getObject3D('sun');
  312. this.sky = new THREE.Sky();
  313. let scene = this.el.sceneEl;
  314. let effectController = {
  315. turbidity: 5,
  316. rayleigh: 2,
  317. mieCoefficient: 0.005,
  318. mieDirectionalG: 0.8,
  319. luminance: 1,
  320. inclination: 0, // elevation / inclination
  321. azimuth: 0.25, // Facing front,
  322. sun: ! true
  323. };
  324. let uniforms = this.sky.uniforms;
  325. uniforms.turbidity.value = effectController.turbidity;
  326. uniforms.rayleigh.value = effectController.rayleigh;
  327. uniforms.luminance.value = effectController.luminance;
  328. uniforms.mieCoefficient.value = effectController.mieCoefficient;
  329. uniforms.mieDirectionalG.value = effectController.mieDirectionalG;
  330. this.el.setObject3D('mesh', this.sky.mesh);
  331. let distance = 400000;
  332. var theta = Math.PI * (effectController.inclination - 0.5);
  333. var phi = 2 * Math.PI * (effectController.azimuth - 0.5);
  334. this.sunSphere.position.x = distance * Math.cos(phi);
  335. this.sunSphere.position.y = distance * Math.sin(phi) * Math.sin(theta);
  336. this.sunSphere.position.z = distance * Math.sin(phi) * Math.cos(theta);
  337. this.sunSphere.visible = effectController.sun;
  338. this.sky.uniforms.sunPosition.value.copy(this.sunSphere.position);
  339. },
  340. update: function () {
  341. },
  342. // tick: function (t) {
  343. // }
  344. })
  345. AFRAME.registerComponent('sun', {
  346. init: function () {
  347. this.sunSphere = new THREE.Mesh(
  348. new THREE.SphereBufferGeometry(20000, 16, 8),
  349. new THREE.MeshBasicMaterial({ color: 0xffffff })
  350. );
  351. this.sunSphere.position.y = - 700000;
  352. this.sunSphere.visible = true;
  353. this.el.setObject3D('mesh', this.sunSphere);
  354. },
  355. update: function () {
  356. },
  357. // tick: function (t) {
  358. // }
  359. })
  360. AFRAME.registerComponent('gearvrcontrol', {
  361. init: function () {
  362. var self = this;
  363. var controllerID = 'gearvr-' + vwf_view.kernel.moniker();
  364. this.el.addEventListener('triggerdown', function (event) {
  365. vwf_view.kernel.callMethod(controllerID, "triggerdown", []);
  366. });
  367. this.el.addEventListener('triggerup', function (event) {
  368. vwf_view.kernel.callMethod(controllerID, "triggerup", []);
  369. });
  370. //X-buttorn Pressed
  371. this.el.addEventListener('buttondown', function (e) { //xbuttondown
  372. //Start pointing position to teleport
  373. //let buttonID = e.detail.id;
  374. //let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  375. //vwf_view.kernel.callMethod(vwf.application(), "createPrimitive", ['text', buttonID, 'debug', null, avatarID]);
  376. if(e.detail.id == 2){
  377. this.emit('teleportstart');
  378. }
  379. });
  380. //X-buttorn Released
  381. this.el.addEventListener('buttonup', function (e) { //xbuttonup
  382. //Jump to pointed position
  383. if(e.detail.id == 2){
  384. this.emit('teleportend');
  385. }
  386. });
  387. },
  388. update: function () {
  389. },
  390. // tick: function (t) {
  391. // }
  392. })
  393. AFRAME.registerComponent('xrcontroller', {
  394. schema: {
  395. hand: { default: 'right' }
  396. },
  397. update: function (old) {
  398. this.hand = this.data.hand;
  399. },
  400. init: function () {
  401. var self = this;
  402. this.hand = this.data.hand;
  403. this.controllerID = 'xrcontroller-' + this.hand + '-' + vwf_view.kernel.moniker();
  404. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  405. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  406. });
  407. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  408. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  409. });
  410. //X-buttorn Pressed
  411. this.el.addEventListener('xbuttondown', function (e) { //xbuttondown
  412. //Start pointing position to teleport
  413. this.emit('teleportstart');
  414. });
  415. //X-buttorn Released
  416. this.el.addEventListener('xbuttonup', function (e) { //xbuttonup
  417. //Jump to pointed position
  418. this.emit('teleportend');
  419. });
  420. this.el.addEventListener('teleported', function (e) { //xbuttonup
  421. //Teleported
  422. console.log('TELEPORTED: ', e);
  423. });
  424. },
  425. // tick: function (t) {
  426. // }
  427. })
  428. AFRAME.registerComponent('wmrvrcontrol', {
  429. schema: {
  430. hand: { default: 'right' }
  431. },
  432. update: function (old) {
  433. this.hand = this.data.hand;
  434. },
  435. init: function () {
  436. var self = this;
  437. this.hand = this.data.hand;
  438. this.controllerID = 'wmrvr-' + this.hand + '-' + vwf_view.kernel.moniker();
  439. //this.gearel = document.querySelector('#gearvrcontrol');
  440. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  441. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  442. });
  443. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  444. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  445. });
  446. },
  447. // tick: function (t) {
  448. // }
  449. })
  450. AFRAME.registerComponent('streamsound', {
  451. schema: {
  452. positional: { default: true }
  453. },
  454. init: function () {
  455. var self = this;
  456. let driver = vwf.views["vwf/view/webrtc"];
  457. this.listener = null;
  458. this.stream = null;
  459. if (!this.sound) {
  460. this.setupSound();
  461. }
  462. if (driver) {
  463. //let avatarID = 'avatar-' + vwf.moniker();
  464. let avatarID = this.el.id.slice(0, 27); //avatar-0RtnYBBTBU84OCNcAAFY
  465. let client = driver.state.clients[avatarID];
  466. if (client) {
  467. if (client.connection) {
  468. this.stream = client.connection.stream;
  469. if (this.stream) {
  470. this.audioEl = new Audio();
  471. this.audioEl.srcObject = this.stream;
  472. this.sound.setNodeSource(this.sound.context.createMediaStreamSource(this.stream));
  473. }
  474. }
  475. }
  476. }
  477. },
  478. setupSound: function () {
  479. var el = this.el;
  480. var sceneEl = el.sceneEl;
  481. if (this.sound) {
  482. el.removeObject3D(this.attrName);
  483. }
  484. if (!sceneEl.audioListener) {
  485. sceneEl.audioListener = new THREE.AudioListener();
  486. sceneEl.camera && sceneEl.camera.add(sceneEl.audioListener);
  487. sceneEl.addEventListener('camera-set-active', function (evt) {
  488. evt.detail.cameraEl.getObject3D('camera').add(sceneEl.audioListener);
  489. });
  490. }
  491. this.listener = sceneEl.audioListener;
  492. this.sound = this.data.positional
  493. ? new THREE.PositionalAudio(this.listener)
  494. : new THREE.Audio(this.listener);
  495. el.setObject3D(this.attrName, this.sound);
  496. },
  497. remove: function () {
  498. if (!this.sound) return;
  499. this.el.removeObject3D(this.attrName);
  500. if (this.stream) {
  501. this.sound.disconnect();
  502. }
  503. },
  504. update: function (old) {
  505. },
  506. // tick: function (t) {
  507. // }
  508. })
  509. AFRAME.registerComponent('viewoffset', {
  510. // fullWidth:
  511. // fullHeight:
  512. // xoffset:
  513. // yoffset:
  514. // width:
  515. // height:
  516. schema: {
  517. fullWidth: { default: window.innerWidth },
  518. fullHeight: { default: window.innerHeight },
  519. xoffset: { default: window.innerWidth / 2 },
  520. yoffset: { default: window.innerHeight / 2 },
  521. width: { default: window.innerWidth },
  522. height: { default: window.innerHeight }
  523. },
  524. init: function () {
  525. var self = this;
  526. this.el.sceneEl.addEventListener('loaded', setOffset);
  527. function setOffset() {
  528. this.setNewOffset();
  529. }
  530. },
  531. update: function (old) {
  532. this.fullWidth = this.data.fullWidth;
  533. this.fullHeight = this.data.fullHeight;
  534. this.xoffset = this.data.xoffset;
  535. this.yoffset = this.data.yoffset;
  536. this.width = this.data.width;
  537. this.height = this.data.height;
  538. //console.log(this.data);
  539. this.setNewOffset();
  540. },
  541. setNewOffset: function () {
  542. this.el.object3DMap.camera.setViewOffset(
  543. this.data.fullWidth,
  544. this.data.fullHeight,
  545. this.data.xoffset,
  546. this.data.yoffset,
  547. this.data.width,
  548. this.data.height)
  549. },
  550. // tick: function (t) {
  551. // }
  552. })
  553. AFRAME.registerComponent("virtual-gamepad-controls", {
  554. schema: {},
  555. init() {
  556. this.onEnterVr = this.onEnterVr.bind(this);
  557. this.onExitVr = this.onExitVr.bind(this);
  558. this.onFirstInteraction = this.onFirstInteraction.bind(this);
  559. this.onMoveJoystickChanged = this.onMoveJoystickChanged.bind(this);
  560. this.onMoveJoystickEnd = this.onMoveJoystickEnd.bind(this);
  561. // this.onLookJoystickChanged = this.onLookJoystickChanged.bind(this);
  562. // this.onLookJoystickEnd = this.onLookJoystickEnd.bind(this);
  563. this.mockJoystickContainer = document.createElement("div");
  564. this.mockJoystickContainer.classList.add('mockJoystickContainer');
  565. const leftMock = document.createElement("div");
  566. leftMock.classList.add('mockJoystick');
  567. const leftMockSmall = document.createElement("div");
  568. leftMockSmall.classList.add('mockJoystick', 'inner');
  569. leftMock.appendChild(leftMockSmall);
  570. this.mockJoystickContainer.appendChild(leftMock);
  571. // const rightMock = document.createElement("div");
  572. // rightMock.classList.add('mockJoystick');
  573. // const rightMockSmall = document.createElement("div");
  574. // rightMockSmall.classList.add('mockJoystick', 'inner');
  575. // rightMock.appendChild(rightMockSmall);
  576. // this.mockJoystickContainer.appendChild(rightMock);
  577. document.body.appendChild(this.mockJoystickContainer);
  578. // Setup gamepad elements
  579. const leftTouchZone = document.createElement("div");
  580. leftTouchZone.classList.add('touchZone', 'left');
  581. document.body.appendChild(leftTouchZone);
  582. this.leftTouchZone = leftTouchZone;
  583. this.leftStick = nipplejs.create({
  584. zone: this.leftTouchZone,
  585. color: "white",
  586. fadeTime: 0
  587. });
  588. this.leftStick.on("start", this.onFirstInteraction);
  589. this.leftStick.on("move", this.onMoveJoystickChanged);
  590. this.leftStick.on("end", this.onMoveJoystickEnd);
  591. // const rightTouchZone = document.createElement("div");
  592. // rightTouchZone.classList.add('touchZone', 'right');
  593. // document.body.appendChild(rightTouchZone);
  594. // this.rightTouchZone = rightTouchZone;
  595. // this.rightStick = nipplejs.create({
  596. // zone: this.rightTouchZone,
  597. // color: "white",
  598. // fadeTime: 0
  599. // });
  600. // this.rightStick.on("start", this.onFirstInteraction);
  601. // this.rightStick.on("move", this.onLookJoystickChanged);
  602. // this.rightStick.on("end", this.onLookJoystickEnd);
  603. this.inVr = false;
  604. this.moving = false;
  605. this.rotating = false;
  606. this.moveEvent = {
  607. axis: [0, 0]
  608. };
  609. // this.rotateYEvent = {
  610. // value: 0
  611. // };
  612. // this.rotateXEvent = {
  613. // value: 0
  614. // };
  615. this.el.sceneEl.addEventListener("enter-vr", this.onEnterVr);
  616. this.el.sceneEl.addEventListener("exit-vr", this.onExitVr);
  617. },
  618. onFirstInteraction() {
  619. this.leftStick.off("start", this.onFirstInteraction);
  620. //this.rightStick.off("start", this.onFirstInteraction);
  621. document.body.removeChild(this.mockJoystickContainer);
  622. },
  623. onMoveJoystickChanged(event, joystick) {
  624. const angle = joystick.angle.radian;
  625. const force = joystick.force < 1 ? joystick.force : 1;
  626. const moveStrength = 1.85;
  627. const x = Math.cos(angle) * force * moveStrength;
  628. const z = Math.sin(angle) * force * moveStrength;
  629. this.moving = true;
  630. this.moveEvent.axis[0] = x;
  631. this.moveEvent.axis[1] = z;
  632. },
  633. onMoveJoystickEnd() {
  634. this.moving = false;
  635. this.moveEvent.axis[0] = 0;
  636. this.moveEvent.axis[1] = 0;
  637. this.el.emit("move", this.moveEvent);
  638. },
  639. onLookJoystickChanged(event, joystick) {
  640. // Set pitch and yaw angles on right stick move
  641. const angle = joystick.angle.radian;
  642. const force = joystick.force < 1 ? joystick.force : 1;
  643. const turnStrength = 0.5;
  644. this.rotating = true;
  645. this.rotateYEvent.value = Math.cos(angle) * force * turnStrength;
  646. this.rotateXEvent.value = Math.sin(angle) * force * turnStrength;
  647. },
  648. onLookJoystickEnd() {
  649. this.rotating = false;
  650. this.rotateYEvent.value = 0;
  651. this.rotateXEvent.value = 0;
  652. this.el.emit("rotateY", this.rotateYEvent);
  653. this.el.emit("rotateX", this.rotateXEvent);
  654. },
  655. tick() {
  656. if (!this.inVr) {
  657. if (this.moving) {
  658. this.el.emit("move", this.moveEvent);
  659. }
  660. // if (this.rotating) {
  661. // this.el.emit("rotateY", this.rotateYEvent);
  662. // this.el.emit("rotateX", this.rotateXEvent);
  663. // }
  664. }
  665. },
  666. onEnterVr() {
  667. // Hide the joystick controls
  668. this.inVr = true;
  669. this.leftTouchZone.style.display = "none";
  670. // this.rightTouchZone.style.display = "none";
  671. },
  672. onExitVr() {
  673. // Show the joystick controls
  674. this.inVr = false;
  675. this.leftTouchZone.style.display = "block";
  676. // this.rightTouchZone.style.display = "block";
  677. },
  678. remove() {
  679. this.el.sceneEl.removeEventListener("entervr", this.onEnterVr);
  680. this.el.sceneEl.removeEventListener("exitvr", this.onExitVr);
  681. if (document.getElementsByClassName('mockJoystickContainer').length > 0){
  682. document.body.removeChild(this.mockJoystickContainer);
  683. }
  684. document.body.removeChild(this.leftTouchZone);
  685. // document.body.removeChild(this.rightTouchZone);
  686. }
  687. });
  688. ////ARJS///
  689. //////////////////////////////////////////////////////////////////////////////
  690. // arjs-anchor
  691. //////////////////////////////////////////////////////////////////////////////
  692. AFRAME.registerComponent('arjs-anchor', {
  693. dependencies: ['arjs', 'artoolkit'],
  694. schema: {
  695. preset: {
  696. type: 'string',
  697. },
  698. markerhelpers: { // IIF preset === 'area'
  699. type: 'boolean',
  700. default: false,
  701. },
  702. // controls parameters
  703. size: {
  704. type: 'number',
  705. default: 1
  706. },
  707. type: {
  708. type: 'string',
  709. },
  710. patternUrl: {
  711. type: 'string',
  712. },
  713. barcodeValue: {
  714. type: 'number'
  715. },
  716. changeMatrixMode: {
  717. type: 'string',
  718. default: 'modelViewMatrix',
  719. },
  720. minConfidence: {
  721. type: 'number',
  722. default: 0.6,
  723. },
  724. smooth: {
  725. type: 'boolean',
  726. default: false,
  727. },
  728. smoothCount: {
  729. type: 'number',
  730. default: 5,
  731. },
  732. smoothTolerance: {
  733. type: 'number',
  734. default: 0.01,
  735. },
  736. smoothThreshold: {
  737. type: 'number',
  738. default: 2,
  739. },
  740. },
  741. init: function () {
  742. var _this = this
  743. // get arjsSystem
  744. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  745. //////////////////////////////////////////////////////////////////////////////
  746. // Code Separator
  747. //////////////////////////////////////////////////////////////////////////////
  748. _this.isReady = false
  749. _this._arAnchor = null
  750. //LiveCoding.space fix for editor mode
  751. if(arjsSystem) {
  752. // honor object visibility
  753. if (_this.data.changeMatrixMode === 'modelViewMatrix') {
  754. _this.el.object3D.visible = false
  755. } else if (_this.data.changeMatrixMode === 'cameraTransformMatrix') {
  756. _this.el.sceneEl.object3D.visible = false
  757. } else console.assert(false)
  758. // trick to wait until arjsSystem is isReady
  759. var startedAt = Date.now()
  760. var timerId = setInterval(function () {
  761. // wait until the system is isReady
  762. if (arjsSystem.isReady === false) return
  763. clearInterval(timerId)
  764. //////////////////////////////////////////////////////////////////////////////
  765. // update arProfile
  766. //////////////////////////////////////////////////////////////////////////////
  767. var arProfile = arjsSystem._arProfile
  768. // arProfile.changeMatrixMode('modelViewMatrix')
  769. arProfile.changeMatrixMode(_this.data.changeMatrixMode)
  770. // honor this.data.preset
  771. var markerParameters = Object.assign({}, arProfile.defaultMarkerParameters)
  772. if (_this.data.preset === 'hiro') {
  773. markerParameters.type = 'pattern'
  774. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-hiro.patt'
  775. markerParameters.markersAreaEnabled = false
  776. } else if (_this.data.preset === 'kanji') {
  777. markerParameters.type = 'pattern'
  778. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-kanji.patt'
  779. markerParameters.markersAreaEnabled = false
  780. } else if (_this.data.preset === 'area') {
  781. markerParameters.type = 'barcode'
  782. markerParameters.barcodeValue = 1001
  783. markerParameters.markersAreaEnabled = true
  784. } else if (_this.data.type === 'barcode') {
  785. markerParameters = {
  786. type: _this.data.type,
  787. changeMatrixMode: 'modelViewMatrix',
  788. barcodeValue: _this.data.barcodeValue,
  789. markersAreaEnabled: false
  790. }
  791. } else if (_this.data.type === 'pattern') {
  792. markerParameters.type = _this.data.type
  793. markerParameters.patternUrl = _this.data.patternUrl;
  794. markerParameters.markersAreaEnabled = false
  795. }
  796. markerParameters.smooth = _this.data.smooth;
  797. markerParameters.smoothCount = _this.data.smoothCount;
  798. markerParameters.smoothTolerance = _this.data.smoothTolerance;
  799. markerParameters.smoothThreshold = _this.data.smoothThreshold;
  800. //////////////////////////////////////////////////////////////////////////////
  801. // create arAnchor
  802. //////////////////////////////////////////////////////////////////////////////
  803. var arSession = arjsSystem._arSession
  804. var arAnchor = _this._arAnchor = new ARjs.Anchor(arSession, markerParameters)
  805. // it is now considered isReady
  806. _this.isReady = true
  807. //////////////////////////////////////////////////////////////////////////////
  808. // honor .debugUIEnabled
  809. //////////////////////////////////////////////////////////////////////////////
  810. if (arjsSystem.data.debugUIEnabled) {
  811. // get or create containerElement
  812. var containerElement = document.querySelector('#arjsDebugUIContainer')
  813. if (containerElement === null) {
  814. containerElement = document.createElement('div')
  815. containerElement.id = 'arjsDebugUIContainer'
  816. containerElement.setAttribute('style', 'position: fixed; bottom: 10px; width:100%; text-align: center; z-index: 1; color: grey;')
  817. document.body.appendChild(containerElement)
  818. }
  819. // create anchorDebugUI
  820. var anchorDebugUI = new ARjs.AnchorDebugUI(arAnchor)
  821. containerElement.appendChild(anchorDebugUI.domElement)
  822. }
  823. }, 1000 / 60)
  824. }
  825. },
  826. remove: function () {
  827. },
  828. update: function () {
  829. },
  830. tick: function () {
  831. var _this = this
  832. // if not yet isReady, do nothing
  833. if (this.isReady === false) return
  834. //////////////////////////////////////////////////////////////////////////////
  835. // update arAnchor
  836. //////////////////////////////////////////////////////////////////////////////
  837. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  838. this._arAnchor.update()
  839. //////////////////////////////////////////////////////////////////////////////
  840. // honor pose
  841. //////////////////////////////////////////////////////////////////////////////
  842. var arWorldRoot = this._arAnchor.object3d
  843. arWorldRoot.updateMatrixWorld(true)
  844. arWorldRoot.matrixWorld.decompose(this.el.object3D.position, this.el.object3D.quaternion, this.el.object3D.scale)
  845. //////////////////////////////////////////////////////////////////////////////
  846. // honor visibility
  847. //////////////////////////////////////////////////////////////////////////////
  848. if (_this._arAnchor.parameters.changeMatrixMode === 'modelViewMatrix') {
  849. var wasVisible = _this.el.object3D.visible
  850. _this.el.object3D.visible = this._arAnchor.object3d.visible
  851. } else if (_this._arAnchor.parameters.changeMatrixMode === 'cameraTransformMatrix') {
  852. var wasVisible = _this.el.sceneEl.object3D.visible
  853. _this.el.sceneEl.object3D.visible = this._arAnchor.object3d.visible
  854. } else console.assert(false)
  855. // emit markerFound markerLost
  856. if (_this._arAnchor.object3d.visible === true && wasVisible === false) {
  857. _this.el.emit('markerFound')
  858. } else if (_this._arAnchor.object3d.visible === false && wasVisible === true) {
  859. _this.el.emit('markerLost')
  860. }
  861. }
  862. })
  863. //////////////////////////////////////////////////////////////////////////////
  864. // define some primitives shortcuts
  865. //////////////////////////////////////////////////////////////////////////////
  866. AFRAME.registerPrimitive('a-anchor', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  867. defaultComponents: {
  868. 'arjs-anchor': {},
  869. 'arjs-hit-testing': {},
  870. },
  871. mappings: {
  872. 'type': 'arjs-anchor.type',
  873. 'size': 'arjs-anchor.size',
  874. 'url': 'arjs-anchor.patternUrl',
  875. 'value': 'arjs-anchor.barcodeValue',
  876. 'preset': 'arjs-anchor.preset',
  877. 'min-confidence': 'arjs-anchor.minConfidence',
  878. 'marker-helpers': 'arjs-anchor.markerhelpers',
  879. 'smooth': 'arjs-anchor.smooth',
  880. 'smooth-count': 'arjs-anchor.smoothCount',
  881. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  882. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  883. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  884. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  885. }
  886. }))
  887. AFRAME.registerPrimitive('a-camera-static', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  888. defaultComponents: {
  889. 'camera': {},
  890. },
  891. mappings: {
  892. }
  893. }))
  894. //////////////////////////////////////////////////////////////////////////////
  895. // backward compatibility
  896. //////////////////////////////////////////////////////////////////////////////
  897. // FIXME
  898. AFRAME.registerPrimitive('a-marker', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  899. defaultComponents: {
  900. 'arjs-anchor': {},
  901. 'arjs-hit-testing': {},
  902. },
  903. mappings: {
  904. 'type': 'arjs-anchor.type',
  905. 'size': 'arjs-anchor.size',
  906. 'url': 'arjs-anchor.patternUrl',
  907. 'value': 'arjs-anchor.barcodeValue',
  908. 'preset': 'arjs-anchor.preset',
  909. 'min-confidence': 'arjs-anchor.minConfidence',
  910. 'marker-helpers': 'arjs-anchor.markerhelpers',
  911. 'smooth': 'arjs-anchor.smooth',
  912. 'smooth-count': 'arjs-anchor.smoothCount',
  913. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  914. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  915. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  916. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  917. }
  918. }))
  919. AFRAME.registerPrimitive('a-marker-camera', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  920. defaultComponents: {
  921. 'arjs-anchor': {
  922. changeMatrixMode: 'cameraTransformMatrix'
  923. },
  924. 'camera': {},
  925. },
  926. mappings: {
  927. 'type': 'arjs-anchor.type',
  928. 'size': 'arjs-anchor.size',
  929. 'url': 'arjs-anchor.patternUrl',
  930. 'value': 'arjs-anchor.barcodeValue',
  931. 'preset': 'arjs-anchor.preset',
  932. 'min-confidence': 'arjs-anchor.minConfidence',
  933. 'marker-helpers': 'arjs-anchor.markerhelpers',
  934. }
  935. }))
  936. //////////////////////////////////////////////////////////////////////////////
  937. // arjs-hit-testing
  938. //////////////////////////////////////////////////////////////////////////////
  939. AFRAME.registerComponent('arjs-hit-testing', {
  940. dependencies: ['arjs', 'artoolkit'],
  941. schema: {
  942. enabled : {
  943. type: 'boolean',
  944. default: false,
  945. },
  946. renderDebug : {
  947. type: 'boolean',
  948. default: false,
  949. },
  950. },
  951. init: function () {
  952. var _this = this
  953. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  954. // TODO make it work on cameraTransformMatrix too
  955. //
  956. _this.isReady = false
  957. _this._arAnchor = null
  958. _this._arHitTesting = null
  959. //LiveCdoing.space fix for editor mode
  960. if(arjsSystem) {
  961. // trick to wait until arjsSystem is isReady
  962. var startedAt = Date.now()
  963. var timerId = setInterval(function(){
  964. var anchorEl = _this.el
  965. var anchorComponent = anchorEl.components['arjs-anchor']
  966. // wait until anchorComponent is isReady
  967. if( anchorComponent === undefined || anchorComponent.isReady === false ) return
  968. clearInterval(timerId)
  969. //////////////////////////////////////////////////////////////////////////////
  970. // create arAnchor
  971. //////////////////////////////////////////////////////////////////////////////
  972. var arAnchor = anchorComponent._arAnchor
  973. var arSession = arjsSystem._arSession
  974. var renderer = arSession.parameters.renderer
  975. var hitTesting = _this._arHitTesting = new ARjs.HitTesting(arSession)
  976. hitTesting.enabled = _this.data.enabled
  977. _this.isReady = true
  978. }, 1000/60)
  979. }
  980. },
  981. remove : function(){
  982. },
  983. update: function () {
  984. },
  985. tick: function(){
  986. var _this = this
  987. // if not yet isReady, do nothing
  988. if( this.isReady === false ) return
  989. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  990. var arSession = arjsSystem._arSession
  991. var anchorEl = _this.el
  992. var anchorComponent = anchorEl.components['arjs-anchor']
  993. var arAnchor = anchorComponent._arAnchor
  994. var hitTesting = this._arHitTesting
  995. var camera = arSession.parameters.camera
  996. // console.log(camera.position)
  997. hitTesting.update(camera, arAnchor.object3d, arAnchor.parameters.changeMatrixMode)
  998. }
  999. });
  1000. ///////////////END ARJS/////////
  1001. ///MIRROR//
  1002. THREE.ShaderLib[ 'mirror' ] = {
  1003. uniforms: {
  1004. "mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
  1005. "mirrorSampler": { value: null },
  1006. "textureMatrix" : { value: new THREE.Matrix4() }
  1007. },
  1008. vertexShader: [
  1009. "uniform mat4 textureMatrix;",
  1010. "varying vec4 mirrorCoord;",
  1011. "void main() {",
  1012. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1013. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  1014. "mirrorCoord = textureMatrix * worldPosition;",
  1015. "gl_Position = projectionMatrix * mvPosition;",
  1016. "}"
  1017. ].join( "\n" ),
  1018. fragmentShader: [
  1019. "uniform vec3 mirrorColor;",
  1020. "uniform sampler2D mirrorSampler;",
  1021. "varying vec4 mirrorCoord;",
  1022. "float blendOverlay(float base, float blend) {",
  1023. "return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
  1024. "}",
  1025. "void main() {",
  1026. "vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
  1027. "color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",
  1028. "gl_FragColor = color;",
  1029. "}"
  1030. ].join( "\n" )
  1031. };
  1032. THREE.Mirror = function ( renderer, camera, options ) {
  1033. THREE.Object3D.call( this );
  1034. this.name = 'mirror_' + this.id;
  1035. options = options || {};
  1036. this.matrixNeedsUpdate = true;
  1037. var width = options.textureWidth !== undefined ? options.textureWidth : 512;
  1038. var height = options.textureHeight !== undefined ? options.textureHeight : 512;
  1039. this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
  1040. var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
  1041. this.renderer = renderer;
  1042. this.mirrorPlane = new THREE.Plane();
  1043. this.normal = new THREE.Vector3( 0, 0, 1 );
  1044. this.mirrorWorldPosition = new THREE.Vector3();
  1045. this.cameraWorldPosition = new THREE.Vector3();
  1046. this.rotationMatrix = new THREE.Matrix4();
  1047. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  1048. this.clipPlane = new THREE.Vector4();
  1049. // For debug only, show the normal and plane of the mirror
  1050. var debugMode = options.debugMode !== undefined ? options.debugMode : false;
  1051. if ( debugMode ) {
  1052. var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
  1053. var planeGeometry = new THREE.Geometry();
  1054. planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
  1055. planeGeometry.vertices.push( new THREE.Vector3( 10, - 10, 0 ) );
  1056. planeGeometry.vertices.push( new THREE.Vector3( 10, 10, 0 ) );
  1057. planeGeometry.vertices.push( new THREE.Vector3( - 10, 10, 0 ) );
  1058. planeGeometry.vertices.push( planeGeometry.vertices[ 0 ] );
  1059. var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );
  1060. this.add( arrow );
  1061. this.add( plane );
  1062. }
  1063. if ( camera instanceof THREE.PerspectiveCamera ) {
  1064. this.camera = camera;
  1065. } else {
  1066. this.camera = new THREE.PerspectiveCamera();
  1067. console.log( this.name + ': camera is not a Perspective Camera!' );
  1068. }
  1069. this.textureMatrix = new THREE.Matrix4();
  1070. this.mirrorCamera = this.camera.clone();
  1071. this.mirrorCamera.matrixAutoUpdate = true;
  1072. var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
  1073. //this.currentRenderTarget = this.renderer.getRenderTarget();
  1074. this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
  1075. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );
  1076. var mirrorShader = THREE.ShaderLib[ "mirror" ];
  1077. var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
  1078. this.material = new THREE.ShaderMaterial( {
  1079. fragmentShader: mirrorShader.fragmentShader,
  1080. vertexShader: mirrorShader.vertexShader,
  1081. uniforms: mirrorUniforms
  1082. } );
  1083. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  1084. this.material.uniforms.mirrorColor.value = mirrorColor;
  1085. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  1086. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  1087. this.renderTarget.texture.generateMipmaps = false;
  1088. this.renderTarget2.texture.generateMipmaps = false;
  1089. }
  1090. this.updateTextureMatrix();
  1091. this.render();
  1092. };
  1093. THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
  1094. THREE.Mirror.prototype.constructor = THREE.Mirror;
  1095. THREE.Mirror.prototype.renderWithMirror = function ( otherMirror, aScene ) {
  1096. // update the mirror matrix to mirror the current view
  1097. this.updateTextureMatrix();
  1098. this.matrixNeedsUpdate = false;
  1099. // set the camera of the other mirror so the mirrored view is the reference view
  1100. var tempCamera = otherMirror.camera;
  1101. otherMirror.camera = this.mirrorCamera;
  1102. // render the other mirror in temp texture
  1103. otherMirror.renderTemp(aScene);
  1104. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;
  1105. // render the current mirror
  1106. this.render(aScene);
  1107. this.matrixNeedsUpdate = true;
  1108. // restore material and camera of other mirror
  1109. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
  1110. otherMirror.camera = tempCamera;
  1111. // restore texture matrix of other mirror
  1112. otherMirror.updateTextureMatrix();
  1113. };
  1114. THREE.Mirror.prototype.updateTextureMatrix = function () {
  1115. this.updateMatrixWorld();
  1116. this.camera.updateMatrixWorld();
  1117. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  1118. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  1119. this.rotationMatrix.extractRotation( this.matrixWorld );
  1120. this.normal.set( 0, 0, 1 );
  1121. this.normal.applyMatrix4( this.rotationMatrix );
  1122. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  1123. view.reflect( this.normal ).negate();
  1124. view.add( this.mirrorWorldPosition );
  1125. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  1126. this.lookAtPosition.set( 0, 0, - 1 );
  1127. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  1128. this.lookAtPosition.add( this.cameraWorldPosition );
  1129. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  1130. target.reflect( this.normal ).negate();
  1131. target.add( this.mirrorWorldPosition );
  1132. this.up.set( 0, - 1, 0 );
  1133. this.up.applyMatrix4( this.rotationMatrix );
  1134. this.up.reflect( this.normal ).negate();
  1135. this.mirrorCamera.position.copy( view );
  1136. this.mirrorCamera.up = this.up;
  1137. this.mirrorCamera.lookAt( target );
  1138. this.mirrorCamera.updateProjectionMatrix();
  1139. this.mirrorCamera.updateMatrixWorld();
  1140. this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
  1141. // Update the texture matrix
  1142. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  1143. 0.0, 0.5, 0.0, 0.5,
  1144. 0.0, 0.0, 0.5, 0.5,
  1145. 0.0, 0.0, 0.0, 1.0 );
  1146. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  1147. this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
  1148. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  1149. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  1150. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  1151. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  1152. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  1153. var q = new THREE.Vector4();
  1154. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  1155. q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  1156. q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  1157. q.z = - 1.0;
  1158. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  1159. // Calculate the scaled plane vector
  1160. var c = new THREE.Vector4();
  1161. c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  1162. // Replacing the third row of the projection matrix
  1163. projectionMatrix.elements[ 2 ] = c.x;
  1164. projectionMatrix.elements[ 6 ] = c.y;
  1165. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  1166. projectionMatrix.elements[ 14 ] = c.w;
  1167. };
  1168. THREE.Mirror.prototype.render = function (aScene) {
  1169. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1170. this.matrixNeedsUpdate = true;
  1171. // Render the mirrored view of the current scene into the target texture
  1172. //var scene = aScene //this;
  1173. // while ( scene.parent !== null ) {
  1174. // scene = scene.parent;
  1175. // }
  1176. //this.renderer.setRenderTarget( null );
  1177. if ( aScene !== undefined) //&& scene instanceof THREE.Scene )
  1178. {
  1179. // We can't render ourself to ourself
  1180. var visible = this.material.visible;
  1181. this.material.visible = false;
  1182. this.renderer.clear();
  1183. this.renderer.setRenderTarget( this.renderTarget);
  1184. this.renderer.render( aScene.object3D, this.mirrorCamera);
  1185. this.renderer.setRenderTarget(null);
  1186. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
  1187. this.material.visible = visible;
  1188. }
  1189. };
  1190. THREE.Mirror.prototype.renderTemp = function (aScene) {
  1191. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1192. this.matrixNeedsUpdate = true;
  1193. // Render the mirrored view of the current scene into the target texture
  1194. // var scene = this;
  1195. // while ( scene.parent !== null ) {
  1196. // scene = scene.parent;
  1197. // }
  1198. if ( aScene !== undefined) //&& scene instanceof THREE.Scene ) {
  1199. {
  1200. this.renderer.clear();
  1201. this.renderer.setRenderTarget( this.renderTarget2);
  1202. this.renderer.render( aScene.object3D, this.mirrorCamera );
  1203. this.renderer.setRenderTarget( null );
  1204. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );
  1205. }
  1206. };
  1207. AFRAME.registerComponent('mirror', {
  1208. schema:{
  1209. renderothermirror:{default:true},
  1210. camera:{default: 'avatarControl'}
  1211. },
  1212. init: function () {
  1213. var scene = this.el.sceneEl;
  1214. this.cameraID = this.data.camera;
  1215. scene.addEventListener('render-target-loaded',this.OnRenderLoaded()); //this.OnRenderLoaded.bind(this)
  1216. },
  1217. // update: function (old) {
  1218. // this.cameraID = this.data.camera;
  1219. // this.OnRenderLoaded();
  1220. // },
  1221. OnRenderLoaded: function()
  1222. {
  1223. var mirrorObj = this.el.getOrCreateObject3D('mesh',THREE.Mesh);
  1224. // var cameraEl = document.querySelector('a-entity[camera]')
  1225. // if(!cameraEl)
  1226. // {
  1227. // cameraEl = document.querySelector('a-camera');
  1228. // }
  1229. // var camera = cameraEl.components.camera.camera;
  1230. let cameraEl = document.querySelector("[id='" + this.cameraID + "']")
  1231. if (cameraEl){
  1232. let camera = cameraEl.getObject3D('camera'); //document.querySelector('#avatarControl').getObject3D('camera');
  1233. var scene = this.el.sceneEl;
  1234. // this.renderer = new THREE.WebGLRenderer({
  1235. // antialias: true,
  1236. // });
  1237. this.renderer = scene.renderer;
  1238. this.mirror = new THREE.Mirror( this.renderer, camera, { clipBias: 0.003, textureWidth: window.innerWidth, textureHeight: window.innerHeight, color: 0x777777, debugMode: false} );
  1239. mirrorObj.material = this.mirror.material;
  1240. //mirrorObj.children = [];
  1241. mirrorObj.add(this.mirror);
  1242. }
  1243. //As of A-Frame tick (behaviours) priority issue need to place mirror tick onto upper tick()
  1244. this.el.sceneEl.components['scene-utils'].mirrors[this.el.id] = this;
  1245. },
  1246. remove: function () {
  1247. delete this.el.sceneEl.components['scene-utils'].mirrors[this.el.id]
  1248. },
  1249. mirrorTick: function () {
  1250. // //this.mirror.render();
  1251. if(!this.data.renderothermirror)
  1252. {
  1253. this.mirror.render(this.el.sceneEl);
  1254. }
  1255. else
  1256. {
  1257. var mirrors = [];
  1258. var mirrorEls = document.querySelectorAll("[mirror]");
  1259. for(var i=0;i<mirrorEls.length;i++)
  1260. {
  1261. if(mirrorEls[i]!=this.el)
  1262. {
  1263. mirrors.push(mirrorEls[i].components.mirror.mirror);
  1264. }
  1265. }
  1266. if(mirrors.length === 0)
  1267. {
  1268. this.mirror.render(this.el.sceneEl);
  1269. }
  1270. for(var i = 0; i<mirrors.length;i++)
  1271. {
  1272. this.mirror.renderWithMirror(mirrors[i], this.el.sceneEl);
  1273. }
  1274. }
  1275. },
  1276. // tick: function () {
  1277. // }
  1278. });