gemercheung il y a 3 ans
Parent
commit
1ebcf3542e
3 fichiers modifiés avec 209 ajouts et 115 suppressions
  1. 7 6
      src/meta.gateway.ts
  2. 199 100
      src/rotate/rotate.service.ts
  3. 3 9
      src/scene/scene.service.ts

+ 7 - 6
src/meta.gateway.ts

@@ -35,12 +35,11 @@ initLogger('Debug');
   path: '/ws',
 })
 export class MetaGateway
-  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
-{
+  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
   constructor(
     private readonly sceneService: SceneService,
     private readonly configService: ConfigService,
-  ) {}
+  ) { }
   private logger: Logger = new Logger('MetaGateway');
   private peer: PeerConnection = null;
   private timer: NodeJS.Timeout;
@@ -49,7 +48,7 @@ export class MetaGateway
   private gameChanel: DataChannel;
   private user_id: string;
   private roomId: string;
-
+  private startstreamingSub: any;
   @WebSocketServer() server: Server;
 
   // @SubscribeMessage('message')
@@ -203,6 +202,7 @@ export class MetaGateway
       this.sceneService.handleDataChanelClose();
       this.stopSendWertcHeartPack();
       cleanup();
+      this.startstreamingSub & this.startstreamingSub.unsubscribe();
     });
     this.gameChanel.onMessage((event) => {
       this.sceneService.handleMessage(event);
@@ -272,14 +272,14 @@ export class MetaGateway
         client_os: '',
         fe_version: '',
       };
-      this.sceneService.startSteaming.subscribe((val) => {
+      this.startstreamingSub = this.sceneService.startSteaming.subscribe((val) => {
         if (val) {
           console.log('onSteaming-start', val);
           client.send(JSON.stringify(startReply));
         }
         // debugger
       });
-    } catch (error) {}
+    } catch (error) { }
   }
 
   handleConnection(client: WebSocket, ...args: any[]) {
@@ -315,5 +315,6 @@ export class MetaGateway
   handleDisconnect(client: WebSocket) {
     this.logger.log(`Client disconnected: ${client.id}`);
     this.peer && this.peer.close();
+    this.startstreamingSub & this.startstreamingSub.unsubscribe();
   }
 }

+ 199 - 100
src/rotate/rotate.service.ts

@@ -11,91 +11,7 @@ export class RotateService {
     Joystick: 15,
   };
   private users = {};
-  private reply = {
-    traceIds: [],
-    vehicle: null,
-    mediaSrc: null,
-    newUserStates: [
-      {
-        userId: 'dcff36ae4fc1d',
-        playerState: {
-          roomTypeId: '',
-          person: 0,
-          avatarId: '',
-          skinId: '',
-          roomId: '',
-          isHost: false,
-          isFollowHost: false,
-          skinDataVersion: '',
-          avatarComponents: '',
-          nickName: '',
-          movingMode: 0,
-          attitude: '',
-          areaName: '',
-          pathName: '',
-          pathId: '',
-          avatarSize: 1,
-          extra: '',
-          prioritySync: false,
-          player: {
-            position: { x: -700, y: 0, z: 0 },
-            angle: {
-              pitch: 0,
-              yaw: 0,
-              roll: 0,
-            },
-          },
-          camera: {
-            position: { x: -1145, y: 0, z: 160 },
-            angle: {
-              pitch: 0,
-              yaw: 0,
-              roll: 0,
-            },
-          },
-          cameraCenter: { x: -700, y: 0, z: 0 },
-        },
-        renderInfo: {
-          renderType: 0,
-          videoFrame: null,
-          cameraStateType: 3,
-          isMoving: 1,
-          needIfr: 0,
-          isVideo: 0,
-          stillFrame: 0,
-          isRotating: 0,
-          isFollowing: 0,
-          clientPanoTitlesBitmap: [],
-          clientPanoTreceId: '',
-          prefetchVideoId: '',
-          noMedia: false,
-        },
-        event: null,
-        relation: 1,
-      },
-    ],
-    actionResponses: [
-      // {
-      //     "actionType": 15,
-      //     "pointType": 100,
-      //     "extra": "",
-      //     "traceId": "d0864cd0-378d-4d49-b7b0-3e8e1b9494c3",
-      //     "packetId": "d44bd2f5-f877-4dd7-868b-803c64f99082",
-      //     "nps": [],
-      //     "peopleNum": 0,
-      //     "zoneId": "",
-      //     "echoMsg": "",
-      //     "reserveDetail": null,
-      //     "userWithAvatarList": [],
-      //     "newUserStates": [],
-      //     "code": 0,
-      //     "msg": ""
-      // }
-    ],
-    getStateType: 0,
-    code: 0,
-    msg: 'OK',
-  };
+  private replys = {};
 
   init(app_id, userId) {
     const user = {
@@ -124,14 +40,104 @@ export class RotateService {
         mediaSrc: null,
       },
       moveInfo: {},
-      traceIds: [],
+      // traceIds: [],
+      // actionResponses:[]
     };
+
     user.appId = app_id;
     user.userId = userId;
     user.breakPointId = 100;
     this.users[userId] = user;
-    this.reply['newUserStates'][0]['userId'] = userId;
-    return this.reply;
+
+    const reply = {
+      traceIds: [],
+      vehicle: null,
+      mediaSrc: null,
+      newUserStates: [
+        {
+          userId: 'dcff36ae4fc1d',
+          playerState: {
+            roomTypeId: '',
+            person: 0,
+            avatarId: '',
+            skinId: '',
+            roomId: '',
+            isHost: false,
+            isFollowHost: false,
+            skinDataVersion: '',
+            avatarComponents: '',
+            nickName: '',
+            movingMode: 0,
+            attitude: '',
+            areaName: '',
+            pathName: '',
+            pathId: '',
+            avatarSize: 1,
+            extra: '',
+            prioritySync: false,
+            player: {
+              position: { x: -700, y: 0, z: 0 },
+              angle: {
+                pitch: 0,
+                yaw: 0,
+                roll: 0,
+              },
+            },
+            camera: {
+              position: { x: -1145, y: 0, z: 160 },
+              angle: {
+                pitch: 0,
+                yaw: 0,
+                roll: 0,
+              },
+            },
+            cameraCenter: { x: -700, y: 0, z: 0 },
+          },
+          renderInfo: {
+            renderType: 0,
+            videoFrame: null,
+            cameraStateType: 3,
+            isMoving: 0,
+            needIfr: 0,
+            isVideo: 0,
+            stillFrame: 0,
+            isRotating: 0,
+            isFollowing: 0,
+            clientPanoTitlesBitmap: [],
+            clientPanoTreceId: '',
+            prefetchVideoId: '',
+            noMedia: false,
+          },
+          event: null,
+          relation: 1,
+        },
+      ],
+      actionResponses: [
+        // {
+        //     "actionType": 15,
+        //     "pointType": 100,
+        //     "extra": "",
+        //     "traceId": "d0864cd0-378d-4d49-b7b0-3e8e1b9494c3",
+        //     "packetId": "d44bd2f5-f877-4dd7-868b-803c64f99082",
+        //     "nps": [],
+        //     "peopleNum": 0,
+        //     "zoneId": "",
+        //     "echoMsg": "",
+        //     "reserveDetail": null,
+        //     "userWithAvatarList": [],
+        //     "newUserStates": [],
+        //     "code": 0,
+        //     "msg": ""
+        // }
+      ],
+      getStateType: 0,
+      code: 0,
+      msg: 'OK',
+    };
+
+    reply['newUserStates'][0]['userId'] = userId;
+    this.replys[userId] = reply;
+    return reply;
   }
 
   async rotate(actionRequest) {
@@ -144,16 +150,23 @@ export class RotateService {
         this.actionRequestPool[userId].push(actionRequest);
       }
 
+      const reply = this.replys[userId];
+
       const actionRequests = this.actionRequestPool[userId];
       const user = this.users[userId];
       // debugger;
       let horizontal_move = user.rotateInfo.horizontal_move;
-      const traceIds = user.traceIds;
+      //const traceIds = user.traceIds;
       let sub = 0;
       for (let i = 0; i < actionRequests.length; ++i) {
         if (actionRequests[i].action_type == this.Actions.Rotation) {
           horizontal_move += actionRequests[i].rotation_action.horizontal_move;
-          traceIds.push(actionRequests[i].trace_id);
+          reply.traceIds.push(actionRequests[i].trace_id);
+          const actionResponse = this.createActionResponse(
+            actionRequests[i].action_type,
+            actionRequests[i].trace_id,
+          );
+          reply.actionResponses.push(actionResponse);
           ++sub;
         } else {
           break;
@@ -164,18 +177,79 @@ export class RotateService {
       const hAngle = horizontal_move * 90;
       if (Math.abs(hAngle) < 1) {
         user.rotateInfo.horizontal_move = horizontal_move;
-        user.traceIds = traceIds;
-      } else {
-        user.rotateInfo.frameIndex += Math.floor(hAngle);
+        //user.traceIds = traceIds;
+        this.replys[userId] = reply;
+        return null;
       }
+      return this.rotateForAngle(userId, hAngle);
+      /*
+      user.rotateInfo.frameIndex += Math.floor(hAngle);
+      if (user.rotateInfo.frameIndex < 0) {
+        user.rotateInfo.frameIndex = 360 - user.rotateInfo.frameIndex;
+      } else if (user.rotateInfo.frameIndex > 359) {
+        user.rotateInfo.frameIndex -= 360;
+      }
+      reply['traceIds'] = traceIds;
+      reply['newUserStates'][0]['userId'] = userId;
+      //从redis里取
+      //let key = user.appId + "-"+user.breakPointId+"-"+user.rotateInfo.frameIndex;
+      const key =
+        'rotateframe:app_id:' +
+        user.appId +
+        ':frame_index:' +
+        user.rotateInfo.frameIndex +
+        ':break_point_id:' +
+        user.breakPointId;
+      // const value = null;
 
+      const redisData = await this.cacheService.get(key);
+      const value = JSON.parse(redisData);
+      console.log('redis', value);
+      user.camera['position'] = value ? value.cameraPosition : '';
+      user.camera['angle'] = value ? value.cameraAngle : '';
+
+      //this.reply['newUserStates'][0]['playerState'] .player
+      reply['newUserStates'][0]['playerState'].camera.position =
+        user.camera['position'];
+      reply['newUserStates'][0]['playerState'].camera.angle =
+        user.camera['angle'];
+      reply['newUserStates'][0]['playerState'].cameraCenter =
+        user.player.position;
+      // debugger
+      reply.mediaSrc =
+        '/' +
+        '0000000001' +
+        '/' +
+        user.breakPointId +
+        '/' +
+        value.directory +
+        '/' +
+        value.fileName +
+        '?m=' +
+        new Date().getTime();
+
+      this.replys[userId].traceIds = [];
+      this.replys[userId].actionResponses = [];
+
+      return reply;
+      */
+    } catch (error) {
+      console.log('RotateService', error);
+    }
+  }
+
+  async rotateForAngle(userId, hAngle) {
+    try {
+      const user = this.users[userId];
+      user.rotateInfo.frameIndex += Math.floor(hAngle);
       if (user.rotateInfo.frameIndex < 0) {
         user.rotateInfo.frameIndex = 360 - user.rotateInfo.frameIndex;
       } else if (user.rotateInfo.frameIndex > 359) {
         user.rotateInfo.frameIndex -= 360;
       }
 
-      this.reply['newUserStates'][0]['userId'] = userId;
+      const reply = JSON.parse(JSON.stringify(this.replys[userId]));
+      reply['newUserStates'][0]['userId'] = userId;
       //从redis里取
       //let key = user.appId + "-"+user.breakPointId+"-"+user.rotateInfo.frameIndex;
       const key =
@@ -189,19 +263,19 @@ export class RotateService {
 
       const redisData = await this.cacheService.get(key);
       const value = JSON.parse(redisData);
-      // console.log('redis', value);
+      console.log('redis', value);
       user.camera['position'] = value ? value.cameraPosition : '';
       user.camera['angle'] = value ? value.cameraAngle : '';
 
       //this.reply['newUserStates'][0]['playerState'] .player
-      this.reply['newUserStates'][0]['playerState'].camera.position =
+      reply['newUserStates'][0]['playerState'].camera.position =
         user.camera['position'];
-      this.reply['newUserStates'][0]['playerState'].camera.angle =
+      reply['newUserStates'][0]['playerState'].camera.angle =
         user.camera['angle'];
-      this.reply['newUserStates'][0]['playerState'].cameraCenter =
+      reply['newUserStates'][0]['playerState'].cameraCenter =
         user.player.position;
       // debugger
-      this.reply.mediaSrc =
+      reply.mediaSrc =
         '/' +
         '0000000001' +
         '/' +
@@ -213,9 +287,34 @@ export class RotateService {
         '?m=' +
         new Date().getTime();
 
-      return this.reply;
+      this.replys[userId].traceIds = [];
+      this.replys[userId].actionResponses = [];
+
+      user.rotateInfo.horizontal_move = 0;
+
+      return reply;
     } catch (error) {
       console.log('RotateService', error);
     }
   }
+
+  createActionResponse(actionType, traceId) {
+    const actionResponse = {
+      actionType: actionType,
+      pointType: 100,
+      extra: '',
+      traceId: traceId,
+      packetId: '',
+      nps: [],
+      peopleNum: 0,
+      zoneId: '',
+      echoMsg: '',
+      reserveDetail: null,
+      userWithAvatarList: [],
+      newUserStates: [],
+      code: 0,
+      msg: '',
+    };
+    return actionResponse;
+  }
 }

+ 3 - 9
src/scene/scene.service.ts

@@ -221,28 +221,22 @@ export class SceneService implements OnModuleInit, OnModuleDestroy {
               this.lastRenderMedia = src;
               const clipPath = path.join(__dirname, `../ws/video/${src}`);
               // console.log('src-clipPath', src, clipPath);
-              // delete redisMeta.mediaSrc;
+              delete redisMeta.mediaSrc;
               const stream: StreamFrameType = {
                 frame: -1,
                 clipPath: clipPath,
-                metaData: JSON.stringify(frameMetaReply),
+                metaData: JSON.stringify(redisMeta),
                 serverTime: this.mockserverTime,
                 DIR: 3,
               };
-              // console.log('stream', stream)
               this.roQueue.next(stream);
-              // this.streamService.pushFrameToSteam(stream);
             }
           }
         }
       }
-
-      // reply.subscribe((res: NormalReply) => {
-      //   if (res.code === 200) {
-      //   }
-      // });
     } catch (error) {
       this.logger.error('rotate', error);
+      console.log('error', error);
     }
   }