aframe-components.js 49 KB

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