aframe-components.js 52 KB

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