aframe-components.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2018 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. */
  5. if (typeof AFRAME === 'undefined') {
  6. throw new Error('Component attempted to register before AFRAME was available.');
  7. }
  8. AFRAME.registerComponent('scene-utils', {
  9. init: function () {
  10. this.mirrors = {};
  11. //this.setCameraControl();
  12. const sceneEnterVR = (e) => {
  13. let driver = vwf.views["vwf/view/aframe"];
  14. // let avatarEl = document.querySelector('#avatarControlParent');
  15. // let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  16. driver.hmd = true;
  17. if (driver.threeDoFMobile || _app.config.d3DoF ) {
  18. driver.threeDoF = true;
  19. //vwf_view.kernel.callMethod(avatarID, "updateYPositionForXR", [0.0]);
  20. } else if (driver.sixDoFMobile || driver.sixDoFDesktop || _app.config.d6DoF ) {
  21. driver.sixDoF = true;
  22. }
  23. }
  24. const sceneExitVR = (e) => {
  25. let driver = vwf.views["vwf/view/aframe"];
  26. driver.hmd = false;
  27. if (driver.threeDoFMobile || _app.config.d3DoF ) {
  28. driver.threeDoF = false;
  29. //vwf_view.kernel.callMethod(avatarID, "updateYPositionForXR", [-1.6]);
  30. } else if (driver.sixDoFMobile || driver.sixDoFDesktop || _app.config.d6DoF ) {
  31. driver.sixDoF = false;
  32. }
  33. }
  34. this.el.sceneEl.addEventListener('enter-vr', sceneEnterVR);
  35. this.el.sceneEl.addEventListener('exit-vr', sceneExitVR);
  36. },
  37. setCameraControl(){
  38. let avatarEl = document.querySelector('#avatarControl');
  39. document.addEventListener('keydown', (event) => {
  40. const keyName = event.key;
  41. if (keyName === 'Alt') {
  42. // do not alert when only Control key is pressed.
  43. console.log(keyName, ' pressed');
  44. avatarEl.setAttribute('look-controls', 'enabled', true)
  45. return;
  46. }
  47. })
  48. document.addEventListener('keyup', (event) => {
  49. const keyName = event.key;
  50. if (keyName === 'Alt') {
  51. // do not alert when only Control key is pressed.
  52. console.log(keyName, ' released');
  53. avatarEl.setAttribute('look-controls', 'enabled', false)
  54. return;
  55. }
  56. })
  57. },
  58. update: function () {
  59. },
  60. tick: function (t) {
  61. Object.values(this.mirrors).forEach(el => {
  62. el.mirrorTick.call(el)
  63. })
  64. }
  65. })
  66. AFRAME.registerComponent('linepath', {
  67. schema: {
  68. color: { default: '#000' },
  69. width: { default: 0.01 },
  70. path: {
  71. default: [
  72. { x: -0.5, y: 0, z: 0 },
  73. { x: 0.5, y: 0, z: 0 }
  74. ]
  75. // Deserialize path in the form of comma-separated vec3s: `0 0 0, 1 1 1, 2 0 3`.
  76. // parse: function (value) {
  77. // return value.split(',').map(coordinates.parse);
  78. // },
  79. // Serialize array of vec3s in case someone does setAttribute('line', 'path', [...]).
  80. // stringify: function (data) {
  81. // return data.map(coordinates.stringify).join(',');
  82. // }
  83. }
  84. },
  85. update: function () {
  86. var material = new MeshLineMaterial({
  87. color: new THREE.Color(this.data.color), //this.data.color
  88. lineWidth: this.data.width
  89. });
  90. var geometry = new THREE.Geometry();
  91. this.data.path.forEach(function (vec3) {
  92. geometry.vertices.push(
  93. new THREE.Vector3(vec3.x, vec3.y, vec3.z)
  94. );
  95. });
  96. let line = new MeshLine();
  97. line.setGeometry(geometry);
  98. //new THREE.Line(geometry, material)
  99. this.el.setObject3D('mesh', new THREE.Mesh(line.geometry, material));
  100. },
  101. remove: function () {
  102. this.el.removeObject3D('mesh');
  103. }
  104. });
  105. AFRAME.registerComponent('gizmo', {
  106. schema: {
  107. mode: { default: 'translate' }
  108. },
  109. update: function (old) {
  110. let modes = ['translate', 'rotate', 'scale'];
  111. if (!this.gizmo) {
  112. let newMode = modes.filter(el => {
  113. return el == this.data.mode
  114. })
  115. if (newMode.length !== 0) {
  116. this.mode = this.data.mode
  117. this.transformControls.setMode(this.mode)
  118. }
  119. }
  120. },
  121. init: function () {
  122. let self = this
  123. this.mode = this.data.mode
  124. let activeCamera = document.querySelector('#avatarControl').getObject3D('camera');
  125. let renderer = this.el.sceneEl.renderer;
  126. this.transformControls = new THREE.TransformControls(activeCamera, renderer.domElement);
  127. this.transformControls.attach(this.el.object3D);
  128. this.el.sceneEl.setObject3D('control-' + this.el.id, this.transformControls);
  129. this.transformControls.addEventListener('change', function (evt) {
  130. // console.log('changed');
  131. var object = self.transformControls.object;
  132. if (object === undefined) {
  133. return;
  134. }
  135. var transformMode = self.transformControls.getMode();
  136. switch (transformMode) {
  137. case 'translate':
  138. vwf_view.kernel.setProperty(object.el.id, 'position',
  139. [object.position.x, object.position.y, object.position.z])
  140. break;
  141. case 'rotate':
  142. // let q = (new THREE.Quaternion()).setFromEuler(new THREE.Euler(
  143. // (object.rotation.x),
  144. // (object.rotation.y),
  145. // (object.rotation.z), 'XYZ'
  146. // ));
  147. // let angle = (new THREE.Euler()).setFromQuaternion(q, 'YXZ');
  148. // vwf_view.kernel.setProperty(object.el.id, 'rotation', [THREE.Math.radToDeg(angle.x), THREE.Math.radToDeg(angle.y), THREE.Math.radToDeg(angle.z)])
  149. vwf_view.kernel.setProperty(object.el.id, 'rotation',
  150. [THREE.Math.radToDeg(object.rotation.x), THREE.Math.radToDeg(object.rotation.y), THREE.Math.radToDeg(object.rotation.z)])
  151. break;
  152. case 'scale':
  153. vwf_view.kernel.setProperty(object.el.id, 'scale',
  154. [object.scale.x, object.scale.y, object.scale.z])
  155. break;
  156. }
  157. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  158. });
  159. },
  160. remove: function () {
  161. this.transformControls.detach();
  162. this.el.sceneEl.removeObject3D('control-' + this.el.id);
  163. },
  164. // tick: function (t) {
  165. // // this.transformControls.update();
  166. // }
  167. });
  168. AFRAME.registerComponent('cursor-listener', {
  169. init: function () {
  170. this.el.addEventListener('click', function (evt) {
  171. console.log('I was clicked at: ', evt.detail.intersection.point);
  172. let cursorID = 'cursor-avatar-' + vwf_view.kernel.moniker();
  173. if (evt.detail.cursorEl.id.includes(vwf_view.kernel.moniker())) {
  174. vwf_view.kernel.fireEvent(evt.detail.intersection.object.el.id, "clickEvent", [vwf_view.kernel.moniker()])
  175. }
  176. //vwf_view.kernel.fireEvent(evt.detail.target.id, "clickEvent")
  177. });
  178. }
  179. });
  180. AFRAME.registerComponent('aabb-collider-listener', {
  181. // If the target collidable object is moving, set <a-entity data-aabb-collider-dynamic> on the target. By default, collidable objects are presumed to be static for performance purposes.
  182. init: function () {
  183. // let self = this;
  184. // this.me = vwf_view.kernel.moniker();
  185. this.el.addEventListener('hitstart', function (evt) {
  186. vwf_view.kernel.fireEvent(evt.target.id, "hitstartEvent");
  187. })
  188. this.el.addEventListener('hitend', function (evt) {
  189. vwf_view.kernel.fireEvent(evt.target.id, "hitendEvent");
  190. })
  191. }
  192. });
  193. AFRAME.registerComponent('raycaster-listener', {
  194. init: function () {
  195. let self = this;
  196. this.intersected = false;
  197. this.casters = {}
  198. this.me = vwf_view.kernel.moniker();
  199. this.driver = vwf.views["vwf/view/aframe"];
  200. this.el.addEventListener('raycaster-intersected', function (evt) {
  201. if (evt.detail.el.nodeName == 'A-CURSOR') {
  202. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  203. } else {
  204. if (self.intersected) {
  205. } else {
  206. console.log('I was intersected at: ', evt.target);//evt.detail.getIntersection().point);
  207. vwf_view.kernel.fireEvent(evt.target.id, "intersectEvent");
  208. }
  209. self.casters[evt.target.id] = evt.target;
  210. self.intersected = true;
  211. }
  212. });
  213. this.el.addEventListener('raycaster-intersected-cleared', function (evt) {
  214. if (evt.detail.el.nodeName == 'A-CURSOR') {
  215. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  216. } else {
  217. if (self.intersected) {
  218. console.log('Clear intersection');
  219. if (Object.entries(self.casters).length == 1 && (self.casters[evt.target.id] !== undefined)) {
  220. vwf_view.kernel.fireEvent(evt.target.id, "clearIntersectEvent")
  221. }
  222. delete self.casters[evt.target.id]
  223. } else { }
  224. self.intersected = false;
  225. }
  226. });
  227. }
  228. });
  229. AFRAME.registerComponent('envmap', {
  230. /**
  231. * Creates a new THREE.ShaderMaterial using the two shaders defined
  232. * in vertex.glsl and fragment.glsl.
  233. */
  234. init: function () {
  235. const data = this.data;
  236. //this.applyToMesh();
  237. this.el.addEventListener('model-loaded', () => this.applyToMesh());
  238. },
  239. /**
  240. * Update the ShaderMaterial when component data changes.
  241. */
  242. update: function () {
  243. },
  244. getEnvMap: function () {
  245. var path = './assets/textures/skybox2/';
  246. var format = '.jpg';
  247. var urls = [
  248. path + 'px' + format, path + 'nx' + format,
  249. path + 'py' + format, path + 'ny' + format,
  250. path + 'pz' + format, path + 'nz' + format
  251. ];
  252. envMap = new THREE.CubeTextureLoader().load(urls);
  253. envMap.format = THREE.RGBFormat;
  254. return envMap;
  255. },
  256. /**
  257. * Apply the material to the current entity.
  258. */
  259. applyToMesh: function () {
  260. const mesh = this.el.getObject3D('mesh');
  261. //var scene = mesh;
  262. var envMap = this.getEnvMap();
  263. mesh.traverse(function (node) {
  264. if (node.material) {
  265. node.material.side = THREE.BackSide;
  266. node.material.needsUpdate = true;
  267. //side = THREE.DoubleSide; break;
  268. }
  269. });
  270. mesh.traverse(function (node) {
  271. if (node.material && (node.material.isMeshStandardMaterial ||
  272. (node.material.isShaderMaterial && node.material.envMap !== undefined))) {
  273. node.material.envMap = envMap;
  274. node.material.needsUpdate = true;
  275. }
  276. });
  277. // const mesh = this.el.getObject3D('mesh');
  278. // if (mesh) {
  279. // mesh.material = this.material;
  280. // }
  281. },
  282. /**
  283. * On each frame, update the 'time' uniform in the shaders.
  284. */
  285. // tick: function (t) {
  286. // }
  287. })
  288. //https://threejs.org/examples/webgl_shaders_sky.html
  289. AFRAME.registerComponent('skyshader', {
  290. makeSun: function () {
  291. let sunSphere = new THREE.Mesh(
  292. new THREE.SphereBufferGeometry(20000, 16, 8),
  293. new THREE.MeshBasicMaterial({ color: 0xffffff })
  294. );
  295. sunSphere.position.y = - 700000;
  296. sunSphere.visible = true;
  297. let scene = this.el.sceneEl;
  298. this.el.sceneEl.setObject3D('sun', sunSphere);
  299. },
  300. init: function () {
  301. //let sunSphereEl = document.querySelector('a-scene').querySelector('#sun');
  302. //this.sunSphere = sunSphereEl.object3D;
  303. this.makeSun();
  304. this.sunSphere = this.el.sceneEl.getObject3D('sun');
  305. this.sky = new THREE.Sky();
  306. let scene = this.el.sceneEl;
  307. let effectController = {
  308. turbidity: 5,
  309. rayleigh: 2,
  310. mieCoefficient: 0.005,
  311. mieDirectionalG: 0.8,
  312. luminance: 1,
  313. inclination: 0, // elevation / inclination
  314. azimuth: 0.25, // Facing front,
  315. sun: ! true
  316. };
  317. let uniforms = this.sky.uniforms;
  318. uniforms.turbidity.value = effectController.turbidity;
  319. uniforms.rayleigh.value = effectController.rayleigh;
  320. uniforms.luminance.value = effectController.luminance;
  321. uniforms.mieCoefficient.value = effectController.mieCoefficient;
  322. uniforms.mieDirectionalG.value = effectController.mieDirectionalG;
  323. this.el.setObject3D('mesh', this.sky.mesh);
  324. let distance = 400000;
  325. var theta = Math.PI * (effectController.inclination - 0.5);
  326. var phi = 2 * Math.PI * (effectController.azimuth - 0.5);
  327. this.sunSphere.position.x = distance * Math.cos(phi);
  328. this.sunSphere.position.y = distance * Math.sin(phi) * Math.sin(theta);
  329. this.sunSphere.position.z = distance * Math.sin(phi) * Math.cos(theta);
  330. this.sunSphere.visible = effectController.sun;
  331. this.sky.uniforms.sunPosition.value.copy(this.sunSphere.position);
  332. },
  333. update: function () {
  334. },
  335. // tick: function (t) {
  336. // }
  337. })
  338. AFRAME.registerComponent('sun', {
  339. init: function () {
  340. this.sunSphere = new THREE.Mesh(
  341. new THREE.SphereBufferGeometry(20000, 16, 8),
  342. new THREE.MeshBasicMaterial({ color: 0xffffff })
  343. );
  344. this.sunSphere.position.y = - 700000;
  345. this.sunSphere.visible = true;
  346. this.el.setObject3D('mesh', this.sunSphere);
  347. },
  348. update: function () {
  349. },
  350. // tick: function (t) {
  351. // }
  352. })
  353. AFRAME.registerComponent('gearvrcontrol', {
  354. init: function () {
  355. var self = this;
  356. var controllerID = 'gearvr-' + vwf_view.kernel.moniker();
  357. this.el.addEventListener('triggerdown', function (event) {
  358. vwf_view.kernel.callMethod(controllerID, "triggerdown", []);
  359. });
  360. this.el.addEventListener('triggerup', function (event) {
  361. vwf_view.kernel.callMethod(controllerID, "triggerup", []);
  362. });
  363. },
  364. update: function () {
  365. },
  366. // tick: function (t) {
  367. // }
  368. })
  369. AFRAME.registerComponent('xrcontroller', {
  370. schema: {
  371. hand: { default: 'right' }
  372. },
  373. update: function (old) {
  374. this.hand = this.data.hand;
  375. },
  376. init: function () {
  377. var self = this;
  378. this.hand = this.data.hand;
  379. this.controllerID = 'xrcontroller-' + this.hand + '-' + vwf_view.kernel.moniker();
  380. //this.gearel = document.querySelector('#gearvrcontrol');
  381. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  382. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  383. });
  384. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  385. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  386. });
  387. },
  388. // tick: function (t) {
  389. // }
  390. })
  391. AFRAME.registerComponent('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. });