aframe-components.js 60 KB

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