chore: merge Lanana fork

Co-authored-by: Fiereu <contact@fiereu.de>
This commit is contained in:
LananaHWPandFiereu authored and Fiereu committed 2026-05-26 16:14:38 +02:00
1 parent e8f666a37f
commit 9486b83cf4
38 files changed
+56619 -176

No files matched your search

@@ -1,8 +1,8 @@
package de.fiereu.openmmo.common.enums package de.fiereu.openmmo.common.enums
enum class Direction { enum class Direction {
NORTH, DOWN,
SOUTH, UP,
EAST, LEFT,
WEST RIGHT
} }
@@ -10,5 +10,10 @@ enum class PokemonContainer {
AUCTION, AUCTION,
VOID, VOID,
DELETED, DELETED,
EVENT EVENT,
BATTLE_BOX_1,
BATTLE_BOX_2,
GTS,
UNKNOWN_13,
UNKNOWN_14
} }
+620
View File
@@ -0,0 +1,620 @@
const fs = require('fs');
const path = require('path');
const POKEEMERALD = 'D:/openmmo/pokeemerald';
const OUTPUT = 'D:/openmmo/server.game/src/main/kotlin/de/fiereu/openmmo/server/game/world/MapManager.kt';
// ---- Load data ----
const mapGroups = JSON.parse(fs.readFileSync(`${POKEEMERALD}/data/maps/map_groups.json`, 'utf-8'));
const layoutsJson = JSON.parse(fs.readFileSync(`${POKEEMERALD}/data/layouts/layouts.json`, 'utf-8'));
const layouts = layoutsJson.layouts;
// Build layout lookup by name (used by map JSON as "layout": "LAYOUT_xxx")
const layoutByName = {};
for (const l of layouts) {
layoutByName[l.id] = l;
}
// Build map group -> [map names] lookup, track index within group
const groupOrder = mapGroups.group_order;
const mapGroupEntries = {};
for (const group of groupOrder) {
mapGroupEntries[group] = mapGroups[group] || [];
}
// Map name -> { groupIndex, mapIndexWithinGroup }
const mapToAddress = {};
// Secondary lookup that normalizes MAP_LITTLEROOT_TOWN -> LittlerootTown
const mapNameLookup = {};
function normalizeMapName(name) {
return name.replace(/^MAP_/, '').replace(/_/g, '').toLowerCase();
}
for (let gi = 0; gi < groupOrder.length; gi++) {
const group = groupOrder[gi];
const maps = mapGroupEntries[group];
for (let mi = 0; mi < maps.length; mi++) {
mapToAddress[maps[mi]] = { groupIndex: gi, mapIndex: mi, mapName: maps[mi] };
mapNameLookup[normalizeMapName(maps[mi])] = mapToAddress[maps[mi]];
}
}
function resolveMap(name) {
return mapToAddress[name] || mapNameLookup[normalizeMapName(name)];
}
// ---- Known palette mappings from capture ----
// tileset_pair_key (primary_secondary) -> [paletteIdx1, paletteIdx2]
const knownPalettes = {
'gTileset_Building_gTileset_BrendansMaysHouse': [116, 142],
'gTileset_Building_gTileset_Lab': [116, 143],
'gTileset_Building_gTileset_ContestHall': [106, 123],
'gTileset_Building_gTileset_GenericBuilding': [98, 128],
'gTileset_Building_gTileset_PlayersRoom': [100, 134],
'gTileset_Building_gTileset_PokemonCenter': [87, 121],
'gTileset_Building_gTileset_PokemonCenterHoenn': [87, 121],
'gTileset_Building_gTileset_PokemonCenterContest': [87, 121],
'gTileset_Building_gTileset_MauvilleGym': [84, 120],
'gTileset_Building_gTileset_DewfordGym': [90, 124],
'gTileset_Building_gTileset_RustboroGym': [82, 118],
'gTileset_Building_gTileset_LilycoveContestLobby': [104, 136],
'gTileset_Building_gTileset_MossdeepGym': [108, 138],
'gTileset_Building_gTileset_SootopolisGym': [110, 140],
'gTileset_Building_gTileset_SlateportGym': [86, 122],
'gTileset_Building_gTileset_FortreeGym': [94, 126],
'gTileset_Building_gTileset_LavaridgeGym': [92, 128],
'gTileset_Building_gTileset_ShoalCaveGym': [96, 130],
'gTileset_Building_gTileset_Cave': [82, 144],
'gTileset_Building_gTileset_SeaCave': [82, 144],
'gTileset_Building_gTileset_OceanicMuseum': [102, 135],
'gTileset_Building_gTileset_ArtisanCave': [84, 146],
'gTileset_General_gTileset_Petalburg': [100, 101],
'gTileset_General_gTileset_Route104': [92, 113],
'gTileset_General_gTileset_Route110': [92, 115],
'gTileset_General_gTileset_Route119': [94, 117],
'gTileset_General_gTileset_Fortree': [94, 126],
'gTileset_General_gTileset_Mauville': [84, 120],
'gTileset_General_gTileset_Slateport': [86, 122],
'gTileset_General_gTileset_Lilycove': [104, 136],
'gTileset_General_gTileset_Mossdeep': [108, 138],
'gTileset_General_gTileset_Pacifidlog': [112, 148],
'gTileset_General_gTileset_Sootopolis': [110, 140],
'gTileset_General_gTileset_EverGrande': [96, 130],
'gTileset_General_gTileset_Rustboro': [82, 118],
'gTileset_General_gTileset_Dewford': [90, 124],
'gTileset_General_gTileset_Lavaridge': [92, 128],
'gTileset_General_gTileset_Fallarbor': [88, 126],
'gTileset_General_gTileset_Verdanturf': [96, 132],
'gTileset_General_gTileset_PacifidlogWait': [112, 148],
'gTileset_General_gTileset_BattleFrontier': [114, 150],
'gTileset_General_gTileset_Oldale': [98, 128],
'gTileset_Cave_gTileset_Cave': [82, 144],
'gTileset_Cave_gTileset_SeaCave': [82, 144],
'gTileset_Cave_gTileset_IcyCave': [80, 140],
'gTileset_Cave_gTileset_Desert': [88, 146],
'gTileset_Cave_gTileset_Underwater': [86, 148],
'gTileset_Cave_gTileset_GraniteCave': [84, 146],
'gTileset_Cave_gTileset_MagmaHideout': [85, 147],
'gTileset_Cave_gTileset_AquaHideout': [86, 148],
};
// Map type -> default palette ranges
function guessPalette(primaryTileset, secondaryTileset, mapType) {
const key = `${primaryTileset}_${secondaryTileset}`;
if (knownPalettes[key]) return knownPalettes[key];
// Assign unique IDs based on tileset names (stable hash-like)
let h1 = 0, h2 = 0;
const s = key;
for (let i = 0; i < s.length; i++) {
h1 = (h1 * 31 + s.charCodeAt(i)) & 0xFFFF;
h2 = (h2 * 17 + s.charCodeAt(i)) & 0xFFFF;
}
return [80 + (h1 % 60), 80 + (h2 % 60)];
}
// ---- Direction mapping ----
const dirMap = { south: 1, north: 2, west: 3, east: 4 };
// Movement type name -> value lookup
const movementTypes = {
'MOVEMENT_TYPE_NONE': 0,
'MOVEMENT_TYPE_LOOK_AROUND': 1,
'MOVEMENT_TYPE_WANDER_AROUND': 2,
'MOVEMENT_TYPE_WANDER_UP_AND_DOWN': 3,
'MOVEMENT_TYPE_WANDER_DOWN_AND_UP': 4,
'MOVEMENT_TYPE_WANDER_LEFT_AND_RIGHT': 5,
'MOVEMENT_TYPE_WANDER_RIGHT_AND_LEFT': 6,
'MOVEMENT_TYPE_FACE_UP': 7,
'MOVEMENT_TYPE_FACE_DOWN': 8,
'MOVEMENT_TYPE_FACE_LEFT': 9,
'MOVEMENT_TYPE_FACE_RIGHT': 10,
'MOVEMENT_TYPE_PLAYER': 11,
'MOVEMENT_TYPE_BERRY_TREE_GROWTH': 12,
'MOVEMENT_TYPE_FACE_DOWN_AND_UP': 13,
'MOVEMENT_TYPE_FACE_LEFT_AND_RIGHT': 14,
'MOVEMENT_TYPE_FACE_UP_AND_LEFT': 15,
'MOVEMENT_TYPE_FACE_UP_AND_RIGHT': 16,
'MOVEMENT_TYPE_FACE_DOWN_AND_LEFT': 17,
'MOVEMENT_TYPE_FACE_DOWN_AND_RIGHT': 18,
'MOVEMENT_TYPE_FACE_DOWN_UP_AND_LEFT': 19,
'MOVEMENT_TYPE_FACE_DOWN_UP_AND_RIGHT': 20,
'MOVEMENT_TYPE_FACE_UP_LEFT_AND_RIGHT': 21,
'MOVEMENT_TYPE_FACE_DOWN_LEFT_AND_RIGHT': 22,
'MOVEMENT_TYPE_ROTATE_COUNTERCLOCKWISE': 23,
'MOVEMENT_TYPE_ROTATE_CLOCKWISE': 24,
'MOVEMENT_TYPE_WALK_UP_AND_DOWN': 25,
'MOVEMENT_TYPE_WALK_DOWN_AND_UP': 26,
'MOVEMENT_TYPE_WALK_LEFT_AND_RIGHT': 27,
'MOVEMENT_TYPE_WALK_RIGHT_AND_LEFT': 28,
'MOVEMENT_TYPE_WALK_IN_PLACE_DOWN': 64,
'MOVEMENT_TYPE_WALK_IN_PLACE_UP': 65,
'MOVEMENT_TYPE_WALK_IN_PLACE_LEFT': 66,
'MOVEMENT_TYPE_WALK_IN_PLACE_RIGHT': 67,
'MOVEMENT_TYPE_JOG_IN_PLACE_DOWN': 68,
'MOVEMENT_TYPE_JOG_IN_PLACE_UP': 69,
'MOVEMENT_TYPE_JOG_IN_PLACE_LEFT': 70,
'MOVEMENT_TYPE_JOG_IN_PLACE_RIGHT': 71,
'MOVEMENT_TYPE_RUN_IN_PLACE_DOWN': 72,
'MOVEMENT_TYPE_RUN_IN_PLACE_UP': 73,
'MOVEMENT_TYPE_RUN_IN_PLACE_LEFT': 74,
'MOVEMENT_TYPE_RUN_IN_PLACE_RIGHT': 75,
'MOVEMENT_TYPE_INVISIBLE': 76,
};
// Graphics ID name -> value lookup (from event_objects.h)
const gfxIds = {};
(function buildGfxTable() {
const entries = [
['OBJ_EVENT_GFX_BRENDAN_NORMAL',0],['OBJ_EVENT_GFX_BRENDAN_MACH_BIKE',1],
['OBJ_EVENT_GFX_BRENDAN_SURFING',2],['OBJ_EVENT_GFX_BRENDAN_FIELD_MOVE',3],
['OBJ_EVENT_GFX_QUINTY_PLUMP',4],['OBJ_EVENT_GFX_NINJA_BOY',5],
['OBJ_EVENT_GFX_TWIN',6],['OBJ_EVENT_GFX_BOY_1',7],
['OBJ_EVENT_GFX_GIRL_1',8],['OBJ_EVENT_GFX_BOY_2',9],
['OBJ_EVENT_GFX_GIRL_2',10],['OBJ_EVENT_GFX_LITTLE_BOY',11],
['OBJ_EVENT_GFX_LITTLE_GIRL',12],['OBJ_EVENT_GFX_BOY_3',13],
['OBJ_EVENT_GFX_GIRL_3',14],['OBJ_EVENT_GFX_RICH_BOY',15],
['OBJ_EVENT_GFX_WOMAN_1',16],['OBJ_EVENT_GFX_FAT_MAN',17],
['OBJ_EVENT_GFX_POKEFAN_F',18],['OBJ_EVENT_GFX_MAN_1',19],
['OBJ_EVENT_GFX_WOMAN_2',20],['OBJ_EVENT_GFX_EXPERT_M',21],
['OBJ_EVENT_GFX_EXPERT_F',22],['OBJ_EVENT_GFX_MAN_2',23],
['OBJ_EVENT_GFX_WOMAN_3',24],['OBJ_EVENT_GFX_POKEFAN_M',25],
['OBJ_EVENT_GFX_WOMAN_4',26],['OBJ_EVENT_GFX_COOK',27],
['OBJ_EVENT_GFX_LINK_RECEPTIONIST',28],['OBJ_EVENT_GFX_OLD_MAN',29],
['OBJ_EVENT_GFX_OLD_WOMAN',30],['OBJ_EVENT_GFX_CAMPER',31],
['OBJ_EVENT_GFX_PICNICKER',32],['OBJ_EVENT_GFX_MAN_3',33],
['OBJ_EVENT_GFX_WOMAN_5',34],['OBJ_EVENT_GFX_YOUNGSTER',35],
['OBJ_EVENT_GFX_BUG_CATCHER',36],['OBJ_EVENT_GFX_PSYCHIC_M',37],
['OBJ_EVENT_GFX_SCHOOL_KID_M',38],['OBJ_EVENT_GFX_MANIAC',39],
['OBJ_EVENT_GFX_HEX_MANIAC',40],['OBJ_EVENT_GFX_RAYQUAZA_STILL',41],
['OBJ_EVENT_GFX_SWIMMER_M',42],['OBJ_EVENT_GFX_SWIMMER_F',43],
['OBJ_EVENT_GFX_BLACK_BELT',44],['OBJ_EVENT_GFX_BEAUTY',45],
['OBJ_EVENT_GFX_SCIENTIST_1',46],['OBJ_EVENT_GFX_LASS',47],
['OBJ_EVENT_GFX_GENTLEMAN',48],['OBJ_EVENT_GFX_SAILOR',49],
['OBJ_EVENT_GFX_FISHERMAN',50],['OBJ_EVENT_GFX_RUNNING_TRIATHLETE_M',51],
['OBJ_EVENT_GFX_RUNNING_TRIATHLETE_F',52],['OBJ_EVENT_GFX_TUBER_F',53],
['OBJ_EVENT_GFX_TUBER_M',54],['OBJ_EVENT_GFX_HIKER',55],
['OBJ_EVENT_GFX_CYCLING_TRIATHLETE_M',56],['OBJ_EVENT_GFX_CYCLING_TRIATHLETE_F',57],
['OBJ_EVENT_GFX_NURSE',58],['OBJ_EVENT_GFX_ITEM_BALL',59],
['OBJ_EVENT_GFX_BERRY_TREE',60],['OBJ_EVENT_GFX_BERRY_TREE_EARLY_STAGES',61],
['OBJ_EVENT_GFX_BERRY_TREE_LATE_STAGES',62],['OBJ_EVENT_GFX_BRENDAN_ACRO_BIKE',63],
['OBJ_EVENT_GFX_PROF_BIRCH',64],['OBJ_EVENT_GFX_MAN_4',65],
['OBJ_EVENT_GFX_MAN_5',66],['OBJ_EVENT_GFX_REPORTER_M',67],
['OBJ_EVENT_GFX_REPORTER_F',68],['OBJ_EVENT_GFX_BARD',69],
['OBJ_EVENT_GFX_ANABEL',70],['OBJ_EVENT_GFX_TUCKER',71],
['OBJ_EVENT_GFX_GRETA',72],['OBJ_EVENT_GFX_SPENSER',73],
['OBJ_EVENT_GFX_NOLAND',74],['OBJ_EVENT_GFX_LUCY',75],
['OBJ_EVENT_GFX_MART_EMPLOYEE',83],['OBJ_EVENT_GFX_SCIENTIST_2',115],
['OBJ_EVENT_GFX_MOM',215],['OBJ_EVENT_GFX_PROF_BIRCH',64],
['OBJ_EVENT_GFX_NORMAN',129],['OBJ_EVENT_GFX_VIGOROTH_CARRYING_BOX',95],
['OBJ_EVENT_GFX_VIGOROTH_FACING_AWAY',96],['OBJ_EVENT_GFX_RIVAL_BRENDAN_NORMAL',100],
['OBJ_EVENT_GFX_RIVAL_MAY_NORMAL',105],['OBJ_EVENT_GFX_TRUCK',94],
['OBJ_EVENT_GFX_VAR_0',240],
];
for (const [k, v] of entries) gfxIds[k] = v;
})();
const facingDirection = { south: 0, north: 1, west: 2, east: 3 };
function movementToFaceDir(movementType) {
// Extract initial facing direction from movement type
if (movementType >= 7 && movementType <= 10) return movementType - 7; // FACE_UP=7→1, FACE_DOWN=8→0, FACE_LEFT=9→2, FACE_RIGHT=10→3
if (movementType >= 64 && movementType <= 67) return movementType - 64; // WALK_IN_PLACE_DOWN=64→0, etc.
if (movementType >= 68 && movementType <= 71) return movementType - 68; // JOG_IN_PLACE_DOWN=68→0, etc.
if (movementType >= 72 && movementType <= 75) return movementType - 72; // RUN_IN_PLACE_DOWN=72→0, etc.
return 0; // default DOWN
}
// ---- Border tile reader ----
function readBorderTiles(borderFilepath) {
const fullPath = `${POKEEMERALD}/${borderFilepath}`;
if (!fs.existsSync(fullPath)) return null;
const buf = fs.readFileSync(fullPath);
const tiles = [];
for (let i = 0; i < buf.length; i += 2) {
if (i + 1 < buf.length) {
const val = buf.readUInt16LE(i);
tiles.push(val);
}
}
return tiles;
}
// ---- Weather/lighting/mapType mapping ----
const weatherMap = {
WEATHER_NONE: 'Weather.IN_HOUSE_WEATHER',
WEATHER_SUNNY: 'Weather.REGULAR_WEATHER',
WEATHER_RAIN: 'Weather.RAINY_WEATHER',
WEATHER_SNOW: 'Weather.THREE_SNOW_FLAKES',
WEATHER_FOG_HORIZONTAL: 'Weather.STEADY_MIST',
WEATHER_FOG_DIAGONAL: 'Weather.STEADY_MIST',
WEATHER_SHADE: 'Weather.CLOUDY',
WEATHER_UNDERWATER_BUBBLES: 'Weather.UNDERWATER_MIST',
WEATHER_VOLCANIC_ASH: 'Weather.DENSE_BRIGHT_MIST',
};
const lightingMap = {
MAP_TYPE_INDOOR: 'Lighting.REGULAR',
MAP_TYPE_TOWN: 'Lighting.REGULAR',
MAP_TYPE_ROUTE: 'Lighting.REGULAR',
};
const mapTypeMap = {
MAP_TYPE_INDOOR: 'MapType.INSIDE',
MAP_TYPE_TOWN: 'MapType.CITY',
MAP_TYPE_CITY: 'MapType.CITY',
MAP_TYPE_ROUTE: 'MapType.ROUTE',
MAP_TYPE_UNDERGROUND: 'MapType.UNDERGROUND',
MAP_TYPE_UNDERWATER: 'MapType.UNDERWATER',
MAP_TYPE_OCEAN_ROUTE: 'MapType.ROUTE',
MAP_TYPE_SECRET_BASE: 'MapType.SECRET_BASE',
};
const encounterMap = {
MAP_TYPE_INDOOR: 'EncounterType.RANDOM',
MAP_TYPE_TOWN: 'EncounterType.GYM_STYLE',
MAP_TYPE_CITY: 'EncounterType.GYM_STYLE',
MAP_TYPE_ROUTE: 'EncounterType.RANDOM',
MAP_TYPE_UNDERGROUND: 'EncounterType.RANDOM',
MAP_TYPE_UNDERWATER: 'EncounterType.UNKNOWN_0x03',
MAP_TYPE_OCEAN_ROUTE: 'EncounterType.RANDOM',
MAP_TYPE_SECRET_BASE: 'EncounterType.UNKNOWN_0x03',
};
// ---- Generate ----
const allEntries = [];
// For each map in each group
for (let gi = 0; gi < groupOrder.length; gi++) {
const group = groupOrder[gi];
const maps = mapGroupEntries[group];
if (!maps) continue;
for (let mi = 0; mi < maps.length; mi++) {
const mapName = maps[mi];
const mapDir = `${POKEEMERALD}/data/maps/${mapName}`;
const mapJsonPath = `${mapDir}/map.json`;
if (!fs.existsSync(mapJsonPath)) continue;
const mapJson = JSON.parse(fs.readFileSync(mapJsonPath, 'utf-8'));
const layoutId = mapJson.layout;
const layout = layoutByName[layoutId];
if (!layout) {
console.warn(` Layout ${layoutId} not found for map ${mapName}`);
continue;
}
const width = layout.width;
const height = layout.height;
const primaryTileset = layout.primary_tileset;
const secondaryTileset = layout.secondary_tileset;
const mapType = mapJson.map_type || 'MAP_TYPE_INDOOR';
const mapTypeStr = mapTypeMap[mapType] || 'MapType.INSIDE';
const weatherStr = weatherMap[mapJson.weather] || 'Weather.REGULAR_WEATHER';
const encounterStr = encounterMap[mapType] || 'EncounterType.RANDOM';
// Palette
const [pal1, pal2] = guessPalette(primaryTileset, secondaryTileset, mapType);
// Per-map overrides (from real server captures)
let mapUnknownShort = 405;
let mapUnknownByte = 0;
if (mapJson.id === 'MAP_LITTLEROOT_TOWN_PROFESSOR_BIRCHS_LAB') {
mapUnknownShort = 383;
}
// Border tiles
let borderTilesStr = 'listOf(Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0))';
if (layout.border_filepath) {
const borderVals = readBorderTiles(layout.border_filepath);
if (borderVals && borderVals.length >= 4) {
borderTilesStr = `listOf(Tile2D(0x${borderVals[0].toString(16).padStart(4, '0').toUpperCase()}, 0), Tile2D(0x${borderVals[1].toString(16).padStart(4, '0').toUpperCase()}, 0), Tile2D(0x${borderVals[2].toString(16).padStart(4, '0').toUpperCase()}, 0), Tile2D(0x${borderVals[3].toString(16).padStart(4, '0').toUpperCase()}, 0))`;
}
}
// Connections
const connections = mapJson.connections || [];
const connStrs = connections.map(c => {
const dir = dirMap[c.direction] || 2;
const addr = resolveMap(c.map);
if (!addr) return null;
const bank = addr.groupIndex + 50;
const mapNum = addr.mapIndex;
return `GbaConnection(direction = ${dir}, unknown = 0, targetBank = ${bank}, targetMap = ${mapNum})`;
}).filter(Boolean);
// Warps
const warps = mapJson.warp_events || [];
const warpStrs = warps.map(w => {
const destAddr = resolveMap(w.dest_map);
if (!destAddr) return null;
const destBank = destAddr.groupIndex + 50;
const destMapNum = destAddr.mapIndex;
// Find dest warp position in destination map
const destMapDir = `${POKEEMERALD}/data/maps/${destAddr.mapName}`;
let destX = w.x, destY = w.y; // fallback
try {
const destMapJson = JSON.parse(fs.readFileSync(`${destMapDir}/map.json`, 'utf-8'));
const destWarps = destMapJson.warp_events || [];
const targetWarpIdx = parseInt(w.dest_warp_id);
if (targetWarpIdx >= 0 && targetWarpIdx < destWarps.length) {
const targetWarp = destWarps[targetWarpIdx];
destX = targetWarp.x;
destY = targetWarp.y;
}
} catch (e) {
// use fallback
}
return `WarpTile(x = ${w.x}, y = ${w.y}, targetRegionId = 1, targetBankId = ${destBank}, targetMapId = ${destMapNum}, targetX = ${destX}, targetY = ${destY})`;
}).filter(Boolean);
// NPCs / object events
const npcs = mapJson.object_events || [];
// Per-map override: NPC entity indices that should be visible despite FLAG_HIDE_* being SET at game start
const defaultVisibleNpcs = {
"LittlerootTown_MaysHouse_1F": [0],
"LittlerootTown_BrendansHouse_1F": [3, 5],
"LittlerootTown_ProfessorBirchsLab": [0],
};
const visibleIndices = defaultVisibleNpcs[mapName] || null;
const npcStrs = [];
npcs.forEach((npc, idx) => {
const isVisible = visibleIndices !== null
? visibleIndices.includes(idx)
: npc.flag === "0";
if (!isVisible) return;
const gfxName = npc.graphics_id || 'OBJ_EVENT_GFX_BOY_1';
const gfxId = gfxIds[gfxName] || 0;
const moveName = npc.movement_type || 'MOVEMENT_TYPE_NONE';
const moveVal = movementTypes[moveName] || 0;
const rangeX = parseInt(npc.movement_range_x) || 0;
const rangeY = parseInt(npc.movement_range_y) || 0;
const faceDir = movementToFaceDir(moveVal);
const trainType = npc.trainer_type === 'TRAINER_TYPE_NONE' ? 0 : 1;
const script = npc.script || "0x0";
npcStrs.push(`NpcDef(entityIdx = ${idx}, graphicsId = ${gfxId}, x = ${npc.x}, y = ${npc.y}, elevation = ${npc.elevation || 3}, movementType = ${moveVal}, movementRangeX = ${rangeX}, movementRangeY = ${rangeY}, trainerType = ${trainType}, facing = ${faceDir}, script = "${script}")`);
});
const npcsStr = npcStrs.length > 0
? `listOf(\n${npcStrs.map(s => ' ' + s).join(',\n')},\n )`
: 'emptyList()';
// bg_events (signs, PCs, TVs, bookshelves, etc.)
const rawBgEvents = mapJson.bg_events || [];
const bgEventStrs = rawBgEvents.map(be =>
`BgEventDef(x = ${be.x}, y = ${be.y}, facingDir = "${be.player_facing_dir || "BG_EVENT_PLAYER_FACING_ANY"}", script = "${be.script}")`
);
const bgEventsStr = bgEventStrs.length > 0
? `listOf(\n${bgEventStrs.map(s => ' ' + s).join(',\n')},\n )`
: 'emptyList()';
const warpsStr = warpStrs.length > 0
? `listOf(\n${warpStrs.map(s => ' ' + s).join(',\n')},\n )`
: 'emptyList()';
const connsStr = connStrs.length > 0
? `listOf(\n${connStrs.map(s => ' ' + s).join(',\n')},\n )`
: 'emptyList()';
// Region: always 1 for now
const region = 1;
const bank = gi + 50;
// Generate MapDef
const comment = `// ${mapName} (${mapJson.id})`;
const def = `
MapDef(
regionId = ${region}, bankId = ${bank}, mapId = ${mi},
width = ${width}, height = ${height},
paletteIdx1 = ${pal1}, paletteIdx2 = ${pal2},
unknownShort = ${mapUnknownShort}, unknownByte = ${mapUnknownByte},
borderTiles = ${borderTilesStr},
lighting = Lighting.REGULAR,
weather = ${weatherStr},
mapType = ${mapTypeStr},
encounterType = ${encounterStr},
connections = ${connsStr},
warps = ${warpsStr},
npcs = ${npcsStr},
bgEvents = ${bgEventsStr},
)`;
allEntries.push({ mapName, group, bank, mi, def, comment });
}
}
// ---- Generate Kotlin file ----
let kt = `package de.fiereu.openmmo.server.game.world
import de.fiereu.openmmo.common.Tile2D
import de.fiereu.openmmo.common.enums.EncounterType
import de.fiereu.openmmo.common.enums.Lighting
import de.fiereu.openmmo.common.enums.MapType
import de.fiereu.openmmo.common.enums.Weather
import de.fiereu.openmmo.protocols.game.packets.LoadMapPacket
import de.fiereu.openmmo.protocols.game.packets.MapData
import de.fiereu.openmmo.protocols.game.packets.MapData.GbaConnection
class MapDef(
val regionId: Byte,
val bankId: Byte,
val mapId: Byte,
val width: Int = 20,
val height: Int = 15,
val paletteIdx1: Int = 12,
val paletteIdx2: Int = 14,
val borderWidth: Int = 2,
val borderHeight: Int = 2,
val unknownShort: Int = 0,
val unknownByte: Int = 0,
val borderTiles: List<Tile2D> = listOf(Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0), Tile2D(8, 0)),
val lighting: Lighting = Lighting.REGULAR,
val weather: Weather = Weather.REGULAR_WEATHER,
val mapType: MapType = MapType.CITY,
val encounterType: EncounterType = EncounterType.RANDOM,
val wildEncounters: List<WildEncounterTable> = emptyList(),
val connections: List<GbaConnection> = emptyList(),
val warps: List<WarpTile> = emptyList(),
val npcs: List<NpcDef> = emptyList(),
val bgEvents: List<BgEventDef> = emptyList(),
)
data class WildEncounterTable(
val encounterRate: Int,
val pokemon: List<WildPokemon>,
)
data class WildPokemon(
val dexId: Int,
val minLevel: Int,
val maxLevel: Int,
val weight: Int,
)
data class WarpTile(
val x: Int,
val y: Int,
val targetRegionId: Byte,
val targetBankId: Byte,
val targetMapId: Byte,
val targetX: Int,
val targetY: Int,
val facingDirection: de.fiereu.openmmo.common.enums.Direction? = null,
)
data class NpcDef(
val entityIdx: Int,
val graphicsId: Int,
val x: Int,
val y: Int,
val elevation: Int,
val movementType: Int,
val movementRangeX: Int,
val movementRangeY: Int,
val trainerType: Int,
val facing: Int,
val script: String = "0x0",
)
data class BgEventDef(
val x: Int,
val y: Int,
val facingDir: String,
val script: String,
)
object MapManager {
private val maps = mutableMapOf<String, MapDef>()
init {
${Array.from({ length: Math.ceil(allEntries.length / 60) }, (_, i) => ` registerDefaultMaps${i}()`).join('\n')}
}
${Array.from({ length: Math.ceil(allEntries.length / 60) }, (_, i) => {
const chunk = allEntries.slice(i * 60, (i + 1) * 60);
return ` private fun registerDefaultMaps${i}() {
val allMaps = listOf(
${chunk.map(e => ` ${e.comment}${e.def},`).join('\n')}
)
allMaps.forEach { registerMap(it) }
}`;
}).join('\n\n')}
`;
kt += `
fun registerMap(map: MapDef) {
maps[key(map.regionId, map.bankId, map.mapId)] = map
}
fun getMap(regionId: Byte, bankId: Byte, mapId: Byte): MapDef? {
return maps[key(regionId, bankId, mapId)]
}
fun createLoadMapPacket(
map: MapDef,
reloadPlayer: Boolean = false,
deleteCache: Boolean = false,
): LoadMapPacket {
return LoadMapPacket(
reloadPlayer = reloadPlayer,
deleteCache = deleteCache,
regionId = map.regionId.toInt(),
bankId = map.bankId.toInt(),
mapId = map.mapId.toInt(),
mapData =
MapData.GbaMapData(
width = map.width,
height = map.height,
paletteIdx1 = map.paletteIdx1,
paletteIdx2 = map.paletteIdx2,
borderWidth = map.borderWidth,
borderHeight = map.borderHeight,
unknownShort = map.unknownShort,
unknownByte = map.unknownByte,
borderTiles = map.borderTiles,
lighting = map.lighting,
weather = map.weather,
mapType = map.mapType,
encounterType = map.encounterType,
connections = map.connections,
),
)
}
data class EncounterResult(val dexId: Int, val level: Int)
fun getEncounter(map: MapDef): EncounterResult? {
val tables = map.wildEncounters
if (tables.isEmpty()) return null
val totalWeight = tables.sumOf { it.encounterRate }
if (totalWeight <= 0) return null
var roll = (0 until totalWeight).random()
for (table in tables) {
roll -= table.encounterRate
if (roll < 0) {
val pokemon = table.pokemon
val totalPokeWeight = pokemon.sumOf { it.weight }
if (totalPokeWeight <= 0) return null
var pokeRoll = (0 until totalPokeWeight).random()
for (poke in pokemon) {
pokeRoll -= poke.weight
if (pokeRoll < 0) {
val level = (poke.minLevel..poke.maxLevel).random()
return EncounterResult(poke.dexId, level)
}
}
}
}
return null
}
private fun key(regionId: Byte, bankId: Byte, mapId: Byte) = "$regionId:$bankId:$mapId"
}
`;
fs.writeFileSync(OUTPUT, kt, 'utf-8');
console.log(`Generated ${allEntries.length} map entries -> ${OUTPUT}`);
// Stats
const groups = {};
for (const e of allEntries) {
groups[e.group] = (groups[e.group] || 0) + 1;
}
console.log('\nMaps per group:');
for (const [g, c] of Object.entries(groups)) {
console.log(` ${g}: ${c}`);
}
Vendored Executable → Regular
View File
File mode changed.
@@ -5,14 +5,48 @@ import de.fiereu.openmmo.protocols.game.packets.CharacterListDeserializer
import de.fiereu.openmmo.protocols.game.packets.CharacterListSerializer import de.fiereu.openmmo.protocols.game.packets.CharacterListSerializer
import de.fiereu.openmmo.protocols.game.packets.ChatMessageDeserialize import de.fiereu.openmmo.protocols.game.packets.ChatMessageDeserialize
import de.fiereu.openmmo.protocols.game.packets.ChatMessageSerialize import de.fiereu.openmmo.protocols.game.packets.ChatMessageSerialize
import de.fiereu.openmmo.protocols.game.packets.CreateCharacterDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogChoiceDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogChoiceSerializer
import de.fiereu.openmmo.protocols.game.packets.DialogDataDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogDataSerializer
import de.fiereu.openmmo.protocols.game.packets.DialogOptionDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogOptionSerializer
import de.fiereu.openmmo.protocols.game.packets.DialogStateDeserializer
import de.fiereu.openmmo.protocols.game.packets.DialogStateSerializer
import de.fiereu.openmmo.protocols.game.packets.EntityInteractDeserializer
import de.fiereu.openmmo.protocols.game.packets.EntityInteractSerializer
import de.fiereu.openmmo.protocols.game.packets.EntityLeaveDeserializer
import de.fiereu.openmmo.protocols.game.packets.EntityLeaveSerializer
import de.fiereu.openmmo.protocols.game.packets.EntityMovePacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.EntityMovePacketSerializer
import de.fiereu.openmmo.protocols.game.packets.FaceDirectionDeserializer
import de.fiereu.openmmo.protocols.game.packets.FaceDirectionSerializer
import de.fiereu.openmmo.protocols.game.packets.InteractiveResponseDeserializer
import de.fiereu.openmmo.protocols.game.packets.InteractiveSerializer
import de.fiereu.openmmo.protocols.game.packets.JoinPacketDeserializer import de.fiereu.openmmo.protocols.game.packets.JoinPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.JoinPacketSerializer import de.fiereu.openmmo.protocols.game.packets.JoinPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.JoinResponseDeserializer import de.fiereu.openmmo.protocols.game.packets.JoinResponseDeserializer
import de.fiereu.openmmo.protocols.game.packets.JoinResponseSerializer import de.fiereu.openmmo.protocols.game.packets.JoinResponseSerializer
import de.fiereu.openmmo.protocols.game.packets.KeepAlivePacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.KeepAlivePacketSerializer
import de.fiereu.openmmo.protocols.game.packets.LoadEntityDeserializer import de.fiereu.openmmo.protocols.game.packets.LoadEntityDeserializer
import de.fiereu.openmmo.protocols.game.packets.LoadEntitySerializer import de.fiereu.openmmo.protocols.game.packets.LoadEntitySerializer
import de.fiereu.openmmo.protocols.game.packets.LoadMapPacketDeserializer import de.fiereu.openmmo.protocols.game.packets.LoadMapPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.LoadMapPacketSerializer import de.fiereu.openmmo.protocols.game.packets.LoadMapPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionAckDeserializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionAckSerializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionDeserializer
import de.fiereu.openmmo.protocols.game.packets.MapTransitionSerializer
import de.fiereu.openmmo.protocols.game.packets.MovementPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.MovementPacketSerializer
import de.fiereu.openmmo.protocols.game.packets.NpcAnimationDeserializer
import de.fiereu.openmmo.protocols.game.packets.NpcAnimationSerializer
import de.fiereu.openmmo.protocols.game.packets.NpcSpawnDeserializer
import de.fiereu.openmmo.protocols.game.packets.NpcSpawnSerializer
import de.fiereu.openmmo.protocols.game.packets.NpcUpdateDeserializer
import de.fiereu.openmmo.protocols.game.packets.NpcUpdateSerializer
import de.fiereu.openmmo.protocols.game.packets.NullPacketDeserializer
import de.fiereu.openmmo.protocols.game.packets.PokemonContainerDeserializer import de.fiereu.openmmo.protocols.game.packets.PokemonContainerDeserializer
import de.fiereu.openmmo.protocols.game.packets.PokemonContainerSerializer import de.fiereu.openmmo.protocols.game.packets.PokemonContainerSerializer
import de.fiereu.openmmo.protocols.game.packets.RenderScreenDeserializer import de.fiereu.openmmo.protocols.game.packets.RenderScreenDeserializer
@@ -25,6 +59,7 @@ import de.fiereu.openmmo.protocols.game.packets.SelectCharacterDeserializer
import de.fiereu.openmmo.protocols.game.packets.SelectCharacterSerializer import de.fiereu.openmmo.protocols.game.packets.SelectCharacterSerializer
import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterDeserializer import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterDeserializer
import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterSerializer import de.fiereu.openmmo.protocols.game.packets.SelectedCharacterSerializer
import de.fiereu.openmmo.protocols.game.packets.TokenPayloadSerializer
import de.fiereu.openmmo.protocols.incomingPacket import de.fiereu.openmmo.protocols.incomingPacket
import de.fiereu.openmmo.protocols.outgoingPacket import de.fiereu.openmmo.protocols.outgoingPacket
@@ -39,34 +74,149 @@ abstract class GameProtocol : Protocol() {
class GameServerProtocol : GameProtocol() { class GameServerProtocol : GameProtocol() {
init { init {
// Game server: client sends 0x01 as first packet (client info / "JoinGame")
incomingPacket(0x01u, JoinPacketDeserializer()) incomingPacket(0x01u, JoinPacketDeserializer())
outgoingPacket(0x01u, JoinResponseSerializer()) outgoingPacket(0x01u, JoinResponseSerializer())
incomingPacket(0x02u, RequestCharactersDeserializer()) incomingPacket(0x02u, RequestCharactersDeserializer())
outgoingPacket(0x02u, CharacterListSerializer()) outgoingPacket(0x02u, CharacterListSerializer())
incomingPacket(0x03u, CreateCharacterDeserializer())
incomingPacket(0x04u, SelectCharacterDeserializer()) incomingPacket(0x04u, SelectCharacterDeserializer())
outgoingPacket(0x04u, SelectedCharacterSerializer()) outgoingPacket(0x04u, SelectedCharacterSerializer())
incomingPacket(0x05u, RequestPlayerDeserializePacket()) incomingPacket(0x05u, RequestPlayerDeserializePacket())
outgoingPacket(0x05u, LoadEntitySerializer()) outgoingPacket(0x05u, LoadEntitySerializer())
incomingPacket(0x06u, MovementPacketDeserializer()) // Client movement
outgoingPacket(0xEAu, EntityMovePacketSerializer()) // Entity move broadcast
incomingPacket(0x07u, FaceDirectionDeserializer()) // Face direction
outgoingPacket(0x08u, EntityLeaveSerializer()) // Entity leave area
incomingPacket(0x09u, ChatMessageDeserialize()) // Chat message
outgoingPacket(0x09u, ChatMessageSerialize()) outgoingPacket(0x09u, ChatMessageSerialize())
outgoingPacket(0x10u, LoadMapPacketSerializer())
outgoingPacket(0x13u, PokemonContainerSerializer()) outgoingPacket(0x10u, LoadMapPacketSerializer()) // Load map
outgoingPacket(0xB4u, RenderScreenSerializer()) incomingPacket(0x10u, LoadMapPacketDeserializer())
outgoingPacket(0x13u, PokemonContainerSerializer()) // Pokemon data
incomingPacket(0x13u, PokemonContainerDeserializer())
incomingPacket(0x20u, NullPacketDeserializer()) // Token exchange (heartbeat/token)
outgoingPacket(0x20u, TokenPayloadSerializer())
outgoingPacket(0xB4u, RenderScreenSerializer()) // Render screen
incomingPacket(0xB4u, RenderScreenDeserializer())
incomingPacket(0xC2u, KeepAlivePacketDeserializer()) // Keepalive echo
outgoingPacket(0xC2u, KeepAlivePacketSerializer())
incomingPacket(0x0Du, DialogDataDeserializer())
outgoingPacket(0x0Du, DialogDataSerializer())
incomingPacket(0x0Eu, DialogStateDeserializer())
outgoingPacket(0x0Eu, DialogStateSerializer())
outgoingPacket(0x11u, NpcUpdateSerializer())
incomingPacket(0x12u, NpcSpawnDeserializer())
outgoingPacket(0x12u, NpcSpawnSerializer())
incomingPacket(0x1Bu, MapTransitionDeserializer())
outgoingPacket(0x1Bu, MapTransitionSerializer())
incomingPacket(0x21u, InteractiveResponseDeserializer())
outgoingPacket(0x21u, InteractiveSerializer())
incomingPacket(0x22u, EntityInteractDeserializer()) // Entity interaction start
outgoingPacket(0x22u, EntityInteractSerializer())
incomingPacket(0x25u, DialogChoiceDeserializer())
outgoingPacket(0x25u, DialogChoiceSerializer())
incomingPacket(0x26u, DialogOptionDeserializer())
outgoingPacket(0x26u, DialogOptionSerializer())
incomingPacket(0xB2u, NpcAnimationDeserializer())
outgoingPacket(0xB2u, NpcAnimationSerializer())
incomingPacket(0xB9u, MapTransitionAckDeserializer())
outgoingPacket(0xB9u, MapTransitionAckSerializer())
} }
} }
class GameClientProtocol : GameProtocol() { class GameClientProtocol : GameProtocol() {
init { init {
outgoingPacket(0x01u, JoinPacketSerializer()) outgoingPacket(0x01u, JoinPacketSerializer()) // Client info / "JoinGame"
incomingPacket(0x01u, JoinResponseDeserializer()) incomingPacket(0x01u, JoinResponseDeserializer())
outgoingPacket(0x02u, RequestCharactersPacketSerializer()) outgoingPacket(0x02u, RequestCharactersPacketSerializer())
incomingPacket(0x02u, CharacterListDeserializer()) incomingPacket(0x02u, CharacterListDeserializer())
outgoingPacket(0x04u, SelectCharacterSerializer()) outgoingPacket(0x04u, SelectCharacterSerializer())
incomingPacket(0x04u, SelectedCharacterDeserializer()) incomingPacket(0x04u, SelectedCharacterDeserializer())
outgoingPacket(0x05u, RequestPlayerSerializer()) outgoingPacket(0x05u, RequestPlayerSerializer())
incomingPacket(0x05u, LoadEntityDeserializer()) incomingPacket(0x05u, LoadEntityDeserializer())
outgoingPacket(0x06u, MovementPacketSerializer()) // Client movement
incomingPacket(0xEAu, EntityMovePacketDeserializer()) // Entity move broadcast
outgoingPacket(0x07u, FaceDirectionSerializer()) // Face direction
incomingPacket(0x08u, EntityLeaveDeserializer()) // Entity leave area
outgoingPacket(0x09u, ChatMessageSerialize())
incomingPacket(0x09u, ChatMessageDeserialize()) incomingPacket(0x09u, ChatMessageDeserialize())
outgoingPacket(0x10u, LoadMapPacketSerializer())
incomingPacket(0x10u, LoadMapPacketDeserializer()) incomingPacket(0x10u, LoadMapPacketDeserializer())
outgoingPacket(0x13u, PokemonContainerSerializer())
incomingPacket(0x13u, PokemonContainerDeserializer()) incomingPacket(0x13u, PokemonContainerDeserializer())
outgoingPacket(0x20u, TokenPayloadSerializer())
incomingPacket(0x20u, NullPacketDeserializer())
outgoingPacket(0xB4u, RenderScreenSerializer())
incomingPacket(0xB4u, RenderScreenDeserializer()) incomingPacket(0xB4u, RenderScreenDeserializer())
outgoingPacket(0xC2u, KeepAlivePacketSerializer()) // Keepalive echo
incomingPacket(0xC2u, KeepAlivePacketDeserializer())
outgoingPacket(0x0Du, DialogDataSerializer())
incomingPacket(0x0Du, DialogDataDeserializer())
outgoingPacket(0x0Eu, DialogStateSerializer())
incomingPacket(0x0Eu, DialogStateDeserializer())
incomingPacket(0x11u, NpcUpdateDeserializer())
outgoingPacket(0x12u, NpcSpawnSerializer())
incomingPacket(0x12u, NpcSpawnDeserializer())
outgoingPacket(0x1Bu, MapTransitionSerializer())
incomingPacket(0x1Bu, MapTransitionDeserializer())
outgoingPacket(0x21u, InteractiveSerializer())
incomingPacket(0x21u, InteractiveResponseDeserializer())
outgoingPacket(0x22u, EntityInteractSerializer())
incomingPacket(0x22u, EntityInteractDeserializer())
outgoingPacket(0x25u, DialogChoiceSerializer())
incomingPacket(0x25u, DialogChoiceDeserializer())
outgoingPacket(0x26u, DialogOptionSerializer())
incomingPacket(0x26u, DialogOptionDeserializer())
outgoingPacket(0xB2u, NpcAnimationSerializer())
incomingPacket(0xB2u, NpcAnimationDeserializer())
outgoingPacket(0xB9u, MapTransitionAckSerializer())
incomingPacket(0xB9u, MapTransitionAckDeserializer())
} }
} }
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.readUtf16LE
import io.netty.buffer.ByteBuf
data class CreateCharacterPacket(val name: String)
class CreateCharacterDeserializer : PacketDeserializer<CreateCharacterPacket> {
override fun deserialize(buffer: ByteBuf): CreateCharacterPacket {
val name = buffer.readUtf16LE()
buffer.skipBytes(buffer.readableBytes())
return CreateCharacterPacket(name)
}
}
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogChoicePacket(
val unk1: Int,
val unk2: Int,
)
class DialogChoiceSerializer : PacketSerializer<DialogChoicePacket> {
override fun serialize(packet: DialogChoicePacket, buffer: ByteBuf) {
buffer.writeByte(packet.unk1)
buffer.writeShortLE(packet.unk2)
}
}
class DialogChoiceDeserializer : PacketDeserializer<DialogChoicePacket> {
override fun deserialize(buffer: ByteBuf): DialogChoicePacket {
val unk1 = buffer.readByte().toInt()
val unk2 = buffer.readShortLE().toInt()
return DialogChoicePacket(unk1, unk2)
}
}
@@ -0,0 +1,27 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogDataPacket(val entityId: Long, val unk1: Int, val type: Int, val data: ByteArray)
class DialogDataSerializer : PacketSerializer<DialogDataPacket> {
override fun serialize(packet: DialogDataPacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeByte(packet.unk1)
buffer.writeByte(packet.type)
buffer.writeBytes(packet.data)
}
}
class DialogDataDeserializer : PacketDeserializer<DialogDataPacket> {
override fun deserialize(buffer: ByteBuf): DialogDataPacket {
val entityId = buffer.readLongLE()
val unk1 = buffer.readByte().toInt()
val type = buffer.readByte().toInt()
val data = ByteArray(buffer.readableBytes())
buffer.readBytes(data)
return DialogDataPacket(entityId, unk1, type, data)
}
}
@@ -0,0 +1,19 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogOptionPacket(val data: Int)
class DialogOptionSerializer : PacketSerializer<DialogOptionPacket> {
override fun serialize(packet: DialogOptionPacket, buffer: ByteBuf) {
buffer.writeIntLE(packet.data)
}
}
class DialogOptionDeserializer : PacketDeserializer<DialogOptionPacket> {
override fun deserialize(buffer: ByteBuf): DialogOptionPacket {
return DialogOptionPacket(buffer.readIntLE())
}
}
@@ -0,0 +1,19 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class DialogStatePacket(val active: Boolean)
class DialogStateSerializer : PacketSerializer<DialogStatePacket> {
override fun serialize(packet: DialogStatePacket, buffer: ByteBuf) {
buffer.writeBoolean(packet.active)
}
}
class DialogStateDeserializer : PacketDeserializer<DialogStatePacket> {
override fun deserialize(buffer: ByteBuf): DialogStatePacket {
return DialogStatePacket(buffer.readBoolean())
}
}
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class EntityInteractPacket(
val entityId: Long,
val token: Long,
)
class EntityInteractSerializer : PacketSerializer<EntityInteractPacket> {
override fun serialize(packet: EntityInteractPacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeLongLE(packet.token)
}
}
class EntityInteractDeserializer : PacketDeserializer<EntityInteractPacket> {
override fun deserialize(buffer: ByteBuf): EntityInteractPacket {
val entityId = buffer.readLongLE()
val token = buffer.readLongLE()
return EntityInteractPacket(entityId, token)
}
}
@@ -0,0 +1,22 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class EntityLeavePacket(
val entityId: Long,
)
class EntityLeaveSerializer : PacketSerializer<EntityLeavePacket> {
override fun serialize(packet: EntityLeavePacket, buffer: ByteBuf) {
buffer.writeLong(packet.entityId)
}
}
class EntityLeaveDeserializer : PacketDeserializer<EntityLeavePacket> {
override fun deserialize(buffer: ByteBuf): EntityLeavePacket {
val entityId = buffer.readLong()
return EntityLeavePacket(entityId)
}
}
@@ -0,0 +1,41 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class EntityMovePacket(
val entityId: Long,
val marker: Byte = 0x33,
val subtype: Byte = 0x03,
val seq: Byte = 0,
val x: Byte,
val y: Byte,
val direction: Direction,
)
class EntityMovePacketSerializer : PacketSerializer<EntityMovePacket> {
override fun serialize(packet: EntityMovePacket, buffer: ByteBuf) {
buffer.writeLong(packet.entityId)
buffer.writeByte(packet.marker.toInt())
buffer.writeByte(packet.subtype.toInt())
buffer.writeByte(packet.seq.toInt())
buffer.writeByte(packet.x.toInt())
buffer.writeByte(packet.y.toInt())
buffer.writeByte(packet.direction.ordinal)
}
}
class EntityMovePacketDeserializer : PacketDeserializer<EntityMovePacket> {
override fun deserialize(buffer: ByteBuf): EntityMovePacket {
val entityId = buffer.readLong()
val marker = buffer.readByte()
val subtype = buffer.readByte()
val seq = buffer.readByte()
val x = buffer.readByte()
val y = buffer.readByte()
val direction = Direction.entries[buffer.readByte().toInt()]
return EntityMovePacket(entityId, marker, subtype, seq, x, y, direction)
}
}
@@ -0,0 +1,23 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class FaceDirectionPacket(
val direction: Direction,
)
class FaceDirectionSerializer : PacketSerializer<FaceDirectionPacket> {
override fun serialize(packet: FaceDirectionPacket, buffer: ByteBuf) {
buffer.writeByte(packet.direction.ordinal)
}
}
class FaceDirectionDeserializer : PacketDeserializer<FaceDirectionPacket> {
override fun deserialize(buffer: ByteBuf): FaceDirectionPacket {
val direction = Direction.entries[buffer.readByte().toInt()]
return FaceDirectionPacket(direction)
}
}
@@ -0,0 +1,40 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class InteractivePacket(
val id: Int,
val type: Int,
val unk1: Int,
val unk2: Int,
val targetEntityId: Long,
val unk3: Int,
val unk4: Int,
)
class InteractiveSerializer : PacketSerializer<InteractivePacket> {
override fun serialize(packet: InteractivePacket, buffer: ByteBuf) {
buffer.writeByte(packet.id)
buffer.writeByte(packet.type)
buffer.writeIntLE(packet.unk1)
buffer.writeIntLE(packet.unk2)
buffer.writeLongLE(packet.targetEntityId)
buffer.writeShortLE(packet.unk3)
buffer.writeShortLE(packet.unk4)
}
}
class InteractiveDeserializer : PacketDeserializer<InteractivePacket> {
override fun deserialize(buffer: ByteBuf): InteractivePacket {
val id = buffer.readByte().toInt()
val type = buffer.readByte().toInt()
val unk1 = buffer.readIntLE()
val unk2 = buffer.readIntLE()
val targetEntityId = buffer.readLongLE()
val unk3 = buffer.readShortLE().toInt()
val unk4 = buffer.readShortLE().toInt()
return InteractivePacket(id, type, unk1, unk2, targetEntityId, unk3, unk4)
}
}
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class InteractiveResponsePacket(
val id: Int,
val unk: Int,
)
class InteractiveResponseSerializer : PacketSerializer<InteractiveResponsePacket> {
override fun serialize(packet: InteractiveResponsePacket, buffer: ByteBuf) {
buffer.writeByte(packet.id)
buffer.writeByte(packet.unk)
}
}
class InteractiveResponseDeserializer : PacketDeserializer<InteractiveResponsePacket> {
override fun deserialize(buffer: ByteBuf): InteractiveResponsePacket {
val id = buffer.readByte().toInt()
val unk = buffer.readByte().toInt()
return InteractiveResponsePacket(id, unk)
}
}
@@ -0,0 +1,26 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class KeepAlivePacket(
val canJoin: Boolean,
val sessionData: ByteArray,
)
class KeepAlivePacketSerializer : PacketSerializer<KeepAlivePacket> {
override fun serialize(packet: KeepAlivePacket, buffer: ByteBuf) {
buffer.writeBoolean(packet.canJoin)
buffer.writeBytes(packet.sessionData)
}
}
class KeepAlivePacketDeserializer : PacketDeserializer<KeepAlivePacket> {
override fun deserialize(buffer: ByteBuf): KeepAlivePacket {
val canJoin = buffer.readBoolean()
val sessionData = ByteArray(buffer.readableBytes())
buffer.readBytes(sessionData)
return KeepAlivePacket(canJoin, sessionData)
}
}
@@ -31,7 +31,7 @@ data class LoadEntityPacket(
class LoadEntitySerializer : PacketSerializer<LoadEntityPacket> { class LoadEntitySerializer : PacketSerializer<LoadEntityPacket> {
override fun serialize(packet: LoadEntityPacket, buffer: ByteBuf) = override fun serialize(packet: LoadEntityPacket, buffer: ByteBuf) =
buffer.run { buffer.run {
writeLong(packet.entityId) writeLongLE(packet.entityId)
writeByte(0) writeByte(0)
writeSkinsLE(packet.skin) writeSkinsLE(packet.skin)
writeUtf16LE(packet.name) writeUtf16LE(packet.name)
@@ -36,6 +36,13 @@ sealed interface MapData {
data class NdsMapData(val lighting: Lighting, val weather: Weather, val mapType: MapType) : data class NdsMapData(val lighting: Lighting, val weather: Weather, val mapType: MapType) :
MapData MapData
data class GbaConnection(
val direction: Int,
val unknown: Int,
val targetBank: Int,
val targetMap: Int,
)
data class GbaMapData( data class GbaMapData(
val width: Int, val width: Int,
val height: Int, val height: Int,
@@ -43,11 +50,14 @@ sealed interface MapData {
val paletteIdx2: Int, val paletteIdx2: Int,
val borderWidth: Int, val borderWidth: Int,
val borderHeight: Int, val borderHeight: Int,
val unknownShort: Int = 0,
val unknownByte: Int = 0,
val borderTiles: List<Tile2D>, val borderTiles: List<Tile2D>,
val lighting: Lighting, val lighting: Lighting,
val weather: Weather, val weather: Weather,
val mapType: MapType, val mapType: MapType,
val encounterType: EncounterType val encounterType: EncounterType,
val connections: List<GbaConnection> = emptyList(),
) : MapData { ) : MapData {
init { init {
require(borderWidth * borderHeight == borderTiles.size) { require(borderWidth * borderHeight == borderTiles.size) {
@@ -93,8 +103,8 @@ class LoadMapPacketSerializer : PacketSerializer<LoadMapPacket> {
writeIntLE(packet.mapData.paletteIdx2) writeIntLE(packet.mapData.paletteIdx2)
writeByte(packet.mapData.borderWidth) writeByte(packet.mapData.borderWidth)
writeByte(packet.mapData.borderHeight) writeByte(packet.mapData.borderHeight)
writeShortLE(0) writeShortLE(packet.mapData.unknownShort)
writeByte(0) writeByte(packet.mapData.unknownByte)
writeByte(packet.mapData.lighting.ordinal) writeByte(packet.mapData.lighting.ordinal)
writeByte(packet.mapData.weather.ordinal) writeByte(packet.mapData.weather.ordinal)
writeByte(packet.mapData.mapType.ordinal) writeByte(packet.mapData.mapType.ordinal)
@@ -112,13 +122,13 @@ class LoadMapPacketSerializer : PacketSerializer<LoadMapPacket> {
writeBytes(unknown.gzipCompress()) writeBytes(unknown.gzipCompress())
} }
val connectionCount = 0 val connections = packet.mapData.connections
writeByte(0) writeByte(connections.size)
for (i in 0 until connectionCount) { for (conn in connections) {
writeByte(0) writeByte(conn.direction)
writeIntLE(0) writeIntLE(conn.unknown)
writeByte(0) writeByte(conn.targetBank)
writeByte(0) writeByte(conn.targetMap)
} }
val hasUnknown2 = false val hasUnknown2 = false
@@ -166,8 +176,8 @@ class LoadMapPacketDeserializer : PacketDeserializer<LoadMapPacket> {
val paletteIdx2 = buffer.readIntLE() val paletteIdx2 = buffer.readIntLE()
val borderWidth = buffer.readByte().toInt() val borderWidth = buffer.readByte().toInt()
val borderHeight = buffer.readByte().toInt() val borderHeight = buffer.readByte().toInt()
buffer.readShortLE() val unknownShort = buffer.readShortLE().toInt()
buffer.readByte() val unknownByte = buffer.readByte().toInt()
val lighting = Lighting.entries[buffer.readByte().toInt()] val lighting = Lighting.entries[buffer.readByte().toInt()]
val weather = Weather.entries[buffer.readByte().toInt()] val weather = Weather.entries[buffer.readByte().toInt()]
val mapType = MapType.entries[buffer.readByte().toInt()] val mapType = MapType.entries[buffer.readByte().toInt()]
@@ -187,11 +197,13 @@ class LoadMapPacketDeserializer : PacketDeserializer<LoadMapPacket> {
} }
val connectionCount = buffer.readByte().toInt() val connectionCount = buffer.readByte().toInt()
val connections = mutableListOf<MapData.GbaConnection>()
for (i in 0 until connectionCount) { for (i in 0 until connectionCount) {
buffer.readByte() val direction = buffer.readByte().toInt()
buffer.readIntLE() val unknown = buffer.readIntLE()
buffer.readByte() val targetBank = buffer.readByte().toInt()
buffer.readByte() val targetMap = buffer.readByte().toInt()
connections.add(MapData.GbaConnection(direction, unknown, targetBank, targetMap))
} }
val hasUnknown2 = buffer.readBoolean() val hasUnknown2 = buffer.readBoolean()
@@ -207,11 +219,14 @@ class LoadMapPacketDeserializer : PacketDeserializer<LoadMapPacket> {
paletteIdx2, paletteIdx2,
borderWidth, borderWidth,
borderHeight, borderHeight,
unknownShort,
unknownByte,
borderTiles, borderTiles,
lighting, lighting,
weather, weather,
mapType, mapType,
encounterType) encounterType,
connections = connections)
} }
LoadMapPacket(reloadPlayer, deleteCache, regionId, bankId, mapId, mapData) LoadMapPacket(reloadPlayer, deleteCache, regionId, bankId, mapId, mapData)
@@ -0,0 +1,19 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class MapTransitionAckPacket(val unk: Int = 0)
class MapTransitionAckSerializer : PacketSerializer<MapTransitionAckPacket> {
override fun serialize(packet: MapTransitionAckPacket, buffer: ByteBuf) {
buffer.writeByte(packet.unk)
}
}
class MapTransitionAckDeserializer : PacketDeserializer<MapTransitionAckPacket> {
override fun deserialize(buffer: ByteBuf): MapTransitionAckPacket {
return MapTransitionAckPacket(buffer.readByte().toInt())
}
}
@@ -0,0 +1,15 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
class MapTransitionPacket
class MapTransitionSerializer : PacketSerializer<MapTransitionPacket> {
override fun serialize(packet: MapTransitionPacket, buffer: ByteBuf) {}
}
class MapTransitionDeserializer : PacketDeserializer<MapTransitionPacket> {
override fun deserialize(buffer: ByteBuf): MapTransitionPacket = MapTransitionPacket()
}
@@ -0,0 +1,29 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.common.enums.Direction
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class MovementPacket(
val x: Int,
val y: Int,
val direction: Direction,
)
class MovementPacketSerializer : PacketSerializer<MovementPacket> {
override fun serialize(packet: MovementPacket, buffer: ByteBuf) {
buffer.writeShortLE(packet.x)
buffer.writeShortLE(packet.y)
buffer.writeByte(packet.direction.ordinal)
}
}
class MovementPacketDeserializer : PacketDeserializer<MovementPacket> {
override fun deserialize(buffer: ByteBuf): MovementPacket {
val x = buffer.readShortLE().toInt()
val y = buffer.readShortLE().toInt()
val direction = Direction.entries[buffer.readByte().toInt()]
return MovementPacket(x, y, direction)
}
}
@@ -0,0 +1,25 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class NpcAnimationPacket(
val entityId: Long,
val animation: Int,
)
class NpcAnimationSerializer : PacketSerializer<NpcAnimationPacket> {
override fun serialize(packet: NpcAnimationPacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeByte(packet.animation)
}
}
class NpcAnimationDeserializer : PacketDeserializer<NpcAnimationPacket> {
override fun deserialize(buffer: ByteBuf): NpcAnimationPacket {
val entityId = buffer.readLongLE()
val animation = buffer.readByte().toInt()
return NpcAnimationPacket(entityId, animation)
}
}
@@ -0,0 +1,59 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class NpcSpawnPacket(
val entityId: Long,
val unk1: Int,
val unk2: Int,
val unk3: Int,
val unk4: Int,
val regionId: Int,
val bankId: Int,
val mapId: Int,
val x: Int,
val y: Int,
val facing: Int,
val unk5: Int,
val unk6: Int,
)
class NpcSpawnSerializer : PacketSerializer<NpcSpawnPacket> {
override fun serialize(packet: NpcSpawnPacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeByte(packet.unk1)
buffer.writeShortLE(packet.unk2)
buffer.writeShortLE(packet.unk3)
buffer.writeShortLE(packet.unk4)
buffer.writeByte(packet.regionId)
buffer.writeByte(packet.bankId)
buffer.writeByte(packet.mapId)
buffer.writeShortLE(packet.x)
buffer.writeShortLE(packet.y)
buffer.writeByte(packet.unk5)
buffer.writeByte(packet.facing)
buffer.writeShortLE(packet.unk6)
}
}
class NpcSpawnDeserializer : PacketDeserializer<NpcSpawnPacket> {
override fun deserialize(buffer: ByteBuf): NpcSpawnPacket {
val entityId = buffer.readLongLE()
val unk1 = buffer.readByte().toInt()
val unk2 = buffer.readShortLE().toInt()
val unk3 = buffer.readShortLE().toInt()
val unk4 = buffer.readShortLE().toInt()
val regionId = buffer.readByte().toInt()
val bankId = buffer.readByte().toInt()
val mapId = buffer.readByte().toInt()
val x = buffer.readShortLE().toInt()
val y = buffer.readShortLE().toInt()
val unk5 = buffer.readByte().toInt()
val facing = buffer.readByte().toInt()
val unk6 = buffer.readShortLE().toInt()
return NpcSpawnPacket(
entityId, unk1, unk2, unk3, unk4, regionId, bankId, mapId, x, y, facing, unk5, unk6)
}
}
@@ -0,0 +1,43 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class NpcUpdatePacket(
val entityId: Long,
val regionId: Int,
val bankId: Int,
val mapId: Int,
val x: Int,
val y: Int,
val facing: Int,
val unk: Int,
)
class NpcUpdateSerializer : PacketSerializer<NpcUpdatePacket> {
override fun serialize(packet: NpcUpdatePacket, buffer: ByteBuf) {
buffer.writeLongLE(packet.entityId)
buffer.writeByte(packet.regionId)
buffer.writeByte(packet.bankId)
buffer.writeByte(packet.mapId)
buffer.writeShortLE(packet.x)
buffer.writeShortLE(packet.y)
buffer.writeByte(packet.facing)
buffer.writeByte(packet.unk)
}
}
class NpcUpdateDeserializer : PacketDeserializer<NpcUpdatePacket> {
override fun deserialize(buffer: ByteBuf): NpcUpdatePacket {
val entityId = buffer.readLongLE()
val regionId = buffer.readByte().toInt()
val bankId = buffer.readByte().toInt()
val mapId = buffer.readByte().toInt()
val x = buffer.readShortLE().toInt()
val y = buffer.readShortLE().toInt()
val facing = buffer.readByte().toInt()
val unk = buffer.readByte().toInt()
return NpcUpdatePacket(entityId, regionId, bankId, mapId, x, y, facing, unk)
}
}
@@ -0,0 +1,10 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import io.netty.buffer.ByteBuf
class NullPacketDeserializer : PacketDeserializer<Unit> {
override fun deserialize(buffer: ByteBuf) {
buffer.skipBytes(buffer.readableBytes())
}
}
@@ -18,8 +18,8 @@ class SelectCharacterSerializer : PacketSerializer<SelectCharacterPacket> {
class SelectCharacterDeserializer : PacketDeserializer<SelectCharacterPacket> { class SelectCharacterDeserializer : PacketDeserializer<SelectCharacterPacket> {
override fun deserialize(buffer: ByteBuf): SelectCharacterPacket = override fun deserialize(buffer: ByteBuf): SelectCharacterPacket =
buffer.run { buffer.run {
val characterId = buffer.readLong() val characterId = buffer.readLongLE()
val characterIdHash = buffer.readLong() val characterIdHash = buffer.readLongLE()
return SelectCharacterPacket(characterId, characterIdHash) return SelectCharacterPacket(characterId, characterIdHash)
} }
} }
@@ -0,0 +1,21 @@
package de.fiereu.openmmo.protocols.game.packets
import de.fiereu.openmmo.protocols.PacketDeserializer
import de.fiereu.openmmo.protocols.PacketSerializer
import io.netty.buffer.ByteBuf
data class TokenPayloadPacket(val payload: ByteArray)
class TokenPayloadSerializer : PacketSerializer<TokenPayloadPacket> {
override fun serialize(packet: TokenPayloadPacket, buffer: ByteBuf) {
buffer.writeBytes(packet.payload)
}
}
class TokenPayloadDeserializer : PacketDeserializer<TokenPayloadPacket> {
override fun deserialize(buffer: ByteBuf): TokenPayloadPacket {
val data = ByteArray(buffer.readableBytes())
buffer.readBytes(data)
return TokenPayloadPacket(data)
}
}
@@ -54,7 +54,7 @@ fun ByteBuf.writeCharacterInfoLE(useLong: Boolean, characterInfo: CharacterInfo)
writeShortLE(characterInfo.lureItemId.toInt()) writeShortLE(characterInfo.lureItemId.toInt())
writeShortLE(characterInfo.lureLeft.toInt()) writeShortLE(characterInfo.lureLeft.toInt())
val bytes = ByteArray(0) val bytes = ByteArray(0)
writeByte(bytes.size) writeShortLE(bytes.size)
writeBytes(bytes) writeBytes(bytes)
} }
@@ -104,7 +104,7 @@ fun ByteBuf.readCharacterInfoLE(useLong: Boolean): CharacterInfo = let {
readByte() readByte()
val lureItemId = readShortLE() val lureItemId = readShortLE()
val lureLeft = readShortLE() val lureLeft = readShortLE()
val arraySize = readByte().toInt() val arraySize = readShortLE().toInt()
if (arraySize > 0) { if (arraySize > 0) {
val bytes = ByteArray(arraySize) val bytes = ByteArray(arraySize)
readBytes(bytes) readBytes(bytes)
@@ -0,0 +1,76 @@
package de.fiereu.openmmo.server.game.session
import de.fiereu.openmmo.common.enums.Direction
import io.netty.channel.Channel
import java.util.concurrent.ConcurrentHashMap
data class ScriptPage(
val type: Int = 0x04,
val unk1: Int,
val unk2: Int,
val unk3: Int,
)
data class Session(
val channel: Channel,
val userId: Int,
var characterId: Long? = null,
var justWarped: Boolean = false,
var facingDirection: Direction = Direction.DOWN,
var inDialog: Boolean = false,
var dialogNpcEntityId: Long = 0,
var dialogSeqId: Int = 0,
var dialogPages: List<ScriptPage> = emptyList(),
var dialogPageIndex: Int = 0,
var regionId: Int = 1,
var bankId: Int = 51,
var mapId: Int = 3,
var x: Short = 4,
var y: Short = 2,
)
object SessionManager {
private val sessionsByChannel = ConcurrentHashMap<Channel, Session>()
private val sessionsByCharacter = ConcurrentHashMap<Long, Session>()
fun createSession(channel: Channel, userId: Int): Session {
removeSession(channel)
val session = Session(channel, userId)
sessionsByChannel[channel] = session
return session
}
fun getSessionByChannel(channel: Channel): Session? = sessionsByChannel[channel]
fun getSessionByCharacterId(characterId: Long): Session? = sessionsByCharacter[characterId]
fun setActiveCharacter(channel: Channel, characterId: Long) {
val session = sessionsByChannel[channel] ?: return
sessionsByCharacter[characterId] = session
session.characterId = characterId
}
fun removeSession(channel: Channel) {
val session = sessionsByChannel.remove(channel)
if (session != null && session.characterId != null) {
sessionsByCharacter.remove(session.characterId)
}
}
fun getOnlineCharacterIds(): Set<Long> = sessionsByCharacter.keys
fun isOnline(characterId: Long): Boolean = sessionsByCharacter.containsKey(characterId)
fun getOthersInMap(
excludeCharacterId: Long,
regionId: Int,
bankId: Int,
mapId: Int,
): List<Session> =
sessionsByCharacter.values.filter { session ->
session.characterId != excludeCharacterId &&
session.regionId == regionId &&
session.bankId == bankId &&
session.mapId == mapId
}
}
@@ -0,0 +1,110 @@
package de.fiereu.openmmo.server.game.storage
import de.fiereu.openmmo.common.CharacterInfo
import de.fiereu.openmmo.common.Pokemon
import java.time.LocalDateTime
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong
data class StoredCharacter(
val info: CharacterInfo,
val pokemon: MutableList<Pokemon>,
val pcStorage: MutableList<Pokemon>,
val items: MutableMap<Int, Int>,
)
object CharacterStore {
private val characters = ConcurrentHashMap<Long, StoredCharacter>()
private val charactersByUser = ConcurrentHashMap<Int, MutableList<Long>>()
private val nextCharId = AtomicLong(1)
private val nextPokemonId = AtomicLong(1)
init {
ensureTestCharacter()
}
private fun ensureTestCharacter() {
if (characters.isEmpty()) {
createCharacter(userId = 1, name = "Test")
}
}
private fun generateEntityId(): Long {
val uniqueId = nextCharId.getAndIncrement()
return (uniqueId shl 16) or 0x9000L
}
fun createCharacter(
userId: Int,
name: String,
): StoredCharacter {
val id = generateEntityId()
val now = LocalDateTime.now()
val info =
CharacterInfo(
id = id,
name = name,
namePrefix = "",
userId = userId,
rivalSex = 0,
lastLogin = now,
createdAt = now,
money = 3000,
permissions = 8,
remainingSafariSteps = 0,
remainingSafariBalls = 0,
pcExtraSlots = 0,
battleBoxExtraSlots = 0,
templateAmount = 0,
positionRegionId = 1,
positionBankId = 51,
positionMapId = 3,
positionX = 4,
positionY = 2,
repelLeft = 0,
repelItemId = 0,
lureLeft = 0,
lureItemId = 0,
)
val stored = StoredCharacter(info, mutableListOf(), mutableListOf(), mutableMapOf())
characters[id] = stored
charactersByUser.getOrPut(userId) { mutableListOf() }.add(id)
return stored
}
fun getCharacter(id: Long): StoredCharacter? = characters[id]
fun getCharactersByUser(userId: Int): List<StoredCharacter> {
return charactersByUser[userId]?.mapNotNull { characters[it] } ?: emptyList()
}
fun updateCharacter(info: CharacterInfo) {
val stored = characters[info.id] ?: return
characters[info.id] = stored.copy(info = info)
}
fun updatePosition(
characterId: Long,
x: Short,
y: Short,
) {
val stored = characters[characterId] ?: return
val oldInfo = stored.info
val newInfo =
oldInfo.copy(
positionX = x,
positionY = y,
)
characters[characterId] = stored.copy(info = newInfo)
}
fun addPokemon(characterId: Long, pokemon: Pokemon) {
characters[characterId]?.pokemon?.add(pokemon)
}
fun addMoney(characterId: Long, amount: Int) {
val stored = characters[characterId] ?: return
val newInfo = stored.info.copy(money = stored.info.money + amount)
characters[characterId] = stored.copy(info = newInfo)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,75 @@
create extension if not exists pgcrypto;
create table "character" (
id bigserial not null,
user_id int not null,
name varchar(16) not null unique,
name_prefix varchar(16) not null default '',
rival_sex smallint not null default 0,
created_at timestamp not null default current_timestamp,
last_login timestamp not null default current_timestamp,
money int not null default 3000,
permissions int not null default 0,
remaining_safari_steps smallint not null default 0,
remaining_safari_balls smallint not null default 0,
pc_extra_slots smallint not null default 0,
battle_box_extra_slots smallint not null default 0,
template_amount smallint not null default 0,
position_region_id smallint not null default 0,
position_bank_id smallint not null default 1,
position_map_id smallint not null default 1,
position_x smallint not null default 100,
position_y smallint not null default 100,
repel_left smallint not null default 0,
repel_item_id smallint not null default 0,
lure_left smallint not null default 0,
lure_item_id smallint not null default 0,
primary key (id)
);
create table pokemon (
id bigserial not null,
character_id bigint not null,
container smallint not null default 0,
container_slot smallint not null default 0,
dex_id int not null,
seed int not null,
ot varchar(16) not null,
nickname varchar(32) not null,
level smallint not null default 1,
hp smallint not null default 10,
xp int not null default 0,
ivs int not null default 0,
ev_hp smallint not null default 0,
ev_atk smallint not null default 0,
ev_def smallint not null default 0,
ev_spatk smallint not null default 0,
ev_spdef smallint not null default 0,
ev_spd smallint not null default 0,
move1_id smallint not null default 0,
move1_pp smallint not null default 0,
move2_id smallint not null default 0,
move2_pp smallint not null default 0,
move3_id smallint not null default 0,
move3_pp smallint not null default 0,
move4_id smallint not null default 0,
move4_pp smallint not null default 0,
is_shiny boolean not null default false,
has_hidden_ability boolean not null default false,
is_alpha boolean not null default false,
is_secret boolean not null default false,
is_fateful_encounter boolean not null default false,
is_raid_encounter boolean not null default false,
caught_at timestamp not null default current_timestamp,
primary key (id),
foreign key (character_id) references "character"(id) on delete cascade
);
create table item (
id bigserial not null,
character_id bigint not null,
item_id int not null,
amount int not null default 1,
primary key (id),
foreign key (character_id) references "character"(id) on delete cascade
);
@@ -6,6 +6,7 @@ import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.config.TlsConfig import de.fiereu.openmmo.server.config.TlsConfig
import de.fiereu.openmmo.server.io.resource import de.fiereu.openmmo.server.io.resource
import de.fiereu.openmmo.server.keys.KeyLoader import de.fiereu.openmmo.server.keys.KeyLoader
import de.fiereu.openmmo.server.login.auth.InMemoryUserStore
import de.fiereu.openmmo.server.login.protocol.login.LoginProtocolHandler import de.fiereu.openmmo.server.login.protocol.login.LoginProtocolHandler
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -15,6 +16,7 @@ fun main() {
val serverConfig = ServerConfig(port = 2106) val serverConfig = ServerConfig(port = 2106)
val tlsConfig = TlsConfig(checksumSize = 16) val tlsConfig = TlsConfig(checksumSize = 16)
val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val userService = InMemoryUserStore()
val server = val server =
ServerBuilder.create() ServerBuilder.create()
.withCoroutineScope(coroutineScope) .withCoroutineScope(coroutineScope)
@@ -23,7 +25,7 @@ fun main() {
.withPublicKey(KeyLoader.loadPemECPublicKey(resource("game.public.pem"))) .withPublicKey(KeyLoader.loadPemECPublicKey(resource("game.public.pem")))
.withPrivateKey(KeyLoader.loadPemECPrivateKey(resource("game.private.pem"))) .withPrivateKey(KeyLoader.loadPemECPrivateKey(resource("game.private.pem")))
.withChannelHandlerProvider { .withChannelHandlerProvider {
LoginProtocolHandler(LoginServerProtocol(), serverConfig, coroutineScope) LoginProtocolHandler(LoginServerProtocol(), serverConfig, coroutineScope, userService)
} }
.build() .build()
server.start() server.start()
@@ -0,0 +1,52 @@
package de.fiereu.openmmo.server.login.auth
import de.fiereu.openmmo.common.enums.LoginState
import java.util.concurrent.ConcurrentHashMap
private val log = io.github.oshai.kotlinlogging.KotlinLogging.logger {}
interface UserService {
data class AuthResult(val state: LoginState, val userId: Int? = null)
fun authenticate(username: String, password: String): AuthResult
fun getUserId(username: String): Int?
}
class InMemoryUserStore : UserService {
private val users = ConcurrentHashMap<String, UserInfo>()
private val nextId = java.util.concurrent.atomic.AtomicInteger(1)
data class UserInfo(val id: Int, val passwordHash: String, val username: String)
init {
addUser("admin", "admin")
addUser("test", "test")
}
/**
* PokeMMO client sends a transformed password hash. We store the value the client sends and
* compare directly. For initial setup, we compute SHA-1 as a best guess.
*/
fun addUser(username: String, password: String): Int {
val id = nextId.getAndIncrement()
val sha1 = java.security.MessageDigest.getInstance("SHA-1")
val hashBytes = sha1.digest(password.toByteArray())
val hex = hashBytes.joinToString("") { "%02x".format(it) }
users[username.lowercase()] = UserInfo(id, hex, username)
return id
}
override fun authenticate(username: String, password: String): UserService.AuthResult {
val user =
users[username.lowercase()] ?: return UserService.AuthResult(LoginState.INVALID_PASSWORD)
if (user.passwordHash != password) {
return UserService.AuthResult(LoginState.INVALID_PASSWORD)
}
return UserService.AuthResult(LoginState.AUTHED, user.id)
}
override fun getUserId(username: String): Int? {
return users[username.lowercase()]?.id
}
}
@@ -11,6 +11,7 @@ import de.fiereu.openmmo.protocols.tls.packets.JoinGameServerPacket
import de.fiereu.openmmo.protocols.tls.packets.LoginRequestPacket import de.fiereu.openmmo.protocols.tls.packets.LoginRequestPacket
import de.fiereu.openmmo.protocols.tls.packets.RequestGameServerListPacket import de.fiereu.openmmo.protocols.tls.packets.RequestGameServerListPacket
import de.fiereu.openmmo.server.config.ServerConfig import de.fiereu.openmmo.server.config.ServerConfig
import de.fiereu.openmmo.server.login.auth.UserService
import de.fiereu.openmmo.server.login.protocol.login.ext.respondForAuthedUser import de.fiereu.openmmo.server.login.protocol.login.ext.respondForAuthedUser
import de.fiereu.openmmo.server.login.protocol.login.ext.respondTo import de.fiereu.openmmo.server.login.protocol.login.ext.respondTo
import de.fiereu.openmmo.server.login.protocol.login.ext.respondWithServers import de.fiereu.openmmo.server.login.protocol.login.ext.respondWithServers
@@ -28,6 +29,7 @@ class LoginProtocolHandler(
protocol: Protocol, protocol: Protocol,
serverConfig: ServerConfig, serverConfig: ServerConfig,
private val coroutineScope: CoroutineScope, private val coroutineScope: CoroutineScope,
private val userService: UserService,
) : ProtocolHandler(protocol, serverConfig) { ) : ProtocolHandler(protocol, serverConfig) {
override fun onActive(ctx: ChannelHandlerContext) { override fun onActive(ctx: ChannelHandlerContext) {
@@ -48,9 +50,22 @@ class LoginProtocolHandler(
} }
fun onLoginRequest(event: PacketEvent<LoginRequestPacket>) { fun onLoginRequest(event: PacketEvent<LoginRequestPacket>) {
log.info { "Received login request for user '${event.packet.username}'" } val username = event.packet.username
// TODO proper authentication val method = event.packet.method
event.respondWithState(LoginState.AUTHED) if (method !is de.fiereu.openmmo.protocols.tls.packets.PasswordLogin) {
log.warn { "Unsupported login method: ${method::class.simpleName}" }
event.respondWithState(LoginState.INVALID_PASSWORD)
return
}
val password = method.password
log.info { "Login attempt for user '$username'" }
val result = userService.authenticate(username, password)
if (result.state != LoginState.AUTHED) {
log.warn { "Failed login for user '$username': ${result.state}" }
} else {
log.info { "Successful login for user '$username' (userId=${result.userId})" }
}
event.respondWithState(result.state)
} }
fun onGameServerListRequest(event: PacketEvent<RequestGameServerListPacket>) { fun onGameServerListRequest(event: PacketEvent<RequestGameServerListPacket>) {
@@ -20,7 +20,7 @@ abstract class ProtocolHandler(
serverConfig: ServerConfig serverConfig: ServerConfig
) : ChannelDuplexHandler() { ) : ChannelDuplexHandler() {
private val compressor = Compressor(serverConfig) protected val compressor = Compressor(serverConfig)
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) { override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
if (msg !is ByteBuf) { if (msg !is ByteBuf) {
@@ -34,10 +34,13 @@ abstract class ProtocolHandler(
return return
} }
val opcodeValue = msg.readUnsignedByte().toUByte() val opcodeValue = msg.readUnsignedByte().toUByte()
val remainingBytes = msg.readableBytes()
log.debug { "<< RX $opcodeValue (${remainingBytes}b) from ${ctx.channel().remoteAddress()}" }
val deserializer = protocol.getDeserializer(opcodeValue) val deserializer = protocol.getDeserializer(opcodeValue)
if (deserializer == null) { if (deserializer == null) {
log.warn { "No deserializer found for ${PacketDirection.CLIENT_TO_SERVER} opcode $opcodeValue" } log.warn { "No deserializer found for ${PacketDirection.CLIENT_TO_SERVER} opcode $opcodeValue (${remainingBytes}b remaining)" }
return return
} }
@@ -52,7 +55,7 @@ abstract class ProtocolHandler(
*/ */
onPacketReceived(PacketEvent(ctx, packetData)) onPacketReceived(PacketEvent(ctx, packetData))
} catch (e: Exception) { } catch (e: Exception) {
log.error(e) { "Error processing packet" } log.error(e) { "Error processing packet: ${e.message}" }
} finally { } finally {
msg.release() msg.release()
} }
@@ -84,17 +87,19 @@ abstract class ProtocolHandler(
*/ */
if (!protocol.compressed) { if (!protocol.compressed) {
serializer.serializeObject(msg, buffer) serializer.serializeObject(msg, buffer)
log.debug { ">> TX $opcode (${buffer.readableBytes() - 1}b payload)" }
} else { } else {
val uncompressedBuffer = Unpooled.buffer() val uncompressedBuffer = Unpooled.buffer()
serializer.serializeObject(msg, uncompressedBuffer) serializer.serializeObject(msg, uncompressedBuffer)
buffer.writeBytes( val uncompressedSize = uncompressedBuffer.readableBytes()
compressor.compress(uncompressedBuffer) val compressed = compressor.compress(uncompressedBuffer)
) buffer.writeBytes(compressed)
log.debug { ">> TX $opcode (payload: ${uncompressedSize}b -> ${compressed.readableBytes()}b compressed)" }
} }
ctx.write(buffer, promise) ctx.write(buffer, promise)
} catch (e: Exception) { } catch (e: Exception) {
log.error(e) { "Error processing packet" } log.error(e) { "Error processing packet: ${e.message}" }
} }
} }
@@ -102,6 +107,22 @@ abstract class ProtocolHandler(
onActive(ctx) onActive(ctx)
} }
protected fun sendRaw(ctx: ChannelHandlerContext, opcode: UByte, data: ByteArray) {
val buffer = ctx.alloc().buffer()
buffer.writeByte(opcode.toInt())
val dataBuf = Unpooled.wrappedBuffer(data)
buffer.writeBytes(compressor.compress(dataBuf))
ctx.write(buffer)
}
protected fun sendRawAndFlush(ctx: ChannelHandlerContext, opcode: UByte, data: ByteArray) {
val buffer = ctx.alloc().buffer()
buffer.writeByte(opcode.toInt())
val dataBuf = Unpooled.wrappedBuffer(data)
buffer.writeBytes(compressor.compress(dataBuf))
ctx.writeAndFlush(buffer)
}
abstract fun onPacketReceived(event: PacketEvent<*>) abstract fun onPacketReceived(event: PacketEvent<*>)
abstract fun onActive(ctx: ChannelHandlerContext) abstract fun onActive(ctx: ChannelHandlerContext)
} }