Files
esengine/packages/tilemap/src/loaders/TilemapLoader.ts

89 lines
2.2 KiB
TypeScript
Raw Normal View History

/**
* Tilemap asset loader
*
*/
import {
IAssetLoader,
IAssetContent,
IAssetParseContext,
AssetContentType
} from '@esengine/asset-system';
import { TilemapAssetType } from '../constants';
/**
* Tilemap data interface
*
*/
export interface ITilemapAsset {
/** 名称 */
name: string;
/** 版本 */
version: number;
/** 宽度(瓦片数) */
width: number;
/** 高度(瓦片数) */
height: number;
/** 瓦片宽度(像素) */
tileWidth: number;
/** 瓦片高度(像素) */
tileHeight: number;
/** 瓦片集资源GUID */
tileset: string;
/** 瓦片数据行主序0表示空 */
data: number[];
/** 图层(可选) */
layers?: Array<{
name: string;
visible: boolean;
opacity: number;
data?: number[];
/** 材质路径 */
materialPath?: string;
}>;
/** 碰撞数据(可选) */
collisionData?: number[];
/** 自定义属性 */
properties?: Record<string, unknown>;
}
/**
* Tilemap loader implementation
*
*/
export class TilemapLoader implements IAssetLoader<ITilemapAsset> {
readonly supportedType = TilemapAssetType;
readonly supportedExtensions = ['.tilemap.json', '.tilemap'];
readonly contentType: AssetContentType = 'text';
/**
* Parse tilemap asset from text content
*
*/
async parse(content: IAssetContent, _context: IAssetParseContext): Promise<ITilemapAsset> {
if (!content.text) {
throw new Error('Tilemap content is empty');
}
const jsonData = JSON.parse(content.text) as ITilemapAsset;
// 验证必要字段
// Validate required fields
if (!jsonData.width || !jsonData.height || !jsonData.data) {
throw new Error('Invalid tilemap format: missing required fields');
}
return jsonData;
}
/**
* Dispose loaded asset
*
*/
dispose(asset: ITilemapAsset): void {
(asset as any).data = null;
(asset as any).layers = null;
(asset as any).collisionData = null;
}
}