aframe-components.js 50 KB

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