aframe.js 41 KB

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