aframe-components.js 65 KB

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