aframe-components.js 51 KB

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