aframe.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. //"use strict";
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2014-2018 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  5. Virtual World Framework Apache 2.0 license (https://github.com/NikolaySuslov/livecodingspace/blob/master/licenses/LICENSE_VWF.md)
  6. */
  7. // VWF & A-Frame view driver
  8. import {Fabric} from '/core/vwf/fabric.js';
  9. class AFrameView extends Fabric {
  10. constructor(module) {
  11. console.log("AFrameView constructor");
  12. super(module, 'View');
  13. }
  14. factory() {
  15. let _self_ = this;
  16. return this.load(this.module,
  17. {
  18. // == Module Definition ====================================================================
  19. initialize: function (options) {
  20. let self = this;
  21. this.fabric = _self_;
  22. this.nodes = {};
  23. // this.tickTime = 0;
  24. // this.realTickDif = 50;
  25. // this.lastrealTickDif = 50;
  26. // this.lastRealTick = performance.now();
  27. this.state.appInitialized = false;
  28. this.state.showMobileJoystick = function(){
  29. let controlEl = document.querySelector('#avatarControl');
  30. if(controlEl){
  31. controlEl.setAttribute("virtual-gamepad-controls", {});
  32. controlEl.addEventListener("move", _self_.setJoystickMoveInput.bind(_self_));
  33. }
  34. }
  35. this.state.hideMobileJoystick = function(){
  36. let controlEl = document.querySelector('#avatarControl');
  37. if(controlEl){
  38. controlEl.removeAttribute("virtual-gamepad-controls");
  39. controlEl.removeEventListener("move", _self_.setJoystickMoveInput.bind(_self_));
  40. }
  41. }
  42. if (options === undefined) { options = {}; }
  43. if (typeof options == "object") {
  44. this.rootSelector = options["application-root"];
  45. }
  46. else {
  47. this.rootSelector = options;
  48. }
  49. // this.gearvr = options.gearvr !== undefined ? options.gearvr : false;
  50. // this.wmrright = options.wmrright !== undefined ? options.wmrright : false;
  51. // this.wmrleft = options.wmrleft !== undefined ? options.wmrleft : false;
  52. this.xrType = undefined;
  53. //TODO: FIX detection in better way! (now works for Oculus Browser only)
  54. this.hmd = false;
  55. this.threeDoF = false;
  56. this.sixDoF = false;
  57. this.threeDoFMobile = AFRAME.utils.device.isMobileVR() && AFRAME.utils.device.checkHeadsetConnected() && !navigator.userAgent.includes('Quest');
  58. this.sixDoFMobile = AFRAME.utils.device.checkHeadsetConnected() && navigator.userAgent.includes('Quest');
  59. this.sixDoFDesktop = !AFRAME.utils.device.isMobile() && !AFRAME.utils.device.isMobileVR() && AFRAME.utils.device.checkHeadsetConnected();
  60. },
  61. createdNode: function (nodeID, childID, childExtendsID, childImplementsIDs,
  62. childSource, childType, childIndex, childName, callback /* ( ready ) */) {
  63. let self = this;
  64. var node = this.state.nodes[childID];
  65. // If the "nodes" object does not have this object in it, it must not be one that
  66. // this driver cares about
  67. if (!node) {
  68. return;
  69. }
  70. if (this.state.scenes[childID]) {
  71. let scene = this.state.scenes[childID];
  72. //TODO: FIX
  73. let prepairAvatar = new Promise((resolve, reject) => {
  74. document.body.appendChild(scene);
  75. let createAvatarPromise = new Promise(r=> r(_self_.createAvatarControl(scene)));
  76. return resolve(createAvatarPromise)
  77. });
  78. prepairAvatar.then(res => {
  79. if (self.threeDoFMobile || _app.config.d3DoF ) {
  80. console.log("CREATE GEARVR HERE!!");
  81. this.xrType = 'mobileVR';
  82. let nodeName = 'gearvr-' + self.kernel.moniker();
  83. _self_.createGearVRControls();
  84. _self_.createGearVRController.call(self, childID, nodeName);
  85. }
  86. // if (!AFRAME.utils.device.isMobileVR()) {
  87. if (self.sixDoFMobile || self.sixDoFDesktop || _app.config.d6DoF ) {
  88. console.log("CREATE XRController RIGHT HERE!!");
  89. let nodeRight = 'xrcontroller-right-' + self.kernel.moniker();
  90. _self_.createXRControls('right');
  91. _self_.createXR.call(this, childID, nodeRight);
  92. // if (!AFRAME.utils.device.isMobileVR()) {
  93. console.log("CREATE XRController LEFT HERE!!");
  94. let nodeLeft = 'xrcontroller-left-' + self.kernel.moniker();
  95. _self_.createXRControls('left');
  96. _self_.createXR.call(this, childID, nodeLeft);
  97. }
  98. // }
  99. // console.log(res);
  100. _self_.createAvatar.call(self, childID);
  101. _self_.postLoadAction.call(self, childID);
  102. }).then(res=>{
  103. //document.body.appendChild(scene);
  104. })
  105. // this.state.appInitialized = true;
  106. //document.body.appendChild(scene); //append is not working in Edge browser
  107. }
  108. if (this.state.nodes[childID] && this.state.nodes[childID].aframeObj) {
  109. this.nodes[childID] = {
  110. id: childID,
  111. extends: childExtendsID,
  112. liveBindings: {}
  113. // lastTransformStep: 0,
  114. // lastAnimationStep: 0
  115. };
  116. }
  117. // if(this.state.nodes[childID]) {
  118. // this.nodes[childID] = {id:childID,extends:childExtendsID};
  119. // }
  120. // else if (this.state.nodes[childID] && this.state.nodes[childID].aframeObj.object3D instanceof THREE.Object3D) {
  121. // this.nodes[childID] = {id:childID,extends:childExtendsID};
  122. // }
  123. },
  124. executed: function (nodeID, scriptText, scriptType) {
  125. let self = this;
  126. let node = this.state.nodes[nodeID];
  127. if (!(node)) {
  128. return;
  129. }
  130. },
  131. initializedNode: function (nodeID, childID) {
  132. let self = this;
  133. var node = this.state.nodes[childID];
  134. if (!node) {
  135. return;
  136. }
  137. if (node.extendsID == "proxy/aframe/gearvrcontroller.vwf") {
  138. console.log("gearVR controller initialized")
  139. }
  140. // if (node.extendsID == "proxy/aframe/atext.vwf") {
  141. // console.log("Text component initialized");
  142. // node.aframeObj.play();
  143. // }
  144. // if (node.prototypes.includes("proxy/aframe/aentity.vwf")) {
  145. // var clientThatSatProperty = self.kernel.client();
  146. // var me = self.kernel.moniker();
  147. // // If the transform property was initially updated by this view....
  148. // if (clientThatSatProperty == me) {
  149. // self.kernel.callMethod(childID, "setOwner", [me]);
  150. // }
  151. // }
  152. // if (propertyName == 'ownedBy')
  153. // {
  154. // // if (!node.aframeObj.el.getAttribute('ownedBy')){
  155. // // }
  156. // }
  157. },
  158. createdProperty: function (nodeId, propertyName, propertyValue) {
  159. return this.satProperty(nodeId, propertyName, propertyValue);
  160. },
  161. initializedProperty: function (nodeId, propertyName, propertyValue) {
  162. return this.satProperty(nodeId, propertyName, propertyValue);
  163. },
  164. gotProperty: function (nodeId, propertyName, propertyValue) {
  165. var node = this.state.nodes[nodeId];
  166. if (!(node && node.aframeObj)) {
  167. return;
  168. }
  169. },
  170. satProperty: function (nodeId, propertyName, propertyValue) {
  171. let self = this;
  172. var node = this.state.nodes[nodeId];
  173. if (!(node && node.aframeObj)) {
  174. return;
  175. }
  176. // if (propertyName == 'arjs') {
  177. // if(propertyValue) {
  178. // node.aframeObj.setAttribute('arjs', {trackingMethod: "best", sourceType: "webcam", debugUIEnabled: "true"});
  179. // // let sceneEl = document.querySelector('a-scene');
  180. // // let marker = document.createElement('a-marker-camera');
  181. // // marker.setAttribute('preset', 'hiro');
  182. // // sceneEl.appendChild(marker);
  183. // //<a-marker-camera preset='hiro'></a-marker-camera>
  184. // } else {
  185. // if(node.aframeObj.getAttribute('arjs')){
  186. // node.aframeObj.removeAttribute('arjs')
  187. // }
  188. // }
  189. // }
  190. if (propertyName == 'position') {
  191. _self_.receiveModelTransformChanges(nodeId, 'position', propertyValue);
  192. }
  193. if (propertyName == 'rotation') {
  194. _self_.receiveModelTransformChanges(nodeId, 'rotation', propertyValue);
  195. }
  196. if (propertyName == 'scale') {
  197. _self_.receiveModelTransformChanges(nodeId, 'scale', propertyValue);
  198. }
  199. if (node.aframeObj.nodeName == "AUDIO" && propertyName == 'itemSrc') {
  200. //console.log("sat new item");
  201. let elID = '#' + node.aframeObj.getAttribute('id');
  202. Object.entries(this.state.nodes).forEach(el => {
  203. let sound = el[1].aframeObj.getAttribute('sound');
  204. if (sound) {
  205. let soundID = vwf.find(el[0], 'sound');
  206. self.kernel.callMethod(soundID, "refreshSrc", [elID])
  207. // if (sound.src !== ""){
  208. // let src = '#' + sound.src.id;
  209. // if (src == elID){
  210. // let soundID = vwf.find(el[0], 'sound');
  211. // self.kernel.callMethod(soundID, "updateSrc", [elID])
  212. // }
  213. // }
  214. }
  215. })
  216. }
  217. if (node.aframeObj.nodeName == "IMG" && propertyName == 'itemSrc') {
  218. _self_.updateMaterial(node);
  219. }
  220. if (node.aframeObj.nodeName == "VIDEO" && propertyName == 'itemSrc') {
  221. _self_.updateMaterial(node);
  222. }
  223. if (node.aframeObj.nodeName == "A-ASSET-ITEM" && propertyName == 'itemSrc') {
  224. //console.log("sat new item");
  225. let elID = '#' + node.aframeObj.getAttribute('id');
  226. Object.entries(this.state.nodes).forEach(el => {
  227. let src = el[1].aframeObj.getAttribute('src');
  228. let mtl = el[1].aframeObj.getAttribute('mtl');
  229. if (src) {
  230. // console.log("my: " + src);
  231. if (src == elID)
  232. self.kernel.callMethod(el[0], "updateModel", [elID])
  233. }
  234. if (mtl) {
  235. // console.log("my: " + mtl);
  236. if (mtl == elID)
  237. self.kernel.callMethod(el[0], "updateModelMtl", [elID])
  238. }
  239. })
  240. }
  241. // var aframeObject = node.aframeObj;
  242. // switch (propertyName) {
  243. // case "clickable":
  244. // if (propertyValue) {
  245. // aframeObject.addEventListener('click', function (evt) {
  246. // let cursorID = 'cursor-avatar-'+selfs.kernel.moniker();
  247. // if (evt.detail.cursorEl.id == cursorID) {
  248. // vwf_view.kernel.fireEvent(nodeId, "clickEvent")
  249. // }
  250. // });
  251. // }
  252. // break;
  253. // }
  254. },
  255. deletedNode: function (childID) {
  256. delete this.nodes[childID];
  257. },
  258. firedEvent: function (nodeID, eventName, eventParameters) {
  259. let self = this;
  260. var node = this.state.nodes[nodeID];
  261. if (!(node)) {
  262. return;
  263. }
  264. if (eventName == "changingTransformFromView") {
  265. var clientThatSatProperty = self.kernel.client();
  266. var me = self.kernel.moniker();
  267. // If the transform property was initially updated by this view....
  268. if (clientThatSatProperty == me) {
  269. var node = this.state.nodes[nodeID];
  270. node.ignoreNextTransformUpdate = true;
  271. }
  272. }
  273. //var avatarID = vwf_view.kernel.find("", avatarName)
  274. // if (eventName == "postLoadAction") {
  275. // Object.entries(self.state.nodes).forEach(el => {
  276. // if (el[1].prototypes.includes("proxy/aframe/aentity.vwf")) {
  277. // vwf_view.kernel.callMethod(el[0], "setOwner", [self.kernel.moniker()]);
  278. // }
  279. // });
  280. // }
  281. var avatarName = 'avatar-' + self.kernel.moniker();
  282. let intersectEvents = ['hitstart', 'hitend', 'intersect', 'clearIntersect']; //'intersect',
  283. let hitEvent = intersectEvents.filter(el=> el == eventName.slice(0,-5))[0]; //slice Event word
  284. if (hitEvent)
  285. {
  286. var clientThatSatProperty = self.kernel.client();
  287. var me = self.kernel.moniker();
  288. // If the transform property was initially updated by this view....
  289. if (clientThatSatProperty == me) {
  290. let methodName = eventName +'Method';
  291. vwf.callMethod(nodeID, methodName, [])
  292. }
  293. }
  294. if (eventName == "clickEvent") {
  295. if (self.kernel.moniker() == eventParameters[0]) {
  296. let avatar = self.nodes[avatarName];
  297. let mode = vwf.getProperty(avatarName, 'selectMode');
  298. vwf_view.kernel.callMethod(nodeID, "clickEventMethod", [])
  299. if (mode) {
  300. console.log("allow to click!!!")
  301. vwf_view.kernel.setProperty(avatarName, 'selectMode', false);
  302. let editorDriver = vwf.views["/drivers/view/editor"];
  303. if (editorDriver) {
  304. let selectSwitch = document.querySelector('#selectNodeSwitch');
  305. // const selectSwitchComp = new mdc.iconButton.MDCIconButtonToggle(selectSwitch); //new mdc.select.MDCIconToggle
  306. selectSwitch._comp.on = false;
  307. let currentNodeDIV = document.querySelector('#currentNode');
  308. if (currentNodeDIV) currentNodeDIV._setNode(nodeID);
  309. }
  310. }
  311. }
  312. }
  313. },
  314. ticked: function (vwfTime) {
  315. let self = this;
  316. _self_.updateAvatarPosition();
  317. //update vr controllers
  318. if(self.hmd){
  319. if(self.threeDoF )
  320. _self_.updateHandControllerVR('gearvr-', '#gearvrcontrol');
  321. if(this.sixDoF ) {
  322. _self_.updateHandControllerVR('xrcontroller-right-', '#xrcontrollerright');
  323. _self_.updateHandControllerVR('xrcontroller-left-', '#xrcontrollerleft');
  324. }
  325. }
  326. //lerpTick ();
  327. },
  328. calledMethod: function (nodeID, methodName, methodParameters, methodValue) {
  329. let self = this;
  330. var node = this.state.nodes[nodeID];
  331. if (!(node && node.aframeObj)) {
  332. return;
  333. }
  334. switch (methodName) {
  335. case "translateBy":
  336. case "translateTo":
  337. //resetInterpolationFromViewDriver(nodeID, methodParameters, 'position')
  338. break;
  339. // No need for rotateBy or rotateTo because they call the quaternion methods
  340. case "quaterniateBy":
  341. case "quaterniateTo":
  342. //resetInterpolationFromViewDriver(nodeID, methodParameters, 'rotation')
  343. break;
  344. case "scaleBy":
  345. case "scaleTo":
  346. // No need for transformBy or worldTransformBy because they call transformTo and worldTransformTo
  347. case "transformTo":
  348. case "worldTransformTo":
  349. //resetInterpolationFromViewDriver(nodeID, methodParameters, 'rotation')
  350. break;
  351. }
  352. if (this.nodes[nodeID].extends == "proxy/aframe/acamera.vwf") {
  353. if (methodName == "setCameraToActive") {
  354. if (methodParameters[0] == vwf.moniker_) {
  355. console.log("set active");
  356. let offsetComp = node.aframeObj.getAttribute('viewoffset');
  357. if (offsetComp) {
  358. let offsetCompID = vwf.find(nodeID, 'viewoffset');
  359. self.kernel.callMethod(offsetCompID, "setParams", []);
  360. }
  361. node.aframeObj.setAttribute('camera', 'active', true);
  362. document.querySelector('a-scene').emit('makeActiveCamera');
  363. }
  364. }
  365. }
  366. // if (methodName == "createGooglePoly") {
  367. // }
  368. }
  369. });
  370. }
  371. resetInterpolationFromViewDriver(nodeID, methodParameters, propertyName) {
  372. if (methodParameters.length < 2 || methodParameters[1] == 0) {
  373. let viewNode = self.nodes[nodeID];
  374. if (viewNode.components.interpolation) {
  375. let interID = viewNode.components.interpolation;
  376. let viewComponentDriver = vwf.views["/drivers/view/aframeComponent"];
  377. viewComponentDriver.resetInterpolation(interID, propertyName);
  378. }
  379. }
  380. }
  381. // Receive Model Transform Changes algorithm
  382. // 1.0 If (own view changes) then IGNORE (only if no external changes have occurred since the user’s view
  383. // requested this change – otherwise, will need to treat like 1.1 or 1.2)
  384. // 1.1 Elseif (other external changes and no outstanding own view changes) then ADOPT
  385. // 1.2 Else Interpolate to the model’s transform (conflict b/w own view and external sourced model changes)
  386. receiveModelTransformChanges(nodeID, propertyName, propertyValue) {
  387. let self = this.instance;
  388. var node = self.state.nodes[nodeID];
  389. // If the node does not exist in the state's list of nodes, then this update is from a prototype and we
  390. // should ignore it
  391. if (!node ) {
  392. return;
  393. }
  394. if(node.aframeObj.object3D) {
  395. // If the transform property was initially updated by this view....
  396. if (node.ignoreNextTransformUpdate) {
  397. node.outstandingTransformRequests.shift();
  398. node.ignoreNextTransformUpdate = false;
  399. } else {
  400. // adoptTransform( node, transformMatrix );
  401. let prop = self.state.setFromValue(propertyValue);
  402. if (propertyName == 'position') {
  403. let pos = goog.vec.Vec3.clone(prop);
  404. node.aframeObj.object3D.position.set(pos[0], pos[1], pos[2]);
  405. } else if (propertyName == 'rotation') {
  406. let rot = goog.vec.Vec3.clone(prop);
  407. node.aframeObj.object3D.rotation.set(
  408. THREE.Math.degToRad(rot[0]),
  409. THREE.Math.degToRad(rot[1]),
  410. THREE.Math.degToRad(rot[2])
  411. )
  412. //node.aframeObj.object3D.rotation.set(rot[0], rot[1], rot[2]);
  413. } else if (propertyName == 'scale') {
  414. let scale = goog.vec.Vec3.clone(prop);
  415. node.aframeObj.object3D.scale.set(scale[0], scale[1], scale[2]);
  416. }
  417. }
  418. }
  419. }
  420. compareCoordinates(a, b, delta) {
  421. return Math.abs(a.x - b.x) > delta || Math.abs(a.y - b.y) > delta || Math.abs(a.z - b.z) > delta
  422. }
  423. getWorldRotation(el, order) {
  424. var worldQuat = new THREE.Quaternion();
  425. el.object3D.getWorldQuaternion(worldQuat);
  426. //console.log(worldQuat);
  427. let angle = (new THREE.Euler()).setFromQuaternion(worldQuat, order);
  428. let rotation = (new THREE.Vector3(THREE.Math.radToDeg(angle.x),
  429. THREE.Math.radToDeg(angle.y), THREE.Math.radToDeg(angle.z)));
  430. return rotation
  431. }
  432. updateAvatarPosition() {
  433. let self = this.instance;
  434. let delta = 0.001;
  435. let avatarName = 'avatar-' + self.kernel.moniker();
  436. var node = self.state.nodes[avatarName];
  437. if (!node) return;
  438. if (!node.aframeObj) return;
  439. let el = document.querySelector('#avatarControl');
  440. let elA = document.querySelector('#avatarControlParent');
  441. if (el && elA) {
  442. var position;
  443. if((self.hmd && self.sixDoF) || (self.hmd && self.threeDoF) || _app.config.d6DoF || _app.config.d3DoF){
  444. let positionC = el.object3D.position.clone();
  445. let positionA = elA.object3D.position.clone();
  446. position = positionC.add(positionA);
  447. } else {
  448. position = el.object3D.position;
  449. }
  450. //let position = el.object3D.position.add(elA.object3D.position);
  451. let rotation = el.getAttribute('rotation'); //getWorldRotation(el, 'YXZ');
  452. let lastRotation = self.nodes[avatarName].selfTickRotation;
  453. let lastPosition = self.nodes[avatarName].selfTickPosition ? self.nodes[avatarName].selfTickPosition: new THREE.Vector3(0, 0, 0);
  454. // let currentPosition = node.aframeObj.getAttribute('position');
  455. // let currentRotation = node.aframeObj.getAttribute('rotation');
  456. // compareCoordinates(position, lastPosition, delta)
  457. if(position && lastPosition ) {
  458. let distance = lastPosition.distanceTo(position);
  459. if (distance > delta)
  460. {
  461. // console.log("position not equal");
  462. self.kernel.setProperty(avatarName, "position", position);
  463. }
  464. }
  465. if (rotation && lastRotation) {
  466. let distance = Math.abs(rotation.y - lastRotation.y);
  467. if ( distance > delta) {
  468. //console.log("rotation not equal")
  469. self.kernel.callMethod(avatarName, "updateAvatarRotation", [rotation]);
  470. }
  471. }
  472. self.nodes[avatarName].selfTickRotation = Object.assign({}, rotation);
  473. //self.nodes[avatarName].selfTickPosition = Object.assign({}, position);
  474. self.nodes[avatarName].selfTickPosition = position.clone();
  475. }
  476. }
  477. updateHandControllerVR(aName, aSelector) {
  478. let self = this.instance;
  479. //let avatarName = 'avatar-' + self.kernel.moniker();
  480. let delta = 0.001
  481. let avatarName = aName + self.kernel.moniker();
  482. var node = self.state.nodes[avatarName];
  483. if (!node) return;
  484. if (!node.aframeObj) return;
  485. let elA = document.querySelector('#avatarControlParent');
  486. let el = document.querySelector(aSelector);
  487. if (el && elA) {
  488. let positionC = el.object3D.position.clone();
  489. let positionA = elA.object3D.position.clone();
  490. let position = positionC.add(positionA);
  491. let rotation = el.getAttribute('rotation'); //getWorldRotation(el, 'YXZ');
  492. let lastRotation = self.nodes[avatarName].selfTickRotation;
  493. let lastPosition = self.nodes[avatarName].selfTickPosition ? self.nodes[avatarName].selfTickPosition: new THREE.Vector3(0, 0, 0);
  494. // let currentPosition = node.aframeObj.getAttribute('position');
  495. //let currentRotation = node.aframeObj.getAttribute('rotation');
  496. if (position && lastPosition) {
  497. let distance = lastPosition.distanceTo(position);
  498. if (distance > delta)
  499. {
  500. // console.log("position not equal");
  501. self.kernel.setProperty(avatarName, "position", position);
  502. self.kernel.callMethod(avatarName, "moveVRController",[]);
  503. }
  504. }
  505. if (rotation && lastRotation) {
  506. let distance = this.compareCoordinates(rotation, lastRotation, delta)
  507. if (distance)
  508. {
  509. //console.log("rotation not equal");
  510. self.kernel.setProperty(avatarName, "rotation", rotation);
  511. self.kernel.callMethod(avatarName, "moveVRController",[]);
  512. }
  513. }
  514. // if (position && rotation && lastRotation && lastPosition) {
  515. // if (compareCoordinates(position, lastPosition, delta) || compareCoordinates(rotation, lastRotation, delta)) {
  516. // console.log("not equal!!");
  517. // vwf_view.kernel.callMethod(avatarName, "updateVRControl", [position, rotation]);
  518. // }
  519. // }
  520. //vwf_view.kernel.callMethod(avatarName, "updateVRControl", [position, rotation]);
  521. self.nodes[avatarName].selfTickPosition = position.clone();
  522. self.nodes[avatarName].selfTickRotation = Object.assign({}, rotation);
  523. }
  524. }
  525. getMovementVector(el, vel) {
  526. var directionVector = new THREE.Vector3(0, 0, 0);
  527. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  528. var rotation = el.getAttribute('rotation');
  529. var velocity = vel;
  530. directionVector.copy(velocity);
  531. directionVector.multiplyScalar(0.05);
  532. // Absolute.
  533. if (!rotation) { return directionVector; }
  534. //xRotation = this.data.fly ? rotation.x : 0;
  535. // Transform direction relative to heading.
  536. rotationEuler.set(THREE.Math.degToRad(0), THREE.Math.degToRad(rotation.y), 0);
  537. directionVector.applyEuler(rotationEuler);
  538. return directionVector;
  539. }
  540. setJoystickMoveInput (event) {
  541. const axes = event.detail.axis;
  542. //console.log(axes);
  543. let el = document.querySelector('#avatarControl');
  544. let position = new THREE.Vector3();
  545. el.object3D.localToWorld(position);//getWorldPosition(position);
  546. let vel = new THREE.Vector3(axes[0], 0, -axes[1]);
  547. el.object3D.position.add(this.getMovementVector(el,vel));
  548. }
  549. setJoystickRotateY (event) {
  550. const val = event.detail.value;
  551. //console.log(val);
  552. let el = document.querySelector('#avatarControl');
  553. let rotation = el.object3D.rotation;
  554. el.object3D.rotation.y += (-val)+rotation.y;
  555. //el.object3D.rotation.set(rotation.x,-val+rotation.y, rotation.z)
  556. }
  557. setJoystickRotateX (event) {
  558. const val = event.detail.value;
  559. //console.log(val);
  560. let el = document.querySelector('#avatarControl');
  561. let rotation = el.object3D.rotation;
  562. el.object3D.rotation.x += val+rotation.x;
  563. //el.object3D.rotation.set(val+rotation.x, rotation.y, rotation.z)
  564. }
  565. async createAvatarControl(aScene) {
  566. let self = this.instance;
  567. let avatarName = 'avatar-' + self.kernel.moniker();
  568. let avatarEl = document.createElement('a-entity');
  569. avatarEl.setAttribute('id', 'avatarControlParent');
  570. if (self.d3DoF || _app.config.d3DoF) {
  571. //avatarEl.setAttribute('gearvr-controls', {});
  572. avatarEl.setAttribute('movement-controls', {});//{'controls': 'gamepad'});
  573. //avatarEl.setAttribute("gamepad-controls", {});
  574. //avatarEl.setAttribute('position', '0 0 0');
  575. }
  576. //avatarEl.setAttribute('position', '0 1.6 0');
  577. let controlEl = document.createElement('a-camera');
  578. controlEl.setAttribute('id', 'avatarControl');
  579. controlEl.setAttribute('wasd-controls', {acceleration:20});
  580. controlEl.setAttribute('look-controls', { pointerLockEnabled: false});
  581. controlEl.setAttribute('look-controls', 'enabled', true );
  582. //controlEl.setAttribute('gamepad-controls', {'controller': 0});
  583. if (AFRAME.utils.device.isMobile()) {
  584. //self.state.showMobileJoystick()
  585. controlEl.setAttribute('look-controls', 'enabled', true );
  586. controlEl.setAttribute("virtual-gamepad-controls", {});
  587. controlEl.addEventListener("move", this.setJoystickMoveInput.bind(this));
  588. }
  589. //controlEl.addEventListener("rotateY", setJoystickRotateY);
  590. //controlEl.addEventListener("rotateX", setJoystickRotateX);
  591. //controlEl.setAttribute('gearvr-controls',{});
  592. let cursorEl = document.createElement('a-cursor');
  593. cursorEl.setAttribute('id', 'cursor-' + avatarName);
  594. cursorEl.setAttribute('raycaster', {});
  595. cursorEl.setAttribute('raycaster', 'objects', '.clickable');
  596. cursorEl.setAttribute('raycaster', 'showLine', false);
  597. // cursorEl.setAttribute('raycaster', {objects: '.intersectable', showLine: true, far: 100});
  598. // cursorEl.setAttribute('raycaster', 'showLine', true);
  599. controlEl.appendChild(cursorEl);
  600. avatarEl.appendChild(controlEl);
  601. aScene.appendChild(avatarEl);
  602. controlEl.setAttribute('camera', 'active', true);
  603. //avatarEl.setAttribute('avatar', {});
  604. // let arControl = document.createElement('a-entity');
  605. // arControl.setAttribute('id', 'arControlParent');
  606. // arControl.setAttribute('camera', {
  607. // active: true,
  608. // "look-controls-enabled": false,
  609. // "wasd-controls-enabled": false,
  610. // "user-height": 0
  611. // });
  612. // aScene.appendChild(arControl);
  613. return "OK!"
  614. // cb();
  615. }
  616. createXR(nodeID, nodeName) {
  617. let self = this;
  618. var newNode = {
  619. "id": nodeName,
  620. "uri": nodeName,
  621. "extends": "proxy/aframe/xrcontroller.vwf",
  622. "properties": {
  623. }
  624. }
  625. if (!self.state.nodes[nodeName]) {
  626. vwf_view.kernel.createChild(nodeID, nodeName, newNode);
  627. vwf_view.kernel.callMethod(nodeName, "createController", []);
  628. //"/../assets/controller/wmrvr.gltf"
  629. }
  630. }
  631. createGearVRController(nodeID, nodeName) {
  632. let self = this;
  633. var newNode = {
  634. "id": nodeName,
  635. "uri": nodeName,
  636. "extends": "proxy/aframe/gearvrcontroller.vwf",
  637. "properties": {
  638. }
  639. }
  640. if (!self.state.nodes[nodeName]) {
  641. vwf_view.kernel.createChild(nodeID, nodeName, newNode);
  642. vwf_view.kernel.callMethod(nodeName, "createController", []);
  643. //"/../assets/controller/gearvr.gltf"
  644. }
  645. }
  646. postLoadAction(nodeID) {
  647. //vwf_view.kernel.fireEvent(nodeID, "postLoadAction")
  648. }
  649. createAvatar(nodeID) {
  650. let self = this;
  651. // vwf_view.kernel.fireEvent(nodeID, "createAvatar");
  652. var avatarName = 'avatar-' + self.kernel.moniker();
  653. console.log("creating avatar...");
  654. // let avatarID = self.kernel.moniker();
  655. // var nodeName = 'avatar-' + avatarID;
  656. var newNode = {
  657. "id": avatarName,
  658. "uri": avatarName,
  659. "extends": "proxy/aframe/avatar.vwf",
  660. "properties": {
  661. "localUrl": '',
  662. "remoteUrl": '',
  663. // "displayName": 'Avatar ' + randId(),
  664. "sharing": { audio: true, video: true },
  665. "selectMode": false,
  666. "position": [0, 1.6, 0]
  667. }
  668. }
  669. if (!self.state.nodes[avatarName]) {
  670. if (_LCSDB.user().is) {
  671. _LCSDB.user().get('profile').get('alias').once(alias => {
  672. if (alias){
  673. newNode.properties.displayName = alias;
  674. //vwf_view.kernel.callMethod(avatarName, "setMyName", [alias]);
  675. }
  676. vwf_view.kernel.createChild(nodeID, avatarName, newNode);
  677. });
  678. _LCSDB.user().get('profile').get('avatarNode').not(res=>{
  679. //vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  680. })
  681. _LCSDB.user().get('profile').get('avatarNode').once(res => {
  682. var myNode = null;
  683. if (res) {
  684. //myNode = JSON.parse(res.avatarNode);
  685. var myNode = res;
  686. if (_app.helpers.testJSON(res)){
  687. myNode = JSON.parse(res);
  688. }
  689. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", [myNode, null]);
  690. } else {
  691. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  692. }
  693. // newNode.properties.displayName = res.alias;
  694. //"/../assets/avatars/male/avatar1.gltf"
  695. //vwf_view.kernel.callMethod(avatarName, 'setUserAvatar', [res] );
  696. });
  697. } else {
  698. vwf_view.kernel.createChild(nodeID, avatarName, newNode);
  699. vwf_view.kernel.callMethod(avatarName, "createAvatarBody", []);
  700. //"/../assets/avatars/male/avatar1.gltf"
  701. }
  702. //
  703. }
  704. }
  705. createGearVRControls() {
  706. let avatarControl = document.querySelector('#avatarControlParent');
  707. let el = document.createElement('a-entity');
  708. el.setAttribute('id', 'gearvrcontrol');
  709. el.setAttribute('gearvr-controls', {
  710. 'hand': 'right',
  711. 'model': true
  712. });
  713. //el.setAttribute('laser-controls', {hand: "right"});
  714. // gearvr.setAttribute('gearvr-controls', 'hand', 'right');
  715. el.setAttribute('teleport-controls', {
  716. cameraRig: '#avatarControlParent',
  717. teleportOrigin: '#avatarControl',
  718. startEvents: 'teleportstart',
  719. endEvents: 'teleportend'
  720. });
  721. el.setAttribute('gearvrcontrol', {});
  722. avatarControl.appendChild(el);
  723. }
  724. createXRControls(hand) {
  725. let self = this.instance;
  726. let avatarControl = document.querySelector('#avatarControlParent');
  727. let el = document.createElement('a-entity');
  728. el.setAttribute('id', 'xrcontroller' + hand);
  729. el.setAttribute('hand-controls', {
  730. 'hand': hand,
  731. 'handModelStyle': 'lowPoly',
  732. 'color': '#ffcccc'
  733. });
  734. el.setAttribute('laser-controls', {hand: hand, model:false});
  735. //el.setAttribute('raycaster', {objects: ".collidable", far: 5, showLine: false});
  736. // wmrvr.setAttribute('windows-motion-controls', '');
  737. // wmrvr.setAttribute('windows-motion-controls', 'hand', hand);
  738. el.setAttribute('xrcontroller', { 'hand': hand });
  739. //add teleport controls
  740. el.setAttribute('teleport-controls', {
  741. cameraRig: '#avatarControlParent',
  742. teleportOrigin: '#avatarControl',
  743. startEvents: 'teleportstart',
  744. endEvents: 'teleportend'
  745. });
  746. avatarControl.appendChild(el);
  747. }
  748. updateMaterial(node) {
  749. let self = this.instance;
  750. let elID = '#' + node.aframeObj.getAttribute('id');
  751. Object.entries(self.state.nodes).forEach(el => {
  752. let material = el[1].aframeObj.getAttribute('material');
  753. if (material) {
  754. if (!material.src) {
  755. let materialID = vwf.find(el[0], 'material');
  756. self.kernel.callMethod(materialID, "refreshSrc", []);
  757. }
  758. else if (material.src) {
  759. if (material.src !== "") {
  760. let src = '#' + material.src.id;
  761. if (src == elID) {
  762. let materialID = vwf.find(el[0], 'material');
  763. self.kernel.callMethod(materialID, "updateSrc", [elID])
  764. }
  765. }
  766. }
  767. }
  768. })
  769. }
  770. }
  771. export { AFrameView as default }