aframe-components.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  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. });