aframe-components.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  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. console.log('I was intersected at: ', evt.target);//evt.detail.getIntersection().point);
  380. vwf_view.kernel.fireEvent(evt.target.id, "intersectEvent");
  381. }
  382. self.casters[evt.target.id] = evt.target;
  383. self.intersected = true;
  384. }
  385. });
  386. this.el.addEventListener('raycaster-intersected-cleared', function (evt) {
  387. if (evt.detail.el.nodeName == 'A-CURSOR') {
  388. //console.log('CURSOR was intersected at: ', evt.detail.intersection.point);
  389. } else {
  390. if (self.intersected) {
  391. console.log('Clear intersection');
  392. if (Object.entries(self.casters).length == 1 && (self.casters[evt.target.id] !== undefined)) {
  393. vwf_view.kernel.fireEvent(evt.target.id, "clearIntersectEvent")
  394. }
  395. delete self.casters[evt.target.id]
  396. } else { }
  397. self.intersected = false;
  398. }
  399. });
  400. }
  401. });
  402. AFRAME.registerComponent('envmap', {
  403. /**
  404. * Creates a new THREE.ShaderMaterial using the two shaders defined
  405. * in vertex.glsl and fragment.glsl.
  406. */
  407. init: function () {
  408. const data = this.data;
  409. //this.applyToMesh();
  410. this.el.addEventListener('model-loaded', () => this.applyToMesh());
  411. },
  412. /**
  413. * Update the ShaderMaterial when component data changes.
  414. */
  415. update: function () {
  416. },
  417. getEnvMap: function () {
  418. var path = './assets/textures/skybox2/';
  419. var format = '.jpg';
  420. var urls = [
  421. path + 'px' + format, path + 'nx' + format,
  422. path + 'py' + format, path + 'ny' + format,
  423. path + 'pz' + format, path + 'nz' + format
  424. ];
  425. envMap = new THREE.CubeTextureLoader().load(urls);
  426. envMap.format = THREE.RGBFormat;
  427. return envMap;
  428. },
  429. /**
  430. * Apply the material to the current entity.
  431. */
  432. applyToMesh: function () {
  433. const mesh = this.el.getObject3D('mesh');
  434. //var scene = mesh;
  435. var envMap = this.getEnvMap();
  436. mesh.traverse(function (node) {
  437. if (node.material) {
  438. node.material.side = THREE.BackSide;
  439. node.material.needsUpdate = true;
  440. //side = THREE.DoubleSide; break;
  441. }
  442. });
  443. mesh.traverse(function (node) {
  444. if (node.material && (node.material.isMeshStandardMaterial ||
  445. (node.material.isShaderMaterial && node.material.envMap !== undefined))) {
  446. node.material.envMap = envMap;
  447. node.material.needsUpdate = true;
  448. }
  449. });
  450. // const mesh = this.el.getObject3D('mesh');
  451. // if (mesh) {
  452. // mesh.material = this.material;
  453. // }
  454. },
  455. /**
  456. * On each frame, update the 'time' uniform in the shaders.
  457. */
  458. // tick: function (t) {
  459. // }
  460. })
  461. //https://threejs.org/examples/webgl_shaders_sky.html
  462. AFRAME.registerComponent('skyshader', {
  463. makeSun: function () {
  464. let sunSphere = new THREE.Mesh(
  465. new THREE.SphereBufferGeometry(20000, 16, 8),
  466. new THREE.MeshBasicMaterial({ color: 0xffffff })
  467. );
  468. sunSphere.position.y = - 700000;
  469. sunSphere.visible = true;
  470. let scene = this.el.sceneEl;
  471. this.el.sceneEl.setObject3D('sun', sunSphere);
  472. },
  473. init: function () {
  474. //let sunSphereEl = document.querySelector('a-scene').querySelector('#sun');
  475. //this.sunSphere = sunSphereEl.object3D;
  476. this.makeSun();
  477. this.sunSphere = this.el.sceneEl.getObject3D('sun');
  478. this.sky = new THREE.Sky();
  479. let scene = this.el.sceneEl;
  480. let effectController = {
  481. turbidity: 5,
  482. rayleigh: 2,
  483. mieCoefficient: 0.005,
  484. mieDirectionalG: 0.8,
  485. luminance: 1,
  486. inclination: 0, // elevation / inclination
  487. azimuth: 0.25, // Facing front,
  488. sun: ! true
  489. };
  490. let uniforms = this.sky.uniforms;
  491. uniforms.turbidity.value = effectController.turbidity;
  492. uniforms.rayleigh.value = effectController.rayleigh;
  493. uniforms.luminance.value = effectController.luminance;
  494. uniforms.mieCoefficient.value = effectController.mieCoefficient;
  495. uniforms.mieDirectionalG.value = effectController.mieDirectionalG;
  496. this.el.setObject3D('mesh', this.sky.mesh);
  497. let distance = 400000;
  498. var theta = Math.PI * (effectController.inclination - 0.5);
  499. var phi = 2 * Math.PI * (effectController.azimuth - 0.5);
  500. this.sunSphere.position.x = distance * Math.cos(phi);
  501. this.sunSphere.position.y = distance * Math.sin(phi) * Math.sin(theta);
  502. this.sunSphere.position.z = distance * Math.sin(phi) * Math.cos(theta);
  503. this.sunSphere.visible = effectController.sun;
  504. this.sky.uniforms.sunPosition.value.copy(this.sunSphere.position);
  505. },
  506. update: function () {
  507. },
  508. // tick: function (t) {
  509. // }
  510. })
  511. AFRAME.registerComponent('sun', {
  512. init: function () {
  513. this.sunSphere = new THREE.Mesh(
  514. new THREE.SphereBufferGeometry(20000, 16, 8),
  515. new THREE.MeshBasicMaterial({ color: 0xffffff })
  516. );
  517. this.sunSphere.position.y = - 700000;
  518. this.sunSphere.visible = true;
  519. this.el.setObject3D('mesh', this.sunSphere);
  520. },
  521. update: function () {
  522. },
  523. // tick: function (t) {
  524. // }
  525. })
  526. AFRAME.registerComponent('gearvrcontrol', {
  527. init: function () {
  528. var self = this;
  529. var controllerID = 'gearvr-' + vwf_view.kernel.moniker();
  530. this.el.addEventListener('triggerdown', function (event) {
  531. vwf_view.kernel.callMethod(controllerID, "triggerdown", []);
  532. });
  533. this.el.addEventListener('triggerup', function (event) {
  534. vwf_view.kernel.callMethod(controllerID, "triggerup", []);
  535. });
  536. //X-buttorn Pressed
  537. this.el.addEventListener('buttondown', function (e) { //xbuttondown
  538. //Start pointing position to teleport
  539. //let buttonID = e.detail.id;
  540. //let avatarID = 'avatar-' + vwf_view.kernel.moniker();
  541. //vwf_view.kernel.callMethod(vwf.application(), "createPrimitive", ['text', buttonID, 'debug', null, avatarID]);
  542. if(e.detail.id == 2){
  543. this.emit('teleportstart');
  544. }
  545. });
  546. //X-buttorn Released
  547. this.el.addEventListener('buttonup', function (e) { //xbuttonup
  548. //Jump to pointed position
  549. if(e.detail.id == 2){
  550. this.emit('teleportend');
  551. }
  552. });
  553. },
  554. update: function () {
  555. },
  556. // tick: function (t) {
  557. // }
  558. })
  559. AFRAME.registerComponent('xrcontroller', {
  560. schema: {
  561. hand: { default: 'right' }
  562. },
  563. update: function (old) {
  564. this.hand = this.data.hand;
  565. },
  566. init: function () {
  567. var self = this;
  568. this.hand = this.data.hand;
  569. this.controllerID = 'xrcontroller-' + this.hand + '-' + vwf_view.kernel.moniker();
  570. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  571. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  572. //this.emit('teleportstart');
  573. });
  574. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  575. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  576. //this.emit('teleportend');
  577. });
  578. //X-buttorn Pressed
  579. this.el.addEventListener('xbuttondown', function (e) { //xbuttondown
  580. //Start pointing position to teleport
  581. console.log('TELEPORT START: ', e);
  582. this.emit('teleportstart');
  583. });
  584. //X-buttorn Released
  585. this.el.addEventListener('xbuttonup', function (e) { //xbuttonup
  586. //Jump to pointed position
  587. console.log('TELEPORT END: ', e);
  588. this.emit('teleportend');
  589. });
  590. this.el.addEventListener('teleported', function (e) { //xbuttonup
  591. //Teleported
  592. console.log('TELEPORTED: ', e);
  593. });
  594. },
  595. // tick: function (t) {
  596. // }
  597. })
  598. AFRAME.registerComponent('wmrvrcontrol', {
  599. schema: {
  600. hand: { default: 'right' }
  601. },
  602. update: function (old) {
  603. this.hand = this.data.hand;
  604. },
  605. init: function () {
  606. var self = this;
  607. this.hand = this.data.hand;
  608. this.controllerID = 'wmrvr-' + this.hand + '-' + vwf_view.kernel.moniker();
  609. //this.gearel = document.querySelector('#gearvrcontrol');
  610. this.el.addEventListener('triggerdown', function (event) { //pointdown 'triggerdown'
  611. vwf_view.kernel.callMethod(self.controllerID, "triggerdown", []);
  612. });
  613. this.el.addEventListener('triggerup', function (event) { //pointup 'triggerup'
  614. vwf_view.kernel.callMethod(self.controllerID, "triggerup", []);
  615. });
  616. },
  617. // tick: function (t) {
  618. // }
  619. })
  620. AFRAME.registerComponent('streamsound', {
  621. schema: {
  622. positional: { default: true }
  623. },
  624. init: function () {
  625. var self = this;
  626. let driver = vwf.views["/drivers/view/webrtc"];
  627. this.listener = null;
  628. this.stream = null;
  629. if (!this.sound) {
  630. this.setupSound();
  631. }
  632. if (driver) {
  633. //let avatarID = 'avatar-' + vwf.moniker();
  634. let avatarID = this.el.id.slice(0, 27); //avatar-0RtnYBBTBU84OCNcAAFY
  635. let client = driver.state.clients[avatarID];
  636. if (client) {
  637. if (client.connection) {
  638. this.stream = client.connection.stream;
  639. if (this.stream) {
  640. this.audioEl = new Audio();
  641. this.audioEl.srcObject = this.stream;
  642. this.sound.setNodeSource(this.sound.context.createMediaStreamSource(this.stream));
  643. }
  644. }
  645. }
  646. }
  647. },
  648. setupSound: function () {
  649. var el = this.el;
  650. var sceneEl = el.sceneEl;
  651. if (this.sound) {
  652. el.removeObject3D(this.attrName);
  653. }
  654. if (!sceneEl.audioListener) {
  655. sceneEl.audioListener = new THREE.AudioListener();
  656. sceneEl.camera && sceneEl.camera.add(sceneEl.audioListener);
  657. sceneEl.addEventListener('camera-set-active', function (evt) {
  658. evt.detail.cameraEl.getObject3D('camera').add(sceneEl.audioListener);
  659. });
  660. }
  661. this.listener = sceneEl.audioListener;
  662. this.sound = this.data.positional
  663. ? new THREE.PositionalAudio(this.listener)
  664. : new THREE.Audio(this.listener);
  665. el.setObject3D(this.attrName, this.sound);
  666. },
  667. remove: function () {
  668. if (!this.sound) return;
  669. this.el.removeObject3D(this.attrName);
  670. if (this.stream) {
  671. this.sound.disconnect();
  672. }
  673. },
  674. update: function (old) {
  675. },
  676. // tick: function (t) {
  677. // }
  678. })
  679. AFRAME.registerComponent('viewoffset', {
  680. // fullWidth:
  681. // fullHeight:
  682. // xoffset:
  683. // yoffset:
  684. // width:
  685. // height:
  686. schema: {
  687. fullWidth: { default: window.innerWidth },
  688. fullHeight: { default: window.innerHeight },
  689. xoffset: { default: window.innerWidth / 2 },
  690. yoffset: { default: window.innerHeight / 2 },
  691. width: { default: window.innerWidth },
  692. height: { default: window.innerHeight }
  693. },
  694. init: function () {
  695. var self = this;
  696. this.el.sceneEl.addEventListener('loaded', setOffset);
  697. function setOffset() {
  698. this.setNewOffset();
  699. }
  700. },
  701. update: function (old) {
  702. this.fullWidth = this.data.fullWidth;
  703. this.fullHeight = this.data.fullHeight;
  704. this.xoffset = this.data.xoffset;
  705. this.yoffset = this.data.yoffset;
  706. this.width = this.data.width;
  707. this.height = this.data.height;
  708. //console.log(this.data);
  709. this.setNewOffset();
  710. },
  711. setNewOffset: function () {
  712. this.el.object3DMap.camera.setViewOffset(
  713. this.data.fullWidth,
  714. this.data.fullHeight,
  715. this.data.xoffset,
  716. this.data.yoffset,
  717. this.data.width,
  718. this.data.height)
  719. },
  720. // tick: function (t) {
  721. // }
  722. })
  723. AFRAME.registerComponent("virtual-gamepad-controls", {
  724. schema: {},
  725. init() {
  726. this.onEnterVr = this.onEnterVr.bind(this);
  727. this.onExitVr = this.onExitVr.bind(this);
  728. this.onFirstInteraction = this.onFirstInteraction.bind(this);
  729. this.onMoveJoystickChanged = this.onMoveJoystickChanged.bind(this);
  730. this.onMoveJoystickEnd = this.onMoveJoystickEnd.bind(this);
  731. // this.onLookJoystickChanged = this.onLookJoystickChanged.bind(this);
  732. // this.onLookJoystickEnd = this.onLookJoystickEnd.bind(this);
  733. this.mockJoystickContainer = document.createElement("div");
  734. this.mockJoystickContainer.classList.add('mockJoystickContainer');
  735. const leftMock = document.createElement("div");
  736. leftMock.classList.add('mockJoystick');
  737. const leftMockSmall = document.createElement("div");
  738. leftMockSmall.classList.add('mockJoystick', 'inner');
  739. leftMock.appendChild(leftMockSmall);
  740. this.mockJoystickContainer.appendChild(leftMock);
  741. // const rightMock = document.createElement("div");
  742. // rightMock.classList.add('mockJoystick');
  743. // const rightMockSmall = document.createElement("div");
  744. // rightMockSmall.classList.add('mockJoystick', 'inner');
  745. // rightMock.appendChild(rightMockSmall);
  746. // this.mockJoystickContainer.appendChild(rightMock);
  747. document.body.appendChild(this.mockJoystickContainer);
  748. // Setup gamepad elements
  749. const leftTouchZone = document.createElement("div");
  750. leftTouchZone.classList.add('touchZone', 'left');
  751. document.body.appendChild(leftTouchZone);
  752. this.leftTouchZone = leftTouchZone;
  753. this.leftStick = nipplejs.create({
  754. zone: this.leftTouchZone,
  755. color: "white",
  756. fadeTime: 0
  757. });
  758. this.leftStick.on("start", this.onFirstInteraction);
  759. this.leftStick.on("move", this.onMoveJoystickChanged);
  760. this.leftStick.on("end", this.onMoveJoystickEnd);
  761. // const rightTouchZone = document.createElement("div");
  762. // rightTouchZone.classList.add('touchZone', 'right');
  763. // document.body.appendChild(rightTouchZone);
  764. // this.rightTouchZone = rightTouchZone;
  765. // this.rightStick = nipplejs.create({
  766. // zone: this.rightTouchZone,
  767. // color: "white",
  768. // fadeTime: 0
  769. // });
  770. // this.rightStick.on("start", this.onFirstInteraction);
  771. // this.rightStick.on("move", this.onLookJoystickChanged);
  772. // this.rightStick.on("end", this.onLookJoystickEnd);
  773. this.inVr = false;
  774. this.moving = false;
  775. this.rotating = false;
  776. this.moveEvent = {
  777. axis: [0, 0]
  778. };
  779. // this.rotateYEvent = {
  780. // value: 0
  781. // };
  782. // this.rotateXEvent = {
  783. // value: 0
  784. // };
  785. this.el.sceneEl.addEventListener("enter-vr", this.onEnterVr);
  786. this.el.sceneEl.addEventListener("exit-vr", this.onExitVr);
  787. },
  788. onFirstInteraction() {
  789. this.leftStick.off("start", this.onFirstInteraction);
  790. //this.rightStick.off("start", this.onFirstInteraction);
  791. document.body.removeChild(this.mockJoystickContainer);
  792. },
  793. onMoveJoystickChanged(event, joystick) {
  794. const angle = joystick.angle.radian;
  795. const force = joystick.force < 1 ? joystick.force : 1;
  796. const moveStrength = 1.85;
  797. const x = Math.cos(angle) * force * moveStrength;
  798. const z = Math.sin(angle) * force * moveStrength;
  799. this.moving = true;
  800. this.moveEvent.axis[0] = x;
  801. this.moveEvent.axis[1] = z;
  802. },
  803. onMoveJoystickEnd() {
  804. this.moving = false;
  805. this.moveEvent.axis[0] = 0;
  806. this.moveEvent.axis[1] = 0;
  807. this.el.emit("move", this.moveEvent);
  808. },
  809. onLookJoystickChanged(event, joystick) {
  810. // Set pitch and yaw angles on right stick move
  811. const angle = joystick.angle.radian;
  812. const force = joystick.force < 1 ? joystick.force : 1;
  813. const turnStrength = 0.5;
  814. this.rotating = true;
  815. this.rotateYEvent.value = Math.cos(angle) * force * turnStrength;
  816. this.rotateXEvent.value = Math.sin(angle) * force * turnStrength;
  817. },
  818. onLookJoystickEnd() {
  819. this.rotating = false;
  820. this.rotateYEvent.value = 0;
  821. this.rotateXEvent.value = 0;
  822. this.el.emit("rotateY", this.rotateYEvent);
  823. this.el.emit("rotateX", this.rotateXEvent);
  824. },
  825. tick() {
  826. if (!this.inVr) {
  827. if (this.moving) {
  828. this.el.emit("move", this.moveEvent);
  829. }
  830. // if (this.rotating) {
  831. // this.el.emit("rotateY", this.rotateYEvent);
  832. // this.el.emit("rotateX", this.rotateXEvent);
  833. // }
  834. }
  835. },
  836. onEnterVr() {
  837. // Hide the joystick controls
  838. this.inVr = true;
  839. this.leftTouchZone.style.display = "none";
  840. // this.rightTouchZone.style.display = "none";
  841. },
  842. onExitVr() {
  843. // Show the joystick controls
  844. this.inVr = false;
  845. this.leftTouchZone.style.display = "block";
  846. // this.rightTouchZone.style.display = "block";
  847. },
  848. remove() {
  849. this.el.sceneEl.removeEventListener("entervr", this.onEnterVr);
  850. this.el.sceneEl.removeEventListener("exitvr", this.onExitVr);
  851. if (document.getElementsByClassName('mockJoystickContainer').length > 0){
  852. document.body.removeChild(this.mockJoystickContainer);
  853. }
  854. document.body.removeChild(this.leftTouchZone);
  855. // document.body.removeChild(this.rightTouchZone);
  856. }
  857. });
  858. ////ARJS///
  859. //////////////////////////////////////////////////////////////////////////////
  860. // arjs-anchor
  861. //////////////////////////////////////////////////////////////////////////////
  862. AFRAME.registerComponent('arjs-anchor', {
  863. dependencies: ['arjs', 'artoolkit'],
  864. schema: {
  865. preset: {
  866. type: 'string',
  867. },
  868. markerhelpers: { // IIF preset === 'area'
  869. type: 'boolean',
  870. default: false,
  871. },
  872. // controls parameters
  873. size: {
  874. type: 'number',
  875. default: 1
  876. },
  877. type: {
  878. type: 'string',
  879. },
  880. patternUrl: {
  881. type: 'string',
  882. },
  883. barcodeValue: {
  884. type: 'number'
  885. },
  886. changeMatrixMode: {
  887. type: 'string',
  888. default: 'modelViewMatrix',
  889. },
  890. minConfidence: {
  891. type: 'number',
  892. default: 0.6,
  893. },
  894. smooth: {
  895. type: 'boolean',
  896. default: false,
  897. },
  898. smoothCount: {
  899. type: 'number',
  900. default: 5,
  901. },
  902. smoothTolerance: {
  903. type: 'number',
  904. default: 0.01,
  905. },
  906. smoothThreshold: {
  907. type: 'number',
  908. default: 2,
  909. },
  910. },
  911. init: function () {
  912. var _this = this
  913. // get arjsSystem
  914. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  915. //////////////////////////////////////////////////////////////////////////////
  916. // Code Separator
  917. //////////////////////////////////////////////////////////////////////////////
  918. _this.isReady = false
  919. _this._arAnchor = null
  920. //LiveCoding.space fix for editor mode
  921. if(arjsSystem) {
  922. // honor object visibility
  923. if (_this.data.changeMatrixMode === 'modelViewMatrix') {
  924. _this.el.object3D.visible = false
  925. } else if (_this.data.changeMatrixMode === 'cameraTransformMatrix') {
  926. _this.el.sceneEl.object3D.visible = false
  927. } else console.assert(false)
  928. // trick to wait until arjsSystem is isReady
  929. var startedAt = Date.now()
  930. var timerId = setInterval(function () {
  931. // wait until the system is isReady
  932. if (arjsSystem.isReady === false) return
  933. clearInterval(timerId)
  934. //////////////////////////////////////////////////////////////////////////////
  935. // update arProfile
  936. //////////////////////////////////////////////////////////////////////////////
  937. var arProfile = arjsSystem._arProfile
  938. // arProfile.changeMatrixMode('modelViewMatrix')
  939. arProfile.changeMatrixMode(_this.data.changeMatrixMode)
  940. // honor this.data.preset
  941. var markerParameters = Object.assign({}, arProfile.defaultMarkerParameters)
  942. if (_this.data.preset === 'hiro') {
  943. markerParameters.type = 'pattern'
  944. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-hiro.patt'
  945. markerParameters.markersAreaEnabled = false
  946. } else if (_this.data.preset === 'kanji') {
  947. markerParameters.type = 'pattern'
  948. markerParameters.patternUrl = THREEx.ArToolkitContext.baseURL + 'examples/marker-training/examples/pattern-files/pattern-kanji.patt'
  949. markerParameters.markersAreaEnabled = false
  950. } else if (_this.data.preset === 'area') {
  951. markerParameters.type = 'barcode'
  952. markerParameters.barcodeValue = 1001
  953. markerParameters.markersAreaEnabled = true
  954. } else if (_this.data.type === 'barcode') {
  955. markerParameters = {
  956. type: _this.data.type,
  957. changeMatrixMode: 'modelViewMatrix',
  958. barcodeValue: _this.data.barcodeValue,
  959. markersAreaEnabled: false
  960. }
  961. } else if (_this.data.type === 'pattern') {
  962. markerParameters.type = _this.data.type
  963. markerParameters.patternUrl = _this.data.patternUrl;
  964. markerParameters.markersAreaEnabled = false
  965. }
  966. markerParameters.smooth = _this.data.smooth;
  967. markerParameters.smoothCount = _this.data.smoothCount;
  968. markerParameters.smoothTolerance = _this.data.smoothTolerance;
  969. markerParameters.smoothThreshold = _this.data.smoothThreshold;
  970. //////////////////////////////////////////////////////////////////////////////
  971. // create arAnchor
  972. //////////////////////////////////////////////////////////////////////////////
  973. var arSession = arjsSystem._arSession
  974. var arAnchor = _this._arAnchor = new ARjs.Anchor(arSession, markerParameters)
  975. // it is now considered isReady
  976. _this.isReady = true
  977. //////////////////////////////////////////////////////////////////////////////
  978. // honor .debugUIEnabled
  979. //////////////////////////////////////////////////////////////////////////////
  980. if (arjsSystem.data.debugUIEnabled) {
  981. // get or create containerElement
  982. var containerElement = document.querySelector('#arjsDebugUIContainer')
  983. if (containerElement === null) {
  984. containerElement = document.createElement('div')
  985. containerElement.id = 'arjsDebugUIContainer'
  986. containerElement.setAttribute('style', 'position: fixed; bottom: 10px; width:100%; text-align: center; z-index: 1; color: grey;')
  987. document.body.appendChild(containerElement)
  988. }
  989. // create anchorDebugUI
  990. var anchorDebugUI = new ARjs.AnchorDebugUI(arAnchor)
  991. containerElement.appendChild(anchorDebugUI.domElement)
  992. }
  993. }, 1000 / 60)
  994. }
  995. },
  996. remove: function () {
  997. },
  998. update: function () {
  999. },
  1000. tick: function () {
  1001. var _this = this
  1002. // if not yet isReady, do nothing
  1003. if (this.isReady === false) return
  1004. //////////////////////////////////////////////////////////////////////////////
  1005. // update arAnchor
  1006. //////////////////////////////////////////////////////////////////////////////
  1007. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  1008. this._arAnchor.update()
  1009. //////////////////////////////////////////////////////////////////////////////
  1010. // honor pose
  1011. //////////////////////////////////////////////////////////////////////////////
  1012. var arWorldRoot = this._arAnchor.object3d
  1013. arWorldRoot.updateMatrixWorld(true)
  1014. arWorldRoot.matrixWorld.decompose(this.el.object3D.position, this.el.object3D.quaternion, this.el.object3D.scale)
  1015. //////////////////////////////////////////////////////////////////////////////
  1016. // honor visibility
  1017. //////////////////////////////////////////////////////////////////////////////
  1018. if (_this._arAnchor.parameters.changeMatrixMode === 'modelViewMatrix') {
  1019. var wasVisible = _this.el.object3D.visible
  1020. _this.el.object3D.visible = this._arAnchor.object3d.visible
  1021. } else if (_this._arAnchor.parameters.changeMatrixMode === 'cameraTransformMatrix') {
  1022. var wasVisible = _this.el.sceneEl.object3D.visible
  1023. _this.el.sceneEl.object3D.visible = this._arAnchor.object3d.visible
  1024. } else console.assert(false)
  1025. // emit markerFound markerLost
  1026. if (_this._arAnchor.object3d.visible === true && wasVisible === false) {
  1027. _this.el.emit('markerFound')
  1028. } else if (_this._arAnchor.object3d.visible === false && wasVisible === true) {
  1029. _this.el.emit('markerLost')
  1030. }
  1031. }
  1032. })
  1033. //////////////////////////////////////////////////////////////////////////////
  1034. // define some primitives shortcuts
  1035. //////////////////////////////////////////////////////////////////////////////
  1036. AFRAME.registerPrimitive('a-anchor', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  1037. defaultComponents: {
  1038. 'arjs-anchor': {},
  1039. 'arjs-hit-testing': {},
  1040. },
  1041. mappings: {
  1042. 'type': 'arjs-anchor.type',
  1043. 'size': 'arjs-anchor.size',
  1044. 'url': 'arjs-anchor.patternUrl',
  1045. 'value': 'arjs-anchor.barcodeValue',
  1046. 'preset': 'arjs-anchor.preset',
  1047. 'min-confidence': 'arjs-anchor.minConfidence',
  1048. 'marker-helpers': 'arjs-anchor.markerhelpers',
  1049. 'smooth': 'arjs-anchor.smooth',
  1050. 'smooth-count': 'arjs-anchor.smoothCount',
  1051. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  1052. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  1053. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  1054. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  1055. }
  1056. }))
  1057. AFRAME.registerPrimitive('a-camera-static', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  1058. defaultComponents: {
  1059. 'camera': {},
  1060. },
  1061. mappings: {
  1062. }
  1063. }))
  1064. //////////////////////////////////////////////////////////////////////////////
  1065. // backward compatibility
  1066. //////////////////////////////////////////////////////////////////////////////
  1067. // FIXME
  1068. AFRAME.registerPrimitive('a-marker', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  1069. defaultComponents: {
  1070. 'arjs-anchor': {},
  1071. 'arjs-hit-testing': {},
  1072. },
  1073. mappings: {
  1074. 'type': 'arjs-anchor.type',
  1075. 'size': 'arjs-anchor.size',
  1076. 'url': 'arjs-anchor.patternUrl',
  1077. 'value': 'arjs-anchor.barcodeValue',
  1078. 'preset': 'arjs-anchor.preset',
  1079. 'min-confidence': 'arjs-anchor.minConfidence',
  1080. 'marker-helpers': 'arjs-anchor.markerhelpers',
  1081. 'smooth': 'arjs-anchor.smooth',
  1082. 'smooth-count': 'arjs-anchor.smoothCount',
  1083. 'smooth-tolerance': 'arjs-anchor.smoothTolerance',
  1084. 'smooth-threshold': 'arjs-anchor.smoothThreshold',
  1085. 'hit-testing-render-debug': 'arjs-hit-testing.renderDebug',
  1086. 'hit-testing-enabled': 'arjs-hit-testing.enabled',
  1087. }
  1088. }))
  1089. AFRAME.registerPrimitive('a-marker-camera', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
  1090. defaultComponents: {
  1091. 'arjs-anchor': {
  1092. changeMatrixMode: 'cameraTransformMatrix'
  1093. },
  1094. 'camera': {},
  1095. },
  1096. mappings: {
  1097. 'type': 'arjs-anchor.type',
  1098. 'size': 'arjs-anchor.size',
  1099. 'url': 'arjs-anchor.patternUrl',
  1100. 'value': 'arjs-anchor.barcodeValue',
  1101. 'preset': 'arjs-anchor.preset',
  1102. 'min-confidence': 'arjs-anchor.minConfidence',
  1103. 'marker-helpers': 'arjs-anchor.markerhelpers',
  1104. }
  1105. }))
  1106. //////////////////////////////////////////////////////////////////////////////
  1107. // arjs-hit-testing
  1108. //////////////////////////////////////////////////////////////////////////////
  1109. AFRAME.registerComponent('arjs-hit-testing', {
  1110. dependencies: ['arjs', 'artoolkit'],
  1111. schema: {
  1112. enabled : {
  1113. type: 'boolean',
  1114. default: false,
  1115. },
  1116. renderDebug : {
  1117. type: 'boolean',
  1118. default: false,
  1119. },
  1120. },
  1121. init: function () {
  1122. var _this = this
  1123. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  1124. // TODO make it work on cameraTransformMatrix too
  1125. //
  1126. _this.isReady = false
  1127. _this._arAnchor = null
  1128. _this._arHitTesting = null
  1129. //LiveCdoing.space fix for editor mode
  1130. if(arjsSystem) {
  1131. // trick to wait until arjsSystem is isReady
  1132. var startedAt = Date.now()
  1133. var timerId = setInterval(function(){
  1134. var anchorEl = _this.el
  1135. var anchorComponent = anchorEl.components['arjs-anchor']
  1136. // wait until anchorComponent is isReady
  1137. if( anchorComponent === undefined || anchorComponent.isReady === false ) return
  1138. clearInterval(timerId)
  1139. //////////////////////////////////////////////////////////////////////////////
  1140. // create arAnchor
  1141. //////////////////////////////////////////////////////////////////////////////
  1142. var arAnchor = anchorComponent._arAnchor
  1143. var arSession = arjsSystem._arSession
  1144. var renderer = arSession.parameters.renderer
  1145. var hitTesting = _this._arHitTesting = new ARjs.HitTesting(arSession)
  1146. hitTesting.enabled = _this.data.enabled
  1147. _this.isReady = true
  1148. }, 1000/60)
  1149. }
  1150. },
  1151. remove : function(){
  1152. },
  1153. update: function () {
  1154. },
  1155. tick: function(){
  1156. var _this = this
  1157. // if not yet isReady, do nothing
  1158. if( this.isReady === false ) return
  1159. var arjsSystem = this.el.sceneEl.systems.arjs || this.el.sceneEl.systems.artoolkit
  1160. var arSession = arjsSystem._arSession
  1161. var anchorEl = _this.el
  1162. var anchorComponent = anchorEl.components['arjs-anchor']
  1163. var arAnchor = anchorComponent._arAnchor
  1164. var hitTesting = this._arHitTesting
  1165. var camera = arSession.parameters.camera
  1166. // console.log(camera.position)
  1167. hitTesting.update(camera, arAnchor.object3d, arAnchor.parameters.changeMatrixMode)
  1168. }
  1169. });
  1170. ///////////////END ARJS/////////
  1171. ///MIRROR//
  1172. THREE.ShaderLib[ 'mirror' ] = {
  1173. uniforms: {
  1174. "mirrorColor": { value: new THREE.Color( 0x7F7F7F ) },
  1175. "mirrorSampler": { value: null },
  1176. "textureMatrix" : { value: new THREE.Matrix4() }
  1177. },
  1178. vertexShader: [
  1179. "uniform mat4 textureMatrix;",
  1180. "varying vec4 mirrorCoord;",
  1181. "void main() {",
  1182. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1183. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  1184. "mirrorCoord = textureMatrix * worldPosition;",
  1185. "gl_Position = projectionMatrix * mvPosition;",
  1186. "}"
  1187. ].join( "\n" ),
  1188. fragmentShader: [
  1189. "uniform vec3 mirrorColor;",
  1190. "uniform sampler2D mirrorSampler;",
  1191. "varying vec4 mirrorCoord;",
  1192. "float blendOverlay(float base, float blend) {",
  1193. "return( base < 0.5 ? ( 2.0 * base * blend ) : (1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );",
  1194. "}",
  1195. "void main() {",
  1196. "vec4 color = texture2DProj(mirrorSampler, mirrorCoord);",
  1197. "color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), 1.0);",
  1198. "gl_FragColor = color;",
  1199. "}"
  1200. ].join( "\n" )
  1201. };
  1202. THREE.Mirror = function ( renderer, camera, options ) {
  1203. THREE.Object3D.call( this );
  1204. this.name = 'mirror_' + this.id;
  1205. options = options || {};
  1206. this.matrixNeedsUpdate = true;
  1207. var width = options.textureWidth !== undefined ? options.textureWidth : 512;
  1208. var height = options.textureHeight !== undefined ? options.textureHeight : 512;
  1209. this.clipBias = options.clipBias !== undefined ? options.clipBias : 0.0;
  1210. var mirrorColor = options.color !== undefined ? new THREE.Color( options.color ) : new THREE.Color( 0x7F7F7F );
  1211. this.renderer = renderer;
  1212. this.mirrorPlane = new THREE.Plane();
  1213. this.normal = new THREE.Vector3( 0, 0, 1 );
  1214. this.mirrorWorldPosition = new THREE.Vector3();
  1215. this.cameraWorldPosition = new THREE.Vector3();
  1216. this.rotationMatrix = new THREE.Matrix4();
  1217. this.lookAtPosition = new THREE.Vector3( 0, 0, - 1 );
  1218. this.clipPlane = new THREE.Vector4();
  1219. // For debug only, show the normal and plane of the mirror
  1220. var debugMode = options.debugMode !== undefined ? options.debugMode : false;
  1221. if ( debugMode ) {
  1222. var arrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, 0 ), 10, 0xffff80 );
  1223. var planeGeometry = new THREE.Geometry();
  1224. planeGeometry.vertices.push( new THREE.Vector3( - 10, - 10, 0 ) );
  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( planeGeometry.vertices[ 0 ] );
  1229. var plane = new THREE.Line( planeGeometry, new THREE.LineBasicMaterial( { color: 0xffff80 } ) );
  1230. this.add( arrow );
  1231. this.add( plane );
  1232. }
  1233. if ( camera instanceof THREE.PerspectiveCamera ) {
  1234. this.camera = camera;
  1235. } else {
  1236. this.camera = new THREE.PerspectiveCamera();
  1237. console.log( this.name + ': camera is not a Perspective Camera!' );
  1238. }
  1239. this.textureMatrix = new THREE.Matrix4();
  1240. this.mirrorCamera = this.camera.clone();
  1241. this.mirrorCamera.matrixAutoUpdate = true;
  1242. var parameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
  1243. //this.currentRenderTarget = this.renderer.getRenderTarget();
  1244. this.renderTarget = new THREE.WebGLRenderTarget( width, height, parameters );
  1245. this.renderTarget2 = new THREE.WebGLRenderTarget( width, height, parameters );
  1246. var mirrorShader = THREE.ShaderLib[ "mirror" ];
  1247. var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
  1248. this.material = new THREE.ShaderMaterial( {
  1249. fragmentShader: mirrorShader.fragmentShader,
  1250. vertexShader: mirrorShader.vertexShader,
  1251. uniforms: mirrorUniforms
  1252. } );
  1253. this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
  1254. this.material.uniforms.mirrorColor.value = mirrorColor;
  1255. this.material.uniforms.textureMatrix.value = this.textureMatrix;
  1256. if ( ! THREE.Math.isPowerOfTwo( width ) || ! THREE.Math.isPowerOfTwo( height ) ) {
  1257. this.renderTarget.texture.generateMipmaps = false;
  1258. this.renderTarget2.texture.generateMipmaps = false;
  1259. }
  1260. this.updateTextureMatrix();
  1261. this.render();
  1262. };
  1263. THREE.Mirror.prototype = Object.create( THREE.Object3D.prototype );
  1264. THREE.Mirror.prototype.constructor = THREE.Mirror;
  1265. THREE.Mirror.prototype.renderWithMirror = function ( otherMirror, aScene ) {
  1266. // update the mirror matrix to mirror the current view
  1267. this.updateTextureMatrix();
  1268. this.matrixNeedsUpdate = false;
  1269. // set the camera of the other mirror so the mirrored view is the reference view
  1270. var tempCamera = otherMirror.camera;
  1271. otherMirror.camera = this.mirrorCamera;
  1272. // render the other mirror in temp texture
  1273. otherMirror.renderTemp(aScene);
  1274. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget2.texture;
  1275. // render the current mirror
  1276. this.render(aScene);
  1277. this.matrixNeedsUpdate = true;
  1278. // restore material and camera of other mirror
  1279. otherMirror.material.uniforms.mirrorSampler.value = otherMirror.renderTarget.texture;
  1280. otherMirror.camera = tempCamera;
  1281. // restore texture matrix of other mirror
  1282. otherMirror.updateTextureMatrix();
  1283. };
  1284. THREE.Mirror.prototype.updateTextureMatrix = function () {
  1285. this.updateMatrixWorld();
  1286. this.camera.updateMatrixWorld();
  1287. this.mirrorWorldPosition.setFromMatrixPosition( this.matrixWorld );
  1288. this.cameraWorldPosition.setFromMatrixPosition( this.camera.matrixWorld );
  1289. this.rotationMatrix.extractRotation( this.matrixWorld );
  1290. this.normal.set( 0, 0, 1 );
  1291. this.normal.applyMatrix4( this.rotationMatrix );
  1292. var view = this.mirrorWorldPosition.clone().sub( this.cameraWorldPosition );
  1293. view.reflect( this.normal ).negate();
  1294. view.add( this.mirrorWorldPosition );
  1295. this.rotationMatrix.extractRotation( this.camera.matrixWorld );
  1296. this.lookAtPosition.set( 0, 0, - 1 );
  1297. this.lookAtPosition.applyMatrix4( this.rotationMatrix );
  1298. this.lookAtPosition.add( this.cameraWorldPosition );
  1299. var target = this.mirrorWorldPosition.clone().sub( this.lookAtPosition );
  1300. target.reflect( this.normal ).negate();
  1301. target.add( this.mirrorWorldPosition );
  1302. this.up.set( 0, - 1, 0 );
  1303. this.up.applyMatrix4( this.rotationMatrix );
  1304. this.up.reflect( this.normal ).negate();
  1305. this.mirrorCamera.position.copy( view );
  1306. this.mirrorCamera.up = this.up;
  1307. this.mirrorCamera.lookAt( target );
  1308. this.mirrorCamera.updateProjectionMatrix();
  1309. this.mirrorCamera.updateMatrixWorld();
  1310. this.mirrorCamera.matrixWorldInverse.getInverse( this.mirrorCamera.matrixWorld );
  1311. // Update the texture matrix
  1312. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  1313. 0.0, 0.5, 0.0, 0.5,
  1314. 0.0, 0.0, 0.5, 0.5,
  1315. 0.0, 0.0, 0.0, 1.0 );
  1316. this.textureMatrix.multiply( this.mirrorCamera.projectionMatrix );
  1317. this.textureMatrix.multiply( this.mirrorCamera.matrixWorldInverse );
  1318. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  1319. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  1320. this.mirrorPlane.setFromNormalAndCoplanarPoint( this.normal, this.mirrorWorldPosition );
  1321. this.mirrorPlane.applyMatrix4( this.mirrorCamera.matrixWorldInverse );
  1322. this.clipPlane.set( this.mirrorPlane.normal.x, this.mirrorPlane.normal.y, this.mirrorPlane.normal.z, this.mirrorPlane.constant );
  1323. var q = new THREE.Vector4();
  1324. var projectionMatrix = this.mirrorCamera.projectionMatrix;
  1325. q.x = ( Math.sign( this.clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  1326. q.y = ( Math.sign( this.clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  1327. q.z = - 1.0;
  1328. q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  1329. // Calculate the scaled plane vector
  1330. var c = new THREE.Vector4();
  1331. c = this.clipPlane.multiplyScalar( 2.0 / this.clipPlane.dot( q ) );
  1332. // Replacing the third row of the projection matrix
  1333. projectionMatrix.elements[ 2 ] = c.x;
  1334. projectionMatrix.elements[ 6 ] = c.y;
  1335. projectionMatrix.elements[ 10 ] = c.z + 1.0 - this.clipBias;
  1336. projectionMatrix.elements[ 14 ] = c.w;
  1337. };
  1338. THREE.Mirror.prototype.render = function (aScene) {
  1339. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1340. this.matrixNeedsUpdate = true;
  1341. // Render the mirrored view of the current scene into the target texture
  1342. //var scene = aScene //this;
  1343. // while ( scene.parent !== null ) {
  1344. // scene = scene.parent;
  1345. // }
  1346. //this.renderer.setRenderTarget( null );
  1347. if ( aScene !== undefined) //&& scene instanceof THREE.Scene )
  1348. {
  1349. // We can't render ourself to ourself
  1350. var visible = this.material.visible;
  1351. this.material.visible = false;
  1352. this.renderer.clear();
  1353. this.renderer.setRenderTarget( this.renderTarget);
  1354. this.renderer.render( aScene.object3D, this.mirrorCamera);
  1355. this.renderer.setRenderTarget(null);
  1356. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget, true );
  1357. this.material.visible = visible;
  1358. }
  1359. };
  1360. THREE.Mirror.prototype.renderTemp = function (aScene) {
  1361. if ( this.matrixNeedsUpdate ) this.updateTextureMatrix();
  1362. this.matrixNeedsUpdate = true;
  1363. // Render the mirrored view of the current scene into the target texture
  1364. // var scene = this;
  1365. // while ( scene.parent !== null ) {
  1366. // scene = scene.parent;
  1367. // }
  1368. if ( aScene !== undefined) //&& scene instanceof THREE.Scene ) {
  1369. {
  1370. this.renderer.clear();
  1371. this.renderer.setRenderTarget( this.renderTarget2);
  1372. this.renderer.render( aScene.object3D, this.mirrorCamera );
  1373. this.renderer.setRenderTarget( null );
  1374. //this.renderer.render( scene, this.mirrorCamera, this.renderTarget2, true );
  1375. }
  1376. };
  1377. AFRAME.registerComponent('mirror', {
  1378. schema:{
  1379. renderothermirror:{default:true},
  1380. camera:{default: 'avatarControl'}
  1381. },
  1382. init: function () {
  1383. var scene = this.el.sceneEl;
  1384. this.cameraID = this.data.camera;
  1385. scene.addEventListener('render-target-loaded',this.OnRenderLoaded()); //this.OnRenderLoaded.bind(this)
  1386. },
  1387. // update: function (old) {
  1388. // this.cameraID = this.data.camera;
  1389. // this.OnRenderLoaded();
  1390. // },
  1391. OnRenderLoaded: function()
  1392. {
  1393. var mirrorObj = this.el.getOrCreateObject3D('mesh',THREE.Mesh);
  1394. // var cameraEl = document.querySelector('a-entity[camera]')
  1395. // if(!cameraEl)
  1396. // {
  1397. // cameraEl = document.querySelector('a-camera');
  1398. // }
  1399. // var camera = cameraEl.components.camera.camera;
  1400. let cameraEl = document.querySelector("[id='" + this.cameraID + "']")
  1401. if (cameraEl){
  1402. let camera = cameraEl.getObject3D('camera'); //document.querySelector('#avatarControl').getObject3D('camera');
  1403. var scene = this.el.sceneEl;
  1404. // this.renderer = new THREE.WebGLRenderer({
  1405. // antialias: true,
  1406. // });
  1407. this.renderer = scene.renderer;
  1408. this.mirror = new THREE.Mirror( this.renderer, camera, { clipBias: 0.003, textureWidth: window.innerWidth, textureHeight: window.innerHeight, color: 0x777777, debugMode: false} );
  1409. mirrorObj.material = this.mirror.material;
  1410. //mirrorObj.children = [];
  1411. mirrorObj.add(this.mirror);
  1412. }
  1413. //As of A-Frame tick (behaviours) priority issue need to place mirror tick onto upper tick()
  1414. this.el.sceneEl.components['scene-utils'].mirrors[this.el.id] = this;
  1415. },
  1416. remove: function () {
  1417. delete this.el.sceneEl.components['scene-utils'].mirrors[this.el.id]
  1418. },
  1419. mirrorTick: function () {
  1420. // //this.mirror.render();
  1421. if(!this.data.renderothermirror)
  1422. {
  1423. this.mirror.render(this.el.sceneEl);
  1424. }
  1425. else
  1426. {
  1427. var mirrors = [];
  1428. var mirrorEls = document.querySelectorAll("[mirror]");
  1429. for(var i=0;i<mirrorEls.length;i++)
  1430. {
  1431. if(mirrorEls[i]!=this.el)
  1432. {
  1433. mirrors.push(mirrorEls[i].components.mirror.mirror);
  1434. }
  1435. }
  1436. if(mirrors.length === 0)
  1437. {
  1438. this.mirror.render(this.el.sceneEl);
  1439. }
  1440. for(var i = 0; i<mirrors.length;i++)
  1441. {
  1442. this.mirror.renderWithMirror(mirrors[i], this.el.sceneEl);
  1443. }
  1444. }
  1445. },
  1446. // tick: function () {
  1447. // }
  1448. });