Improve map editor tools and add entity settings

This commit is contained in:
Terncode committed 2026-12-02 19:22:15 +01:00
1 parent 8d4d3f663e
commit 6635e0e84e
26 files changed
+1974 -302

No files matched your search

+8 -1
View File
@@ -1,7 +1,8 @@
import { NgZone } from '@angular/core';
import {
MapInfo, WorldState, PartyMember, PartyFlags, Action, NotificationFlags, Pony, LeaveReason,
SayData, MapState, defaultMapState, Apply, InfoFlags, PonyData, FriendStatusData, WorldMap
SayData, MapState, defaultMapState, Apply, InfoFlags, PonyData, FriendStatusData, WorldMap,
EditorEntityInfo, EditorBehaviorInfo
} from '../common/interfaces';
import { hasFlag, findById } from '../common/utils';
import { setTileAtRegion, findEntityById, createWorldMap, removeRegions, updateMapState } from './worldMap';
@@ -258,6 +259,12 @@ export class ClientActions extends ClientActionsTemplate {
console.log(`ENTITIES:\n${list}`);
}
}
// @Method({ binary: [Bin.Obj, Bin.Obj] })
editorEntityInfo(entities: EditorEntityInfo[], info: EditorBehaviorInfo) {
if (BETA) {
this.game.onEditorEntityInfo.next({ entities, info });
}
}
// @Method({ binary: [Bin.Obj] })
testPositions(data: { frame: number; x: number | undefined; y: number | undefined; moved: boolean; }[]) {
if (DEVELOPMENT) {
+168 -26
View File
@@ -6,7 +6,7 @@ import {
EntityState, Pony, Notification, TileType, Action, IServerActions, WorldState,
TileSets, ChatMessage, PartyInfo, Entity, DrawOptions, Engine, defaultDrawOptions, PonyStateFlags,
DoAction, ChatType, WorldStateFlags, DebugFlags, MessageType, AccountSettings, Matrix4,
FakeEntity, SelectFlags, WorldMap, EntityFlags, houseTiles, isValidTile, GraphicsQuality
FakeEntity, SelectFlags, WorldMap, EntityFlags, houseTiles, isValidTile, GraphicsQuality, EditorTool, EditorPick, EditorEntityInfo, EditorBehaviorInfo
} from '../common/interfaces';
import {
clamp, lengthOfXY, setFlag, hasFlag, boundsIntersect, point, toInt, lerpColor, distanceXY,
@@ -20,7 +20,7 @@ import {
import {
ensureAllVisiblePoniesAreDecoded, invalidatePalettes, updateMap, updateEntities,
getMapHeightAt, updateEntitiesWithNames, updateEntitiesCoverLifted,
pickEntities, updateEntitiesTriggers, getElevation, setElevation, createWorldMap
pickEntities, updateEntitiesTriggers, getElevation, setElevation, createWorldMap, pickAnyEntities
} from './worldMap';
import { updateCamera, centerCameraOn, screenToWorld, createCamera } from '../common/camera';
import { WHITE, BLACK, SHADOW_COLOR, getTileColor, RED, CAVE_LIGHT, CAVE_SHADOW } from '../common/colors';
@@ -30,7 +30,7 @@ import { getEntityTypeName, hammer, broom, createAnEntity, saw, placeableEntitie
import { hasExtendedInfo, setHeadAnimation, createPony } from './pony';
import { PaletteManager } from '../graphics/paletteManager';
import { isWebGL2 } from '../graphics/webgl/webglUtils';
import { drawFullScreenMessage, drawNames, drawChat } from '../graphics/graphicsUtils';
import { drawFullScreenMessage, drawNames, drawChat, drawOutline } from '../graphics/graphicsUtils';
import { Key } from './input/input';
import { version, isMobile } from './data';
import { Game } from './gameLoop';
@@ -56,7 +56,7 @@ import { createEntitiesFromName } from './entityPreview';
import { updateTileSets, initializeTileHeightmaps, getTile } from '../common/tileUtils';
import {
downAction, upAction, turnHeadAction, boopAction, interact, toggleWall, editorMoveEntities,
editorSelectEntities, editorDragEntities
editorDragEntities
} from './playerActions';
import { fontSmallPal, fontSmall, font, fontMono } from '../common/fonts';
import { drawText, drawOutlinedText, measureText } from '../graphics/spriteFont';
@@ -163,20 +163,21 @@ export class PonyTownGame implements Game {
showMinimap = false;
minimap: Minimap | undefined = undefined;
editor = {
tool: '' as EditorTool,
type: 'stoneWall',
brushSize: 1,
tile: -1,
tile: TileType.Grass,
elevation: '',
special: '',
draggingEntities: false,
draggingStart: point(0, 0),
selectingEntities: false,
selectedEntities: [] as Entity[],
customLight: false,
lightColor: 'ffffff',
placing: false,
snapToTile: false,
};
onEditorPick = new Subject<EditorPick>();
onEditorEntityInfo = new Subject<{ entities: EditorEntityInfo[]; info: EditorBehaviorInfo; }>();
incompleteSays: IncompleteSay[] = [];
shadowColor = SHADOW_COLOR;
onChat = new Subject<void>();
@@ -275,6 +276,8 @@ export class PonyTownGame implements Game {
private editorGhost: Entity[] = [];
private editorGhostKey = '';
private editorGhostOffsets: { x: number; y: number; }[] = [];
private editorLastPaint = '';
editorSelectionBox?: { x0: number; y0: number; x1: number; y1: number; additive: boolean; };
placeEntity = 0;
placeTile = 0;
constructor(
@@ -755,6 +758,18 @@ export class PonyTownGame implements Game {
pixelRatioEnabled = !pixelRatioEnabled;
}
private escape() {
if (BETA && this.mod && this.editor.tool) {
this.apply(() => {
if (this.editor.tool === 'select' && this.editor.selectedEntities.length) {
this.editor.selectedEntities = [];
}
else {
this.setEditorTool('');
}
});
return;
}
if (this.socket && !this.onCancel()) {
this.select(undefined);
}
@@ -1012,11 +1027,25 @@ export class PonyTownGame implements Game {
if (this.fullyLoaded) {
if (BETA && this.editor.draggingEntities) {
editorDragEntities(this, hover, input.isPressed(Key.MOUSE_BUTTON2));
editorDragEntities(this, hover, input.isPressed(Key.MOUSE_BUTTON1) || input.isPressed(Key.MOUSE_BUTTON2));
}
if (BETA) {
this.updateEditorGhost(hover);
if (this.isEditorPainting && input.isPressed(Key.MOUSE_BUTTON1) && !input.wasPressed(Key.MOUSE_BUTTON1)) {
this.paintEditorTiles(hover, false);
}
if (this.editorSelectionBox) {
if (input.isPressed(Key.MOUSE_BUTTON1)) {
this.editorSelectionBox.x1 = hover.x;
this.editorSelectionBox.y1 = hover.y;
}
else {
this.finishEditorSelectionBox();
}
}
}
if (hasFlag(this.map.flags, MapFlags.EditableEntities)) {
@@ -1046,13 +1075,16 @@ export class PonyTownGame implements Game {
const editableMap = hasFlag(this.map.flags, MapFlags.EditableEntities);
const holdingTool = holdingRemoveTool || holdingPlaceTool;
if (BETA && this.editor.selectingEntities) {
editorSelectEntities(this, hover, shift);
if (BETA && this.isEditorSelecting) {
this.editorSelectPress(hover, shift);
}
else if (BETA && this.isEditorPlacing) {
const { x, y } = this.getEditorPlacePosition(hover);
server.editorAction({ type: 'place', entity: this.editor.type, x, y });
}
else if (BETA && this.isEditorPainting) {
this.paintEditorTiles(hover, true);
}
else if (pickedEntity && (!holdingTool || !editableMap || hasFlag(pickedEntity.flags, EntityFlags.IgnoreTool))) {
if (pickedEntity.type === PONY_TYPE) {
this.select(pickedEntity as Pony);
@@ -1061,19 +1093,6 @@ export class PonyTownGame implements Game {
server.interact(pickedEntity.id);
}
}
else if (BETA && this.editor.tile !== -1) {
if (this.editor.brushSize > 1) {
const x = Math.floor((hover.x - (this.editor.brushSize / 2)));
const y = Math.floor((hover.y - (this.editor.brushSize / 2)));
server.editorAction({ type: 'tile', x, y, tile: this.editor.tile, size: this.editor.brushSize });
}
else {
const x = hover.x | 0;
const y = hover.y | 0;
const type = this.editor.tile === getTile(this.map, hover.x, hover.y) ? TileType.Dirt : this.editor.tile;
server.changeTile(x, y, type);
}
}
else if (player.hold === changeTileTool.type && hasFlag(this.map.flags, MapFlags.EditableTiles)) {
const x = hover.x | 0;
const y = hover.y | 0;
@@ -1111,9 +1130,17 @@ export class PonyTownGame implements Game {
if (BETA && input.wasPressed(Key.MOUSE_BUTTON2)) {
if (this.isEditorPlacing) {
this.editor.placing = false;
const entity = pickAnyEntities(this.map, hover).find(e => e.type !== PONY_TYPE);
if (entity) {
this.apply(() => this.onEditorPick.next({ entityType: entity.type }));
}
}
else if (this.editor.selectingEntities) {
else if (this.isEditorPainting) {
const tile = getTile(this.map, hover.x, hover.y);
this.apply(() => this.onEditorPick.next({ tile }));
}
else if (this.isEditorSelecting) {
editorMoveEntities(this, hover);
}
else if (this.mod) {
@@ -1593,6 +1620,26 @@ export class PonyTownGame implements Game {
}
}
if (BETA && this.editorSelectionBox) {
const box = this.editorSelectionBox;
const x0 = toScreenX(Math.min(box.x0, box.x1)) - this.camera.x;
const y0 = toScreenY(Math.min(box.y0, box.y1)) - this.camera.actualY;
const x1 = toScreenX(Math.max(box.x0, box.x1)) - this.camera.x;
const y1 = toScreenY(Math.max(box.y0, box.y1)) - this.camera.actualY;
paletteBatch.drawRect(makeTransparent(WHITE, 0.12), x0, y0, x1 - x0, y1 - y0);
drawOutline(paletteBatch, makeTransparent(WHITE, 0.9), x0, y0, x1 - x0, y1 - y0);
}
if (BETA && this.isEditorPainting && this.hover.x >= 0 && !isOutsideMap(this.hover.x, this.hover.y, this.map)) {
const brush = this.getEditorBrushRect(this.hover);
const screenX = toScreenX(brush.x) - this.camera.x;
const screenY = toScreenY(brush.y) - this.camera.actualY;
const w = brush.w * tileWidth;
const h = brush.h * tileHeight;
paletteBatch.drawRect(makeTransparent(WHITE, 0.15), screenX, screenY, w, h);
drawOutline(paletteBatch, makeTransparent(WHITE, 0.8), screenX, screenY, w, h);
}
if (this.showWallPlaceholder) {
const x = this.hover.x | 0;
const y = this.hover.y | 0;
@@ -1824,7 +1871,102 @@ export class PonyTownGame implements Game {
}
}
get isEditorPlacing() {
return this.mod && this.editor.placing && !this.editor.selectingEntities && this.editor.tile === -1;
return this.mod && this.editor.tool === 'place';
}
get isEditorPainting() {
return this.mod && this.editor.tool === 'tile';
}
get isEditorSelecting() {
return this.mod && this.editor.tool === 'select';
}
setEditorTool(tool: EditorTool) {
this.editor.tool = tool;
this.editorLastPaint = '';
this.editorSelectionBox = undefined;
if (tool !== 'select') {
this.editor.selectedEntities.length = 0;
this.editor.draggingEntities = false;
}
}
selectEditorEntities(entities: Entity[], additive = false) {
const selected = additive ? this.editor.selectedEntities.slice() : [];
for (const entity of entities) {
if (entity.type !== PONY_TYPE && selected.indexOf(entity) === -1) {
selected.push(entity);
}
}
this.editor.selectedEntities = selected;
}
private editorSelectPress(hover: { x: number; y: number; }, shift: boolean) {
const picked = pickAnyEntities(this.map, hover).filter(e => e.type !== PONY_TYPE);
const selected = this.editor.selectedEntities;
const entity = picked.find(e => selected.indexOf(e) !== -1) || picked[0];
this.apply(() => {
if (!entity) {
this.editorSelectionBox = { x0: hover.x, y0: hover.y, x1: hover.x, y1: hover.y, additive: shift };
if (!shift) {
this.editor.selectedEntities = [];
}
}
else if (shift) {
const index = selected.indexOf(entity);
if (index === -1) {
this.editor.selectedEntities = [...selected, entity];
}
else {
this.editor.selectedEntities = selected.filter(e => e !== entity);
}
}
else {
if (selected.indexOf(entity) === -1) {
this.editor.selectedEntities = [entity];
}
editorMoveEntities(this, hover);
}
});
}
private finishEditorSelectionBox() {
const box = this.editorSelectionBox!;
this.editorSelectionBox = undefined;
const minX = Math.min(box.x0, box.x1);
const maxX = Math.max(box.x0, box.x1);
const minY = Math.min(box.y0, box.y1);
const maxY = Math.max(box.y0, box.y1);
if ((maxX - minX) < 0.1 && (maxY - minY) < 0.1) {
return;
}
const entities = this.map.entities.filter(e => e.x >= minX && e.x <= maxX && e.y >= minY && e.y <= maxY);
this.apply(() => this.selectEditorEntities(entities, box.additive));
}
getEditorBrushRect(hover: { x: number; y: number; }) {
const size = this.editor.brushSize;
const x = Math.floor(hover.x - (size - 1) / 2);
const y = Math.floor(hover.y - (size - 1) / 2);
return { x, y, w: size, h: size };
}
private paintEditorTiles(hover: { x: number; y: number; }, force: boolean) {
if (hover.x < 0 || isOutsideMap(hover.x, hover.y, this.map)) {
return;
}
const { x, y, w } = this.getEditorBrushRect(hover);
const key = `${x}:${y}:${w}:${this.editor.tile}`;
if (force || key !== this.editorLastPaint) {
this.editorLastPaint = key;
const tile = this.editor.tile;
this.send(server => server.editorAction({ type: 'tile', x, y, tile, size: w }));
}
}
getEditorPlacePosition(hover: { x: number; y: number; }) {
if (this.editor.snapToTile) {
+2 -20
View File
@@ -1,4 +1,4 @@
import { isCommand, processCommand, hasFlag, includes, point } from '../common/utils';
import { isCommand, processCommand, hasFlag, point } from '../common/utils';
import { canPonyLie, canPonyFlyUp, canPonyStand, canPonySit, doBoopPonyAction } from './pony';
import { PonyTownGame } from './game';
import {
@@ -8,7 +8,7 @@ import {
import { EntityState, Action, Pony, ChatType, EntityFlags, Point, TileType } from '../common/interfaces';
import { FLY_DELAY } from '../common/constants';
import { randomString } from '../common/stringUtils';
import { pickEntitiesByRect, pickAnyEntities } from './worldMap';
import { pickEntitiesByRect } from './worldMap';
import { centerPoint } from '../common/rect';
import { pointToWorld, roundPositionX, roundPositionY } from '../common/positionUtils';
import { hammer, shovel } from '../common/entities';
@@ -216,24 +216,6 @@ export function toggleWall(game: PonyTownGame, hover: Point) {
}
}
export function editorSelectEntities(game: PonyTownGame, hover: Point, shift: boolean) {
game.apply(() => {
const entities = pickAnyEntities(game.map, hover);
if (shift) {
const entity = entities.filter(e => !includes(game.editor.selectedEntities, e))[0];
if (entity) {
game.editor.selectedEntities.push(entity);
}
}
else {
const index = entities.findIndex(e => includes(game.editor.selectedEntities, e));
const entity = entities[(index + 1) % entities.length];
game.editor.selectedEntities = entity ? [entity] : [];
}
});
}
export function editorDragEntities(game: PonyTownGame, hover: Point, buttonPressed: boolean) {
if (buttonPressed) {
const dx = hover.x - game.editor.draggingStart.x;
+66
View File
@@ -0,0 +1,66 @@
import { TileType, defaultDrawOptions } from '../common/interfaces';
import { Season, MapType } from '../common/commonInterfaces';
import { REGION_SIZE, tileWidth, tileHeight } from '../common/constants';
import { createRegion, setRegionTile } from '../common/region';
import { createTileSets, updateTileIndices, drawTiles } from '../common/tileUtils';
import { mockPaletteManager } from '../common/ponyInfo';
import { drawCanvas } from '../graphics/contextSpriteBatch';
import { paletteSpriteSheet } from '../generated/sprites';
const PATCH_START = 2;
const PATCH_SIZE = 3;
const VIEW_START = 1;
const VIEW_SIZE = 5;
export const TILE_PREVIEW_WIDTH = VIEW_SIZE * tileWidth;
export const TILE_PREVIEW_HEIGHT = VIEW_SIZE * tileHeight;
const previewCache = new Map<string, HTMLCanvasElement | null>();
function getBackgroundTile(tile: TileType) {
return tile === TileType.Dirt || tile === TileType.ElevatedDirt ? TileType.Grass : TileType.Dirt;
}
function renderTilePreview(tile: TileType, season: Season, mapType: MapType): HTMLCanvasElement | null {
const region = createRegion(0, 0);
const background = getBackgroundTile(tile);
for (let y = 0; y < REGION_SIZE; y++) {
for (let x = 0; x < REGION_SIZE; x++) {
const inPatch = x >= PATCH_START && x < PATCH_START + PATCH_SIZE && y >= PATCH_START && y < PATCH_START + PATCH_SIZE;
setRegionTile(region, x, y, inPatch ? tile : background);
}
}
const map: any = { width: REGION_SIZE, height: REGION_SIZE, regionsX: 1, regionsY: 1, regions: [region], tileTime: 0 };
updateTileIndices(region, map);
const tileSets = createTileSets(mockPaletteManager, season, mapType);
const camera = {
x: VIEW_START * tileWidth, y: VIEW_START * tileHeight, actualY: VIEW_START * tileHeight,
w: TILE_PREVIEW_WIDTH, h: TILE_PREVIEW_HEIGHT, offset: 0, shift: 0, shiftTarget: 0, shiftRatio: 0,
};
try {
return drawCanvas(TILE_PREVIEW_WIDTH, TILE_PREVIEW_HEIGHT, paletteSpriteSheet, undefined, batch => {
batch.translate(-camera.x, -camera.actualY);
drawTiles(batch, region, camera, map, tileSets, { ...defaultDrawOptions, season });
});
}
catch (e) {
console.warn(`failed to render preview of tile ${tile}`, e);
return null;
}
}
export function getTilePreview(tile: TileType, season: Season, mapType = MapType.None): HTMLCanvasElement | null {
const key = `${tile}:${season}:${mapType}`;
let preview = previewCache.get(key);
if (preview === undefined) {
preview = renderTilePreview(tile, season, mapType);
previewCache.set(key, preview);
}
return preview;
}
+3 -1
View File
@@ -1,7 +1,7 @@
import { Method, SocketClient, Bin, getMethods } from 'ag-sockets/dist/browser';
import {
MapInfo, WorldState, PartyFlags, Action, NotificationFlags, LeaveReason,
SayData, MapState, PonyData, FriendStatusData} from './interfaces';
SayData, MapState, PonyData, FriendStatusData, EditorEntityInfo, EditorBehaviorInfo} from './interfaces';
const BinEntityId = Bin.U32;
const BinEntityPlayerState = Bin.U8;
const BinNotificationId = Bin.U16;
@@ -48,6 +48,8 @@ export class ClientActionsTemplate implements SocketClient {
entityInfo(_id: number, _name: string, _crc: number, _nameBad: boolean) {}
@Method({ binary: [Bin.Obj] })
entityList(_value: { name: string; x: number; y: number; }[]) {}
@Method({ binary: [Bin.Obj, Bin.Obj] })
editorEntityInfo(_entities: EditorEntityInfo[], _info: EditorBehaviorInfo) {}
@Method({ binary: [Bin.Obj] })
testPositions(_data: { frame: number; x: number | undefined; y: number | undefined; moved: boolean; }[]) {}
}
+57 -1
View File
@@ -1121,13 +1121,69 @@ export interface EditorPartyAction {
type: 'party';
}
export interface EditorInspectAction {
type: 'inspect';
entities: number[];
}
export interface EditorUpdateAction {
type: 'update';
id: number;
data: EditorEntityData;
}
export type EditorBehaviorKind = 'interact' | 'trigger' | 'boop' | 'update';
export const editorBehaviorKinds: EditorBehaviorKind[] = ['interact', 'trigger', 'boop', 'update'];
export interface EditorBehavior {
action: string;
args?: any;
}
export interface EditorEntityData {
name?: string;
tag?: string;
editable?: boolean;
layer?: string;
options?: any;
interact?: EditorBehavior | null;
trigger?: EditorBehavior | null;
boop?: EditorBehavior | null;
update?: EditorBehavior | null;
}
export interface EditorEntityInfo {
id: number;
type: string;
data: EditorEntityData;
canInteract: boolean;
canTrigger: boolean;
fixed: EditorBehaviorKind[];
}
export interface EditorBehaviorInfo {
actions: { [K in EditorBehaviorKind]: string[]; };
templates: { [key: string]: any; };
layers: string[];
}
export type EditorTool = '' | 'select' | 'place' | 'tile';
export interface EditorPick {
entityType?: number;
tile?: TileType;
}
export type EditorAction =
EditorPlaceAction |
EditorMoveAction |
EditorRemoveAction |
EditorOtherAction |
EditorTileAction |
EditorPartyAction;
EditorPartyAction |
EditorInspectAction |
EditorUpdateAction;
export const enum SelectFlags {
None = 0,
+4
View File
@@ -17,6 +17,8 @@ import { Account } from './account/account';
import { Character } from './character/character';
import { EditorBox } from './editor-box/editor-box';
import { EntityPicker, EntityPreviewCanvas } from './entity-picker/entity-picker';
import { TilePreviewCanvas } from './editor-box/tile-preview';
import { EntitySettings } from './editor-box/entity-settings';
import { AuthGuard } from '../services/authGuard';
import { RollbarService, rollbarFactory, RollbarErrorHandler } from '../services/rollbarErrorHandler';
@@ -55,6 +57,8 @@ export const routes: Routes = [
EditorBox,
EntityPicker,
EntityPreviewCanvas,
TilePreviewCanvas,
EntitySettings,
],
providers: [
provideZoneChangeDetection(),
+1
View File
@@ -113,6 +113,7 @@ $chat-pad: 5px;
position: fixed;
left: 5px;
top: 5px;
z-index: 3;
}
#settings-box {
@@ -0,0 +1,61 @@
$editor-btn-hover-bg: rgba(255, 255, 255, 0.12);
.editor-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
min-width: 30px;
height: 30px;
padding: 0 7px;
color: #fff;
font-size: 13px;
line-height: 1;
background: transparent;
border: none;
border-radius: 6px;
cursor: pointer;
text-shadow: 0 0 2px #000;
fa-icon {
filter: drop-shadow(0 0 1px #000);
}
&:hover:not(:disabled) {
background: $editor-btn-hover-bg;
}
&:focus-visible {
outline: 2px solid rgba($link-color, 0.8);
outline-offset: -2px;
}
&.active,
&[aria-pressed="true"] {
background: $link-color;
text-shadow: none;
fa-icon {
filter: none;
}
}
&:disabled {
opacity: 0.4;
cursor: default;
}
&.dropdown-toggle::after {
margin-left: 2px;
}
}
.editor-btn-danger:hover:not(:disabled) {
background: rgba($danger, 0.8);
}
.editor-btn-sm {
min-width: 26px;
height: 26px;
padding: 0 5px;
}
+182 -141
View File
@@ -1,153 +1,194 @@
.d-flex
button.game-button.px-2((click)="toggleEditor()")
.d-flex.align-items-start
button.game-button.px-2((click)="toggleEditor()" [class.active]="hasEditor" title="Map editor" aria-label="Map editor")
fa-icon([icon]="editIcon")
.d-flex.align-items-start.ps-2.pt-1(*ngIf="hasEditor")
.dropdown-menu.p-0(*ngIf="hasSelectedEntities" style="display: block; width: 500px; position: absolute; top: 36px; left: 0;")
.px-2
//- name
div
.row.form-group.mb-2
label.col-12.col-form-label
.float-end
button.btn.btn-xs.btn-dark.ms-1((click)="showEntitiesInfo()" title="Show info")
| info
button.btn.btn-xs.btn-danger.ms-1((click)="deleteEntities()" title="Delete entities")
fa-icon([icon]="deleteIcon")
| {{entityName}}
.editor-panel.ms-2(*ngIf="hasEditor")
.editor-toolbar(role="toolbar" aria-label="Map editor")
.editor-tools(role="group" aria-label="Tools")
button.editor-btn(
*ngFor="let t of tools"
type="button"
[class.active]="isTool(t.id)"
[attr.aria-pressed]="isTool(t.id)"
[title]="t.title"
(click)="setTool(t.id)")
fa-icon([icon]="t.icon" [fixedWidth]="true")
span.editor-tool-name {{t.name}}
//- position
div(*ngIf="singleEntity")
.row.form-group.mb-2
label.col-4.col-form-label
| position
label.col-1.col-form-label
| x
.col-3
input.form-control([(ngModel)]="entityX" type="number")
label.col-1.col-form-label
| y
.col-3
input.form-control([(ngModel)]="entityY" type="number")
ng-container(*ngIf="isTool('place')")
.editor-separator
.position-relative
button.editor-btn.editor-current(
type="button" (click)="togglePicker()" [class.active]="showPicker" title="Choose entity")
canvas.editor-current-preview([entityPreview]="editorEntity" [worldState]="game" width="24" height="24")
span.editor-current-name {{editorEntity}}
fa-icon.ms-1([icon]="caretIcon" size="xs")
entity-picker.editor-popup(
*ngIf="showPicker"
[names]="editorEntities"
[selected]="editorEntity"
[worldState]="game"
(selectedChange)="pickEntity($event)"
(close)="showPicker = false")
.editor-recent(*ngIf="recentEntities.length" aria-label="Recent entities")
button.editor-recent-item(
*ngFor="let name of recentEntities"
type="button"
[class.active]="name === editorEntity"
[title]="name"
(click)="pickEntity(name)")
canvas([entityPreview]="name" [worldState]="game" width="24" height="24")
button.editor-btn(
type="button" [class.active]="editor.snapToTile" (click)="toggleSnap()"
[attr.aria-pressed]="editor.snapToTile" title="Snap to tile center")
fa-icon([icon]="snapIcon" [fixedWidth]="true")
button.editor-btn(type="button" (click)="undo()" title="Undo last placed entity (Backspace)")
fa-icon([icon]="undoIcon" [fixedWidth]="true" flip="horizontal")
//- light
div(*ngIf="isLightEntity")
.row.form-group.mb-2
label.col-5.col-form-label
| light color
.col-7
color-picker([(color)]="entityLightColor")
.row.form-group.mb-2
label.col-5.col-form-label
| light scale ({{entityLightScale | number:'0.1-1'}})
.col-7.py-2
slider-bar([(value)]="entityLightScale" [min]="0" [max]="3")
ng-container(*ngIf="isTool('tile')")
.editor-separator
.position-relative
button.editor-btn.editor-current(
type="button" (click)="toggleTiles()" [class.active]="showTiles" title="Choose tile")
canvas.editor-current-tile([tilePreview]="editorTile" [season]="game.season" width="32" height="24")
span.editor-current-name {{editorTileName}}
fa-icon.ms-1([icon]="caretIcon" size="xs")
.editor-popup.editor-tiles(*ngIf="showTiles" role="listbox" aria-label="Tiles")
button.editor-tile(
*ngFor="let t of tileTypes"
type="button"
role="option"
[class.active]="t.type === editorTile"
[attr.aria-selected]="t.type === editorTile"
[title]="t.name"
(click)="pickTile(t.type)")
canvas([tilePreview]="t.type" [season]="game.season" width="80" height="60")
.editor-tile-name {{t.name}}
.editor-brush(role="group" aria-label="Brush size")
button.editor-btn(type="button" (click)="changeBrush(-1)" [disabled]="brushSize <= 1" title="Smaller brush")
fa-icon([icon]="minusIcon" [fixedWidth]="true")
.editor-brush-size(title="Brush size")
.editor-brush-glyph([style.width.px]="4 + brushSize * 2" [style.height.px]="4 + brushSize * 2")
span {{brushSize}}×{{brushSize}}
button.editor-btn(type="button" (click)="changeBrush(1)" [disabled]="brushSize >= 8" title="Bigger brush")
fa-icon([icon]="plusIcon" [fixedWidth]="true")
//- light sprite
div(*ngIf="isLightSpriteEntity")
.row.form-group.mb-2
label.col-5.col-form-label
| light sprite color
.col-7
color-picker([(color)]="entityLightSpriteColor")
.row.form-group.mb-2
label.col-4.col-form-label
| light sprite
label.col-1.col-form-label
| x
.col-3
input.form-control([(ngModel)]="entityLightSpriteX" type="number")
label.col-1.col-form-label
| y
.col-3
input.form-control([(ngModel)]="entityLightSpriteY" type="number")
.editor-entity-group.position-relative
.btn-group
button.btn.btn-sm.btn-default.d-flex.align-items-center(
(click)="togglePicker()" [class.active]="showPicker" title="Pick entity")
canvas.editor-entity-preview.me-1([entityPreview]="editorEntity" [worldState]="game" width="20" height="20")
span.editor-entity-name {{editorEntity}}
button.btn.btn-sm.btn-default(
[btnHighlight]="placing" (click)="togglePlacing()"
title="Place entities with left click (right click to stop)")
fa-icon([icon]="placeIcon" [fixedWidth]="true")
entity-picker.editor-entity-picker(
*ngIf="showPicker"
[names]="editorEntities"
[selected]="editorEntity"
[worldState]="game"
(selectedChange)="pickEntity($event)"
(close)="showPicker = false")
ng-container(*ngIf="isTool('select')")
.editor-separator
span.editor-status {{selectedCount ? selectedCount + ' selected' : 'nothing selected'}}
button.editor-btn(
type="button" (click)="clearSelection()" [disabled]="!hasSelectedEntities" title="Clear selection")
fa-icon([icon]="closeIcon" [fixedWidth]="true")
button.editor-btn.editor-btn-danger(
type="button" (click)="deleteEntities()" [disabled]="!hasSelectedEntities" title="Delete selected (Delete)")
fa-icon([icon]="deleteIcon" [fixedWidth]="true")
.dropdown.ms-1(dropdown)
button.btn.btn-sm.btn-default.dropdown-toggle(dropdownToggle)
fa-icon([icon]="cogIcon")
.dropdown-menu(*dropdownMenu)
a.dropdown-item((click)="clearLocalStorage()")
| Clear local storage
a.dropdown-item((click)="editorClear()" title="Remove all placed entities")
| Clear all entities
a.dropdown-item((click)="listEntities()" title="List all placed entities in console")
| List entities
a.dropdown-item((click)="toggleSnap(); $event.stopPropagation()" title="Place entities in the center of tiles")
fa-icon.me-1([icon]="editor.snapToTile ? checkIcon : emptyIcon" [fixedWidth]="true")
| Snap to tile
a.dropdown-item((click)="saveMap()" title="Save map and its seasonal layers to store folder")
| Save map
div(*ngIf="dev")
h6.dropdown-header Show (numpad 4)
a.dropdown-item(*ngFor="let field of showFields" (click)="toggleShow(field); $event.stopPropagation()")
fa-icon.me-1([icon]="isShow(field) ? checkIcon : emptyIcon" [fixedWidth]="true")
| {{field}}
.editor-separator
.dropdown(dropdown autoClose="outsideClick")
button.editor-btn.dropdown-toggle(dropdownToggle type="button" title="Editor settings")
fa-icon([icon]="cogIcon" [fixedWidth]="true")
.dropdown-menu.editor-settings(*dropdownMenu)
h6.dropdown-header Map
a.dropdown-item((click)="saveMap()" title="Save map and its seasonal layers to store folder")
fa-icon.me-2([icon]="saveIcon" [fixedWidth]="true")
| Save map…
a.dropdown-item.text-warning(*ngIf="dev" (click)="overwriteMap()" title="Dev only: replace src/maps JSON files this map was loaded from")
fa-icon.me-2([icon]="saveIcon" [fixedWidth]="true")
| Overwrite source map
a.dropdown-item((click)="listEntities()" title="List all placed entities in console")
fa-icon.me-2([icon]="emptyIcon" [fixedWidth]="true")
| List placed entities
a.dropdown-item.text-danger((click)="editorClear()" title="Remove all entities placed with the editor")
fa-icon.me-2([icon]="deleteIcon" [fixedWidth]="true")
| Clear placed entities
.dropdown-divider
h6.dropdown-header Lighting
.px-3.pb-2
.d-flex.align-items-center.justify-content-between.mb-1
custom-checkbox.mb-0([(checked)]="editor.customLight") Custom light color
color-picker([(color)]="editor.lightColor" [isDisabled]="!editor.customLight")
label.mt-2.mb-1.small Shadow opacity ({{shadowOpacity}})
slider-bar([(value)]="shadowOpacity" [min]="0" [max]="255")
.dropdown-divider
h6.dropdown-header Renderer
a.dropdown-item(*ngFor="let e of engines" (click)="setEngine(e)")
fa-icon.me-2([icon]="isActiveEngine(e) ? checkIcon : emptyIcon" [fixedWidth]="true")
| {{e.name}}
ng-container(*ngIf="dev")
.dropdown-divider
h6.dropdown-header Show (numpad 4)
a.dropdown-item(*ngFor="let field of showFields" (click)="toggleShow(field)")
fa-icon.me-2([icon]="isShow(field) ? checkIcon : emptyIcon" [fixedWidth]="true")
| {{field}}
.dropdown-divider
a.dropdown-item((click)="clearLocalStorage()")
fa-icon.me-2([icon]="emptyIcon" [fixedWidth]="true")
| Clear local storage
button.btn.btn-sm.btn-default.ms-1(
[btnHighlight]="selectingEntities" (click)="toggleSelecting()" title="Select entities")
fa-icon([icon]="selectIcon")
ng-container(*ngIf="hasElevation")
span.editor-status elevation: {{editorElevation}}
span.editor-status special: {{editorSpecial}}
.dropdown.ms-1(dropdown)
button.btn.btn-sm.btn-default.dropdown-toggle(dropdownToggle)
| tile: {{tiles[editorTile + 1]}}
.dropdown-menu(*dropdownMenu)
a.dropdown-item(*ngFor="let t of tiles; let i = index" (click)="editorTile = i - 1")
| {{t}}
.editor-hint
span(*ngFor="let h of hint") {{h}}
.dropdown.ms-1(dropdown)
button.btn.btn-sm.btn-default.dropdown-toggle(dropdownToggle)
| brush: {{editor.brushSize}}
.dropdown-menu(*dropdownMenu)
a.dropdown-item((click)="editor.brushSize = 1") 1
a.dropdown-item((click)="editor.brushSize = 2") 2
a.dropdown-item((click)="editor.brushSize = 3") 3
a.dropdown-item((click)="editor.brushSize = 4") 4
a.dropdown-item((click)="editor.brushSize = 5") 5
a.dropdown-item((click)="editor.brushSize = 6") 6
.editor-popup.editor-details(*ngIf="isTool('select') && hasSelectedEntities")
.d-flex.align-items-center.mb-2
canvas.editor-current-preview.me-2(
*ngIf="selectedEntityNames.length === 1"
[entityPreview]="selectedEntityNames[0]" [worldState]="game" width="24" height="24")
.flex-grow-1.text-truncate
b(*ngIf="singleEntity") {{entityName}}
ng-container(*ngIf="!singleEntity")
b {{selectedCount}} entities
span.text-muted.ms-1 {{entityName}}
button.editor-btn.editor-btn-sm.ms-1((click)="selectSameType()" title="Select all entities of the same type on the map")
fa-icon([icon]="selectIcon" [fixedWidth]="true")
button.editor-btn.editor-btn-sm.ms-1((click)="showEntitiesInfo()" title="Log entities to console")
fa-icon([icon]="infoIcon" [fixedWidth]="true")
button.editor-btn.editor-btn-sm.editor-btn-danger.ms-1((click)="deleteEntities()" title="Delete selected (Delete)")
fa-icon([icon]="deleteIcon" [fixedWidth]="true")
.dropdown.ms-1(dropdown [autoClose]="false")
button.btn.btn-sm.btn-default.dropdown-toggle(dropdownToggle)
| global
.dropdown-menu(*dropdownMenu style="width: 400px")
button(style="display: block; width: 0; height: 0;")
.px-2
.row.form-group
label.col-5.col-form-label.d-flex.justify-content-between
| light color
custom-checkbox([(checked)]="editor.customLight")
.col-7
color-picker([(color)]="editor.lightColor" [isDisabled]="!editor.customLight")
.row.form-group.mb-0
label.col-5.col-form-label shadow opacity ({{shadowOpacity}})
.col-7.py-2
slider-bar([(value)]="shadowOpacity" [min]="0" [max]="255")
.editor-selection(*ngIf="!singleEntity")
button.editor-selection-item(
*ngFor="let g of selectionGroups"
type="button"
[title]="'Select only ' + g.name"
(click)="selectOnly(g.type)")
canvas([entityPreview]="g.name" [worldState]="game" width="24" height="24")
span {{g.count}}
.dropdown.ms-1(dropdown)
button.btn.btn-sm.btn-default.dropdown-toggle(dropdownToggle)
| engine
.dropdown-menu(*dropdownMenu)
a.dropdown-item(*ngFor="let e of engines" (click)="setEngine(e)" [class.active]="isActiveEngine(e)")
| {{e.name}}
.row.g-2.align-items-center.mb-2(*ngIf="singleEntity")
label.col-3.mb-0 position
.col-auto x
.col
input.form-control.form-control-sm([(ngModel)]="entityX" type="number" step="0.03125" aria-label="x")
.col-auto y
.col
input.form-control.form-control-sm([(ngModel)]="entityY" type="number" step="0.041666" aria-label="y")
.btn.btn-sm.btn-default.disabled.ms-1(*ngIf="hasElevation")
| elevation: {{editorElevation}}
.btn.btn-sm.btn-default.disabled.ms-1(*ngIf="hasElevation")
| special: {{editorSpecial}}
ng-container(*ngIf="isLightEntity")
.row.g-2.align-items-center.mb-2
label.col-5.mb-0 light color
.col-7
color-picker([(color)]="entityLightColor")
.row.g-2.align-items-center.mb-2
label.col-5.mb-0 light scale ({{entityLightScale | number:'0.1-1'}})
.col-7
slider-bar([(value)]="entityLightScale" [min]="0" [max]="3")
ng-container(*ngIf="isLightSpriteEntity")
.row.g-2.align-items-center.mb-2
label.col-5.mb-0 light sprite color
.col-7
color-picker([(color)]="entityLightSpriteColor")
.row.g-2.align-items-center.mb-2
label.col-3.mb-0 light sprite
.col-auto x
.col
input.form-control.form-control-sm([(ngModel)]="entityLightSpriteX" type="number" aria-label="light sprite x")
.col-auto y
.col
input.form-control.form-control-sm([(ngModel)]="entityLightSpriteY" type="number" aria-label="light sprite y")
entity-settings(*ngIf="singleEntity" [entityId]="editor.selectedEntities[0].id" [itemNames]="editorEntities")
@@ -1,20 +1,233 @@
.editor-entity-preview {
width: 20px;
height: 20px;
@import '../../../../styles/partials/variables';
@import 'editor-buttons';
$editor-panel-bg: rgba(0, 0, 0, 0.55);
$editor-popup-bg: rgba(20, 20, 20, 0.95);
$editor-hover-bg: rgba(255, 255, 255, 0.12);
$editor-line: rgba(255, 255, 255, 0.15);
.editor-panel {
position: relative;
padding-top: 2px;
color: #fff;
}
.editor-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 2px;
padding: 3px;
background: $editor-panel-bg;
border-radius: 8px;
}
.editor-tools {
display: flex;
gap: 2px;
}
.editor-separator {
align-self: stretch;
width: 1px;
margin: 3px 3px;
background: $editor-line;
}
.editor-tool-name {
@media (max-width: 800px) {
display: none;
}
}
.editor-current {
max-width: 220px;
}
.editor-current-preview {
flex: 0 0 auto;
width: 24px;
height: 24px;
image-rendering: pixelated;
}
.editor-entity-name {
max-width: 140px;
.editor-current-tile {
flex: 0 0 auto;
width: 32px;
height: 24px;
border-radius: 3px;
}
.editor-current-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.editor-entity-picker {
.editor-recent {
display: flex;
gap: 2px;
}
.editor-recent-item,
.editor-selection-item {
display: flex;
align-items: center;
justify-content: center;
width: 30px;
height: 30px;
padding: 0;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
cursor: pointer;
&:hover {
background: $editor-hover-bg;
}
&.active {
border-color: $link-color;
background: rgba($link-color, 0.25);
}
canvas {
width: 24px;
height: 24px;
image-rendering: pixelated;
}
}
.editor-brush {
display: flex;
align-items: center;
}
.editor-brush-size {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
min-width: 60px;
font-size: 12px;
text-shadow: 0 0 2px #000;
}
.editor-brush-glyph {
border: 1px solid #fff;
background: rgba(255, 255, 255, 0.25);
}
.editor-status {
padding: 0 6px;
font-size: 12px;
white-space: nowrap;
text-shadow: 0 0 2px #000;
}
.editor-hint {
display: flex;
flex-wrap: wrap;
gap: 2px 12px;
margin-top: 3px;
padding: 0 6px;
font-size: 11px;
color: #fff;
text-shadow: 0 0 3px #000, 0 0 2px #000;
pointer-events: none;
}
.editor-popup {
position: absolute;
top: 100%;
left: 0;
margin-top: 4px;
margin-top: 6px;
z-index: 1000;
color: $body-color;
}
.editor-tiles {
display: grid;
grid-template-columns: repeat(4, 88px);
gap: 4px;
padding: 6px;
background: $editor-popup-bg;
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
}
.editor-tile {
display: flex;
flex-direction: column;
align-items: center;
padding: 3px;
color: $body-color;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
cursor: pointer;
&:hover {
background: $editor-hover-bg;
}
&.active {
border-color: $link-color;
background: rgba($link-color, 0.25);
}
canvas {
width: 80px;
height: 60px;
border-radius: 3px;
}
}
.editor-tile-name {
width: 100%;
margin-top: 3px;
font-size: 10px;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.editor-details {
top: auto;
width: 380px;
max-height: calc(100vh - 90px);
overflow-y: auto;
max-width: calc(100vw - 80px);
padding: 8px;
font-size: 12px;
background: $editor-popup-bg;
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
.form-control {
background: rgba(255, 255, 255, 0.08);
border-color: $editor-line;
}
}
.editor-selection {
display: flex;
flex-wrap: wrap;
gap: 2px;
margin-bottom: 4px;
}
.editor-selection-item {
position: relative;
width: auto;
min-width: 30px;
padding: 0 4px;
gap: 3px;
color: $body-color;
font-size: 11px;
}
.editor-settings {
min-width: 260px;
}
+194 -63
View File
@@ -1,12 +1,45 @@
import { Component, NgZone, ChangeDetectionStrategy } from '@angular/core';
import { Component, NgZone, ChangeDetectionStrategy, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { uniq } from 'lodash';
import { faEdit, faCog, faDrawPolygon, faTrash, emptyIcon, faCheck, faPaintbrush } from '../../../client/icons';
import {
faEdit, faCog, faDrawPolygon, faTrash, emptyIcon, faCheck, faPaintbrush, faMapMarkerAlt, faRedo, faHashtag,
faChevronDown, faMinus, faPlus, faInfoCircle, faSave, faTimes
} from '../../../client/icons';
import { PonyTownGame, engines } from '../../../client/game';
import { StorageService } from '../../services/storageService';
import { Model, getEntityNameFromType, getEntityNames } from '../../services/model';
import { Model, getEntityNameFromType, getEntityNames, getEntityTypesFromName } from '../../services/model';
import { getAlpha, withAlpha, colorToHexRGB, parseColor } from '../../../common/color';
import { BLACK } from '../../../common/colors';
import { Entity, Engine, EngineInfo, DebugFlags, tileTypeNames, ChatType } from '../../../common/interfaces';
import {
Entity, Engine, EngineInfo, DebugFlags, tileTypeNames, ChatType, TileType, EditorTool, EditorPick
} from '../../../common/interfaces';
import { clamp } from '../../../common/utils';
const MAX_RECENT = 10;
const MAX_BRUSH_SIZE = 8;
interface SelectionGroup {
type: number;
name: string;
count: number;
}
interface ToolInfo {
id: EditorTool;
name: string;
title: string;
icon: any;
}
const hints: { [key: string]: string[]; } = {
'': ['Pick a tool to edit the map', 'Middle click: place current entity'],
select: [
'Click: select', 'Drag empty area: box select', 'Shift: add or remove', 'Drag selected: move', 'Arrows: nudge',
'Delete: remove', 'Esc: deselect',
],
place: ['Click: place', 'Right click: pick entity from map', 'Backspace: undo', 'Esc: exit'],
tile: ['Click or drag: paint', 'Right click: pick tile from map', 'Esc: exit'],
};
@Component({
changeDetection: ChangeDetectionStrategy.Eager,
@@ -15,21 +48,38 @@ import { Entity, Engine, EngineInfo, DebugFlags, tileTypeNames, ChatType } from
templateUrl: 'editor-box.pug',
styleUrls: ['editor-box.scss'],
})
export class EditorBox {
export class EditorBox implements OnDestroy {
readonly dev = DEVELOPMENT;
readonly cogIcon = faCog;
readonly editIcon = faEdit;
readonly selectIcon = faDrawPolygon;
readonly deleteIcon = faTrash;
readonly checkIcon = faCheck;
readonly placeIcon = faPaintbrush;
readonly undoIcon = faRedo;
readonly snapIcon = faHashtag;
readonly caretIcon = faChevronDown;
readonly minusIcon = faMinus;
readonly plusIcon = faPlus;
readonly infoIcon = faInfoCircle;
readonly saveIcon = faSave;
readonly closeIcon = faTimes;
readonly selectIcon = faDrawPolygon;
readonly emptyIcon = emptyIcon;
readonly tiles = ['---', ...tileTypeNames];
readonly engines = engines;
readonly editorEntities: string[];
readonly showFields: (keyof DebugFlags)[] = ['id', 'bounds', 'collider', 'cover', 'interact', 'trigger'];
readonly tools: ToolInfo[] = [
{ id: 'select', name: 'Select', title: 'Select and move entities', icon: faDrawPolygon },
{ id: 'place', name: 'Place', title: 'Place entities', icon: faMapMarkerAlt },
{ id: 'tile', name: 'Paint', title: 'Paint tiles', icon: faPaintbrush },
];
readonly tileTypes = tileTypeNames.map((name, type) => ({ name, type: type as TileType }));
showPicker = false;
showTiles = false;
recentEntities: string[];
private showEditor = false;
private typeToName = new Map<number, string>();
private groupsCache: { key: Entity[]; length: number; groups: SelectionGroup[]; } | undefined;
private subscription: Subscription;
constructor(
public model: Model,
public game: PonyTownGame,
@@ -37,13 +87,37 @@ export class EditorBox {
private zone: NgZone,
) {
this.game.editor.type = this.storage.getItem('editor-entity') || 'rock';
this.showEditor = this.storage.getBoolean('show-editor');
this.game.editor.tile = clamp(this.storage.getInt('editor-tile') || TileType.Grass, 0, tileTypeNames.length - 1);
this.game.editor.brushSize = clamp(this.storage.getInt('editor-brush') || 1, 1, MAX_BRUSH_SIZE);
this.game.editor.snapToTile = this.storage.getBoolean('editor-snap');
this.showEditor = this.storage.getBoolean('show-editor');
this.editorEntities = getEntityNames().slice().sort();
this.recentEntities = this.storage.getJSON<string[]>('editor-recent', [])
.filter(name => this.editorEntities.indexOf(name) !== -1)
.slice(0, MAX_RECENT);
for (const name of this.editorEntities) {
const types = getEntityTypesFromName(name) || [];
if (types.length === 1 && !this.typeToName.has(types[0])) {
this.typeToName.set(types[0], name);
}
}
this.subscription = this.game.onEditorPick.subscribe(pick => this.pickFromMap(pick));
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
get editor() {
return this.game.editor;
}
get tool() {
return this.game.editor.tool;
}
get hint() {
return hints[this.tool] || hints[''];
}
get hasElevation() {
return this.game.engine === Engine.LayeredTiles;
}
@@ -60,30 +134,67 @@ export class EditorBox {
this.game.editor.type = value;
this.storage.setItem('editor-entity', value);
}
get placing() {
return this.game.editor.placing;
get editorTile() {
return this.game.editor.tile;
}
get editorTileName() {
return tileTypeNames[this.editorTile] || 'none';
}
get brushSize() {
return this.game.editor.brushSize;
}
get hasEditor() {
return this.model.isMod && this.showEditor;
}
setTool(tool: EditorTool) {
const next = this.tool === tool ? '' : tool;
this.game.setEditorTool(next);
this.showPicker = next === 'place' && this.showPicker;
this.showTiles = next === 'tile' && this.showTiles;
}
isTool(tool: EditorTool) {
return this.tool === tool;
}
togglePicker() {
this.showPicker = !this.showPicker;
}
pickEntity(name: string) {
this.editorEntity = name;
this.game.editor.placing = true;
this.game.editor.selectingEntities = false;
this.game.editor.tile = -1;
}
togglePlacing() {
this.game.editor.placing = !this.game.editor.placing;
this.recentEntities = [name, ...this.recentEntities.filter(n => n !== name)].slice(0, MAX_RECENT);
this.storage.setJSON('editor-recent', this.recentEntities);
if (this.game.editor.placing) {
this.game.editor.selectingEntities = false;
this.game.editor.tile = -1;
if (this.tool !== 'place') {
this.game.setEditorTool('place');
}
}
toggleTiles() {
this.showTiles = !this.showTiles;
}
pickTile(tile: TileType) {
this.game.editor.tile = tile;
this.storage.setInt('editor-tile', tile);
this.showTiles = false;
if (this.tool !== 'tile') {
this.game.setEditorTool('tile');
}
}
changeBrush(delta: number) {
this.game.editor.brushSize = clamp(this.brushSize + delta, 1, MAX_BRUSH_SIZE);
this.storage.setInt('editor-brush', this.game.editor.brushSize);
}
toggleSnap() {
this.game.editor.snapToTile = !this.game.editor.snapToTile;
this.storage.setBoolean('editor-snap', this.game.editor.snapToTile);
}
undo() {
this.game.send(server => server.editorAction({ type: 'undo' }));
}
overwriteMap() {
if (DEVELOPMENT && confirm('Overwrite source map files in src/maps with the current map? The server will restart.')) {
this.game.send(server => server.say(0, '/overwritemap', ChatType.Say));
}
}
saveMap() {
const name = prompt('Save map as (saved to store folder)', 'map');
@@ -94,14 +205,20 @@ export class EditorBox {
alert('Invalid file name, use only letters, numbers, dashes and underscores');
}
}
get editorTile() {
return this.game.editor.tile;
private pickFromMap(pick: EditorPick) {
if (pick.entityType !== undefined) {
const name = this.typeToName.get(pick.entityType);
if (name) {
this.pickEntity(name);
}
}
else if (pick.tile !== undefined && tileTypeNames[pick.tile]) {
this.pickTile(pick.tile);
}
}
set editorTile(value: number) {
this.game.editor.tile = value;
}
get hasEditor() {
return this.model.isMod && this.showEditor;
get selectedCount() {
return this.editor.selectedEntities.length;
}
get oneEntity() {
return this.editor.selectedEntities[0];
@@ -112,27 +229,21 @@ export class EditorBox {
get hasSelectedEntities() {
return this.editor.selectedEntities.length > 0;
}
get selectedEntityNames() {
return uniq(this.editor.selectedEntities.map(e => this.typeToName.get(e.type))).filter(x => !!x) as string[];
}
get isLightEntity() {
return this.editor.selectedEntities.some(e => !!e.drawLight);
}
get isLightSpriteEntity() {
return this.editor.selectedEntities.some(e => !!e.drawLightSprite);
}
get selectingEntities() {
return this.game.editor.selectingEntities;
}
set selectingEntities(value) {
this.game.editor.selectingEntities = value;
}
get shadowOpacity() {
return getAlpha(this.game.shadowColor);
}
set shadowOpacity(value) {
this.game.shadowColor = withAlpha(this.game.shadowColor, value);
}
private getEntityName(type: number) {
return getEntityNameFromType(type);
}
private getEntityValue<T>(map: (entity: Entity) => T) {
const entity = this.editor.selectedEntities[0] as any;
return map(entity);
@@ -140,7 +251,7 @@ export class EditorBox {
get entityName() {
const entities = this.editor.selectedEntities;
const types = entities.map(e => e.type);
const names = uniq(types).map(type => this.getEntityName(type)).join(', ');
const names = uniq(types).map(type => getEntityNameFromType(type)).join(', ');
return types.length === 1 ? `${names} [${entities[0].id}]` : names;
}
get entityLightColor() {
@@ -161,7 +272,6 @@ export class EditorBox {
return entity && entity.lightSpriteX || 0;
}
set entityLightSpriteX(value) {
console.log('set x', value, this.editor.selectedEntities);
this.editor.selectedEntities.forEach(e => e.lightSpriteX = value);
}
get entityLightSpriteY() {
@@ -181,26 +291,25 @@ export class EditorBox {
return this.oneEntity.x;
}
set entityX(value) {
this.oneEntity.x = value;
const { id, x, y } = this.oneEntity;
this.game.send(server => server.editorAction({
type: 'move',
entities: [{ id, x, y }],
}));
this.moveEntity(value, this.oneEntity.y);
}
get entityY() {
return this.oneEntity.y;
}
set entityY(value) {
this.oneEntity.y = value;
const { id, x, y } = this.oneEntity;
this.game.send(server => server.editorAction({
type: 'move',
entities: [{ id, x, y }],
}));
this.moveEntity(this.oneEntity.x, value);
}
private moveEntity(x: number, y: number) {
const entity = this.oneEntity;
entity.x = x;
entity.y = y;
const { id } = entity;
this.game.send(server => server.editorAction({ type: 'move', entities: [{ id, x, y }] }));
}
editorClear() {
this.game.send(server => server.editorAction({ type: 'clear' }));
if (confirm('Remove all entities placed with the editor?')) {
this.game.send(server => server.editorAction({ type: 'clear' }));
}
}
clearLocalStorage() {
this.storage.clear();
@@ -215,26 +324,48 @@ export class EditorBox {
this.zone.run(() => {
this.showEditor = !this.showEditor;
this.storage.setBoolean('show-editor', this.showEditor);
if (!this.showEditor) {
this.game.setEditorTool('');
}
});
}
toggleSelecting() {
this.selectingEntities = !this.selectingEntities;
if (this.selectingEntities) {
this.game.editor.placing = false;
}
if (!this.selectingEntities) {
this.editor.selectedEntities.length = 0;
}
}
listEntities() {
this.game.send(server => server.editorAction({ type: 'list' }));
}
deleteEntities() {
const entities = this.editor.selectedEntities.map(e => e.id);
this.game.send(server => server.editorAction({ type: 'remove', entities }));
this.editor.selectedEntities.length = 0;
this.editor.selectedEntities = [];
}
clearSelection() {
this.editor.selectedEntities = [];
}
get selectionGroups(): SelectionGroup[] {
const selected = this.editor.selectedEntities;
const cache = this.groupsCache;
if (cache && cache.key === selected && cache.length === selected.length) {
return cache.groups;
}
const counts = new Map<number, number>();
selected.forEach(e => counts.set(e.type, (counts.get(e.type) || 0) + 1));
const groups = Array.from(counts.entries())
.map(([type, count]) => ({ type, count, name: this.typeToName.get(type) || '' }))
.filter(g => !!g.name)
.sort((a, b) => b.count - a.count);
this.groupsCache = { key: selected, length: selected.length, groups };
return groups;
}
selectSameType() {
const types = new Set(this.editor.selectedEntities.map(e => e.type));
this.game.selectEditorEntities(this.game.map.entities.filter(e => types.has(e.type)));
}
selectOnly(type: number) {
this.editor.selectedEntities = this.editor.selectedEntities.filter(e => e.type === type);
}
showEntitiesInfo() {
console.log(this.editor.selectedEntities);
@@ -0,0 +1,65 @@
.entity-settings
.entity-settings-loading(*ngIf="!entity") {{loading ? 'Loading…' : 'No data'}}
ng-container(*ngIf="entity")
.entity-settings-row
label.entity-settings-label(for="es-name") Name
input#es-name.form-control.form-control-sm([(ngModel)]="name" placeholder="none" autocomplete="off")
.entity-settings-row
label.entity-settings-label(for="es-tag" title="Used by other entities to reference this one") Tag
input#es-tag.form-control.form-control-sm([(ngModel)]="tag" placeholder="none" autocomplete="off")
.entity-settings-row
label.entity-settings-label(for="es-layer" title="Seasonal or holiday layer this entity is saved to") Layer
select#es-layer.form-select.form-select-sm([(ngModel)]="layer")
option(value="") base (always)
option(*ngFor="let l of layers" [value]="l") {{l}}
.entity-settings-row
span.entity-settings-label
label.entity-settings-check
input(type="checkbox" [(ngModel)]="editable")
| Movable by players
.entity-settings-behavior(*ngFor="let b of behaviors; trackBy: trackKind")
.entity-settings-row
label.entity-settings-label([title]="b.hint" [attr.for]="'es-' + b.kind") {{b.label}}
ng-container(*ngIf="b.fixed")
span.entity-settings-fixed set by game code
ng-container(*ngIf="!b.fixed")
select.form-select.form-select-sm(
[id]="'es-' + b.kind" [ngModel]="b.action" (ngModelChange)="setAction(b, $event)")
option(value="") nothing
option(*ngFor="let a of actionsFor(b.kind)" [value]="a") {{a}}
button.editor-btn.editor-btn-sm(
*ngIf="b.action" type="button" (click)="toggleRaw(b)" [class.active]="b.raw" title="Edit arguments as JSON")
fa-icon([icon]="codeIcon" [fixedWidth]="true")
ng-container(*ngIf="!b.fixed && b.action")
textarea.form-control.form-control-sm.entity-settings-json(
*ngIf="b.raw" [(ngModel)]="b.json" rows="3" spellcheck="false" placeholder="{ }")
ng-container(*ngIf="!b.raw")
.entity-settings-row.entity-settings-arg(*ngFor="let f of b.fields")
label.entity-settings-label {{f.key}}
ng-container([ngSwitch]="f.type")
textarea.form-control.form-control-sm(*ngSwitchCase="'text'" [(ngModel)]="f.value" rows="2")
input.form-control.form-control-sm(*ngSwitchCase="'number'" type="number" [(ngModel)]="f.value")
input(*ngSwitchCase="'boolean'" type="checkbox" [(ngModel)]="f.value")
input.form-control.form-control-sm(
*ngSwitchDefault [(ngModel)]="f.value" autocomplete="off"
[attr.list]="f.key === 'item' ? 'es-items' : null")
details.entity-settings-options
summary Options (JSON)
textarea.form-control.form-control-sm.entity-settings-json([(ngModel)]="options" rows="3" spellcheck="false" placeholder="{ }")
.entity-settings-error(*ngIf="error") {{error}}
.entity-settings-actions
span.text-muted.small {{entity.type}} [{{entity.id}}]
button.editor-btn.editor-btn-sm(type="button" (click)="revert()" [disabled]="!dirty" title="Revert changes")
fa-icon([icon]="revertIcon" [fixedWidth]="true" flip="horizontal")
button.editor-btn.editor-btn-sm.entity-settings-apply(type="button" (click)="apply()" [disabled]="!dirty" title="Apply changes")
fa-icon([icon]="applyIcon" [fixedWidth]="true")
| Apply
datalist#es-items
option(*ngFor="let n of itemNames" [value]="n")
@@ -0,0 +1,113 @@
@import '../../../../styles/partials/variables';
@import 'editor-buttons';
.entity-settings {
margin-top: 6px;
padding-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.15);
.form-control,
.form-select {
color: #fff;
background-color: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.15);
}
.form-select option {
color: #fff;
background: #222;
}
}
.entity-settings-row {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 4px;
> .form-control,
> .form-select {
flex: 1 1 auto;
min-width: 0;
}
}
.entity-settings-label {
flex: 0 0 76px;
margin: 0;
color: $text-muted;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.entity-settings-check {
display: flex;
align-items: center;
gap: 4px;
margin: 0;
cursor: pointer;
}
.entity-settings-behavior {
margin-top: 6px;
}
.entity-settings-arg {
padding-left: 12px;
.entity-settings-label {
flex-basis: 64px;
}
}
.entity-settings-json {
margin: 0 0 4px 82px;
width: calc(100% - 82px);
font-family: monospace;
font-size: 11px;
}
.entity-settings-fixed {
color: $text-muted;
font-style: italic;
}
.entity-settings-options {
margin-top: 6px;
summary {
color: $text-muted;
cursor: pointer;
}
.entity-settings-json {
margin: 4px 0 0;
width: 100%;
}
}
.entity-settings-error {
margin-top: 6px;
color: $danger;
}
.entity-settings-loading {
color: $text-muted;
}
.entity-settings-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
margin-top: 8px;
> span {
margin-right: auto;
}
}
.entity-settings-apply:not(:disabled) {
background: $link-color;
}
@@ -0,0 +1,247 @@
import { Component, ChangeDetectionStrategy, Input, OnChanges, OnDestroy, NgZone, inject } from '@angular/core';
import { Subscription } from 'rxjs';
import { PonyTownGame } from '../../../client/game';
import {
EditorEntityInfo, EditorBehaviorInfo, EditorBehaviorKind, editorBehaviorKinds, EditorEntityData, EditorBehavior
} from '../../../common/interfaces';
import { faRedo, faCheck, faCode } from '../../../client/icons';
type FieldType = 'string' | 'text' | 'number' | 'boolean';
interface ArgField {
key: string;
type: FieldType;
value: any;
}
interface BehaviorDraft {
kind: EditorBehaviorKind;
label: string;
hint: string;
fixed: boolean;
action: string;
raw: boolean;
json: string;
fields: ArgField[];
}
const kindLabels: { [K in EditorBehaviorKind]: [string, string]; } = {
interact: ['On click', 'Runs when player clicks the entity'],
trigger: ['On enter', 'Runs when player walks into the trigger area'],
boop: ['On boop', 'Runs when player boops the entity'],
update: ['Every tick', 'Runs continuously on the server'],
};
const textKeys = ['text', 'message'];
function isPrimitive(value: any) {
return value === null || ['string', 'number', 'boolean'].indexOf(typeof value) !== -1;
}
function canUseFields(args: any) {
return !!args && typeof args === 'object' && !Array.isArray(args) && Object.keys(args).every(key => isPrimitive(args[key]));
}
function toFields(args: any): ArgField[] {
return Object.keys(args || {}).map(key => {
const value = args[key];
const type: FieldType = typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' :
textKeys.indexOf(key) !== -1 ? 'text' : 'string';
return { key, type, value: value === null ? '' : value };
});
}
function fromFields(fields: ArgField[]) {
const args: any = {};
for (const field of fields) {
args[field.key] = field.type === 'number' ? (+field.value || 0) : field.value;
}
return args;
}
function stringify(value: any) {
return value === undefined ? '' : JSON.stringify(value, null, 2);
}
function parseJSON(text: string, label: string) {
if (!text.trim()) {
return undefined;
}
try {
return JSON.parse(text);
}
catch {
throw new Error(`${label}: invalid JSON`);
}
}
@Component({
changeDetection: ChangeDetectionStrategy.Eager,
standalone: false,
selector: 'entity-settings',
templateUrl: 'entity-settings.pug',
styleUrls: ['entity-settings.scss'],
})
export class EntitySettings implements OnChanges, OnDestroy {
@Input() entityId = 0;
@Input() itemNames: string[] = [];
readonly revertIcon = faRedo;
readonly applyIcon = faCheck;
readonly codeIcon = faCode;
readonly game = inject(PonyTownGame);
private readonly zone = inject(NgZone);
entity: EditorEntityInfo | undefined;
info: EditorBehaviorInfo | undefined;
loading = false;
error = '';
name = '';
tag = '';
layer = '';
editable = false;
options = '';
behaviors: BehaviorDraft[] = [];
private original = '';
private subscription: Subscription;
constructor() {
this.subscription = this.game.onEditorEntityInfo.subscribe(({ entities, info }) => this.zone.run(() => {
const entity = entities.find(e => e.id === this.entityId);
if (entity) {
this.info = info;
this.load(entity);
}
}));
}
ngOnChanges() {
this.entity = undefined;
this.error = '';
this.refresh();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
get layers() {
return this.info ? this.info.layers : [];
}
get dirty() {
try {
return JSON.stringify(this.build()) !== this.original;
}
catch {
return true;
}
}
refresh() {
if (this.entityId) {
this.loading = true;
this.game.send(server => server.editorAction({ type: 'inspect', entities: [this.entityId] }));
}
}
actionsFor(kind: EditorBehaviorKind) {
return this.info ? this.info.actions[kind] : [];
}
setAction(behavior: BehaviorDraft, action: string) {
behavior.action = action;
const template = this.info && this.info.templates[`${behavior.kind}:${action}`];
this.setArgs(behavior, template === undefined ? undefined : JSON.parse(JSON.stringify(template)));
}
toggleRaw(behavior: BehaviorDraft) {
if (behavior.raw) {
const args = parseJSON(behavior.json, behavior.label);
if (args !== undefined && !canUseFields(args)) {
this.error = `${behavior.label}: arguments are too complex for fields`;
return;
}
behavior.fields = toFields(args);
behavior.raw = false;
}
else {
behavior.json = stringify(behavior.fields.length ? fromFields(behavior.fields) : undefined);
behavior.raw = true;
}
this.error = '';
}
revert() {
if (this.entity) {
this.load(this.entity);
}
}
apply() {
if (!this.entity) {
return;
}
try {
const data = this.build();
this.error = '';
this.game.send(server => server.editorAction({ type: 'update', id: this.entity!.id, data }));
}
catch (e) {
this.error = (e as Error).message;
}
}
trackKind(_: number, behavior: BehaviorDraft) {
return behavior.kind;
}
private setArgs(behavior: BehaviorDraft, args: any) {
behavior.raw = args !== undefined && !canUseFields(args);
behavior.fields = behavior.raw ? [] : toFields(args);
behavior.json = stringify(args);
}
private load(entity: EditorEntityInfo) {
const data = entity.data;
this.entity = entity;
this.loading = false;
this.error = '';
this.name = data.name || '';
this.tag = data.tag || '';
this.layer = data.layer || '';
this.editable = !!data.editable;
this.options = stringify(data.options);
this.behaviors = editorBehaviorKinds
.filter(kind => kind === 'interact' ? entity.canInteract : kind === 'trigger' ? entity.canTrigger : true)
.map(kind => {
const def = data[kind] as EditorBehavior | undefined;
const [label, hint] = kindLabels[kind];
const behavior: BehaviorDraft = {
kind, label, hint, fixed: entity.fixed.indexOf(kind) !== -1, action: def ? def.action : '',
raw: false, json: '', fields: [],
};
this.setArgs(behavior, def && def.args);
return behavior;
});
this.original = JSON.stringify(this.build());
}
private build(): EditorEntityData {
const data: EditorEntityData = {
name: this.name,
tag: this.tag,
layer: this.layer,
editable: this.editable,
options: parseJSON(this.options, 'Options') || null,
};
for (const behavior of this.behaviors) {
if (behavior.fixed) {
continue;
}
if (!behavior.action) {
data[behavior.kind] = null;
}
else {
const args = behavior.raw ? parseJSON(behavior.json, behavior.label) : fromFields(behavior.fields);
const hasArgs = args !== undefined && !(typeof args === 'object' && args && Object.keys(args).length === 0);
data[behavior.kind] = hasArgs ? { action: behavior.action, args } : { action: behavior.action };
}
}
return data;
}
}
@@ -0,0 +1,36 @@
import { Directive, DoCheck, ElementRef, Input, inject } from '@angular/core';
import { TileType } from '../../../common/interfaces';
import { Season, MapType } from '../../../common/commonInterfaces';
import { getTilePreview } from '../../../client/tilePreview';
import { drawPreviewToCanvas } from '../../../client/entityPreview';
import { loadAndInitSpriteSheets } from '../../../client/loadSprites';
let spritesReady = false;
@Directive({
standalone: false,
selector: 'canvas[tilePreview]',
})
export class TilePreviewCanvas implements DoCheck {
@Input() tilePreview: TileType = TileType.None;
@Input() season: Season = Season.Summer;
@Input() mapType: MapType = MapType.None;
private readonly element: ElementRef<HTMLCanvasElement> = inject(ElementRef);
private drawn = '';
constructor() {
if (!spritesReady) {
loadAndInitSpriteSheets().then(() => {
spritesReady = true;
this.ngDoCheck();
});
}
}
ngDoCheck() {
const key = `${this.tilePreview}:${this.season}:${this.mapType}`;
if (spritesReady && this.drawn !== key) {
this.drawn = key;
drawPreviewToCanvas(this.element.nativeElement, getTilePreview(this.tilePreview, this.season, this.mapType));
}
}
}
@@ -1,9 +1,8 @@
.entity-picker
.entity-picker-header.d-flex.align-items-center.p-1
.input-group.input-group-sm.flex-grow-1
span.input-group-text
fa-icon([icon]="searchIcon" [fixedWidth]="true")
input.form-control(
.entity-picker-search.flex-grow-1
fa-icon.entity-picker-search-icon([icon]="searchIcon" [fixedWidth]="true")
input.form-control.form-control-sm(
#searchInput
[ngModel]="search"
(ngModelChange)="setSearch($event)"
@@ -11,7 +10,7 @@
placeholder="search entities"
aria-label="Search entities")
span.text-muted.small.mx-2 {{filtered.length}}
button.btn.btn-sm.btn-default((click)="closePicker()" title="Close" aria-label="Close")
button.entity-picker-close(type="button" (click)="closePicker()" title="Close" aria-label="Close")
fa-icon([icon]="closeIcon" [fixedWidth]="true")
.entity-picker-list(#list)
button.entity-picker-item(
@@ -10,10 +10,44 @@
width: 420px;
max-width: calc(100vw - 20px);
height: 60vh;
background: $dark-bg;
border: 1px solid $border-color;
border-radius: $border-radius-lg;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
background: rgba(20, 20, 20, 0.95);
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5);
}
.entity-picker-search {
position: relative;
.form-control {
padding-left: 28px;
color: #fff;
background: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.15);
}
}
.entity-picker-search-icon {
position: absolute;
top: 50%;
left: 8px;
transform: translateY(-50%);
color: $text-muted;
pointer-events: none;
}
.entity-picker-close {
width: 28px;
height: 28px;
padding: 0;
color: #fff;
background: transparent;
border: none;
border-radius: 6px;
cursor: pointer;
&:hover {
background: rgba(255, 255, 255, 0.12);
}
}
.entity-picker-list {
@@ -34,29 +68,27 @@
min-width: 0;
padding: 2px;
color: $body-color;
background: $body-bg;
background: transparent;
border: 1px solid transparent;
border-radius: $border-radius-sm;
border-radius: 6px;
cursor: pointer;
&:hover {
border-color: $border-color;
background: lighten($body-bg, 5%);
background: rgba(255, 255, 255, 0.12);
}
&.active {
border-color: $link-color;
background: lighten($body-bg, 8%);
background: rgba($link-color, 0.25);
}
canvas {
width: 64px;
height: 64px;
image-rendering: pixelated;
background: repeating-conic-gradient(#3a3a3a 0% 25%, #444 0% 50%) 50% / 16px 16px;
&.entity-preview-empty {
background: #2a2a2a;
background: rgba(255, 255, 255, 0.05);
border-radius: 4px;
}
}
}
@@ -71,7 +103,3 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.input-group-text {
color: #000;
}
+16 -1
View File
@@ -27,7 +27,7 @@ import {
findEntities, updateMapState, loadMapFromFile, saveMapToFile, saveEntitiesToFile, getSizeOfMap,
saveMapToFileBinaryAlt, saveRegionCollider, saveMap, loadMap
} from './serverMap';
import { saveMapFiles } from './mapFiles';
import { saveMapFiles, overwriteMapFiles } from './mapFiles';
import { PARTY_LIMIT, tileWidth, tileHeight, MAP_LOAD_SAVE_TIMEOUT } from '../common/constants';
import { PartyService } from './services/party';
import { swapCharacter } from './characterUtils';
@@ -479,6 +479,21 @@ export function createCommands(world: World): Command[] {
return `saved ${saved.join(', ')}${warnings.length ? ` (${warnings.length} warnings, see log)` : ''}`;
});
}),
DEVELOPMENT && command(['overwritemap'], '/overwritemap - overwrite source map files in src/maps', 'superadmin', (_, client) => {
try {
const { saved, warnings } = overwriteMapFiles(client.map);
for (const warning of warnings) {
logger.warn(warning);
}
saySystem(client, `overwritten ${saved.join(', ')}${warnings.length ? ` (${warnings.length} warnings, see log)` : ''}`);
}
catch (e) {
logger.error(e);
saySystem(client, `failed to overwrite map: ${(e as Error).message}`);
}
}),
command(['savetiles'], '/savetiles <file name> - save map tiles to file', 'superadmin', (_, client, message) => {
execWithFileName(client, message, async fileName => {
await saveMapToFile(client.map, pathTo('store', `${fileName}.json`), { saveTiles: true });
+196
View File
@@ -0,0 +1,196 @@
import {
EditorEntityData, EditorEntityInfo, EditorBehaviorInfo, EditorBehaviorKind, editorBehaviorKinds, EditorBehavior,
EntityFlags, EntityState, ServerFlags
} from '../common/interfaces';
import { hasFlag } from '../common/utils';
import { ServerEntity, ServerMap } from './serverInterfaces';
import { World } from './world';
import { serializeEntity } from './serverMap';
import {
BehaviorKind, getBehaviorActions, getBehaviorArgsTemplate, getBehaviorDef, getEntityBehavior, isDerivedBehavior,
createBehavior, createBehaviorContext
} from './mapBehaviors';
import { setEntityName, updateEntityNameInfo, updateEntityOptions, updateEntityState } from './entityUtils';
import { getLoadedLayers } from './mapFiles';
import { UpdateController } from './controllers/updateController';
const MAX_TEXT_LENGTH = 1000;
function getProperty(kind: EditorBehaviorKind): 'interact' | 'trigger' | 'boop' | 'serverUpdate' {
return kind === 'update' ? 'serverUpdate' : kind;
}
function isFixedBehavior(entity: ServerEntity, kind: EditorBehaviorKind) {
const callback = getEntityBehavior(entity, kind);
return !!callback && !getBehaviorDef(callback) && !isDerivedBehavior(callback);
}
export function canHaveBehavior(entity: ServerEntity, kind: EditorBehaviorKind) {
switch (kind) {
case 'interact':
return hasFlag(entity.flags, EntityFlags.Interactive);
case 'trigger':
return !!entity.triggerBounds;
default:
return true;
}
}
export function getEditorEntityInfo(entity: ServerEntity): EditorEntityInfo {
const saved = serializeEntity(entity, () => { });
const result: EditorEntityData = { ...saved };
delete (result as any).type;
delete (result as any).x;
delete (result as any).y;
if (entity.layer) {
result.layer = entity.layer;
}
return {
id: entity.id,
type: saved.type,
data: result,
canInteract: canHaveBehavior(entity, 'interact'),
canTrigger: canHaveBehavior(entity, 'trigger'),
fixed: editorBehaviorKinds.filter(kind => isFixedBehavior(entity, kind)),
};
}
export function getEditorBehaviorInfo(map: ServerMap): EditorBehaviorInfo {
const templates: { [key: string]: any; } = {};
const actions = {} as EditorBehaviorInfo['actions'];
for (const kind of editorBehaviorKinds) {
actions[kind] = getBehaviorActions(kind).sort();
for (const action of actions[kind]) {
const template = getBehaviorArgsTemplate(kind, action);
if (template !== undefined) {
templates[`${kind}:${action}`] = template;
}
}
}
return { actions, templates, layers: getLoadedLayers(map) };
}
function validateText(value: any, field: string): string | undefined {
if (value === undefined || value === null || value === '') {
return undefined;
}
if (typeof value !== 'string' || value.length > MAX_TEXT_LENGTH) {
throw new Error(`invalid ${field}`);
}
return value;
}
function isPlainObject(value: any) {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
function cloneJSON<T>(value: T): T {
return JSON.parse(JSON.stringify(value));
}
export function applyEditorEntityData(world: World, map: ServerMap, entity: ServerEntity, data: EditorEntityData) {
if (!isPlainObject(data)) {
throw new Error('invalid data');
}
const name = validateText(data.name, 'name');
const tag = validateText(data.tag, 'tag');
const layer = validateText(data.layer, 'layer');
if (layer !== undefined && getLoadedLayers(map).indexOf(layer) === -1) {
throw new Error(`layer "${layer}" is not loaded on this map`);
}
if (data.options !== undefined && data.options !== null && !isPlainObject(data.options)) {
throw new Error('options must be an object');
}
const ctx = createBehaviorContext(world, map);
const behaviors = new Map<EditorBehaviorKind, ((...args: any[]) => any) | undefined>();
for (const kind of editorBehaviorKinds) {
const def = data[kind] as EditorBehavior | null | undefined;
if (def === undefined || isFixedBehavior(entity, kind)) {
continue;
}
if (def === null) {
behaviors.set(kind, undefined);
continue;
}
if (!isPlainObject(def) || typeof def.action !== 'string') {
throw new Error(`invalid ${kind} behavior`);
}
if (!canHaveBehavior(entity, kind)) {
throw new Error(`${data.name || 'entity'} can't have ${kind} behavior`);
}
if (def.args !== undefined && !isPlainObject(def.args)) {
throw new Error(`${kind} arguments must be an object`);
}
const args = def.args === undefined ? undefined : cloneJSON(def.args);
behaviors.set(kind, createBehavior(kind as BehaviorKind, { action: def.action, args }, ctx, entity));
}
if (name !== entity.name) {
if (name) {
setEntityName(entity, name);
}
else {
entity.name = undefined;
entity.nameBad = undefined;
entity.encodedName = undefined;
}
updateEntityNameInfo(entity);
}
entity.tag = tag;
if (data.options !== undefined) {
const options = data.options ? cloneJSON(data.options) : {};
entity.options = {} as any;
updateEntityOptions(entity, options);
}
if (data.editable !== undefined) {
const state = data.editable ? (entity.state | EntityState.Editable) : (entity.state & ~EntityState.Editable);
if (state !== entity.state) {
updateEntityState(entity, state);
}
}
if (data.layer !== undefined) {
entity.layer = layer;
if (layer) {
entity.serverFlags = (entity.serverFlags || 0) | ServerFlags.Seasonal;
}
else {
entity.serverFlags = (entity.serverFlags || 0) & ~ServerFlags.Seasonal;
}
}
behaviors.forEach((callback, kind) => (entity as any)[getProperty(kind)] = callback);
if (behaviors.has('update')) {
for (const controller of map.controllers) {
if (controller instanceof UpdateController) {
controller.initialize();
}
}
}
}
+23 -9
View File
@@ -38,6 +38,7 @@ const interactActions = new Map<string, InteractFactory>();
const boopActions = new Map<string, BoopFactory>();
const updateActions = new Map<string, UpdateFactory>();
const argsTemplates = new Map<string, any>();
const definitions = new WeakMap<BehaviorCallback, BehaviorDef>();
const derived = new WeakSet<BehaviorCallback>();
@@ -59,22 +60,35 @@ function getProperty(kind: BehaviorKind): 'interact' | 'trigger' | 'boop' | 'ser
return kind === 'update' ? 'serverUpdate' : kind;
}
export function registerInteractAction(action: string, factory: InteractFactory) {
function setArgsTemplate(kind: string, action: string, template: any) {
if (template !== undefined) {
argsTemplates.set(`${kind}:${action}`, template);
}
}
export function registerInteractAction(action: string, factory: InteractFactory, argsTemplate?: any) {
interactActions.set(action, factory);
setArgsTemplate('interact', action, argsTemplate);
}
export function registerBoopAction(action: string, factory: BoopFactory) {
export function registerBoopAction(action: string, factory: BoopFactory, argsTemplate?: any) {
boopActions.set(action, factory);
setArgsTemplate('boop', action, argsTemplate);
}
export function registerUpdateAction(action: string, factory: UpdateFactory) {
export function registerUpdateAction(action: string, factory: UpdateFactory, argsTemplate?: any) {
updateActions.set(action, factory);
setArgsTemplate('update', action, argsTemplate);
}
export function getBehaviorActions(kind: BehaviorKind) {
return Array.from(getRegistry(kind).keys());
}
export function getBehaviorArgsTemplate(kind: BehaviorKind, action: string): any {
return argsTemplates.get(`${kind === 'trigger' ? 'interact' : kind}:${action}`);
}
export function markDerivedBehavior<T extends BehaviorCallback>(callback: T): T {
derived.add(callback);
return callback;
@@ -197,7 +211,7 @@ export interface GoToMapArgs {
registerInteractAction('goToMap', ({ map, spawn, publicMap }: GoToMapArgs, { world, map: current }) => {
const target = (publicMap !== undefined && current.usage !== MapUsage.Party) ? publicMap : map;
return (_, client) => goToMap(world, client, target || '', spawn);
});
}, { map: '', spawn: '' });
export interface GiveArgs {
item: string;
@@ -221,16 +235,16 @@ export function give(type: number, message?: string): Interact {
}, { action: 'give', args });
}
registerInteractAction('give', ({ item, message }: GiveArgs) => give(getItemType(item), message));
registerInteractAction('give', ({ item, message }: GiveArgs) => give(getItemType(item), message), { item: '', message: '' });
registerInteractAction('hold', ({ item }: { item: string; }) => {
const type = getItemType(item);
return (_, client) => holdItem(client.pony, type);
});
}, { item: '' });
registerInteractAction('say', ({ text }: { text: string; }) => {
return (entity, client) => sayTo(client, entity, text, MessageType.System);
});
}, { text: '' });
export function say(text: string): Interact {
return interactBehavior({ action: 'say', args: { text } });
@@ -352,7 +366,7 @@ registerUpdateAction('bunny', ({ waypoints }: BunnyArgs, _, entity) => {
}
}
};
});
}, { waypoints: [] });
export interface GhostArgs {
anims: number[];
@@ -395,7 +409,7 @@ registerUpdateAction('ghost', ({ anims, hooves: hoovesTag }: GhostArgs, ctx, gho
reset = true;
}
};
});
}, { anims: [], hooves: '' });
registerUpdateAction('eyes', (_, __, entity) => {
let delay = 5;
+22 -3
View File
@@ -135,12 +135,17 @@ export function saveMapFiles(map: ServerMap, path: string, name: string) {
const saved: string[] = [];
const base = saveMap(map, {
saveTiles: true, saveSpawns: true, saveLockedTiles: !files, saveWalls: true, saveEntities: true,
saveTiles: true, saveSpawns: true, saveLockedTiles: true, saveWalls: true, saveEntities: true,
filter: e => e.layer === undefined, warn,
});
if (files && files.base.lockedTiles) {
base.lockedTiles = files.base.lockedTiles;
if (files) {
if (files.base.lockedTiles) {
base.lockedTiles = files.base.lockedTiles;
}
else {
delete base.lockedTiles;
}
}
fs.writeFileSync(`${path}/${name}.json`, stringifyMapData(base), 'utf8');
@@ -176,3 +181,17 @@ export function saveMapFiles(map: ServerMap, path: string, name: string) {
return { saved, warnings };
}
export function overwriteMapFiles(map: ServerMap) {
const files = getMapFiles(map);
if (!files) {
throw new Error('map was not loaded from map files');
}
const result = saveMapFiles(map, getMapsPath(), files.name);
const updated = readMapFiles(files.name);
files.base = updated.base;
files.layers = updated.layers;
return { name: files.name, ...result };
}
+36
View File
@@ -38,6 +38,7 @@ import { createAnEntity } from '../common/entities';
import { mockPaletteManager } from '../common/ponyInfo';
import { getTile } from '../common/tileUtils';
import { MapFlags } from '../common/commonInterfaces';
import { getEditorEntityInfo, getEditorBehaviorInfo, applyEditorEntityData } from './editorEntities';
interface AddedEntity {
name: string;
@@ -60,6 +61,7 @@ const playerActionNames = [
const editorAdded = new Map<string, AddedEntity[]>();
const MAX_EDITOR_BRUSH_SIZE = 16;
const MAX_EDITOR_INSPECT = 100;
const MAX_NOTE_LENGTH = 2000;
const debugRate = DEVELOPMENT ? '1000/s' : '';
@@ -758,6 +760,40 @@ export class ServerActions implements IServerActions, SocketServer {
break;
}
case 'inspect': {
if (!Array.isArray(action.entities)) {
throw new Error(`Invalid editor action (inspect)`);
}
const infos = action.entities
.slice(0, MAX_EDITOR_INSPECT)
.map(id => this.world.getEntityById(id))
.filter(e => !!e && e.type !== PONY_TYPE)
.map(e => getEditorEntityInfo(e!));
this.client.editorEntityInfo(infos, getEditorBehaviorInfo(this.map));
break;
}
case 'update': {
validateNumber(action.id, 'id');
const entity = this.world.getEntityById(action.id);
if (!entity || entity.type === PONY_TYPE) {
saySystem(this.client, 'Entity not found');
break;
}
try {
applyEditorEntityData(this.world, this.map, entity, action.data);
this.client.editorEntityInfo([getEditorEntityInfo(entity)], getEditorBehaviorInfo(this.map));
saySystem(this.client, 'Entity updated');
}
catch (e) {
saySystem(this.client, `Failed to update entity: ${(e as Error).message}`);
}
break;
}
case 'party': {
const entities = findEntities(this.map, e => !!e.client && /^debug/.test(e.name || ''));
+8 -8
View File
@@ -331,6 +331,14 @@ export function saveMap(map: ServerMap, saveOptions: MapSaveOptions): MapData {
data.lockedTiles = encodeLockedTiles(map.lockedTiles);
}
if (saveOptions.saveWalls) {
const controller = map.controllers.find(c => c.toggleWall) as WallController | undefined;
if (controller) {
data.walls = controller.serialize();
}
}
if (saveOptions.saveEntities) {
const filter = saveOptions.filter;
const entities = findEntities(map, entity => isSaveableEntity(entity)
@@ -340,14 +348,6 @@ export function saveMap(map: ServerMap, saveOptions: MapSaveOptions): MapData {
data.entities = serializeEntities(entities, saveOptions.warn);
}
if (saveOptions.saveWalls) {
const controller = map.controllers.find(c => c.toggleWall) as WallController | undefined;
if (controller) {
data.walls = controller.serialize();
}
}
return data;
}
+31
View File
@@ -0,0 +1,31 @@
import { loadSprites } from '../lib';
import { expect } from 'chai';
import { TileType, tileTypeNames } from '../../common/interfaces';
import { Season } from '../../common/commonInterfaces';
import { getTilePreview, TILE_PREVIEW_WIDTH, TILE_PREVIEW_HEIGHT } from '../../client/tilePreview';
describe('tilePreview', () => {
before(loadSprites);
it('renders preview of a tile', () => {
const preview = getTilePreview(TileType.Water, Season.Summer)!;
expect(preview.width).equal(TILE_PREVIEW_WIDTH);
expect(preview.height).equal(TILE_PREVIEW_HEIGHT);
});
it('caches previews per tile and season', () => {
const summer = getTilePreview(TileType.Grass, Season.Summer);
expect(getTilePreview(TileType.Grass, Season.Summer)).equal(summer);
expect(getTilePreview(TileType.Grass, Season.Winter)).not.equal(summer);
});
it('renders all tile types in all seasons', () => {
for (const season of [Season.Summer, Season.Autumn, Season.Winter, Season.Spring]) {
tileTypeNames.forEach((name, tile) => {
expect(getTilePreview(tile as TileType, season), name).not.equal(null);
});
}
});
});
+167
View File
@@ -0,0 +1,167 @@
import '../lib';
import { expect } from 'chai';
import * as entities from '../../common/entities';
import { EntityState, ServerFlags } from '../../common/interfaces';
import { createServerMap } from '../../server/serverMap';
import { worldForTemplates } from '../../server/mapUtils';
import { ServerEntity, ServerMap } from '../../server/serverInterfaces';
import { getBehaviorDef, setInteract, createBehaviorContext } from '../../server/mapBehaviors';
import { applyEditorEntityData, getEditorEntityInfo, getEditorBehaviorInfo } from '../../server/editorEntities';
import { applyMapLayers, loadBaseMap } from '../../server/mapFiles';
describe('editorEntities', () => {
const world: any = worldForTemplates;
let map: ServerMap;
beforeEach(() => {
map = createServerMap('test', 0, 2, 2);
});
function add(entity: ServerEntity) {
return world.addEntity(entity, map) as ServerEntity;
}
describe('getEditorEntityInfo()', () => {
it('returns saved data and what behaviors entity supports', () => {
const sign = add(entities.sign(1, 1));
sign.name = 'hello';
setInteract(sign, { action: 'say', args: { text: 'hi' } }, createBehaviorContext(world, map));
const info = getEditorEntityInfo(sign);
expect(info.type).equal('sign');
expect(info.data).eql({ name: 'hello', interact: { action: 'say', args: { text: 'hi' } } });
expect(info.canInteract).equal(true);
expect(info.canTrigger).equal(false);
expect(info.fixed).eql([]);
});
it('reports trigger support', () => {
expect(getEditorEntityInfo(add(entities.triggerDoor(1, 1))).canTrigger).equal(true);
});
it('reports behaviors set by code as fixed', () => {
const sign = add(entities.sign(1, 1));
sign.interact = () => { };
expect(getEditorEntityInfo(sign).fixed).eql(['interact']);
});
});
describe('getEditorBehaviorInfo()', () => {
it('lists actions and argument templates', () => {
const info = getEditorBehaviorInfo(map);
expect(info.actions.interact).include('goToMap');
expect(info.actions.trigger).eql(info.actions.interact);
expect(info.actions.boop).include('light');
expect(info.templates['trigger:goToMap']).eql({ map: '', spawn: '' });
});
});
describe('applyEditorEntityData()', () => {
it('sets trigger behavior', () => {
const door = add(entities.triggerDoor(1, 1));
applyEditorEntityData(world, map, door, { trigger: { action: 'goToMap', args: { map: 'cave' } } });
expect(getBehaviorDef(door.trigger)).eql({ action: 'goToMap', args: { map: 'cave' } });
});
it('removes behavior', () => {
const sign = add(entities.sign(1, 1));
setInteract(sign, 'toyStash', createBehaviorContext(world, map));
applyEditorEntityData(world, map, sign, { interact: null });
expect(sign.interact).equal(undefined);
});
it('keeps behaviors that are not in data', () => {
const sign = add(entities.sign(1, 1));
setInteract(sign, 'toyStash', createBehaviorContext(world, map));
applyEditorEntityData(world, map, sign, { name: 'x' });
expect(getBehaviorDef(sign.interact)).eql({ action: 'toyStash' });
});
it('sets name, tag, editable and options', () => {
const barrel = add(entities.barrel(1, 1));
applyEditorEntityData(world, map, barrel, { name: 'Bob', tag: 'b1', editable: true, options: { flip: true } });
expect(barrel.name).equal('Bob');
expect(barrel.tag).equal('b1');
expect(barrel.state & EntityState.Editable).not.equal(0);
expect(barrel.options).eql({ flip: true });
});
it('clears name and tag', () => {
const barrel = add(entities.barrel(1, 1));
applyEditorEntityData(world, map, barrel, { name: 'Bob', tag: 'b1' });
applyEditorEntityData(world, map, barrel, { name: '', tag: '' });
expect(barrel.name).equal(undefined);
expect(barrel.tag).equal(undefined);
});
it('rejects trigger on entity without trigger bounds and changes nothing', () => {
const barrel = add(entities.barrel(1, 1));
expect(() => applyEditorEntityData(world, map, barrel, { name: 'Bob', trigger: { action: 'goToMap' } }))
.throw(`can't have trigger behavior`);
expect(barrel.name).equal(undefined);
expect(barrel.trigger).equal(undefined);
});
it('rejects unknown action and changes nothing', () => {
const sign = add(entities.sign(1, 1));
expect(() => applyEditorEntityData(world, map, sign, { name: 'Bob', interact: { action: 'nope' } }))
.throw('Unknown interact behavior action (nope)');
expect(sign.name).equal(undefined);
});
it('rejects non-object arguments', () => {
const sign = add(entities.sign(1, 1));
expect(() => applyEditorEntityData(world, map, sign, { interact: { action: 'say', args: 'hi' } }))
.throw('interact arguments must be an object');
});
it('does not replace behaviors set by code', () => {
const sign = add(entities.sign(1, 1));
const interact = () => { };
sign.interact = interact;
applyEditorEntityData(world, map, sign, { interact: null });
expect(sign.interact).equal(interact);
});
it('moves entity to loaded layer', () => {
const files = { name: 'test', base: { width: map.width, height: map.height }, layers: new Map([['winter', {}]]) };
loadBaseMap(world, map, files);
applyMapLayers(world, map, files, ['winter']);
const barrel = add(entities.barrel(1, 1));
applyEditorEntityData(world, map, barrel, { layer: 'winter' });
expect(barrel.layer).equal('winter');
expect(barrel.serverFlags! & ServerFlags.Seasonal).not.equal(0);
applyEditorEntityData(world, map, barrel, { layer: '' });
expect(barrel.layer).equal(undefined);
expect(barrel.serverFlags! & ServerFlags.Seasonal).equal(0);
});
it('rejects layer that is not loaded', () => {
const barrel = add(entities.barrel(1, 1));
expect(() => applyEditorEntityData(world, map, barrel, { layer: 'winter' })).throw('is not loaded');
});
});
});