partey_workadventure/back/src/Model/GameRoom.ts

298 lines
10 KiB
TypeScript
Raw Normal View History

2020-04-07 10:08:04 +02:00
import {PointInterface} from "./Websocket/PointInterface";
import {Group} from "./Group";
import {User, UserSocket} from "./User";
2020-04-29 01:40:32 +02:00
import {ExSocketInterface} from "_Model/Websocket/ExSocketInterface";
import {PositionInterface} from "_Model/PositionInterface";
import {Identificable} from "_Model/Websocket/Identificable";
2020-10-06 15:37:00 +02:00
import {EntersCallback, LeavesCallback, MovesCallback} from "_Model/Zone";
import {PositionNotifier} from "./PositionNotifier";
import {ViewportInterface} from "_Model/Websocket/ViewportMessage";
2020-09-16 16:06:43 +02:00
import {Movable} from "_Model/Movable";
import {extractDataFromPrivateRoomId, extractRoomSlugPublicRoomId, isRoomAnonymous} from "./RoomIdentifier";
import {arrayIntersect} from "../Services/ArrayHelper";
2020-10-21 23:45:08 +02:00
import {MAX_USERS_PER_ROOM} from "../Enum/EnvironmentVariable";
import {JoinRoomMessage} from "../Messages/generated/messages_pb";
import {ProtobufUtils} from "../Model/Websocket/ProtobufUtils";
import { ZoneSocket } from "src/RoomManager";
2020-04-07 10:08:04 +02:00
2020-09-29 16:01:22 +02:00
export type ConnectCallback = (user: User, group: Group) => void;
export type DisconnectCallback = (user: User, group: Group) => void;
export enum GameRoomPolicyTypes {
ANONYMUS_POLICY = 1,
MEMBERS_ONLY_POLICY,
USE_TAGS_POLICY,
}
2020-10-06 15:37:00 +02:00
export class GameRoom {
private readonly minDistance: number;
private readonly groupRadius: number;
2020-04-08 20:40:44 +02:00
2020-04-07 10:08:04 +02:00
// Users, sorted by ID
private readonly users: Map<number, User>;
2020-06-29 22:13:07 +02:00
private readonly groups: Set<Group>;
2020-04-08 20:40:44 +02:00
private readonly connectCallback: ConnectCallback;
private readonly disconnectCallback: DisconnectCallback;
2020-04-07 10:08:04 +02:00
2020-07-27 22:36:07 +02:00
private itemsState: Map<number, unknown> = new Map<number, unknown>();
private readonly positionNotifier: PositionNotifier;
public readonly roomId: string;
public readonly anonymous: boolean;
public tags: string[];
public policyType: GameRoomPolicyTypes;
public readonly roomSlug: string;
public readonly worldSlug: string = '';
public readonly organizationSlug: string = '';
private nextUserId: number = 1;
constructor(roomId: string,
connectCallback: ConnectCallback,
2020-05-03 17:47:54 +02:00
disconnectCallback: DisconnectCallback,
minDistance: number,
groupRadius: number,
2020-09-16 16:06:43 +02:00
onEnters: EntersCallback,
onMoves: MovesCallback,
onLeaves: LeavesCallback)
2020-04-07 10:08:04 +02:00
{
this.roomId = roomId;
this.anonymous = isRoomAnonymous(roomId);
this.tags = [];
this.policyType = GameRoomPolicyTypes.ANONYMUS_POLICY;
if (this.anonymous) {
this.roomSlug = extractRoomSlugPublicRoomId(this.roomId);
} else {
const {organizationSlug, worldSlug, roomSlug} = extractDataFromPrivateRoomId(this.roomId);
this.roomSlug = roomSlug;
this.organizationSlug = organizationSlug;
this.worldSlug = worldSlug;
}
this.users = new Map<number, User>();
2020-06-29 22:13:07 +02:00
this.groups = new Set<Group>();
2020-04-07 10:08:04 +02:00
this.connectCallback = connectCallback;
this.disconnectCallback = disconnectCallback;
this.minDistance = minDistance;
this.groupRadius = groupRadius;
// A zone is 10 sprites wide.
2020-09-16 16:06:43 +02:00
this.positionNotifier = new PositionNotifier(320, 320, onEnters, onMoves, onLeaves);
2020-04-28 23:23:50 +02:00
}
2020-04-07 10:08:04 +02:00
public getGroups(): Group[] {
return Array.from(this.groups.values());
}
public getUsers(): Map<number, User> {
return this.users;
}
public join(socket : UserSocket, joinRoomMessage: JoinRoomMessage): User {
const positionMessage = joinRoomMessage.getPositionmessage();
if (positionMessage === undefined) {
throw new Error('Missing position message');
}
const position = ProtobufUtils.toPointInterface(positionMessage);
const user = new User(this.nextUserId, joinRoomMessage.getUseruuid(), position, false, this.positionNotifier, socket, joinRoomMessage.getTagList(), joinRoomMessage.getName(), ProtobufUtils.toCharacterLayerObjects(joinRoomMessage.getCharacterlayerList()));
this.nextUserId++;
this.users.set(user.id, user);
// Let's call update position to trigger the join / leave room
//this.updatePosition(socket, userPosition);
this.updateUserGroup(user);
return user;
2020-04-07 10:08:04 +02:00
}
public leave(user : User){
const userObj = this.users.get(user.id);
if (userObj === undefined) {
console.warn('User ', user.id, 'does not belong to this game room! It should!');
}
if (userObj !== undefined && typeof userObj.group !== 'undefined') {
this.leaveGroup(userObj);
}
this.users.delete(user.id);
if (userObj !== undefined) {
2020-09-28 18:52:54 +02:00
this.positionNotifier.leave(userObj);
}
2020-04-29 01:40:32 +02:00
}
2020-10-21 23:45:08 +02:00
get isFull(): boolean {
return this.users.size >= MAX_USERS_PER_ROOM;
}
2020-06-29 19:14:54 +02:00
public isEmpty(): boolean {
return this.users.size === 0;
}
public updatePosition(user : User, userPosition: PointInterface): void {
user.setPosition(userPosition);
2020-09-16 16:06:43 +02:00
this.updateUserGroup(user);
}
private updateUserGroup(user: User): void {
2020-09-24 10:05:16 +02:00
user.group?.updatePosition();
if (user.silent) {
return;
}
2020-09-16 16:06:43 +02:00
if (user.group === undefined) {
// If the user is not part of a group:
// should he join a group?
// If the user is moving, don't try to join
if (user.getPosition().moving) {
return;
}
2020-09-16 16:06:43 +02:00
const closestItem: User|Group|null = this.searchClosestAvailableUserOrGroup(user);
if (closestItem !== null) {
if (closestItem instanceof Group) {
// Let's join the group!
closestItem.join(user);
} else {
2020-09-16 16:06:43 +02:00
const closestUser : User = closestItem;
const group: Group = new Group(this.roomId,[
user,
closestUser
], this.connectCallback, this.disconnectCallback, this.positionNotifier);
2020-06-29 22:13:07 +02:00
this.groups.add(group);
}
}
2020-04-28 23:23:50 +02:00
} else {
// If the user is part of a group:
// should he leave the group?
2020-10-06 15:37:00 +02:00
const distance = GameRoom.computeDistanceBetweenPositions(user.getPosition(), user.group.getPosition());
if (distance > this.groupRadius) {
this.leaveGroup(user);
}
}
}
2020-04-28 23:23:50 +02:00
setSilent(user: User, silent: boolean) {
if (user.silent === silent) {
return;
}
user.silent = silent;
if (silent && user.group !== undefined) {
this.leaveGroup(user);
}
if (!silent) {
// If we are back to life, let's trigger a position update to see if we can join some group.
this.updatePosition(user, user.getPosition());
}
}
/**
* Makes a user leave a group and closes and destroy the group if the group contains only one remaining person.
*
* @param user
*/
2020-09-16 16:06:43 +02:00
private leaveGroup(user: User): void {
const group = user.group;
2020-09-21 11:24:03 +02:00
if (group === undefined) {
throw new Error("The user is part of no group");
}
group.leave(user);
if (group.isEmpty()) {
2020-09-16 16:06:43 +02:00
this.positionNotifier.leave(group);
group.destroy();
2020-06-29 22:13:07 +02:00
if (!this.groups.has(group)) {
throw new Error("Could not find group "+group.getId()+" referenced by user "+user.id+" in World.");
}
2020-06-29 22:13:07 +02:00
this.groups.delete(group);
//todo: is the group garbage collected?
} else {
group.updatePosition();
//this.positionNotifier.updatePosition(group, group.getPosition(), oldPosition);
}
}
/**
* Looks for the closest user that is:
* - close enough (distance <= minDistance)
* - not in a group
* - not silent
* OR
* - close enough to a group (distance <= groupRadius)
*/
2020-09-16 16:06:43 +02:00
private searchClosestAvailableUserOrGroup(user: User): User|Group|null
{
let minimumDistanceFound: number = Math.max(this.minDistance, this.groupRadius);
2020-09-16 16:06:43 +02:00
let matchingItem: User | Group | null = null;
this.users.forEach((currentUser, userId) => {
// Let's only check users that are not part of a group
if (typeof currentUser.group !== 'undefined') {
return;
}
if(currentUser === user) {
return;
}
if (currentUser.silent) {
return;
}
2020-10-06 15:37:00 +02:00
const distance = GameRoom.computeDistance(user, currentUser); // compute distance between peers.
2020-04-28 23:23:50 +02:00
if(distance <= minimumDistanceFound && distance <= this.minDistance) {
minimumDistanceFound = distance;
matchingItem = currentUser;
}
});
this.groups.forEach((group: Group) => {
if (group.isFull()) {
return;
2020-04-08 20:40:44 +02:00
}
2020-10-06 15:37:00 +02:00
const distance = GameRoom.computeDistanceBetweenPositions(user.getPosition(), group.getPosition());
if(distance <= minimumDistanceFound && distance <= this.groupRadius) {
minimumDistanceFound = distance;
matchingItem = group;
}
});
2020-04-08 20:40:44 +02:00
return matchingItem;
2020-04-08 20:40:44 +02:00
}
2020-09-16 16:06:43 +02:00
public static computeDistance(user1: User, user2: User): number
2020-04-08 20:40:44 +02:00
{
const user1Position = user1.getPosition();
const user2Position = user2.getPosition();
return Math.sqrt(Math.pow(user2Position.x - user1Position.x, 2) + Math.pow(user2Position.y - user1Position.y, 2));
2020-04-08 20:40:44 +02:00
}
2020-04-07 10:08:04 +02:00
public static computeDistanceBetweenPositions(position1: PositionInterface, position2: PositionInterface): number
{
return Math.sqrt(Math.pow(position2.x - position1.x, 2) + Math.pow(position2.y - position1.y, 2));
}
2020-07-27 22:36:07 +02:00
public setItemState(itemId: number, state: unknown) {
this.itemsState.set(itemId, state);
}
public getItemsState(): Map<number, unknown> {
return this.itemsState;
}
public canAccess(userTags: string[]): boolean {
return arrayIntersect(userTags, this.tags);
}
public addZoneListener(call: ZoneSocket, x: number, y: number): Set<Movable> {
return this.positionNotifier.addZoneListener(call, x, y);
}
public removeZoneListener(call: ZoneSocket, x: number, y: number): void {
return this.positionNotifier.removeZoneListener(call, x, y);
}
2020-04-28 23:23:50 +02:00
}