aframe-components.js 49 KB

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