Merge branch 'update-game-tiles' into correct-merge

This commit is contained in:
GRL 2021-05-27 09:45:25 +02:00
commit acbe4f89a6
19 changed files with 9038 additions and 144 deletions

27
back/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,27 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Example",
"type": "node",
"request": "launch",
"runtimeExecutable": "node",
"runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register/transpile-only"
],
"args": [
"server.ts",
"--example",
"hello"
],
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": [
"<node_internals>/**",
"node_modules/**"
]
}
]
}

8393
front/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
import * as tg from "generic-type-guard";
export const updateTile = "updateTile"
export const isUpdateTileEvent = tg.isArray(
new tg.IsInterface().withProperties({
x: tg.isNumber,
y: tg.isNumber,
tile: tg.isUnion(tg.isNumber, tg.isString),
layer: tg.isUnion(tg.isNumber, tg.isString)
}).get()
);
/**
* A message sent from the game to the iFrame when a user enters or leaves a zone marked with the "zone" property.
*/
export type UpdateTileEvent = tg.GuardedType<typeof isUpdateTileEvent>;

View File

@ -0,0 +1,13 @@
import * as tg from "generic-type-guard";
export const isDataLayerEvent =
new tg.IsInterface().withProperties({
data: tg.isObject
}).get();
/**
* A message sent from the game to the iFrame when the data of the layers change after the iFrame send a message to the game that it want to listen to the data of the layers
*/
export type DataLayerEvent = tg.GuardedType<typeof isDataLayerEvent>;

View File

@ -0,0 +1,28 @@
import * as tg from "generic-type-guard";
/*export const isPositionState = new tg.IsInterface().withProperties({
x: tg.isNumber,
y: tg.isNumber
}).get()
export const isPlayerState = new tg.IsInterface()
.withStringIndexSignature(
new tg.IsInterface().withProperties({
position: isPositionState,
pusherId: tg.isUnion(tg.isNumber, tg.isUndefined)
}).get()
).get()
export type PlayerStateObject = tg.GuardedType<typeof isPlayerState>;*/
export const isGameStateEvent =
new tg.IsInterface().withProperties({
roomId: tg.isString,
mapUrl: tg.isString,
nickname: tg.isUnion(tg.isString, tg.isNull),
uuid: tg.isUnion(tg.isString, tg.isUndefined),
startLayerName: tg.isUnion(tg.isString, tg.isNull)
}).get();
/**
* A message sent from the game to the iFrame when the gameState is got by the script
*/
export type GameStateEvent = tg.GuardedType<typeof isGameStateEvent>;

View File

@ -0,0 +1,19 @@
import * as tg from "generic-type-guard";
export const isHasPlayerMovedEvent =
new tg.IsInterface().withProperties({
direction: tg.isString,
moving: tg.isBoolean,
x: tg.isNumber,
y: tg.isNumber
}).get();
/**
* A message sent from the game to the iFrame when the player move after the iFrame send a message to the game that it want to listen to the position of the player
*/
export type HasPlayerMovedEvent = tg.GuardedType<typeof isHasPlayerMovedEvent>;
export type HasPlayerMovedEventCallback = (event: HasPlayerMovedEvent) => void

View File

@ -9,8 +9,10 @@ import type { OpenCoWebSiteEvent } from './OpenCoWebSiteEvent';
import type { OpenPopupEvent } from './OpenPopupEvent'; import type { OpenPopupEvent } from './OpenPopupEvent';
import type { OpenTabEvent } from './OpenTabEvent'; import type { OpenTabEvent } from './OpenTabEvent';
import type { UserInputChatEvent } from './UserInputChatEvent'; import type { UserInputChatEvent } from './UserInputChatEvent';
import type {LoadSoundEvent} from "./LoadSoundEvent"; import type { LoadSoundEvent } from "./LoadSoundEvent";
import type {PlaySoundEvent} from "./PlaySoundEvent"; import type { PlaySoundEvent } from "./PlaySoundEvent";
import type { LoadPageEvent } from "./LoadPageEvent";
import type { UpdateTileEvent } from "./ApiUpdateTileEvent";
export interface TypedMessageEvent<T> extends MessageEvent { export interface TypedMessageEvent<T> extends MessageEvent {
@ -34,6 +36,8 @@ export type IframeEventMap = {
loadSound: LoadSoundEvent loadSound: LoadSoundEvent
playSound: PlaySoundEvent playSound: PlaySoundEvent
stopSound: null stopSound: null
loadPage: LoadPageEvent
updateTile: UpdateTileEvent
} }
export interface IframeEvent<T extends keyof IframeEventMap> { export interface IframeEvent<T extends keyof IframeEventMap> {
type: T; type: T;

View File

@ -0,0 +1,10 @@
import * as tg from "generic-type-guard";
export const isLayerEvent =
new tg.IsInterface().withProperties({
name: tg.isString,
}).get();
/**
* A message sent from the iFrame to the game to show/hide a layer.
*/
export type LayerEvent = tg.GuardedType<typeof isLayerEvent>;

View File

@ -0,0 +1,13 @@
import * as tg from "generic-type-guard";
export const isLoadPageEvent =
new tg.IsInterface().withProperties({
url: tg.isString,
}).get();
/**
* A message sent from the iFrame to the game to add a message in the chat.
*/
export type LoadPageEvent = tg.GuardedType<typeof isLoadPageEvent>;

View File

@ -0,0 +1,12 @@
import * as tg from "generic-type-guard";
export const isSetPropertyEvent =
new tg.IsInterface().withProperties({
layerName: tg.isString,
propertyName: tg.isString,
propertyValue: tg.isUnion(tg.isString, tg.isUnion(tg.isNumber, tg.isUnion(tg.isBoolean, tg.isUndefined)))
}).get();
/**
* A message sent from the iFrame to the game to change the value of the property of the layer
*/
export type SetPropertyEvent = tg.GuardedType<typeof isSetPropertyEvent>;

View File

@ -12,9 +12,12 @@ import { GoToPageEvent, isGoToPageEvent } from "./Events/GoToPageEvent";
import { isOpenCoWebsite, OpenCoWebSiteEvent } from "./Events/OpenCoWebSiteEvent"; import { isOpenCoWebsite, OpenCoWebSiteEvent } from "./Events/OpenCoWebSiteEvent";
import { IframeEventMap, IframeEvent, IframeResponseEvent, IframeResponseEventMap, isIframeEventWrapper, TypedMessageEvent } from "./Events/IframeEvent"; import { IframeEventMap, IframeEvent, IframeResponseEvent, IframeResponseEventMap, isIframeEventWrapper, TypedMessageEvent } from "./Events/IframeEvent";
import type { UserInputChatEvent } from "./Events/UserInputChatEvent"; import type { UserInputChatEvent } from "./Events/UserInputChatEvent";
import {isPlaySoundEvent, PlaySoundEvent} from "./Events/PlaySoundEvent"; import { isPlaySoundEvent, PlaySoundEvent } from "./Events/PlaySoundEvent";
import {isStopSoundEvent, StopSoundEvent} from "./Events/StopSoundEvent"; import { isStopSoundEvent, StopSoundEvent } from "./Events/StopSoundEvent";
import {isLoadSoundEvent, LoadSoundEvent} from "./Events/LoadSoundEvent"; import { isLoadSoundEvent, LoadSoundEvent } from "./Events/LoadSoundEvent";
import { isLoadPageEvent } from './Events/LoadPageEvent';
import { isUpdateTileEvent, UpdateTileEvent } from './Events/ApiUpdateTileEvent';
/** /**
* Listens to messages from iframes and turn those messages into easy to use observables. * Listens to messages from iframes and turn those messages into easy to use observables.
* Also allows to send messages to those iframes. * Also allows to send messages to those iframes.
@ -32,6 +35,9 @@ class IframeListener {
private readonly _goToPageStream: Subject<GoToPageEvent> = new Subject(); private readonly _goToPageStream: Subject<GoToPageEvent> = new Subject();
public readonly goToPageStream = this._goToPageStream.asObservable(); public readonly goToPageStream = this._goToPageStream.asObservable();
private readonly _loadPageStream: Subject<string> = new Subject();
public readonly loadPageStream = this._loadPageStream.asObservable();
private readonly _openCoWebSiteStream: Subject<OpenCoWebSiteEvent> = new Subject(); private readonly _openCoWebSiteStream: Subject<OpenCoWebSiteEvent> = new Subject();
public readonly openCoWebSiteStream = this._openCoWebSiteStream.asObservable(); public readonly openCoWebSiteStream = this._openCoWebSiteStream.asObservable();
@ -62,6 +68,9 @@ class IframeListener {
private readonly _loadSoundStream: Subject<LoadSoundEvent> = new Subject(); private readonly _loadSoundStream: Subject<LoadSoundEvent> = new Subject();
public readonly loadSoundStream = this._loadSoundStream.asObservable(); public readonly loadSoundStream = this._loadSoundStream.asObservable();
private readonly _updateTileEvent: Subject<UpdateTileEvent> = new Subject();
public readonly updateTileEvent = this._updateTileEvent.asObservable();
private readonly iframes = new Set<HTMLIFrameElement>(); private readonly iframes = new Set<HTMLIFrameElement>();
private readonly scripts = new Map<string, HTMLIFrameElement>(); private readonly scripts = new Map<string, HTMLIFrameElement>();
@ -128,6 +137,10 @@ class IframeListener {
} }
else if (payload.type === 'removeBubble') { else if (payload.type === 'removeBubble') {
this._removeBubbleStream.next(); this._removeBubbleStream.next();
} else if (payload.type === 'loadPage' && isLoadPageEvent(payload.data)) {
this._loadPageStream.next(payload.data.url);
} else if (payload.type == "updateTile" && isUpdateTileEvent(payload.data)) {
this._updateTileEvent.next(payload.data)
} }
} }

View File

@ -1,4 +1,4 @@
import {gameManager, HasMovedEvent} from "./GameManager"; import { gameManager, HasMovedEvent } from "./GameManager";
import type { import type {
GroupCreatedUpdatedMessageInterface, GroupCreatedUpdatedMessageInterface,
MessageUserJoined, MessageUserJoined,
@ -9,7 +9,7 @@ import type {
PositionInterface, PositionInterface,
RoomJoinedMessageInterface RoomJoinedMessageInterface
} from "../../Connexion/ConnexionModels"; } from "../../Connexion/ConnexionModels";
import {hasMovedEventName, Player, requestEmoteEventName} from "../Player/Player"; import { hasMovedEventName, Player, requestEmoteEventName} from "../Player/Player";
import { import {
DEBUG_MODE, DEBUG_MODE,
JITSI_PRIVATE_MODE, JITSI_PRIVATE_MODE,
@ -25,15 +25,15 @@ import type {
ITiledMapTileLayer, ITiledMapTileLayer,
ITiledTileSet ITiledTileSet
} from "../Map/ITiledMap"; } from "../Map/ITiledMap";
import type {AddPlayerInterface} from "./AddPlayerInterface"; import type { AddPlayerInterface } from "./AddPlayerInterface";
import {PlayerAnimationDirections} from "../Player/Animation"; import { PlayerAnimationDirections } from "../Player/Animation";
import {PlayerMovement} from "./PlayerMovement"; import { PlayerMovement } from "./PlayerMovement";
import {PlayersPositionInterpolator} from "./PlayersPositionInterpolator"; import { PlayersPositionInterpolator } from "./PlayersPositionInterpolator";
import {RemotePlayer} from "../Entity/RemotePlayer"; import { RemotePlayer } from "../Entity/RemotePlayer";
import {Queue} from 'queue-typescript'; import { Queue } from 'queue-typescript';
import {SimplePeer, UserSimplePeerInterface} from "../../WebRtc/SimplePeer"; import { SimplePeer, UserSimplePeerInterface } from "../../WebRtc/SimplePeer";
import {ReconnectingSceneName} from "../Reconnecting/ReconnectingScene"; import { ReconnectingSceneName } from "../Reconnecting/ReconnectingScene";
import {lazyLoadPlayerCharacterTextures, loadCustomTexture} from "../Entity/PlayerTexturesLoadingManager"; import { lazyLoadPlayerCharacterTextures, loadCustomTexture } from "../Entity/PlayerTexturesLoadingManager";
import { import {
CenterListener, CenterListener,
JITSI_MESSAGE_PROPERTIES, JITSI_MESSAGE_PROPERTIES,
@ -46,16 +46,16 @@ import {
AUDIO_VOLUME_PROPERTY, AUDIO_VOLUME_PROPERTY,
AUDIO_LOOP_PROPERTY AUDIO_LOOP_PROPERTY
} from "../../WebRtc/LayoutManager"; } from "../../WebRtc/LayoutManager";
import {GameMap} from "./GameMap"; import { GameMap } from "./GameMap";
import {coWebsiteManager} from "../../WebRtc/CoWebsiteManager"; import { coWebsiteManager } from "../../WebRtc/CoWebsiteManager";
import {mediaManager} from "../../WebRtc/MediaManager"; import { mediaManager } from "../../WebRtc/MediaManager";
import type {ItemFactoryInterface} from "../Items/ItemFactoryInterface"; import type {ItemFactoryInterface} from "../Items/ItemFactoryInterface";
import type {ActionableItem} from "../Items/ActionableItem"; import type {ActionableItem} from "../Items/ActionableItem";
import {UserInputManager} from "../UserInput/UserInputManager"; import {UserInputManager} from "../UserInput/UserInputManager";
import {soundManager} from "./SoundManager"; import {soundManager} from "./SoundManager";
import type {UserMovedMessage} from "../../Messages/generated/messages_pb"; import type {UserMovedMessage } from "../../Messages/generated/messages_pb";
import {ProtobufClientUtils} from "../../Network/ProtobufClientUtils"; import { ProtobufClientUtils } from "../../Network/ProtobufClientUtils";
import {connectionManager} from "../../Connexion/ConnectionManager"; import { connectionManager } from "../../Connexion/ConnectionManager";
import type {RoomConnection} from "../../Connexion/RoomConnection"; import type {RoomConnection} from "../../Connexion/RoomConnection";
import {GlobalMessageManager} from "../../Administration/GlobalMessageManager"; import {GlobalMessageManager} from "../../Administration/GlobalMessageManager";
import {userMessageManager} from "../../Administration/UserMessageManager"; import {userMessageManager} from "../../Administration/UserMessageManager";
@ -81,8 +81,9 @@ import CanvasTexture = Phaser.Textures.CanvasTexture;
import GameObject = Phaser.GameObjects.GameObject; import GameObject = Phaser.GameObjects.GameObject;
import FILE_LOAD_ERROR = Phaser.Loader.Events.FILE_LOAD_ERROR; import FILE_LOAD_ERROR = Phaser.Loader.Events.FILE_LOAD_ERROR;
import DOMElement = Phaser.GameObjects.DOMElement; import DOMElement = Phaser.GameObjects.DOMElement;
import type {Subscription} from "rxjs"; import EVENT_TYPE = Phaser.Scenes.Events
import {worldFullMessageStream} from "../../Connexion/WorldFullMessageStream"; import type { Subscription } from "rxjs";
import { worldFullMessageStream } from "../../Connexion/WorldFullMessageStream";
import { lazyLoadCompanionResource } from "../Companion/CompanionTexturesLoadingManager"; import { lazyLoadCompanionResource } from "../Companion/CompanionTexturesLoadingManager";
import RenderTexture = Phaser.GameObjects.RenderTexture; import RenderTexture = Phaser.GameObjects.RenderTexture;
import Tilemap = Phaser.Tilemaps.Tilemap; import Tilemap = Phaser.Tilemaps.Tilemap;
@ -97,7 +98,7 @@ import {peerStore} from "../../Stores/PeerStore";
import {EmoteManager} from "./EmoteManager"; import {EmoteManager} from "./EmoteManager";
export interface GameSceneInitInterface { export interface GameSceneInitInterface {
initPosition: PointInterface|null, initPosition: PointInterface | null,
reconnecting: boolean reconnecting: boolean
} }
@ -134,10 +135,10 @@ interface DeleteGroupEventInterface {
const defaultStartLayerName = 'start'; const defaultStartLayerName = 'start';
export class GameScene extends DirtyScene implements CenterListener { export class GameScene extends DirtyScene implements CenterListener {
Terrains : Array<Phaser.Tilemaps.Tileset>; Terrains: Array<Phaser.Tilemaps.Tileset>;
CurrentPlayer!: Player; CurrentPlayer!: Player;
MapPlayers!: Phaser.Physics.Arcade.Group; MapPlayers!: Phaser.Physics.Arcade.Group;
MapPlayersByKey : Map<number, RemotePlayer> = new Map<number, RemotePlayer>(); MapPlayersByKey: Map<number, RemotePlayer> = new Map<number, RemotePlayer>();
Map!: Phaser.Tilemaps.Tilemap; Map!: Phaser.Tilemaps.Tilemap;
Layers!: Array<Phaser.Tilemaps.TilemapLayer>; Layers!: Array<Phaser.Tilemaps.TilemapLayer>;
Objects!: Array<Phaser.Physics.Arcade.Sprite>; Objects!: Array<Phaser.Physics.Arcade.Sprite>;
@ -147,10 +148,10 @@ export class GameScene extends DirtyScene implements CenterListener {
startY!: number; startY!: number;
circleTexture!: CanvasTexture; circleTexture!: CanvasTexture;
circleRedTexture!: CanvasTexture; circleRedTexture!: CanvasTexture;
pendingEvents: Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface|AddPlayerEventInterface|RemovePlayerEventInterface|UserMovedEventInterface|GroupCreatedUpdatedEventInterface|DeleteGroupEventInterface>(); pendingEvents: Queue<InitUserPositionEventInterface | AddPlayerEventInterface | RemovePlayerEventInterface | UserMovedEventInterface | GroupCreatedUpdatedEventInterface | DeleteGroupEventInterface> = new Queue<InitUserPositionEventInterface | AddPlayerEventInterface | RemovePlayerEventInterface | UserMovedEventInterface | GroupCreatedUpdatedEventInterface | DeleteGroupEventInterface>();
private initPosition: PositionInterface|null = null; private initPosition: PositionInterface | null = null;
private playersPositionInterpolator = new PlayersPositionInterpolator(); private playersPositionInterpolator = new PlayersPositionInterpolator();
public connection: RoomConnection|undefined; public connection: RoomConnection | undefined;
private simplePeer!: SimplePeer; private simplePeer!: SimplePeer;
private GlobalMessageManager!: GlobalMessageManager; private GlobalMessageManager!: GlobalMessageManager;
public ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager; public ConsoleGlobalMessageManager!: ConsoleGlobalMessageManager;
@ -159,7 +160,7 @@ export class GameScene extends DirtyScene implements CenterListener {
// A promise that will resolve when the "create" method is called (signaling loading is ended) // A promise that will resolve when the "create" method is called (signaling loading is ended)
private createPromise: Promise<void>; private createPromise: Promise<void>;
private createPromiseResolve!: (value?: void | PromiseLike<void>) => void; private createPromiseResolve!: (value?: void | PromiseLike<void>) => void;
private iframeSubscriptionList! : Array<Subscription>; private iframeSubscriptionList!: Array<Subscription>;
MapUrlFile: string; MapUrlFile: string;
RoomId: string; RoomId: string;
instance: string; instance: string;
@ -178,22 +179,22 @@ export class GameScene extends DirtyScene implements CenterListener {
private gameMap!: GameMap; private gameMap!: GameMap;
private actionableItems: Map<number, ActionableItem> = new Map<number, ActionableItem>(); private actionableItems: Map<number, ActionableItem> = new Map<number, ActionableItem>();
// The item that can be selected by pressing the space key. // The item that can be selected by pressing the space key.
private outlinedItem: ActionableItem|null = null; private outlinedItem: ActionableItem | null = null;
public userInputManager!: UserInputManager; public userInputManager!: UserInputManager;
private isReconnecting: boolean|undefined = undefined; private isReconnecting: boolean | undefined = undefined;
private startLayerName!: string | null; private startLayerName!: string | null;
private openChatIcon!: OpenChatIcon; private openChatIcon!: OpenChatIcon;
private playerName!: string; private playerName!: string;
private characterLayers!: string[]; private characterLayers!: string[];
private companion!: string|null; private companion!: string | null;
private messageSubscription: Subscription|null = null; private messageSubscription: Subscription | null = null;
private popUpElements : Map<number, DOMElement> = new Map<number, Phaser.GameObjects.DOMElement>(); private popUpElements: Map<number, DOMElement> = new Map<number, Phaser.GameObjects.DOMElement>();
private originalMapUrl: string|undefined; private originalMapUrl: string | undefined;
private pinchManager: PinchManager|undefined; private pinchManager: PinchManager|undefined;
private mapTransitioning: boolean = false; //used to prevent transitions happenning at the same time. private mapTransitioning: boolean = false; //used to prevent transitions happenning at the same time.
private emoteManager!: EmoteManager; private emoteManager!: EmoteManager;
constructor(private room: Room, MapUrlFile: string, customKey?: string|undefined) { constructor(private room: Room, MapUrlFile: string, customKey?: string | undefined) {
super({ super({
key: customKey ?? room.id key: customKey ?? room.id
}); });
@ -233,13 +234,13 @@ export class GameScene extends DirtyScene implements CenterListener {
frameHeight: 32, frameHeight: 32,
frameWidth: 32, frameWidth: 32,
}); });
this.load.on(FILE_LOAD_ERROR, (file: {src: string}) => { this.load.on(FILE_LOAD_ERROR, (file: { src: string }) => {
// If we happen to be in HTTP and we are trying to load a URL in HTTPS only... (this happens only in dev environments) // If we happen to be in HTTP and we are trying to load a URL in HTTPS only... (this happens only in dev environments)
if (window.location.protocol === 'http:' && file.src === this.MapUrlFile && file.src.startsWith('http:') && this.originalMapUrl === undefined) { if (window.location.protocol === 'http:' && file.src === this.MapUrlFile && file.src.startsWith('http:') && this.originalMapUrl === undefined) {
this.originalMapUrl = this.MapUrlFile; this.originalMapUrl = this.MapUrlFile;
this.MapUrlFile = this.MapUrlFile.replace('http://', 'https://'); this.MapUrlFile = this.MapUrlFile.replace('http://', 'https://');
this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile); this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile);
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => { this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
}); });
return; return;
@ -253,7 +254,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.originalMapUrl = this.MapUrlFile; this.originalMapUrl = this.MapUrlFile;
this.MapUrlFile = this.MapUrlFile.replace('https://', 'http://'); this.MapUrlFile = this.MapUrlFile.replace('https://', 'http://');
this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile); this.load.tilemapTiledJSON(this.MapUrlFile, this.MapUrlFile);
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => { this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
}); });
return; return;
@ -265,7 +266,7 @@ export class GameScene extends DirtyScene implements CenterListener {
message: this.originalMapUrl ?? file.src message: this.originalMapUrl ?? file.src
}); });
}); });
this.load.on('filecomplete-tilemapJSON-'+this.MapUrlFile, (key: string, type: string, data: unknown) => { this.load.on('filecomplete-tilemapJSON-' + this.MapUrlFile, (key: string, type: string, data: unknown) => {
this.onMapLoad(data); this.onMapLoad(data);
}); });
//TODO strategy to add access token //TODO strategy to add access token
@ -277,7 +278,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.onMapLoad(data); this.onMapLoad(data);
} }
this.load.spritesheet('layout_modes', 'resources/objects/layout_modes.png', {frameWidth: 32, frameHeight: 32}); this.load.spritesheet('layout_modes', 'resources/objects/layout_modes.png', { frameWidth: 32, frameHeight: 32 });
this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml'); this.load.bitmapFont('main_font', 'resources/fonts/arcade.png', 'resources/fonts/arcade.xml');
//this function must stay at the end of preload function //this function must stay at the end of preload function
@ -306,7 +307,7 @@ export class GameScene extends DirtyScene implements CenterListener {
for (const layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (layer.type === 'objectgroup') { if (layer.type === 'objectgroup') {
for (const object of layer.objects) { for (const object of layer.objects) {
let objectsOfType: ITiledMapObject[]|undefined; let objectsOfType: ITiledMapObject[] | undefined;
if (!objects.has(object.type)) { if (!objects.has(object.type)) {
objectsOfType = new Array<ITiledMapObject>(); objectsOfType = new Array<ITiledMapObject>();
} else { } else {
@ -369,7 +370,7 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
//hook initialisation //hook initialisation
init(initData : GameSceneInitInterface) { init(initData: GameSceneInitInterface) {
if (initData.initPosition !== undefined) { if (initData.initPosition !== undefined) {
this.initPosition = initData.initPosition; //todo: still used? this.initPosition = initData.initPosition; //todo: still used?
} }
@ -448,7 +449,7 @@ export class GameScene extends DirtyScene implements CenterListener {
this.Objects = new Array<Phaser.Physics.Arcade.Sprite>(); this.Objects = new Array<Phaser.Physics.Arcade.Sprite>();
//initialise list of other player //initialise list of other player
this.MapPlayers = this.physics.add.group({immovable: true}); this.MapPlayers = this.physics.add.group({ immovable: true });
//create input to move //create input to move
@ -698,16 +699,16 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
private safeParseJSONstring(jsonString: string|undefined, propertyName: string) { private safeParseJSONstring(jsonString: string | undefined, propertyName: string) {
try { try {
return jsonString ? JSON.parse(jsonString) : {}; return jsonString ? JSON.parse(jsonString) : {};
} catch(e) { } catch (e) {
console.warn('Invalid JSON found in property "' + propertyName + '" of the map:' + jsonString, e); console.warn('Invalid JSON found in property "' + propertyName + '" of the map:' + jsonString, e);
return {} return {}
} }
} }
private triggerOnMapLayerPropertyChange(){ private triggerOnMapLayerPropertyChange() {
this.gameMap.onPropertyChange('exitSceneUrl', (newValue, oldValue) => { this.gameMap.onPropertyChange('exitSceneUrl', (newValue, oldValue) => {
if (newValue) this.onMapExit(newValue as string); if (newValue) this.onMapExit(newValue as string);
}); });
@ -718,22 +719,22 @@ export class GameScene extends DirtyScene implements CenterListener {
if (newValue === undefined) { if (newValue === undefined) {
layoutManager.removeActionButton('openWebsite', this.userInputManager); layoutManager.removeActionButton('openWebsite', this.userInputManager);
coWebsiteManager.closeCoWebsite(); coWebsiteManager.closeCoWebsite();
}else{ } else {
const openWebsiteFunction = () => { const openWebsiteFunction = () => {
coWebsiteManager.loadCoWebsite(newValue as string, this.MapUrlFile, allProps.get('openWebsiteAllowApi') as boolean | undefined, allProps.get('openWebsitePolicy') as string | undefined); coWebsiteManager.loadCoWebsite(newValue as string, this.MapUrlFile, allProps.get('openWebsiteAllowApi') as boolean | undefined, allProps.get('openWebsitePolicy') as string | undefined);
layoutManager.removeActionButton('openWebsite', this.userInputManager); layoutManager.removeActionButton('openWebsite', this.userInputManager);
}; };
const openWebsiteTriggerValue = allProps.get(TRIGGER_WEBSITE_PROPERTIES); const openWebsiteTriggerValue = allProps.get(TRIGGER_WEBSITE_PROPERTIES);
if(openWebsiteTriggerValue && openWebsiteTriggerValue === ON_ACTION_TRIGGER_BUTTON) { if (openWebsiteTriggerValue && openWebsiteTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
let message = allProps.get(WEBSITE_MESSAGE_PROPERTIES); let message = allProps.get(WEBSITE_MESSAGE_PROPERTIES);
if(message === undefined){ if (message === undefined) {
message = 'Press SPACE or touch here to open web site'; message = 'Press SPACE or touch here to open web site';
} }
layoutManager.addActionButton('openWebsite', message.toString(), () => { layoutManager.addActionButton('openWebsite', message.toString(), () => {
openWebsiteFunction(); openWebsiteFunction();
}, this.userInputManager); }, this.userInputManager);
}else{ } else {
openWebsiteFunction(); openWebsiteFunction();
} }
} }
@ -742,12 +743,12 @@ export class GameScene extends DirtyScene implements CenterListener {
if (newValue === undefined) { if (newValue === undefined) {
layoutManager.removeActionButton('jitsiRoom', this.userInputManager); layoutManager.removeActionButton('jitsiRoom', this.userInputManager);
this.stopJitsi(); this.stopJitsi();
}else{ } else {
const openJitsiRoomFunction = () => { const openJitsiRoomFunction = () => {
const roomName = jitsiFactory.getRoomName(newValue.toString(), this.instance); const roomName = jitsiFactory.getRoomName(newValue.toString(), this.instance);
const jitsiUrl = allProps.get("jitsiUrl") as string|undefined; const jitsiUrl = allProps.get("jitsiUrl") as string | undefined;
if (JITSI_PRIVATE_MODE && !jitsiUrl) { if (JITSI_PRIVATE_MODE && !jitsiUrl) {
const adminTag = allProps.get("jitsiRoomAdminTag") as string|undefined; const adminTag = allProps.get("jitsiRoomAdminTag") as string | undefined;
this.connection?.emitQueryJitsiJwtMessage(roomName, adminTag); this.connection?.emitQueryJitsiJwtMessage(roomName, adminTag);
} else { } else {
@ -757,7 +758,7 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
const jitsiTriggerValue = allProps.get(TRIGGER_JITSI_PROPERTIES); const jitsiTriggerValue = allProps.get(TRIGGER_JITSI_PROPERTIES);
if(jitsiTriggerValue && jitsiTriggerValue === ON_ACTION_TRIGGER_BUTTON) { if (jitsiTriggerValue && jitsiTriggerValue === ON_ACTION_TRIGGER_BUTTON) {
let message = allProps.get(JITSI_MESSAGE_PROPERTIES); let message = allProps.get(JITSI_MESSAGE_PROPERTIES);
if (message === undefined) { if (message === undefined) {
message = 'Press SPACE or touch here to enter Jitsi Meet room'; message = 'Press SPACE or touch here to enter Jitsi Meet room';
@ -765,7 +766,7 @@ export class GameScene extends DirtyScene implements CenterListener {
layoutManager.addActionButton('jitsiRoom', message.toString(), () => { layoutManager.addActionButton('jitsiRoom', message.toString(), () => {
openJitsiRoomFunction(); openJitsiRoomFunction();
}, this.userInputManager); }, this.userInputManager);
}else{ } else {
openJitsiRoomFunction(); openJitsiRoomFunction();
} }
} }
@ -778,8 +779,8 @@ export class GameScene extends DirtyScene implements CenterListener {
} }
}); });
this.gameMap.onPropertyChange('playAudio', (newValue, oldValue, allProps) => { this.gameMap.onPropertyChange('playAudio', (newValue, oldValue, allProps) => {
const volume = allProps.get(AUDIO_VOLUME_PROPERTY) as number|undefined; const volume = allProps.get(AUDIO_VOLUME_PROPERTY) as number | undefined;
const loop = allProps.get(AUDIO_LOOP_PROPERTY) as boolean|undefined; const loop = allProps.get(AUDIO_LOOP_PROPERTY) as boolean | undefined;
newValue === undefined ? audioManager.unloadAudio() : audioManager.playAudio(newValue, this.getMapDirUrl(), volume, loop); newValue === undefined ? audioManager.unloadAudio() : audioManager.playAudio(newValue, this.getMapDirUrl(), volume, loop);
}); });
// TODO: This legacy property should be removed at some point // TODO: This legacy property should be removed at some point
@ -801,9 +802,9 @@ export class GameScene extends DirtyScene implements CenterListener {
this.iframeSubscriptionList = []; this.iframeSubscriptionList = [];
this.iframeSubscriptionList.push(iframeListener.openPopupStream.subscribe((openPopupEvent) => { this.iframeSubscriptionList.push(iframeListener.openPopupStream.subscribe((openPopupEvent) => {
let objectLayerSquare : ITiledMapObject; let objectLayerSquare: ITiledMapObject;
const targetObjectData = this.getObjectLayerData(openPopupEvent.targetObject); const targetObjectData = this.getObjectLayerData(openPopupEvent.targetObject);
if (targetObjectData !== undefined){ if (targetObjectData !== undefined) {
objectLayerSquare = targetObjectData; objectLayerSquare = targetObjectData;
} else { } else {
console.error("Error while opening a popup. Cannot find an object on the map with name '" + openPopupEvent.targetObject + "'. The first parameter of WA.openPopup() must be the name of a rectangle object in your map."); console.error("Error while opening a popup. Cannot find an object on the map with name '" + openPopupEvent.targetObject + "'. The first parameter of WA.openPopup() must be the name of a rectangle object in your map.");
@ -821,10 +822,10 @@ ${escapedMessage}
id++; id++;
} }
html += '</div>'; html += '</div>';
const domElement = this.add.dom(objectLayerSquare.x , const domElement = this.add.dom(objectLayerSquare.x,
objectLayerSquare.y).createFromHTML(html); objectLayerSquare.y).createFromHTML(html);
const container : HTMLDivElement = domElement.getChildByID("container") as HTMLDivElement; const container: HTMLDivElement = domElement.getChildByID("container") as HTMLDivElement;
container.style.width = objectLayerSquare.width + "px"; container.style.width = objectLayerSquare.width + "px";
domElement.scale = 0; domElement.scale = 0;
domElement.setClassName('popUpElement'); domElement.setClassName('popUpElement');
@ -844,10 +845,10 @@ ${escapedMessage}
id++; id++;
} }
this.tweens.add({ this.tweens.add({
targets : domElement , targets: domElement,
scale : 1, scale: 1,
ease : "EaseOut", ease: "EaseOut",
duration : 400, duration: 400,
}); });
this.popUpElements.set(openPopupEvent.popupId, domElement); this.popUpElements.set(openPopupEvent.popupId, domElement);
@ -856,22 +857,22 @@ ${escapedMessage}
this.iframeSubscriptionList.push(iframeListener.closePopupStream.subscribe((closePopupEvent) => { this.iframeSubscriptionList.push(iframeListener.closePopupStream.subscribe((closePopupEvent) => {
const popUpElement = this.popUpElements.get(closePopupEvent.popupId); const popUpElement = this.popUpElements.get(closePopupEvent.popupId);
if (popUpElement === undefined) { if (popUpElement === undefined) {
console.error('Could not close popup with ID ', closePopupEvent.popupId,'. Maybe it has already been closed?'); console.error('Could not close popup with ID ', closePopupEvent.popupId, '. Maybe it has already been closed?');
} }
this.tweens.add({ this.tweens.add({
targets : popUpElement , targets: popUpElement,
scale : 0, scale: 0,
ease : "EaseOut", ease: "EaseOut",
duration : 400, duration: 400,
onComplete : () => { onComplete: () => {
popUpElement?.destroy(); popUpElement?.destroy();
this.popUpElements.delete(closePopupEvent.popupId); this.popUpElements.delete(closePopupEvent.popupId);
}, },
}); });
})); }));
this.iframeSubscriptionList.push(iframeListener.disablePlayerControlStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.disablePlayerControlStream.subscribe(() => {
this.userInputManager.disableControls(); this.userInputManager.disableControls();
})); }));
@ -895,21 +896,62 @@ ${escapedMessage}
this.iframeSubscriptionList.push(iframeListener.enablePlayerControlStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.enablePlayerControlStream.subscribe(()=>{
this.userInputManager.restoreControls(); this.userInputManager.restoreControls();
})); }))
let scriptedBubbleSprite : Sprite; /* this.iframeSubscriptionList.push(iframeListener.loadPageStream.subscribe((url: string) => {
this.iframeSubscriptionList.push(iframeListener.displayBubbleStream.subscribe(()=>{ this.loadNextGame(url).then(() => {
scriptedBubbleSprite = new Sprite(this,this.CurrentPlayer.x + 25,this.CurrentPlayer.y,'circleSprite-white'); this.events.once(EVENT_TYPE.POST_UPDATE, () => {
this.onMapExit(url);
})
})
}))*/
this.iframeSubscriptionList.push(iframeListener.updateTileEvent.subscribe(event => {
for (const eventTile of event) {
const layer = this.Layers.find(layer => layer.layer.name == eventTile.layer)
if (layer) {
const tile = layer.getTileAt(eventTile.x, eventTile.y)
if (typeof eventTile.tile == "string") {
const tileIndex = this.getIndexForTileType(eventTile.tile);
if (tileIndex) {
tile.index = tileIndex
} else {
return
}
} else {
tile.index = eventTile.tile
}
}
}
this.scene.scene.sys.game.events.emit("contextrestored")
}))
let scriptedBubbleSprite: Sprite;
this.iframeSubscriptionList.push(iframeListener.displayBubbleStream.subscribe(() => {
scriptedBubbleSprite = new Sprite(this, this.CurrentPlayer.x + 25, this.CurrentPlayer.y, 'circleSprite-white');
scriptedBubbleSprite.setDisplayOrigin(48, 48); scriptedBubbleSprite.setDisplayOrigin(48, 48);
this.add.existing(scriptedBubbleSprite); this.add.existing(scriptedBubbleSprite);
})); }));
this.iframeSubscriptionList.push(iframeListener.removeBubbleStream.subscribe(()=>{ this.iframeSubscriptionList.push(iframeListener.removeBubbleStream.subscribe(() => {
scriptedBubbleSprite.destroy(); scriptedBubbleSprite.destroy();
})); }));
} }
private getIndexForTileType(tileType: string): number | null {
for (const tileset of this.mapFile.tilesets) {
if (tileset.tiles) {
for (const tilesetTile of tileset.tiles) {
if (tilesetTile.type == tileType) {
return tileset.firstgid + tilesetTile.id
}
}
}
}
return null
}
private getMapDirUrl(): string { private getMapDirUrl(): string {
return this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/')); return this.MapUrlFile.substr(0, this.MapUrlFile.lastIndexOf('/'));
} }
@ -917,8 +959,8 @@ ${escapedMessage}
private onMapExit(exitKey: string) { private onMapExit(exitKey: string) {
if (this.mapTransitioning) return; if (this.mapTransitioning) return;
this.mapTransitioning = true; this.mapTransitioning = true;
const {roomId, hash} = Room.getIdFromIdentifier(exitKey, this.MapUrlFile, this.instance); const { roomId, hash } = Room.getIdFromIdentifier(exitKey, this.MapUrlFile, this.instance);
if (!roomId) throw new Error('Could not find the room from its exit key: '+exitKey); if (!roomId) throw new Error('Could not find the room from its exit key: ' + exitKey);
urlManager.pushStartLayerNameToUrl(hash); urlManager.pushStartLayerNameToUrl(hash);
if (roomId !== this.scene.key) { if (roomId !== this.scene.key) {
if (this.scene.get(roomId) === null) { if (this.scene.get(roomId) === null) {
@ -958,7 +1000,7 @@ ${escapedMessage}
this.pinchManager?.destroy(); this.pinchManager?.destroy();
this.emoteManager.destroy(); this.emoteManager.destroy();
for(const iframeEvents of this.iframeSubscriptionList){ for (const iframeEvents of this.iframeSubscriptionList) {
iframeEvents.unsubscribe(); iframeEvents.unsubscribe();
} }
} }
@ -978,7 +1020,7 @@ ${escapedMessage}
private switchLayoutMode(): void { private switchLayoutMode(): void {
//if discussion is activated, this layout cannot be activated //if discussion is activated, this layout cannot be activated
if(mediaManager.activatedDiscussion){ if (mediaManager.activatedDiscussion) {
return; return;
} }
const mode = layoutManager.getLayoutMode(); const mode = layoutManager.getLayoutMode();
@ -1019,24 +1061,24 @@ ${escapedMessage}
private initPositionFromLayerName(layerName: string) { private initPositionFromLayerName(layerName: string) {
for (const layer of this.gameMap.layersIterator) { for (const layer of this.gameMap.layersIterator) {
if ((layerName === layer.name || layer.name.endsWith('/'+layerName)) && layer.type === 'tilelayer' && (layerName === defaultStartLayerName || this.isStartLayer(layer))) { if ((layerName === layer.name || layer.name.endsWith('/' + layerName)) && layer.type === 'tilelayer' && (layerName === defaultStartLayerName || this.isStartLayer(layer))) {
const startPosition = this.startUser(layer); const startPosition = this.startUser(layer);
this.startX = startPosition.x + this.mapFile.tilewidth/2; this.startX = startPosition.x + this.mapFile.tilewidth / 2;
this.startY = startPosition.y + this.mapFile.tileheight/2; this.startY = startPosition.y + this.mapFile.tileheight / 2;
} }
} }
} }
private getExitUrl(layer: ITiledMapLayer): string|undefined { private getExitUrl(layer: ITiledMapLayer): string | undefined {
return this.getProperty(layer, "exitUrl") as string|undefined; return this.getProperty(layer, "exitUrl") as string | undefined;
} }
/** /**
* @deprecated the map property exitSceneUrl is deprecated * @deprecated the map property exitSceneUrl is deprecated
*/ */
private getExitSceneUrl(layer: ITiledMapLayer): string|undefined { private getExitSceneUrl(layer: ITiledMapLayer): string | undefined {
return this.getProperty(layer, "exitSceneUrl") as string|undefined; return this.getProperty(layer, "exitSceneUrl") as string | undefined;
} }
private isStartLayer(layer: ITiledMapLayer): boolean { private isStartLayer(layer: ITiledMapLayer): boolean {
@ -1047,8 +1089,8 @@ ${escapedMessage}
return (this.getProperties(map, "script") as string[]).map((script) => (new URL(script, this.MapUrlFile)).toString()); return (this.getProperties(map, "script") as string[]).map((script) => (new URL(script, this.MapUrlFile)).toString());
} }
private getProperty(layer: ITiledMapLayer|ITiledMap, name: string): string|boolean|number|undefined { private getProperty(layer: ITiledMapLayer | ITiledMap, name: string): string | boolean | number | undefined {
const properties: ITiledMapLayerProperty[]|undefined = layer.properties; const properties: ITiledMapLayerProperty[] | undefined = layer.properties;
if (!properties) { if (!properties) {
return undefined; return undefined;
} }
@ -1059,8 +1101,8 @@ ${escapedMessage}
return obj.value; return obj.value;
} }
private getProperties(layer: ITiledMapLayer|ITiledMap, name: string): (string|number|boolean|undefined)[] { private getProperties(layer: ITiledMapLayer | ITiledMap, name: string): (string | number | boolean | undefined)[] {
const properties: ITiledMapLayerProperty[]|undefined = layer.properties; const properties: ITiledMapLayerProperty[] | undefined = layer.properties;
if (!properties) { if (!properties) {
return []; return [];
} }
@ -1069,29 +1111,29 @@ ${escapedMessage}
//todo: push that into the gameManager //todo: push that into the gameManager
private loadNextGame(exitSceneIdentifier: string): void { private loadNextGame(exitSceneIdentifier: string): void {
const {roomId, hash} = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance); const { roomId, hash } = Room.getIdFromIdentifier(exitSceneIdentifier, this.MapUrlFile, this.instance);
const room = new Room(roomId); const room = new Room(roomId);
gameManager.loadMap(room, this.scene).catch(() => {}); gameManager.loadMap(room, this.scene).catch(() => {});
} }
private startUser(layer: ITiledMapTileLayer): PositionInterface { private startUser(layer: ITiledMapTileLayer): PositionInterface {
const tiles = layer.data; const tiles = layer.data;
if (typeof(tiles) === 'string') { if (typeof (tiles) === 'string') {
throw new Error('The content of a JSON map must be filled as a JSON array, not as a string'); throw new Error('The content of a JSON map must be filled as a JSON array, not as a string');
} }
const possibleStartPositions : PositionInterface[] = []; const possibleStartPositions: PositionInterface[] = [];
tiles.forEach((objectKey : number, key: number) => { tiles.forEach((objectKey: number, key: number) => {
if(objectKey === 0){ if (objectKey === 0) {
return; return;
} }
const y = Math.floor(key / layer.width); const y = Math.floor(key / layer.width);
const x = key % layer.width; const x = key % layer.width;
possibleStartPositions.push({x: x * this.mapFile.tilewidth, y: y * this.mapFile.tilewidth}); possibleStartPositions.push({ x: x * this.mapFile.tilewidth, y: y * this.mapFile.tilewidth });
}); });
// Get a value at random amongst allowed values // Get a value at random amongst allowed values
if (possibleStartPositions.length === 0) { if (possibleStartPositions.length === 0) {
console.warn('The start layer "'+layer.name+'" for this map is empty.'); console.warn('The start layer "' + layer.name + '" for this map is empty.');
return { return {
x: 0, x: 0,
y: 0 y: 0
@ -1103,12 +1145,12 @@ ${escapedMessage}
//todo: in a dedicated class/function? //todo: in a dedicated class/function?
initCamera() { initCamera() {
this.cameras.main.setBounds(0,0, this.Map.widthInPixels, this.Map.heightInPixels); this.cameras.main.setBounds(0, 0, this.Map.widthInPixels, this.Map.heightInPixels);
this.cameras.main.startFollow(this.CurrentPlayer, true); this.cameras.main.startFollow(this.CurrentPlayer, true);
this.updateCameraOffset(); this.updateCameraOffset();
} }
addLayer(Layer : Phaser.Tilemaps.TilemapLayer){ addLayer(Layer: Phaser.Tilemaps.TilemapLayer) {
this.Layers.push(Layer); this.Layers.push(Layer);
} }
@ -1118,7 +1160,7 @@ ${escapedMessage}
this.physics.add.collider(this.CurrentPlayer, Layer, (object1: GameObject, object2: GameObject) => { this.physics.add.collider(this.CurrentPlayer, Layer, (object1: GameObject, object2: GameObject) => {
//this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name) //this.CurrentPlayer.say("Collision with layer : "+ (object2 as Tile).layer.name)
}); });
Layer.setCollisionByProperty({collides: true}); Layer.setCollisionByProperty({ collides: true });
if (DEBUG_MODE) { if (DEBUG_MODE) {
//debug code to see the collision hitbox of the object in the top layer //debug code to see the collision hitbox of the object in the top layer
Layer.renderDebug(this.add.graphics(), { Layer.renderDebug(this.add.graphics(), {
@ -1130,7 +1172,7 @@ ${escapedMessage}
}); });
} }
createCurrentPlayer(){ createCurrentPlayer() {
//TODO create animation moving between exit and start //TODO create animation moving between exit and start
const texturesPromise = lazyLoadPlayerCharacterTextures(this.load, this.characterLayers); const texturesPromise = lazyLoadPlayerCharacterTextures(this.load, this.characterLayers);
try { try {
@ -1152,8 +1194,8 @@ ${escapedMessage}
this.CurrentPlayer.on(requestEmoteEventName, (emoteKey: string) => { this.CurrentPlayer.on(requestEmoteEventName, (emoteKey: string) => {
this.connection?.emitEmoteEvent(emoteKey); this.connection?.emitEmoteEvent(emoteKey);
}) })
}catch (err){ } catch (err) {
if(err instanceof TextureError) { if (err instanceof TextureError) {
gameManager.leaveGame(this, SelectCharacterSceneName, new SelectCharacterScene()); gameManager.leaveGame(this, SelectCharacterSceneName, new SelectCharacterScene());
} }
throw err; throw err;
@ -1214,7 +1256,7 @@ ${escapedMessage}
} }
let shortestDistance: number = Infinity; let shortestDistance: number = Infinity;
let selectedItem: ActionableItem|null = null; let selectedItem: ActionableItem | null = null;
for (const item of this.actionableItems.values()) { for (const item of this.actionableItems.values()) {
const distance = item.actionableDistance(x, y); const distance = item.actionableDistance(x, y);
if (distance !== null && distance < shortestDistance) { if (distance !== null && distance < shortestDistance) {
@ -1248,7 +1290,7 @@ ${escapedMessage}
* @param time * @param time
* @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate. * @param delta The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
*/ */
update(time: number, delta: number) : void { update(time: number, delta: number): void {
this.dirty = false; this.dirty = false;
mediaManager.updateScene(); mediaManager.updateScene();
this.currentTick = time; this.currentTick = time;
@ -1308,8 +1350,8 @@ ${escapedMessage}
const currentPlayerId = this.connection?.getUserId(); const currentPlayerId = this.connection?.getUserId();
this.removeAllRemotePlayers(); this.removeAllRemotePlayers();
// load map // load map
usersPosition.forEach((userPosition : MessageUserPositionInterface) => { usersPosition.forEach((userPosition: MessageUserPositionInterface) => {
if(userPosition.userId === currentPlayerId){ if (userPosition.userId === currentPlayerId) {
return; return;
} }
this.addPlayer(userPosition); this.addPlayer(userPosition);
@ -1319,16 +1361,16 @@ ${escapedMessage}
/** /**
* Called by the connexion when a new player arrives on a map * Called by the connexion when a new player arrives on a map
*/ */
public addPlayer(addPlayerData : AddPlayerInterface) : void { public addPlayer(addPlayerData: AddPlayerInterface): void {
this.pendingEvents.enqueue({ this.pendingEvents.enqueue({
type: "AddPlayerEvent", type: "AddPlayerEvent",
event: addPlayerData event: addPlayerData
}); });
} }
private doAddPlayer(addPlayerData : AddPlayerInterface): void { private doAddPlayer(addPlayerData: AddPlayerInterface): void {
//check if exist player, if exist, move position //check if exist player, if exist, move position
if(this.MapPlayersByKey.has(addPlayerData.userId)){ if (this.MapPlayersByKey.has(addPlayerData.userId)) {
this.updatePlayerPosition({ this.updatePlayerPosition({
userId: addPlayerData.userId, userId: addPlayerData.userId,
position: addPlayerData.position position: addPlayerData.position
@ -1389,10 +1431,10 @@ ${escapedMessage}
} }
private doUpdatePlayerPosition(message: MessageUserMovedInterface): void { private doUpdatePlayerPosition(message: MessageUserMovedInterface): void {
const player : RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId); const player: RemotePlayer | undefined = this.MapPlayersByKey.get(message.userId);
if (player === undefined) { if (player === undefined) {
//throw new Error('Cannot find player with ID "' + message.userId +'"'); //throw new Error('Cannot find player with ID "' + message.userId +'"');
console.error('Cannot update position of player with ID "' + message.userId +'": player not found'); console.error('Cannot update position of player with ID "' + message.userId + '": player not found');
return; return;
} }
@ -1436,7 +1478,7 @@ ${escapedMessage}
doDeleteGroup(groupId: number): void { doDeleteGroup(groupId: number): void {
const group = this.groups.get(groupId); const group = this.groups.get(groupId);
if(!group){ if (!group) {
return; return;
} }
group.destroy(); group.destroy();
@ -1465,7 +1507,7 @@ ${escapedMessage}
bottom: camera.scrollY + camera.height, bottom: camera.scrollY + camera.height,
}); });
} }
private getObjectLayerData(objectName : string) : ITiledMapObject| undefined{ private getObjectLayerData(objectName: string): ITiledMapObject | undefined {
for (const layer of this.mapFile.layers) { for (const layer of this.mapFile.layers) {
if (layer.type === 'objectgroup' && layer.name === 'floorLayer') { if (layer.type === 'objectgroup' && layer.name === 'floorLayer') {
for (const object of layer.objects) { for (const object of layer.objects) {
@ -1508,16 +1550,16 @@ ${escapedMessage}
public startJitsi(roomName: string, jwt?: string): void { public startJitsi(roomName: string, jwt?: string): void {
const allProps = this.gameMap.getCurrentProperties(); const allProps = this.gameMap.getCurrentProperties();
const jitsiConfig = this.safeParseJSONstring(allProps.get("jitsiConfig") as string|undefined, 'jitsiConfig'); const jitsiConfig = this.safeParseJSONstring(allProps.get("jitsiConfig") as string | undefined, 'jitsiConfig');
const jitsiInterfaceConfig = this.safeParseJSONstring(allProps.get("jitsiInterfaceConfig") as string|undefined, 'jitsiInterfaceConfig'); const jitsiInterfaceConfig = this.safeParseJSONstring(allProps.get("jitsiInterfaceConfig") as string | undefined, 'jitsiInterfaceConfig');
const jitsiUrl = allProps.get("jitsiUrl") as string|undefined; const jitsiUrl = allProps.get("jitsiUrl") as string | undefined;
jitsiFactory.start(roomName, this.playerName, jwt, jitsiConfig, jitsiInterfaceConfig, jitsiUrl); jitsiFactory.start(roomName, this.playerName, jwt, jitsiConfig, jitsiInterfaceConfig, jitsiUrl);
this.connection?.setSilent(true); this.connection?.setSilent(true);
mediaManager.hideGameOverlay(); mediaManager.hideGameOverlay();
//permit to stop jitsi when user close iframe //permit to stop jitsi when user close iframe
mediaManager.addTriggerCloseJitsiFrameButton('close-jisi',() => { mediaManager.addTriggerCloseJitsiFrameButton('close-jisi', () => {
this.stopJitsi(); this.stopJitsi();
}); });
} }
@ -1531,7 +1573,7 @@ ${escapedMessage}
} }
//todo: put this into an 'orchestrator' scene (EntryScene?) //todo: put this into an 'orchestrator' scene (EntryScene?)
private bannedUser(){ private bannedUser() {
this.cleanupClosingScene(); this.cleanupClosingScene();
this.userInputManager.disableControls(); this.userInputManager.disableControls();
this.scene.start(ErrorSceneName, { this.scene.start(ErrorSceneName, {

View File

@ -34,7 +34,7 @@ export interface ITiledMap {
export interface ITiledMapLayerProperty { export interface ITiledMapLayerProperty {
name: string; name: string;
type: string; type: string;
value: string|boolean|number|undefined; value: string | boolean | number | undefined;
} }
/*export interface ITiledMapLayerBooleanProperty { /*export interface ITiledMapLayerBooleanProperty {
@ -63,7 +63,7 @@ export interface ITiledMapGroupLayer {
export interface ITiledMapTileLayer { export interface ITiledMapTileLayer {
id?: number, id?: number,
data: number[]|string; data: number[] | string;
height: number; height: number;
name: string; name: string;
opacity: number; opacity: number;
@ -114,7 +114,7 @@ export interface ITiledMapObject {
gid: number; gid: number;
height: number; height: number;
name: string; name: string;
properties: {[key: string]: string}; properties: { [key: string]: string };
rotation: number; rotation: number;
type: string; type: string;
visible: boolean; visible: boolean;
@ -130,12 +130,12 @@ export interface ITiledMapObject {
/** /**
* Polygon points * Polygon points
*/ */
polygon: {x: number, y: number}[]; polygon: { x: number, y: number }[];
/** /**
* Polyline points * Polyline points
*/ */
polyline: {x: number, y: number}[]; polyline: { x: number, y: number }[];
text?: ITiledText text?: ITiledText
} }
@ -149,7 +149,7 @@ export interface ITiledText {
underline?: boolean, underline?: boolean,
italic?: boolean, italic?: boolean,
strikeout?: boolean, strikeout?: boolean,
halign?: "center"|"right"|"justify"|"left" halign?: "center" | "right" | "justify" | "left"
} }
export interface ITiledTileSet { export interface ITiledTileSet {
@ -160,14 +160,14 @@ export interface ITiledTileSet {
imagewidth: number; imagewidth: number;
margin: number; margin: number;
name: string; name: string;
properties: {[key: string]: string}; properties: { [key: string]: string };
spacing: number; spacing: number;
tilecount: number; tilecount: number;
tileheight: number; tileheight: number;
tilewidth: number; tilewidth: number;
transparentcolor: string; transparentcolor: string;
terrains: ITiledMapTerrain[]; terrains: ITiledMapTerrain[];
tiles: {[key: string]: { terrain: number[] }}; tiles: Array<ITile>;
/** /**
* Refers to external tileset file (should be JSON) * Refers to external tileset file (should be JSON)
@ -175,6 +175,11 @@ export interface ITiledTileSet {
source: string; source: string;
} }
export interface ITile {
id: number,
type?: string
}
export interface ITiledMapTerrain { export interface ITiledMapTerrain {
name: string; name: string;
tile: number; tile: number;

View File

@ -0,0 +1,21 @@
import type {ITiledMap, ITiledMapLayer} from "./ITiledMap";
/**
* Flatten the grouped layers
*/
export function flattenGroupLayersMap(map: ITiledMap) {
const flatLayers: ITiledMapLayer[] = [];
flattenGroupLayers(map.layers, '', flatLayers);
return flatLayers;
}
function flattenGroupLayers(layers : ITiledMapLayer[], prefix : string, flatLayers: ITiledMapLayer[]) {
for (const layer of layers) {
if (layer.type === 'group') {
flattenGroupLayers(layer.layers, prefix + layer.name + '/', flatLayers);
} else {
layer.name = prefix+layer.name
flatLayers.push(layer);
}
}
}

View File

@ -9,10 +9,11 @@ import type { ClosePopupEvent } from "./Api/Events/ClosePopupEvent";
import type { OpenTabEvent } from "./Api/Events/OpenTabEvent"; import type { OpenTabEvent } from "./Api/Events/OpenTabEvent";
import type { GoToPageEvent } from "./Api/Events/GoToPageEvent"; import type { GoToPageEvent } from "./Api/Events/GoToPageEvent";
import type { OpenCoWebSiteEvent } from "./Api/Events/OpenCoWebSiteEvent"; import type { OpenCoWebSiteEvent } from "./Api/Events/OpenCoWebSiteEvent";
import type {PlaySoundEvent} from "./Api/Events/PlaySoundEvent"; import type { PlaySoundEvent } from "./Api/Events/PlaySoundEvent";
import type {StopSoundEvent} from "./Api/Events/StopSoundEvent"; import type {StopSoundEvent } from "./Api/Events/StopSoundEvent";
import type {LoadSoundEvent} from "./Api/Events/LoadSoundEvent"; import type { LoadSoundEvent } from "./Api/Events/LoadSoundEvent";
import SoundConfig = Phaser.Types.Sound.SoundConfig; import SoundConfig = Phaser.Types.Sound.SoundConfig;
import type { LoadPageEvent } from './Api/Events/LoadPageEvent';
interface WorkAdventureApi { interface WorkAdventureApi {
sendChatMessage(message: string, author: string): void; sendChatMessage(message: string, author: string): void;
@ -22,6 +23,7 @@ interface WorkAdventureApi {
openPopup(targetObject: string, message: string, buttons: ButtonDescriptor[]): Popup; openPopup(targetObject: string, message: string, buttons: ButtonDescriptor[]): Popup;
openTab(url : string): void; openTab(url : string): void;
goToPage(url : string): void; goToPage(url : string): void;
loadPage(url : string): void;
openCoWebSite(url : string): void; openCoWebSite(url : string): void;
closeCoWebSite(): void; closeCoWebSite(): void;
disablePlayerControls(): void; disablePlayerControls(): void;
@ -166,6 +168,15 @@ window.WA = {
}, '*'); }, '*');
}, },
loadPage(url : string) : void{
window.parent.postMessage({
"type" : 'loadPage',
"data" : {
url
} as LoadPageEvent
},'*');
},
openCoWebSite(url : string) : void{ openCoWebSite(url : string) : void{
window.parent.postMessage({ window.parent.postMessage({
"type" : 'openCoWebSite', "type" : 'openCoWebSite',

View File

@ -0,0 +1,230 @@
{ "compressionlevel":-1,
"height":10,
"infinite":false,
"layers":[
{
"data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"height":10,
"id":1,
"name":"start",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":10,
"x":0,
"y":0
},
{
"data":[46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 33, 34, 34, 34, 34, 34, 34, 35, 46, 46, 41, 42, 42, 42, 42, 42, 42, 43, 46, 46, 41, 42, 42, 42, 42, 42, 42, 43, 46, 46, 41, 42, 42, 42, 42, 42, 42, 43, 46, 46, 41, 42, 42, 42, 42, 42, 42, 43, 46, 46, 41, 42, 42, 42, 42, 42, 42, 43, 46, 46, 41, 42, 42, 42, 42, 42, 42, 43, 46, 46, 49, 50, 50, 50, 50, 50, 50, 51, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46],
"height":10,
"id":2,
"name":"bottom",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":10,
"x":0,
"y":0
},
{
"data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52, 52, 52, 0, 0, 0, 0, 0, 0, 0, 52, 52, 52, 0, 0, 0, 0, 0, 0, 0, 52, 52, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"height":10,
"id":4,
"name":"metadata",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":10,
"x":0,
"y":0
},
{
"draworder":"topdown",
"id":5,
"name":"floorLayer",
"objects":[],
"opacity":1,
"type":"objectgroup",
"visible":true,
"x":0,
"y":0
},
{
"data":[1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0, 11, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19],
"height":10,
"id":3,
"name":"wall",
"opacity":1,
"type":"tilelayer",
"visible":true,
"width":10,
"x":0,
"y":0
}],
"nextlayerid":6,
"nextobjectid":1,
"orientation":"orthogonal",
"properties":[
{
"name":"script",
"type":"string",
"value":"script.js"
}],
"renderorder":"right-down",
"tiledversion":"1.4.3",
"tileheight":32,
"tilesets":[
{
"columns":8,
"firstgid":1,
"image":"tileset_dungeon.png",
"imageheight":256,
"imagewidth":256,
"margin":0,
"name":"TDungeon",
"spacing":0,
"tilecount":64,
"tileheight":32,
"tiles":[
{
"id":0,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":1,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":2,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":3,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":4,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":8,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":9,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":10,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":11,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":12,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":16,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":17,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":18,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":19,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
},
{
"id":20,
"properties":[
{
"name":"collides",
"type":"bool",
"value":true
}]
}],
"tilewidth":32
}],
"tilewidth":32,
"type":"map",
"version":1.4,
"width":10
}

View File

@ -0,0 +1,9 @@
/*WA.getMapUrl().then((map) => {console.log('mapUrl : ', map)});
WA.getUuid().then((uuid) => {console.log('Uuid : ',uuid)});
WA.getRoomId().then((roomId) => console.log('roomID : ',roomId));*/
//WA.onPlayerMove(console.log);
WA.setProperty('metadata', 'openWebsite', 'https://fr.wikipedia.org/');
WA.getDataLayer().then((data) => {console.log('data 1 : ', data)});

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.5 KiB

27
pusher/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,27 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Pusher",
"type": "node",
"request": "launch",
"runtimeExecutable": "node",
"runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register/transpile-only"
],
"args": [
"server.ts",
"--example",
"hello"
],
"cwd": "${workspaceRoot}",
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": [
"<node_internals>/**",
"node_modules/**"
]
}
]
}