aframe.js 38 KB

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