Add Binding 2.0 asset pack

This commit is contained in:
2026-06-19 15:50:02 +03:00
parent db545ce80b
commit 3cdd3ac738
47 changed files with 472 additions and 23 deletions
+8 -1
View File
@@ -21,7 +21,7 @@ if (!result.success) {
await Bun.write('./dist/index.html', await Bun.file('./index.html').text()); await Bun.write('./dist/index.html', await Bun.file('./index.html').text());
// Копируем картинки в dist/assets (если папка есть). // Копируем картинки в dist/<asset-pack> (если папка есть).
try { try {
await mkdir('./dist/assets', { recursive: true }); await mkdir('./dist/assets', { recursive: true });
await cp('./src/assets', './dist/assets', { recursive: true }); await cp('./src/assets', './dist/assets', { recursive: true });
@@ -29,4 +29,11 @@ try {
// src/assets ещё нет — не страшно, рендер откатится на процедурную графику. // src/assets ещё нет — не страшно, рендер откатится на процедурную графику.
} }
try {
await mkdir('./dist/assets-binding-2', { recursive: true });
await cp('./src/assets-binding-2', './dist/assets-binding-2', { recursive: true });
} catch {
// Второй пак ассетов опционален.
}
console.log('Сборка готова → dist/ (открой dist/index.html)'); console.log('Сборка готова → dist/ (открой dist/index.html)');
+2 -2
View File
@@ -22,8 +22,8 @@ const server = Bun.serve({
if (url.pathname === '/' || url.pathname === '/index.html') { if (url.pathname === '/' || url.pathname === '/index.html') {
return new Response(Bun.file('./index.html')); return new Response(Bun.file('./index.html'));
} }
// Картинки отдаём прямо из src/assets/ — положил PNG → сразу подхватился (без пересборки). // Картинки отдаём прямо из src/<asset-pack>/ — положил PNG → сразу подхватился.
if (url.pathname.startsWith('/assets/')) { if (url.pathname.startsWith('/assets/') || url.pathname.startsWith('/assets-binding-2/')) {
const asset = Bun.file('./src' + url.pathname); const asset = Bun.file('./src' + url.pathname);
if (await asset.exists()) return new Response(asset); if (await asset.exists()) return new Response(asset);
return new Response('Not found', { status: 404 }); return new Response('Not found', { status: 404 });
+363
View File
@@ -0,0 +1,363 @@
# Промпты для ассетов: «Биндинг 2.0»
Этот файл нужен, чтобы сгенерировать второй набор ассетов в стиле постера
`docs/assets/binding_fignyashka.png`, но в формате, который легко положить в игру
и при необходимости вырезать руками.
## Как пользоваться
1. В генераторе сначала загрузи постер `docs/assets/binding_fignyashka.png` как
style reference, если сервис это поддерживает.
2. Скопируй **базовый промпт** ниже в начало каждой генерации.
3. Ниже по файлу копируй промпт конкретного ассета.
4. Сохраняй результат ровно с указанным именем файла.
Если генератор плохо делает прозрачный фон, проси однотонный chroma key:
`pure #00ff00 background, no shadow, no glow touching the background`, затем
удаляй фон любым инструментом. Для игры лучше PNG с alpha.
## Базовый промпт
```text
Use the uploaded poster "Биндим Фигняшку" as the style reference only.
Create one game asset for a top-down roguelike called "Биндинг 2.0".
Style: grotesque dark cartoon dungeon art, chunky hand-painted shapes, high contrast, juicy slime colors, thick uneven black-purple outlines, expressive silly-horror faces, grimy stone dungeon details, saturated neon accents, readable silhouette at small size.
Technical requirements:
- One isolated asset only, centered.
- Transparent PNG background with clean alpha.
- If transparent background is not possible: pure #00ff00 chroma key background, no gradients, no contact shadow, no glow touching the background.
- No text, no letters, no watermark, no UI frame, no mockup, no floor under the object, no baked shadow, unless the specific prompt asks for logo/menu background/floor/wall/shadow.
- Keep the whole object inside the canvas with 8-12% padding.
- Use the requested exact canvas size and filename.
- Front-facing billboard sprite for characters, slightly top-down camera feel, feet aligned near the bottom edge.
- Same lighting, palette, outline thickness, and detail density across all assets.
- Make it easy to cut out: crisp silhouette, transparent outside pixels, no loose dust outside the silhouette.
Negative prompt:
photorealistic, realistic gore, anime, flat vector icon, pixel art, low contrast, blurry edges, tiny unreadable details, background scene, multiple objects, text, signature, watermark, drop shadow, floor shadow, square UI border, cropped body, cut off feet
```
## Персонажи и враги
### `player-ranged.png` — игрок с дальним оружием, 192x256
```text
Asset: player-ranged.png, canvas 192x256.
Small grotesque hero, huge uneven eyes, patched purple hood with little horns, anxious grin, compact body, holding a weird toy-like slime pistol or water gun pointed diagonally down-right. Blue/cyan weapon glow, tiny dungeon grime, funny horror expression. Full body, front-facing billboard sprite, feet at the bottom edge, transparent background.
```
### `player-melee.png` — игрок с ближним оружием, 192x256
```text
Asset: player-melee.png, canvas 192x256.
Same hero as player-ranged, same face and purple hood, but holding a ridiculous melee weapon: toilet brush, rusty knife, or plunger club. Warmer red/orange accents, aggressive grin, ready to swing. Full body, front-facing billboard sprite, feet at the bottom edge, transparent background.
```
### `enemy-normal.png` — обычный враг, 192x256
```text
Asset: enemy-normal.png, canvas 192x256.
Round lumpy dungeon monster, terracotta-pink skin, one lazy eye and one tiny eye, small teeth, stubby legs, goofy but hostile. Thick black-purple outline, slime spots, readable chunky silhouette. Full body, front-facing billboard sprite, feet at the bottom edge, transparent background.
```
### `enemy-fast.png` — быстрый враг, 160x213
```text
Asset: enemy-fast.png, canvas 160x213.
Small twitchy fast monster, red bug-like gobbet, long thin legs, bulging eyes, frantic expression, motion-ready pose but not blurred. Bright red and magenta accents, sharp silhouette. Full body, front-facing billboard sprite, feet at the bottom edge, transparent background.
```
### `enemy-boss.png` — босс, 288x384
```text
Asset: enemy-boss.png, canvas 288x384.
Huge grotesque boss head-body hybrid, swollen pink-brown flesh, mismatched giant eyes, crown made of junk metal, open screaming mouth, tiny arms with a plunger hammer. Dark dungeon grime, purple slime rim light, very readable massive silhouette. Full body, front-facing billboard sprite, base at bottom edge, transparent background.
```
### `enemy-charger.png` — рывковый враг, 192x256
```text
Asset: enemy-charger.png, canvas 192x256.
Aggressive charger monster, red-orange flesh, low hunched body, one horn or metal spike on forehead, angry slit eyes, oversized jaw, pose leaning forward like it is about to rush. Thick outline, neon orange highlights. Full body, front-facing billboard sprite, feet at bottom edge, transparent background.
```
### `enemy-tank.png` — тяжёлый враг, 224x288
```text
Asset: enemy-tank.png, canvas 224x288.
Heavy tank monster, bulky stone-and-flesh body, cracked skull plates, slow stupid face, tiny eyes, big square jaw, metal rivets embedded in skin. Dark brown, grey, bruised purple palette. Full body, front-facing billboard sprite, feet/base at bottom edge, transparent background.
```
### `enemy-shooter.png` — стрелок, 192x256
```text
Asset: enemy-shooter.png, canvas 192x256.
Shooter monster, bluish sickly body, huge single watery eye, tiny nozzle mouth or fish-gun growth, cheeks full of glowing slime projectile. Cyan/green spit glow, nervous mean expression. Full body, front-facing billboard sprite, feet at bottom edge, transparent background.
```
## Окружение
### `floor.png` — бесшовный пол, 256x256
```text
Asset: floor.png, canvas 256x256.
Seamless tileable dungeon floor texture, top-down stone slabs from the poster style, dark grey-brown stones, subtle purple grime, tiny cracks, small slime stains, no strong directional light, no objects, no text. Must tile perfectly on all edges.
```
### `wall.png` — бесшовная стена, 256x256
```text
Asset: wall.png, canvas 256x256.
Seamless tileable dungeon wall brick texture, cold blue-grey bricks, black-purple mortar, moss and slime in cracks, hand-painted chunky style, no perspective object, no text. Must tile perfectly on all edges.
```
### `door-closed.png` — закрытая дверь, 192x256
```text
Asset: door-closed.png, canvas 192x256.
Closed dungeon doorway sprite, arched stone frame, chunky wooden planks, heavy golden latch/bar, purple slime outline, front-facing vertical billboard object. Transparent background outside the door frame, no floor, no shadow.
```
### `door-open.png` — открытая дверь, 192x256
```text
Asset: door-open.png, canvas 192x256.
Open dungeon doorway sprite, arched stone frame, dark black interior void, broken wooden bits, purple slime rim light, front-facing vertical billboard object. Transparent background outside the door frame, no floor, no shadow.
```
### `chest.png` — сундук, 192x192
```text
Asset: chest.png, canvas 192x192.
Treasure chest object, red-brown wood, gold metal bands, one goofy eye-shaped lock, tiny slime drips, cute-horror style from the poster. Isolated object, three-quarter top-down object view, transparent background, no shadow.
```
### `pickup.png` — универсальный пикап, 128x128
```text
Asset: pickup.png, canvas 128x128.
Floating weapon pickup marker, glowing golden-purple diamond with slime sparkle, chunky outline, readable at small size. Isolated object, transparent background, no shadow.
```
## Снаряды и эффекты
### `tear.png` — слеза, 64x64
```text
Asset: tear.png, canvas 64x64.
Single glowing blue tear projectile, chunky droplet shape, white highlight, cyan edge glow contained inside transparent canvas. No trail, no shadow, transparent background.
```
### `fireball.png` — огненный шар, 64x64
```text
Asset: fireball.png, canvas 64x64.
Single grotesque fireball projectile, orange-red slime flame orb, white-yellow hot center, small black-purple outline, contained glow, transparent background, no trail.
```
### `beam.png` — луч лазера, 128x128
```text
Asset: beam.png, canvas 128x128.
Laser impact/beam blob sprite, bright white-cyan center with electric blue-purple rim, circular radial energy burst suitable for additive blending, transparent background, no hard square edges.
```
### `muzzle.png` — вспышка выстрела, 128x128
```text
Asset: muzzle.png, canvas 128x128.
Muzzle flash effect sprite, white-hot center, yellow-orange starburst, purple edge sparks, soft radial alpha, designed for additive blending. Transparent background.
```
### `spark.png` — искра попадания, 128x128
```text
Asset: spark.png, canvas 128x128.
Hit spark effect sprite, jagged white-yellow impact burst with tiny purple fragments, clear center, fades to transparent edges, designed for additive blending. Transparent background.
```
### `puff.png` — дымок смерти, 128x128
```text
Asset: puff.png, canvas 128x128.
Cartoon death puff cloud, grey-white smoke with purple grime, soft edges, funny splat-cloud shape, fades to transparent, no hard outline outside the cloud. Transparent background.
```
### `shadow.png` — тень, 128x64
```text
Asset: shadow.png, canvas 128x64.
Soft oval blob shadow, black center fading smoothly to full transparency, no colored tint, no hard edge. Transparent PNG, exactly one horizontal ellipse.
```
## HUD и меню
### `logo.png` — логотип, 900x220
```text
Asset: logo.png, canvas 900x220.
Logo text in Russian: "Биндим Фигняшку".
Use the exact poster lettering vibe: chunky slime letters, green top word "Биндим", orange-yellow bottom word "Фигняшку", purple slime outline, black thick shadow. Transparent background. No extra characters, no subtitle, no watermark.
```
### `menu-bg.png` — фон меню, 880x660
```text
Asset: menu-bg.png, canvas 880x660.
Dark dungeon menu background in the same poster style, top-down room fragments, dim torches, purple slime, scattered silly-horror props. No text, no logo, no centered character, leave the central area readable for UI overlay. Full rectangular background, not transparent.
```
### `heart-full.png` — полное сердце, 48x48
```text
Asset: heart-full.png, canvas 48x48.
Full HP heart icon, red fleshy cartoon heart, thick dark outline, tiny slime highlight, readable at 24 px. Transparent background, no shadow.
```
### `heart-half.png` — половина сердца, 48x48
```text
Asset: heart-half.png, canvas 48x48.
Half HP heart icon matching heart-full, left half full red flesh, right half dark empty husk, thick dark outline, readable at 24 px. Transparent background, no shadow.
```
### `heart-empty.png` — пустое сердце, 48x48
```text
Asset: heart-empty.png, canvas 48x48.
Empty HP heart icon matching heart-full, dark cracked heart outline with hollow center, subtle purple grime, readable at 24 px. Transparent background, no shadow.
```
### `icon-ranged.png` — иконка дальнего режима, 48x48
```text
Asset: icon-ranged.png, canvas 48x48.
Ranged mode HUD icon, tiny goofy slime pistol firing one blue tear, thick outline, high contrast, readable at 24 px. Transparent background, no shadow.
```
### `icon-melee.png` — иконка ближнего режима, 48x48
```text
Asset: icon-melee.png, canvas 48x48.
Melee mode HUD icon, tiny ridiculous knife/plunger/brush weapon, red-orange accent, thick outline, high contrast, readable at 24 px. Transparent background, no shadow.
```
## Иконки оружия
### `weapon-icon-tears.png`, 48x48
```text
Asset: weapon-icon-tears.png, canvas 48x48.
Weapon icon for "Слёзы": single blue tear orb with white highlight, chunky outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-melee.png`, 48x48
```text
Asset: weapon-icon-melee.png, canvas 48x48.
Weapon icon for "Кулак": goofy clenched fist, bruised peach color, thick dark outline, tiny slime detail, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-shotgun.png`, 48x48
```text
Asset: weapon-icon-shotgun.png, canvas 48x48.
Weapon icon for "Дробовик": three small glowing pellets spreading outward, yellow-orange centers, dark outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-axe.png`, 48x48
```text
Asset: weapon-icon-axe.png, canvas 48x48.
Weapon icon for "Топор": rusty cartoon axe with chipped metal head and short handle, purple grime, thick outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-staff.png`, 48x48
```text
Asset: weapon-icon-staff.png, canvas 48x48.
Weapon icon for "Посох": crooked wooden staff with glowing orange fire gem, tiny slime drips, thick outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-whip.png`, 48x48
```text
Asset: weapon-icon-whip.png, canvas 48x48.
Weapon icon for "Хлыст": curled leather whip, exaggerated curve, warm brown with purple rim, thick outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-bomb.png`, 48x48
```text
Asset: weapon-icon-bomb.png, canvas 48x48.
Weapon icon for "Бомба": round black cartoon bomb with lit fuse, orange spark, silly eye-like rivet, thick outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-boomerang.png`, 48x48
```text
Asset: weapon-icon-boomerang.png, canvas 48x48.
Weapon icon for "Бумеранг": crooked wooden boomerang with teeth marks and purple slime stripe, thick outline, readable at 24 px. Transparent background, no shadow.
```
### `weapon-icon-laser.png`, 48x48
```text
Asset: weapon-icon-laser.png, canvas 48x48.
Weapon icon for "Лазер": compact blue-white laser emitter crystal or ray gun barrel, cyan glow contained inside icon, thick outline, readable at 24 px. Transparent background, no shadow.
```
## После генерации
Сложи файлы второго набора в отдельную папку, например:
```text
src/assets-binding-2/
```
Потом можно добавить выбор в меню:
- `Классика` -> текущая папка `src/assets/`;
- `Биндинг 2.0` -> новая папка `src/assets-binding-2/`.
Когда ассеты будут готовы, самый чистый следующий шаг в коде: дать `Assets` параметр
`packPath` и прокинуть выбранный пак из `StartMenu` в `ThreeRenderer`/`HudOverlay`.
+10
View File
@@ -36,6 +36,16 @@
#menu h1 { font-size: 40px; letter-spacing: 4px; color: #c9b27a; margin-bottom: 4px; } #menu h1 { font-size: 40px; letter-spacing: 4px; color: #c9b27a; margin-bottom: 4px; }
#menu-logo { display: block; width: min(560px, 80%); height: auto; } #menu-logo { display: block; width: min(560px, 80%); height: auto; }
.menu-sub { color: #888; margin-bottom: 6px; } .menu-sub { color: #888; margin-bottom: 6px; }
.menu-packs { display: flex; gap: 8px; margin-bottom: 2px; }
.menu-pack {
cursor: pointer;
background: rgba(12,12,18,0.86); color: #aaa;
border: 1px solid #333; border-radius: 4px;
padding: 7px 12px; font-family: monospace; font-size: 12px;
transition: background .12s, border-color .12s, color .12s;
}
.menu-pack:hover { background: #1d1d2c; border-color: #5a78c0; color: #ddd; }
.menu-pack.is-selected { color: #f0d887; border-color: #8f6f25; background: rgba(42,32,12,0.88); }
#menu-presets { display: flex; flex-direction: column; gap: 10px; width: 360px; max-width: 90%; } #menu-presets { display: flex; flex-direction: column; gap: 10px; width: 360px; max-width: 90%; }
.menu-preset { .menu-preset {
display: flex; flex-direction: column; gap: 3px; display: flex; flex-direction: column; gap: 3px;
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

+18 -7
View File
@@ -13,6 +13,7 @@ import { ThreeRenderer } from './render/ThreeRenderer';
import { HudOverlay } from './render/HudOverlay'; import { HudOverlay } from './render/HudOverlay';
import { GameLoop } from './engine/GameLoop'; import { GameLoop } from './engine/GameLoop';
import { StartMenu } from './ui/StartMenu'; import { StartMenu } from './ui/StartMenu';
import { ASSET_PACKS, type AssetPack } from './render/assetPacks';
function boot(): void { function boot(): void {
const world = document.getElementById('game') as HTMLCanvasElement | null; const world = document.getElementById('game') as HTMLCanvasElement | null;
@@ -24,21 +25,27 @@ function boot(): void {
return; return;
} }
// Рендер и ввод создаём один раз — они переиспользуются между забегами. // Ввод живёт всё приложение; рендер создаётся на забег, потому что зависит от пака ассетов.
const controller = new KeyboardController(); const controller = new KeyboardController();
const world3d = new ThreeRenderer(world);
const hud = new HudOverlay(hudCanvas);
controller.attach(); controller.attach();
let loop: GameLoop | null = null; let loop: GameLoop | null = null;
let world3d: ThreeRenderer | null = null;
let hud: HudOverlay | null = null;
const startGame = (rules: LevelRules): void => { const startGame = (rules: LevelRules, assetPack: AssetPack): void => {
loop?.stop(); loop?.stop();
world3d?.dispose();
hud?.dispose();
controller.reset(); // чистый ввод: не тащим зажатые клавиши/смену оружия из прошлого забега controller.reset(); // чистый ввод: не тащим зажатые клавиши/смену оружия из прошлого забега
const game = new Game(rules); const game = new Game(rules);
const currentWorld = new ThreeRenderer(world, assetPack.path);
const currentHud = new HudOverlay(hudCanvas, assetPack.path);
world3d = currentWorld;
hud = currentHud;
loop = new GameLoop(game, controller, (alpha) => { loop = new GameLoop(game, controller, (alpha) => {
world3d.render(game, alpha); currentWorld.render(game, alpha);
hud.render(game); currentHud.render(game);
}); });
menu.hide(); menu.hide();
loop.start(); loop.start();
@@ -49,10 +56,14 @@ function boot(): void {
const toMenu = (): void => { const toMenu = (): void => {
loop?.stop(); loop?.stop();
loop = null; loop = null;
world3d?.dispose();
hud?.dispose();
world3d = null;
hud = null;
menu.show(); // фон меню перекрывает «замёрзший» последний кадр menu.show(); // фон меню перекрывает «замёрзший» последний кадр
}; };
const menu = new StartMenu(menuEl, PRESETS, startGame); const menu = new StartMenu(menuEl, PRESETS, ASSET_PACKS, startGame);
menu.show(); menu.show();
// Esc во время игры — вернуться к выбору уровня (по физической клавише). // Esc во время игры — вернуться к выбору уровня (по физической клавише).
+5 -3
View File
@@ -10,19 +10,21 @@ import type { Renderer } from './Renderer';
export class HudOverlay implements Renderer { export class HudOverlay implements Renderer {
private readonly ctx: CanvasRenderingContext2D; private readonly ctx: CanvasRenderingContext2D;
private readonly images = new Map<string, HTMLImageElement>(); private readonly images = new Map<string, HTMLImageElement>();
private readonly assetBasePath: string;
/** Лениво грузит PNG из assets/<name>.png; возвращает картинку, только когда она готова. */ /** Лениво грузит PNG из выбранного пака; возвращает картинку, только когда она готова. */
private img(name: string): HTMLImageElement | null { private img(name: string): HTMLImageElement | null {
let im = this.images.get(name); let im = this.images.get(name);
if (!im) { if (!im) {
im = new Image(); im = new Image();
im.src = `assets/${name}.png`; im.src = `${this.assetBasePath}/${name}.png`;
this.images.set(name, im); this.images.set(name, im);
} }
return im.complete && im.naturalWidth > 0 ? im : null; return im.complete && im.naturalWidth > 0 ? im : null;
} }
constructor(canvas: HTMLCanvasElement) { constructor(canvas: HTMLCanvasElement, assetBasePath = 'assets') {
this.assetBasePath = assetBasePath;
// Буфер увеличиваем под плотность пикселей (чёткий текст на HiDPI), // Буфер увеличиваем под плотность пикселей (чёткий текст на HiDPI),
// а рисуем по-прежнему в логических координатах CW×CH. // а рисуем по-прежнему в логических координатах CW×CH.
const dpr = Math.min(window.devicePixelRatio || 1, 2); const dpr = Math.min(window.devicePixelRatio || 1, 2);
+5 -3
View File
@@ -40,7 +40,7 @@ export class ThreeRenderer implements Renderer {
private readonly renderer: THREE.WebGLRenderer; private readonly renderer: THREE.WebGLRenderer;
private readonly scene = new THREE.Scene(); private readonly scene = new THREE.Scene();
private readonly camera: THREE.PerspectiveCamera; private readonly camera: THREE.PerspectiveCamera;
private readonly assets = new Assets(); private readonly assets: Assets;
private readonly theme: Theme; private readonly theme: Theme;
// Общие геометрии. // Общие геометрии.
@@ -75,8 +75,10 @@ export class ThreeRenderer implements Renderer {
private pickupMesh: THREE.Mesh | null = null; private pickupMesh: THREE.Mesh | null = null;
private currentPickupWeapon: WeaponId | null = null; private currentPickupWeapon: WeaponId | null = null;
constructor(canvas: HTMLCanvasElement, theme: Theme = DEFAULT_THEME) { constructor(canvas: HTMLCanvasElement, assetBasePathOrTheme: string | Theme = 'assets', theme: Theme = DEFAULT_THEME) {
this.theme = theme; const assetBasePath = typeof assetBasePathOrTheme === 'string' ? assetBasePathOrTheme : 'assets';
this.theme = typeof assetBasePathOrTheme === 'string' ? theme : assetBasePathOrTheme;
this.assets = new Assets(assetBasePath);
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.setSize(CW, CH, false); this.renderer.setSize(CW, CH, false);
+15
View File
@@ -0,0 +1,15 @@
/** Наборы ассетов. Логика игры про них не знает — это чисто настройка рендера/HUD. */
export type AssetPackId = 'classic' | 'binding-2';
export interface AssetPack {
id: AssetPackId;
name: string;
path: string;
}
export const ASSET_PACKS: readonly AssetPack[] = [
{ id: 'classic', name: 'Классика', path: 'assets' },
{ id: 'binding-2', name: 'Биндинг 2.0', path: 'assets-binding-2' },
];
export const DEFAULT_ASSET_PACK = ASSET_PACKS[0];
+7 -5
View File
@@ -3,12 +3,12 @@ import type { WeaponId } from '../core/weapons';
/** /**
* assets.ts — поставщик текстур. Каждая текстура грузится из * assets.ts — поставщик текстур. Каждая текстура грузится из
* `src/assets/<ключ>.png` через THREE.TextureLoader; если PNG нет — рисуется * `<пак>/<ключ>.png` через THREE.TextureLoader; если PNG нет — рисуется
* процедурный фолбэк на canvas (функции drawX ниже), чтобы игра работала без * процедурный фолбэк на canvas (функции drawX ниже), чтобы игра работала без
* ассетов. Текстуры кэшируются и освобождаются в dispose(). * ассетов. Текстуры кэшируются и освобождаются в dispose().
* *
* Как заменить/добавить графику: положи PNG с именем `<ключ>.png` в `src/assets/` * Как заменить/добавить графику: положи PNG с именем `<ключ>.png` в папку пака
* (dev-сервер отдаёт их из src/assets, прод-сборка копирует в dist/assets). Код * (dev-сервер отдаёт их из src/<asset-pack>, прод-сборка копирует в dist/). Код
* трогать не нужно. Функции drawX — это лишь плейсхолдер-фолбэк; правь их, только * трогать не нужно. Функции drawX — это лишь плейсхолдер-фолбэк; правь их, только
* если хочешь другой запасной рисунок. Полный список ключей — в docs/ASSET_BRIEF.md. * если хочешь другой запасной рисунок. Полный список ключей — в docs/ASSET_BRIEF.md.
*/ */
@@ -364,9 +364,11 @@ export class Assets {
private cache = new Map<string, THREE.Texture>(); private cache = new Map<string, THREE.Texture>();
private readonly loader = new THREE.TextureLoader(); private readonly loader = new THREE.TextureLoader();
constructor(private readonly basePath = 'assets') {}
/** /**
* Возвращает текстуру по ключу. Сначала пытается загрузить PNG из * Возвращает текстуру по ключу. Сначала пытается загрузить PNG из
* `src/assets/<key>.png` (поставляется художником, см. docs/ASSET_BRIEF.md); * `<basePath>/<key>.png` (поставляется художником, см. docs/ASSET_BRIEF.md);
* если файла нет — рисует процедурный фолбэк, чтобы игра не ломалась. * если файла нет — рисует процедурный фолбэк, чтобы игра не ломалась.
* 404 в консоли для ещё не добавленных ассетов — это норма (сработал фолбэк). * 404 в консоли для ещё не добавленных ассетов — это норма (сработал фолбэк).
*/ */
@@ -375,7 +377,7 @@ export class Assets {
if (cached) return cached; if (cached) return cached;
const tex = this.loader.load( const tex = this.loader.load(
`assets/${key}.png`, `${this.basePath}/${key}.png`,
undefined, undefined,
undefined, undefined,
() => { tex.image = build() as unknown as HTMLImageElement; tex.needsUpdate = true; }, // PNG нет → процедурный фолбэк () => { tex.image = build() as unknown as HTMLImageElement; tex.needsUpdate = true; }, // PNG нет → процедурный фолбэк
+39 -2
View File
@@ -1,4 +1,5 @@
import type { LevelRules } from '../core/rules'; import type { LevelRules } from '../core/rules';
import { DEFAULT_ASSET_PACK, type AssetPack } from '../render/assetPacks';
/** /**
* Стартовое меню на DOM (поверх холстов). Показывает список пресетов-уровней; * Стартовое меню на DOM (поверх холстов). Показывает список пресетов-уровней;
@@ -10,12 +11,38 @@ import type { LevelRules } from '../core/rules';
*/ */
export class StartMenu { export class StartMenu {
private readonly root: HTMLElement; private readonly root: HTMLElement;
private selectedPack: AssetPack;
constructor(root: HTMLElement, presets: LevelRules[], onStart: (rules: LevelRules) => void) { constructor(
root: HTMLElement,
presets: LevelRules[],
assetPacks: readonly AssetPack[],
onStart: (rules: LevelRules, assetPack: AssetPack) => void,
) {
this.root = root; this.root = root;
this.selectedPack = assetPacks[0] ?? DEFAULT_ASSET_PACK;
const list = root.querySelector('#menu-presets'); const list = root.querySelector('#menu-presets');
if (!list) throw new Error('StartMenu: не найден #menu-presets внутри #menu'); if (!list) throw new Error('StartMenu: не найден #menu-presets внутри #menu');
const packs = document.createElement('div');
packs.className = 'menu-packs';
const packButtons: HTMLButtonElement[] = [];
for (const pack of assetPacks) {
const btn = document.createElement('button');
btn.className = 'menu-pack';
btn.type = 'button';
btn.textContent = pack.name;
btn.addEventListener('click', () => {
this.selectedPack = pack;
for (const b of packButtons) b.classList.toggle('is-selected', b === btn);
this.applyPackPreview();
});
packButtons.push(btn);
packs.appendChild(btn);
}
packButtons[0]?.classList.add('is-selected');
list.before(packs);
for (const rules of presets) { for (const rules of presets) {
const btn = document.createElement('button'); const btn = document.createElement('button');
btn.className = 'menu-preset'; btn.className = 'menu-preset';
@@ -30,9 +57,11 @@ export class StartMenu {
desc.textContent = rules.description; desc.textContent = rules.description;
btn.append(name, desc); btn.append(name, desc);
btn.addEventListener('click', () => onStart(rules)); btn.addEventListener('click', () => onStart(rules, this.selectedPack));
list.appendChild(btn); list.appendChild(btn);
} }
this.applyPackPreview();
} }
show(): void { show(): void {
@@ -42,4 +71,12 @@ export class StartMenu {
hide(): void { hide(): void {
this.root.style.display = 'none'; this.root.style.display = 'none';
} }
private applyPackPreview(): void {
const path = this.selectedPack.path;
const logo = this.root.querySelector<HTMLImageElement>('#menu-logo');
if (logo) logo.src = `${path}/logo.png`;
this.root.style.background =
`linear-gradient(rgba(10,10,15,0.7), rgba(10,10,15,0.82)), url(${path}/menu-bg.png) center / cover no-repeat, #0a0a0f`;
}
} }