Spinner mod: a real 3D space battle in terminal quarter-blocks while Claude works. Six ships, a cutting camera, torpedoes and a cinematic hyperspace jump…

A Claude Code mod that replaces the spinner with a space battle. While Claude works, a real 3D scene plays under the prompt: your ship dodges and rolls, enemies make attack runs, lasers and proton torpedoes fly, and every 34 seconds it makes a cinematic jump to hyperspace.
<img src="assets/scene.webp" alt="An X-wing dogfight rendered in terminal quarter-blocks, ending in a jump to hyperspace" width="100%">
/plugin marketplace add alexregrets/hyperspace
/plugin install hyperspace@hyperspace
Or try it for one session from a clone: claude --plugin-dir ./hyperspace.
/ship picks the ship: xwing, ywing, awing, falcon, tie, interceptor. The choice persists across sessions./cam picks the camera: auto cuts between shots, or lock one of side, rear, low, front, top, cockpit.THINKING in hooks/register.tsx to make them yours.hooks/three.ts is a small software rasterizer: triangle meshes for six ships, a star destroyer and asteroids, a perspective camera, a shared z-buffer, Lambert and Blinn shading with rim light and point lights for explosions. hooks/frame.ts builds a frame as a pure function frame(t, columns, ship, cam), so the same t always gives the same picture. The HDR buffer goes through bloom and an anamorphic flare, then tone mapping, then every 2×2 block of pixels becomes one terminal cell: a quarter-block glyph (▘ ▝ ▖ ▗) plus the two colors that fit it best.
The jump has four beats: stars stretch into rays from the vanishing point, the ship lurches forward and collapses into a point with a flash, a blue tunnel streams past with a white core, then the tunnel tears and the rays snap back into stars.
It stays cheap on purpose:
turn.complete;node tools/bench_jump.mts).On surfaces other than the terminal, or in terminals narrower than 40 columns, you get the normal spinner with the custom phrase.
HYPERSPACE_DIR=. node tools/render_scene.mts out.raw xwing auto 100 3000 23000 15
python tools/to_webp.py out.raw scene.webp 200 24 15
claude plugin test .
MIT
hooks/register.tsx 245 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import { CAMS, encode, frame, hyper, jumpTime, killsAt, ROWS, SHIPS, type CamMode, type Ev, type Res, type Ship } from './frame'
4
5const FRAME_MS = 66 // тик таймера; в обычном полёте рисуем через раз (~10 к/с), в прыжке каждый (~15 к/с)
6const EDGE = 4 // столбцы, оставленные пустыми у правого края
7const MAX_COLS = 220 // сцена во всю ширину терминала, но не шире этого
8
9// фразы, пока модель думает (mode === 'thinking')
10const THINKING = [
11 'Варю мысль на медленном огне', 'Спорю сам с собой и проигрываю', 'Гоняю гипотезы по кругу',
12 'Делаю вид, что знал это всегда', 'Собираю мозг из запчастей', 'Ищу подвох в собственном ответе',
13 'Сверяю с картой реальности', 'Прокачиваю стат «интеллект»', 'Локнулся, не мешай',
14 'Думаю дороже, чем стою', 'Чувствую возмущение в Силе', 'Рассчитываю прыжок через гиперпространство',
15]
16
17// что говорит /ship и каким цветом строка под сценой
18const SHIP_LINE: Record<Ship, string> = {
19 xwing: 'X-wing на взлёте. Red Five, standing by',
20 tie: 'TIE в строю. Империя одобряет',
21 falcon: 'Сокол на ходу. Kessel Run меньше чем за 12 парсеков',
22 ywing: 'Y-wing в строю. Gold Leader, заходим на траншею',
23 awing: 'A-wing на форсаже. Быстрее только слухи',
24 interceptor: 'TIE-перехватчик. Кинжалы наточены',
25}
26const SHIP_COLOR: Record<Ship, string> = {
27 xwing: '#ff6b5a', tie: '#5aff7a', falcon: '#7fd0ff', ywing: '#ffc94a', awing: '#ff7a6a', interceptor: '#5aff7a',
28}
29// что говорит /cam
30const CAM_LINE: Record<CamMode, string> = {
31 auto: 'Камера: монтаж, план раз в 6.5 с', side: 'Камера: сбоку', rear: 'Камера: из-за хвоста',
32 low: 'Камера: снизу, героический ракурс', front: 'Камера: спереди, летит на нас', top: 'Камера: сверху',
33 cockpit: 'Камера: из кабины, прицел на враге',
34}
35const RES_LINE: Record<Res, string> = {
36 quad: 'Разрешение: четвертьблоки 2×2 — работают везде',
37 sext: 'Секстанты недоступны: Raster в Claude Code не пускает символы вне BMP. Остаёмся на четвертьблоках',
38}
39// инструменты, правка которыми — торпеда; остальные — залп лазеров
40const TORPEDO_TOOLS = /^(Edit|Write|MultiEdit|NotebookEdit)$/
41
42// сегодняшняя дата для счётчика сбитых
43const today = () => new Date().toISOString().slice(0, 10)
44
45// случайный элемент массива
46const pick = (xs: string[]) => xs[Math.floor(Math.random() * xs.length)]!
47
48// состояние спиннера на ход; переменные модуля — перезагрузка начнёт заново, это ок
49const spin = {
50 turnAt: 0, working: false, last: '', blit: true, ship: 'xwing' as Ship, cam: 'auto' as CamMode,
51 res: 'quad' as Res, seed: 0, events: [] as Ev[], killsToday: 0,
52 thought: pick(THINKING), lastMode: '',
53 mount: null as { requestId: string; columns: number } | null,
54 timer: null as { cancel: () => void } | null, busy: false, tick: 0,
55}
56
57// параметры кадра из состояния: сценарий хода, события, разрешение
58// секстанты (U+1FB00) Raster не пускает: вне BMP — движок отказывает каждый кадр. Пока только четвертьблоки
59const opts = () => ({ seed: spin.seed, events: spin.events, res: 'quad' as Res })
60
61// новый ход: свой сценарий боя и пустой журнал событий
62function newTurn(now: number) {
63 [spin.working, spin.turnAt] = [true, now]
64 spin.seed = Math.floor(Math.random() * 1_000)
65 spin.events = []
66}
67
68// время хода в виде «12s» / «1m 05s»
69const elapsed = (ms: number) => {
70 const s = Math.floor(ms / 1000)
71 return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`
72}
73
74// один тик анимации: перерисовать сетку через blit, без полного рендера
75async function paint($: EngineInterface) {
76 const m = spin.mount
77 if (!m || !spin.working || spin.busy) return // прошлый кадр ещё в пути — пропускаем, не копим очередь
78 spin.busy = true
79 try {
80 await paintOnce($, m)
81 } finally {
82 spin.busy = false
83 }
84}
85
86// отрисовать один кадр в смонтированную сетку
87async function paintOnce($: EngineInterface, m: { requestId: string; columns: number }) {
88 const now = await $.clock.now()
89 spin.tick++
90 if (jumpTime(now - spin.turnAt) < 0 && spin.tick % 2) return // в покое хватит половины кадров
91 const cells = encode(frame(now - spin.turnAt, m.columns, spin.ship, spin.cam, opts()))
92 if (cells === spin.last) return
93 spin.last = cells
94 if (!spin.blit) {
95 $.ui.invalidate('ui.render')
96 return
97 }
98 const r = await $.ui.blit({ requestId: m.requestId, key: 'sky', cells })
99 if ('deny' in r && r.deny) {
100 spin.blit = false
101 $.ui.invalidate('ui.render')
102 }
103}
104
105// завести таймер анимации, если ещё не идёт
106function startTimer($: EngineInterface) {
107 if (!spin.timer) spin.timer = $.clock.every(FRAME_MS, () => void paint($))
108}
109
110export const register: Register = on => {
111 on('session.start', async ($, e, next) => {
112 if (!e.isInteractive) return next(e)
113 try {
114 const s = await $.store.get('ship')
115 if (SHIPS.includes(s as Ship)) spin.ship = s as Ship
116 const c = await $.store.get('cam')
117 if (CAMS.includes(c as CamMode)) spin.cam = c as CamMode
118 const r = await $.store.get('res')
119 if (r === 'quad' || r === 'sext') spin.res = r
120 const k = await $.store.get(`kills:${today()}`)
121 if (typeof k === 'number') spin.killsToday = k
122 } catch {
123 // нет хранилища — летим на дефолтном
124 }
125 await $.command.register({ name: 'ship', description: 'Сменить корабль: xwing / ywing / awing / falcon / tie / interceptor' })
126 await $.command.register({ name: 'cam', description: 'Камера сцены: auto / side / rear / low / front / top / cockpit' })
127 await $.command.register({ name: 'res', description: 'Разрешение сцены: quad (2×2, везде) / sext (2×3, чётче)' })
128 return next(e)
129 })
130
131 // /ship — следующий корабль по кругу, /ship tie|xwing|falcon — выбрать; выбор помнится между сессиями
132 on('command.run', { command: 'ship' }, async ($, e) => {
133 const arg = String((e as { args?: string }).args ?? '').trim().toLowerCase()
134 spin.ship = SHIPS.includes(arg as Ship) ? (arg as Ship) : SHIPS[(SHIPS.indexOf(spin.ship) + 1) % SHIPS.length]!
135 try {
136 await $.store.set('ship', spin.ship)
137 } catch {
138 // запомнится только на эту сессию
139 }
140 spin.last = ''
141 return { text: SHIP_LINE[spin.ship] }
142 })
143
144 // /cam — следующий план по кругу, /cam rear — выбрать; auto — монтаж сам режет планы
145 on('command.run', { command: 'cam' }, async ($, e) => {
146 const arg = String((e as { args?: string }).args ?? '').trim().toLowerCase()
147 spin.cam = CAMS.includes(arg as CamMode) ? (arg as CamMode) : CAMS[(CAMS.indexOf(spin.cam) + 1) % CAMS.length]!
148 try {
149 await $.store.set('cam', spin.cam)
150 } catch {
151 // запомнится только на эту сессию
152 }
153 spin.last = ''
154 return { text: CAM_LINE[spin.cam] }
155 })
156
157 // /res — переключить разрешение; секстанты чётче, но нужен терминал, который их рисует
158 on('command.run', { command: 'res' }, async ($, e) => {
159 const arg = String((e as { args?: string }).args ?? '').trim().toLowerCase()
160 spin.res = 'quad' // sext недоступен: Raster принимает только символы BMP
161 try {
162 await $.store.set('res', spin.res)
163 } catch {
164 // запомнится только на эту сессию
165 }
166 spin.last = ''
167 return { text: arg === 'sext' ? RES_LINE.sext : RES_LINE.quad }
168 })
169
170 // работа Claude в сцене: инструмент — залп, правка файла — торпеда, ошибка инструмента — попадание по нам
171 on('tool.call', async ($, e, next) => {
172 if (spin.working) {
173 const at = (await $.clock.now()) - spin.turnAt
174 spin.events.push({ t: at, kind: TORPEDO_TOOLS.test(e.tool) ? 'torpedo' : 'shot' })
175 }
176 const r = await next(e)
177 if (spin.working && r && typeof r === 'object' && 'isError' in r && r.isError) {
178 spin.events.push({ t: (await $.clock.now()) - spin.turnAt, kind: 'hit' })
179 }
180 if (spin.events.length > 40) spin.events = spin.events.slice(-40) // старые давно отыграли
181 return r
182 })
183
184 // начало хода: засекаем время (субагент не сбрасывает часы главного хода)
185 on('turn.start', async ($, e, next) => {
186 if (!spin.working) newTurn(await $.clock.now())
187 startTimer($)
188 return next(e)
189 })
190
191 // конец главного хода: анимация стоп
192 on('turn.complete', async ($, e, next) => {
193 const done = await next(e)
194 if (!e.agentId) {
195 // засчитать сбитых за ход в дневной счёт
196 if (spin.working) {
197 spin.killsToday += killsAt((await $.clock.now()) - spin.turnAt)
198 try {
199 await $.store.set(`kills:${today()}`, spin.killsToday)
200 } catch {
201 // без хранилища счёт живёт до конца сессии
202 }
203 }
204 [spin.working, spin.mount] = [false, null]
205 spin.timer?.cancel() // между ходами таймер не тикает вообще
206 spin.timer = null
207 }
208 return done
209 })
210
211 // сцена над строкой спиннера; узкий терминал или не терминал — обычный спиннер со своими фразами
212 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
213 const mode = e.props.mode
214 if (mode === 'thinking' && spin.lastMode !== 'thinking') spin.thought = pick(THINKING)
215 spin.lastMode = mode
216 const word = mode === 'thinking' ? spin.thought : e.props.word
217 const text = e.props.message ?? word
218
219 const columns = Math.min(MAX_COLS, (e.viewport?.columns ?? 0) - EDGE)
220 if (e.surface !== 'terminal' || columns < 40) {
221 spin.mount = null
222 return next({ ...e, props: { ...e.props, word } })
223 }
224 const { Raster, Box, Text } = $.ui.resolve(e)
225 const now = await $.clock.now()
226 if (!spin.working) newTurn(now) // перезагрузка посреди хода
227 startTimer($)
228 if (spin.mount?.requestId !== e.requestId) spin.blit = true
229 spin.mount = { requestId: e.requestId, columns }
230 const t = now - spin.turnAt
231 const cells = encode(frame(t, columns, spin.ship, spin.cam, opts()))
232 spin.last = cells
233 const color = SHIP_COLOR[spin.ship]
234 return (
235 <Box flexDirection="column">
236 <Raster key="sky" columns={columns} rows={ROWS} cells={cells} />
237 <Text>
238 <Text color={color}>{hyper(t) > 0.3 ? '✦ ' : '✧ '}{text}{e.props.suffix}</Text>
239 <Text dimColor> ({elapsed(t)} · сбито {killsAt(t)} · сегодня {spin.killsToday + killsAt(t)})</Text>
240 </Text>
241 </Box>
242 )
243 })
244}
245hooks/frame.ts 885 lines1// Кадр анимации: настоящая 3D-сцена в четвертьблоках ▘▝▖▗ (2×2 пикселя на клетку).
2// Корабль летит по +x, вокруг звёзды и космическая пыль, враги заходят в атаку, лазеры, протонные торпеды,
3// взрывы с ударным кольцом, камера режет планы, прыжок в гиперпространство с туннелем как в кино.
4// Чистая функция от времени: одно и то же t всегда даёт один и тот же кадр.
5
6import {
7 xwing, ywing, awing, tie, interceptor, falcon, destroyer, asteroid,
8 Scene, project, toWorld, camPos, camDirToWorld, type Cam, type Light, Mesh, type Obj, type V,
9} from './three.ts'
10
11export const ROWS = 12 // строк терминала под сцену
12export const DEF = 0x01000000 // цвет терминала по умолчанию
13
14// разрешение: quad — четвертьблоки 2×2 на клетку, sext — секстанты 2×3 (Unicode 13, нужен свежий терминал)
15export type Res = 'quad' | 'sext'
16// событие из работы Claude: выстрел (инструмент), торпеда (правка файла), попадание по нам (ошибка)
17export type Ev = { t: number; kind: 'shot' | 'torpedo' | 'hit' }
18export type Opts = { seed?: number; events?: Ev[]; res?: Res }
19
20export type Ship = 'xwing' | 'ywing' | 'awing' | 'falcon' | 'tie' | 'interceptor'
21export const SHIPS: Ship[] = ['xwing', 'ywing', 'awing', 'falcon', 'tie', 'interceptor']
22export type CamMode = 'auto' | 'side' | 'rear' | 'low' | 'front' | 'top' | 'cockpit'
23export const CAMS: CamMode[] = ['auto', 'side', 'rear', 'low', 'front', 'top', 'cockpit']
24
25const IMPERIAL = new Set<Ship>(['tie', 'interceptor'])
26
27// детерминированный «рандом» от целого
28const hash = (n: number) => {
29 let x = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b)
30 x ^= x >>> 13
31 x = Math.imul(x, 0xc2b2ae35)
32 return ((x ^ (x >>> 16)) >>> 0) / 0xffffffff
33}
34const clamp01 = (x: number) => Math.max(0, Math.min(1, x))
35const ease = (x: number) => { const k = clamp01(x); return k * k * (3 - 2 * k) }
36const lerp = (a: number, b: number, k: number) => a + (b - a) * k
37const lerpV = (a: V, b: V, k: number): V => [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]
38
39// ── меши: X-wing складывает крылья, остальные постоянные ──
40const meshes = new Map<string, Mesh>()
41function meshOf(ship: Ship | 'destroyer' | `rock${number}`, open = 0.24, head = 0, brace = 0): Mesh {
42 const headStep = Math.round(head * 8), braceStep = Math.round(brace * 16)
43 const key = ship === 'xwing' ? `x${Math.round(open * 40)}:${headStep}:${braceStep}` : ship
44 if (ship.startsWith('rock')) {
45 let r = meshes.get(key)
46 if (!r) meshes.set(key, (r = asteroid(Number(ship.slice(4)))))
47 return r
48 }
49 let m = meshes.get(key)
50 if (!m) {
51 m = ship === 'xwing' ? xwing(Math.round(open * 40) / 40, headStep / 8, braceStep / 16) : ship === 'ywing' ? ywing() : ship === 'awing' ? awing()
52 : ship === 'falcon' ? falcon() : ship === 'tie' ? tie() : ship === 'interceptor' ? interceptor() : destroyer()
53 if (meshes.size >= 128) meshes.clear()
54 meshes.set(key, m)
55 }
56 return m
57}
58
59// ── прыжок в гиперпространство: тайминг фаз, мс от начала прыжка ──
60const FIRST_JUMP = 12_000 // сначала бой, потом прыжок
61const JUMP_EVERY = 34_000
62const CHARGE = 1_300 // подготовка, затем ускоряющийся рост лучей
63const STRETCH = 2_350 // камера остаётся, корабль уходит вдаль за 350 мс
64const FLASH = 2_700 // точка → короткая белая вспышка → туннель
65const EXIT = 8_200 // разрыв туннеля; лучи сжимаются за 520 мс
66export const JUMP_LEN = 10_000
67
68// мс от начала прыжка или −1
69export const jumpTime = (t: number) => {
70 if (t < FIRST_JUMP) return -1
71 const p = (t - FIRST_JUMP) % JUMP_EVERY
72 return p < JUMP_LEN ? p : -1
73}
74export const hyper = (t: number) => {
75 const p = jumpTime(t)
76 if (p < 0) return 0
77 if (p < FLASH) return Math.pow(clamp01(p / STRETCH), 3)
78 if (p < EXIT) return 1
79 return 1 - ease((p - EXIT) / 700)
80}
81// Доля радиального удлинения: рост ease-in, сжатие намного быстрее.
82const streakAt = (p: number) => {
83 if (p < 0) return 0
84 if (p < FLASH) return Math.pow(clamp01((p - 350) / (STRETCH - 350)), 3)
85 if (p < EXIT) return 0
86 return Math.pow(1 - clamp01((p - EXIT) / 520), 2)
87}
88
89// Только поза прыжка: модели не меняются. Дальность и сжатие дают уход в точку.
90export function jumpPose(t: number) {
91 const p = jumpTime(t)
92 let forward = 0, scale = 1, stretch = 1, point = 0
93 if (p >= STRETCH && p < FLASH + 650) {
94 const q = p < FLASH ? clamp01((p - STRETCH) / (FLASH - STRETCH)) : 1 - ease((p - FLASH - 120) / 530)
95 forward = 650 * q * q * q
96 scale = 1 - 0.94 * q * q
97 stretch = 1 + 4 * Math.sin(Math.PI * q)
98 point = ease((q - 0.65) / 0.35)
99 } else if (p >= EXIT) {
100 const q = clamp01((p - EXIT - 40) / 1_050)
101 forward = q === 1 ? 0 : 650 * Math.pow(1 - q, 5) - 448 * Math.pow(q * (1 - q), 3)
102 scale = 0.06 + 0.94 * (1 - Math.pow(1 - q, 3))
103 stretch = 1 + 3 * Math.sin(Math.PI * q) * (1 - q)
104 point = Math.pow(1 - q, 4)
105 }
106 return { forward, scale, stretch, point }
107}
108// Аналитическая кинематика: скорость — производная пути, никаких интеграторов и dt.
109// Корпус летит носом по касательной; крен отвечает боковому ускорению, а не отдельной синусоиде.
110export function flightAt(t: number, evading = false): Obj {
111 const u = t % 5_200, q = clamp01((u - 1_150) / 950)
112 const sn = Math.sin(Math.PI * q), cs = Math.cos(Math.PI * q)
113 const sign = Math.floor(t / 5_200) % 2 ? -1 : 1
114 const dodge = evading ? Math.pow(sn, 4) : 0
115 const dv = evading ? 4 * sn * sn * sn * cs * Math.PI / 950 : 0
116 const da = evading ? (12 * sn * sn * cs * cs - 4 * Math.pow(sn, 4)) * Math.pow(Math.PI / 950, 2) : 0
117 const y = 0.55 * Math.sin(t / 1_250) + 0.13 * Math.sin(t / 520) + dodge * 0.24
118 const z = 0.9 * Math.sin(t / 1_700) + 0.2 * Math.sin(t / 730) + sign * dodge * 1.2
119 const vy = 0.55 / 1_250 * Math.cos(t / 1_250) + 0.13 / 520 * Math.cos(t / 520) + dv * 0.24
120 const vz = 0.9 / 1_700 * Math.cos(t / 1_700) + 0.2 / 730 * Math.cos(t / 730) + sign * dv * 1.2
121 const az = -0.9 / (1_700 * 1_700) * Math.sin(t / 1_700) - 0.2 / (730 * 730) * Math.sin(t / 730) + sign * da * 1.2
122 const br = clamp01(((t + 21_000) % 24_000) / 1_400)
123 const barrel = br < 1 ? br * br * br * (10 + br * (-15 + 6 * br)) * Math.PI * 2 : 0
124 return { pos: [0, y, z], yaw: -Math.atan2(vz, 0.03), pitch: Math.atan2(vy, 0.03), roll: -Math.atan(az * 8_000) - barrel }
125}
126
127// Сервопривод головы: плавный обзор, фиксация по курсу при разгоне и затухающая стабилизация.
128export function r2At(t: number, attitude: Pick<Obj, 'yaw' | 'pitch'> = flightAt(t)) {
129 const p = jumpTime(t)
130 const charge = p >= 0 && p < FLASH ? ease(p / STRETCH) : 0
131 const braking = p >= EXIT ? Math.exp(-(p - EXIT) / 240) * Math.sin((p - EXIT) / 105) : 0
132 const scan = 0.65 * Math.sin(t / 2_600) + 0.18 * Math.sin(t / 970)
133 return { head: scan * (1 - charge) * (p >= FLASH && p < EXIT ? 0.3 : 1) - attitude.yaw * 0.6, brace: Math.max(-0.16, Math.min(0.16, -attitude.pitch * 0.7 - 0.1 * charge + 0.08 * braking)) }
134}
135
136// идёт ли прыжок где-то в отрезке [a, b]
137const jumpIn = (a: number, b: number) => {
138 for (let x = a; x <= b; x += 250) if (jumpTime(x) >= 0) return true
139 return jumpTime(b) >= 0
140}
141
142// ── цвет ──
143type RGB = [number, number, number]
144const rgbOf = (c: number): RGB => [((c >> 16) & 255) / 255, ((c >> 8) & 255) / 255, (c & 255) / 255]
145const hexOf = (c: RGB) => {
146 const ch = (v: number) => Math.max(0, Math.min(255, Math.round(v * 255)))
147 return (ch(c[0]) << 16) | (ch(c[1]) << 8) | ch(c[2])
148}
149const mixC = (a: RGB, b: RGB, k: number): RGB => [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)]
150const WHITE: RGB = [1, 1, 1]
151// огонь: белый → жёлтый → оранжевый → красный → дым
152const FIRE: RGB[] = [[1, 1, 0.95], [1, 0.9, 0.45], [1, 0.55, 0.15], [0.85, 0.2, 0.05], [0.25, 0.2, 0.2], [0, 0, 0]]
153const fire = (k: number): RGB => {
154 const x = clamp01(k) * (FIRE.length - 1), i = Math.min(FIRE.length - 2, Math.floor(x))
155 return mixC(FIRE[i]!, FIRE[i + 1]!, x - i)
156}
157// туннель: глубокая синь → кобальт → голубой → белый
158const TUN: RGB[] = [[0.01, 0.03, 0.1], [0.04, 0.14, 0.42], [0.16, 0.42, 0.88], [0.6, 0.85, 1], [1, 1, 1]]
159const tun = (k: number): RGB => {
160 const x = clamp01(k) * (TUN.length - 1), i = Math.min(TUN.length - 2, Math.floor(x))
161 return mixC(TUN[i]!, TUN[i + 1]!, x - i)
162}
163
164// гладкий шум 2D: значения в узлах решётки, между ними smoothstep
165function noise(x: number, y: number) {
166 const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi
167 const h = (a: number, b: number) => hash(a * 374761 + b * 668265)
168 const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf)
169 return lerp(lerp(h(xi, yi), h(xi + 1, yi), u), lerp(h(xi, yi + 1), h(xi + 1, yi + 1), u), v)
170}
171
172// цвет пикселя небесного тела по нормали: 0 — Звезда Смерти, 1 — пустынная планета, 2 — ледяная
173function bodyColor(kind: number, nx: number, ny: number, seed: number): RGB {
174 const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny))
175 const lam = Math.max(0, -0.35 * nx - 0.75 * ny + 0.55 * nz)
176 const shade = 0.04 + 0.96 * lam
177 const g = noise(nx * 9 + seed, ny * 9)
178 let c: RGB
179 if (kind === 0) {
180 c = mixC([0.55, 0.57, 0.6], [0.72, 0.74, 0.77], g)
181 if (Math.abs(ny + 0.04) < 0.06) c = mixC(c, [0.15, 0.15, 0.17], 0.7) // экваториальная траншея
182 const dx = nx + 0.38, dy = ny + 0.36, dd = dx * dx + dy * dy
183 if (dd < 0.07) c = mixC(c, [0.2, 0.21, 0.23], dd < 0.01 ? 0.3 : 0.6) // чаша суперлазера
184 } else if (kind === 1) {
185 c = mixC([0.85, 0.68, 0.45], [0.6, 0.42, 0.26], 0.5 + 0.5 * Math.sin(ny * 10 + g * 2.5))
186 } else {
187 c = mixC([0.92, 0.95, 1], [0.55, 0.68, 0.84], g * 0.8 + (Math.abs(ny) > 0.7 ? 0 : 0.15))
188 }
189 // атмосфера: голубой ободок по краю у планет
190 const rim = kind === 0 ? 0 : Math.pow(1 - nz, 4) * 0.5 * (0.3 + lam)
191 return [c[0] * shade + rim * 0.4, c[1] * shade + rim * 0.6, c[2] * shade + rim]
192}
193
194// ── камера: планы, монтаж по времени, ручная тряска ──
195type Shot = { azim: number; elev: number; dist: number; fy: number; tx: number; cx: number; drift: number }
196// прыжок: камера прямо за хвостом, точка схода по центру — как Сокол уходит в гипер в фильме
197const JUMP_SHOT: Shot = { azim: Math.PI / 2, elev: 0.025, dist: 21, fy: 2.9, tx: 1, cx: 0.5, drift: 0 }
198const SHOTS: Record<Exclude<CamMode, 'auto'>, Shot> = {
199 side: { azim: 0.42, elev: 0.22, dist: 34, fy: 2.67, tx: 1, cx: 0.3, drift: 0.12 }, // классика: идёт вправо, чуть от нас
200 rear: { azim: 1.18, elev: 0.12, dist: 30, fy: 2.73, tx: 3, cx: 0.34, drift: 0.08 }, // из-за хвоста: видна точка, куда летим
201 low: { azim: 0.75, elev: -0.3, dist: 28, fy: 2.79, tx: 1, cx: 0.32, drift: 0.15 }, // снизу, героический ракурс
202 front: { azim: -0.75, elev: 0.16, dist: 32, fy: 2.67, tx: 4, cx: 0.62, drift: -0.12 }, // спереди-сбоку: летит на нас
203 top: { azim: 0.3, elev: 0.95, dist: 34, fy: 2.60, tx: 1, cx: 0.3, drift: 0.1 }, // сверху: вид на крылья
204 cockpit: { azim: Math.PI / 2, elev: -0.02, dist: 30, fy: 2.6, tx: 30, cx: 0.5, drift: 0.04 }, // из кабины: камера в фонаре, смотрит по курсу
205}
206const CUT_ORDER: Exclude<CamMode, 'auto'>[] = ['side', 'rear', 'cockpit', 'low', 'side', 'front', 'top', 'cockpit']
207const CUT = 6_500
208
209// камера в момент t: в прыжке всегда из-за хвоста, иначе по монтажу или выбранная
210export function cameraAt(t: number, mode: CamMode, PW: number, PH = ROWS * 2, shakeUntil = -1): { cam: Cam; name: string } {
211 const p = jumpTime(t)
212 let name: Exclude<CamMode, 'auto'>, u: number
213 if (p >= 0) { name = 'rear'; u = p / JUMP_LEN }
214 else if (mode === 'auto') { const k = Math.floor(t / CUT); name = CUT_ORDER[k % CUT_ORDER.length]!; u = (t % CUT) / CUT }
215 else { name = mode; u = (t % 12_000) / 12_000 }
216 const s = p >= 0 ? JUMP_SHOT : SHOTS[name]
217 // ручная камера: медленный дрейф по плану + мелкая дрожь, на разгоне сильнее
218 const hitShake = shakeUntil > t ? 0.05 * ((shakeUntil - t) / 450) : 0 // попадание по нам
219 const shake = (p >= 0 ? (p < STRETCH ? 0.025 * Math.pow(p / STRETCH, 3) : p < FLASH ? 0.025 : 0.0015) : 0.004) + hitShake
220 const jx = (noise(t / 140, 1) - 0.5) * shake, jy = (noise(t / 140, 7) - 0.5) * shake
221 const SY = PH / ROWS // пикселей на клетку по вертикали: 2 или 3
222 const cockpit = name === 'cockpit' && p < 0
223 const cam: Cam = {
224 target: [s.tx, cockpit ? 0.95 : 0, 0], azim: s.azim + s.drift * (u - 0.5) + jx, elev: s.elev + jy,
225 roll: (p >= 0 ? 0 : cockpit ? Math.sin(t / 1300) * 0.2 : Math.sin(t / 2300) * 0.03) + jx * 0.5,
226 dist: s.dist, fy: (s.fy * SY) / 2, ax: 4 / SY, cx: PW * s.cx, cy: PH / 2,
227 }
228 return { cam, name: p >= 0 ? 'jump' : name }
229}
230
231// ── звёзды и пыль: точки в мире, корабль летит сквозь них ──
232type Star = { p: V; b: number; tint: RGB }
233const TINTS: RGB[] = [[1, 1, 1], [0.8, 0.88, 1], [1, 0.93, 0.82], [1, 1, 1], [0.75, 0.82, 1]]
234const STARS: Star[] = Array.from({ length: 1400 }, (_, i) => {
235 let p: V = [0, 0, 0]
236 for (let k = 0; k < 8; k++) {
237 p = [(hash(i * 3 + 1 + k * 9001) - 0.5) * 520, (hash(i * 3 + 2 + k * 9001) - 0.5) * 300, (hash(i * 3 + 3 + k * 9001) - 0.5) * 520]
238 if (Math.hypot(p[0], p[1], p[2]) > 70) break // не рядом с кораблём и камерой
239 }
240 return { p, b: 0.25 + 0.75 * Math.pow(hash(i * 7 + 5), 3), tint: TINTS[Math.floor(hash(i * 11) * TINTS.length)]! }
241})
242const DUST: V[] = Array.from({ length: 90 }, (_, i) => [(hash(i * 5 + 1) - 0.5) * 80, (hash(i * 5 + 2) - 0.5) * 30, (hash(i * 5 + 3) - 0.5) * 70])
243
244const CRUISE = 0.03 // единиц мира за мс: ~2 корпуса в секунду
245
246// ── бой: детерминированная хореография на цикле ──
247const WAVE = 5_200
248// болт: летит из a в b; abs — время задано абсолютно (а не от начала волны)
249type Bolt = { a: V; b: V; t0: number; t1: number; col: RGB; abs?: boolean }
250
251// позиция врага в волне на время u (мс от начала волны); враг заходит справа-сзади и идёт на нас
252function enemyPath(k: number, u: number, reach: number): { pos: V; yaw: number; roll: number } {
253 const sy = hash(k * 13) < 0.5 ? 1 : -1
254 const S: V = [reach + 55, sy * (3 + hash(k * 5) * 3), -50 - hash(k * 3) * 25]
255 const H: V = [reach, sy * (0.5 + hash(k * 9) * 1.5), -5 - hash(k * 17) * 6]
256 const e = ease(u / 2_700)
257 const pos: V = [lerp(S[0], H[0], e), lerp(S[1], H[1], e) + Math.sin(u / 300) * 0.6, lerp(S[2], H[2], e)]
258 return { pos, yaw: Math.PI - 0.25 + Math.sin(u / 500) * 0.2, roll: Math.sin(u / 420 + k) * 0.6 }
259}
260
261// ── основной кадр ──
262// буферы кадра живут между кадрами: на 15 к/с не плодим мусор для сборщика
263const pool = new Map<string, { rgb: Float32Array; br: Float32Array; tmp: Float32Array; scene: Scene }>()
264function buffers(PW: number, PH: number) {
265 const key = `${PW}x${PH}`
266 let b = pool.get(key)
267 if (!b) {
268 if (pool.size > 4) pool.clear()
269 const n = PW * PH * 3
270 pool.set(key, (b = { rgb: new Float32Array(n), br: new Float32Array(n), tmp: new Float32Array(n), scene: new Scene(PW, PH) }))
271 }
272 b.rgb.fill(0)
273 b.scene.reset()
274 return b
275}
276
277// сколько врагов сбито к моменту t хода: волна засчитана, когда враг взорвался
278export function killsAt(t: number): number {
279 let n = 0
280 for (let k = 0; k * WAVE + 2_700 <= t; k++) if (!jumpIn(k * WAVE, k * WAVE + WAVE)) n++
281 return n
282}
283
284export function frame(t: number, columns: number, ship: Ship, camMode: CamMode = 'auto', opts: Opts = {}): Uint32Array {
285 const res = opts.res ?? 'quad', SY = res === 'sext' ? 3 : 2
286 const PW = columns * 2, PH = ROWS * SY
287 const N = PW * PH
288 const seed = opts.seed ?? 0
289 const events = opts.events ?? []
290 const buf = buffers(PW, PH)
291 const rgb = buf.rgb // HDR-буфер: может быть > 1, потом блум и мягкий клип
292 const add = (x: number, y: number, c: RGB, a: number) => {
293 x = Math.round(x); y = Math.round(y)
294 if (x < 0 || x >= PW || y < 0 || y >= PH) return
295 const o = (y * PW + x) * 3
296 rgb[o] += c[0] * a; rgb[o + 1] += c[1] * a; rgb[o + 2] += c[2] * a
297 }
298 // отрезок с аддитивным свечением, яркость от головы к хвосту
299 const ray = (x0: number, y0: number, x1: number, y1: number, c: RGB, a0: number, a1: number, occl?: (x: number, y: number) => boolean) => {
300 const n = Math.min(600, Math.max(1, Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0) * 2))))
301 for (let i = 0; i <= n; i++) {
302 const k = i / n, x = lerp(x0, x1, k), y = lerp(y0, y1, k)
303 if (occl && occl(x, y)) continue
304 add(x, y, c, lerp(a0, a1, k))
305 }
306 }
307
308 const p = jumpTime(t)
309 const h = hyper(t)
310 const lastHit = events.reduce((m, e) => (e.kind === 'hit' && e.t <= t ? Math.max(m, e.t) : m), -1e9)
311 const { cam, name: shotName } = cameraAt(t, camMode, PW, PH, lastHit + 450)
312 const cockpit = shotName === 'cockpit'
313 const cp = camPos(cam)
314 const imperial = IMPERIAL.has(ship)
315 const myLaser: RGB = imperial ? [0.35, 1, 0.4] : [1, 0.25, 0.18]
316 const theirLaser: RGB = imperial ? [1, 0.25, 0.18] : [0.35, 1, 0.4]
317 const reach = Math.min(34, Math.max(16, (columns * 0.55) / 2.5)) // как далеко вперёд видно на этой ширине
318
319 const inTunnel = p >= FLASH && p < EXIT + 80
320 const scene = buf.scene
321
322 // ── 1. цилиндр: широкие облачные потоки, смаз вдоль курса, белый центр ──
323 if (inTunnel) {
324 const tt = p - FLASH, R = 14
325 // Ортонормальный базис один раз на кадр. Ненормированный луч даёт тот же
326 // корень пересечения, экономя три поворота и hypot на каждом пикселе.
327 const right = camDirToWorld([1, 0, 0], cam), up = camDirToWorld([0, 1, 0], cam)
328 const forward = camDirToWorld([0, 0, -cam.dist], cam)
329 const invX = 1 / (cam.ax * cam.fy), invY = 1 / cam.fy
330 for (let y = 0; y < PH; y++) for (let x = 0; x < PW; x++) {
331 const sx = (x + 0.5 - cam.cx) * invX, sy = -(y + 0.5 - cam.cy) * invY
332 const wx = forward[0] + sx * right[0] + sy * up[0]
333 const wy = forward[1] + sx * right[1] + sy * up[1]
334 const wz = forward[2] + sx * right[2] + sy * up[2]
335 const A = wy * wy + wz * wz, B = 2 * (cp[1] * wy + cp[2] * wz), C = cp[1] * cp[1] + cp[2] * cp[2] - R * R
336 const distance = A < 1e-5 ? 2_000 : (-B + Math.sqrt(Math.max(0, B * B - 4 * A * C))) / (2 * A)
337 const u = Math.min(450, cp[0] + distance * wx)
338 const th = Math.atan2(cp[1] + distance * wy, cp[2] + distance * wz) + u * 0.002 + tt * 0.000065
339 // Плюс время: облака идут от большой глубины к камере, от центра к краям.
340 const flow = u * 0.026 + tt * 0.0045
341 // Три выдержки вдоль оси: продольный смаз без высокочастотных октав.
342 const angular = Math.cos(th) * 2.1 + 8
343 const cloud = (noise(angular, flow) + 2 * noise(angular, flow - 0.65) + noise(angular, flow - 1.3)) / 4
344 const cloudLight = ease((cloud - 0.25) / 0.5)
345 const bands = Math.pow(0.5 + 0.5 * Math.sin(th * 7 + 1.3 * Math.sin(th * 3) + cloud * 2), 3)
346 const trace = Math.pow(0.5 + 0.5 * Math.sin(th * 11 + Math.sin(th * 4) + u * 0.004), 18)
347 const pulse = 0.4 + 0.6 * noise(Math.sin(th) * 2 + 20, flow * 0.45)
348 const fog = 1 - Math.exp(-Math.max(0, u) / 105)
349 const c = tun(0.08 + fog * 0.78 + bands * (0.05 + cloudLight * 0.43) + trace * pulse * 0.25)
350 const core = Math.pow(fog, 8) * 1.5
351 const o = (y * PW + x) * 3
352 rgb[o] = c[0] + core; rgb[o + 1] = c[1] + core; rgb[o + 2] = c[2] + core
353 }
354 }
355
356 // ── 2. далёкое: Звезда Смерти / пустынная / ледяная / звёздный разрушитель, раз в проход ──
357 const span = 300, passX = (t * 0.006) % span
358 const pass = Math.floor((t * 0.006) / span) + (t > FIRST_JUMP + EXIT ? 1 : 0)
359 const kind = (pass + seed) % 5 // 0–2 планеты, 3 — разрушитель, 4 — поле астероидов
360 if (!inTunnel && kind < 3) {
361 const R = kind === 0 ? 26 : 34
362 const center: V = [140 - passX, kind === 0 ? 30 : -28, -170]
363 const pc = project(center, cam)
364 if (pc) {
365 const rpx = R * pc[3]
366 for (let y = Math.max(0, Math.floor(pc[1] - rpx)); y <= Math.min(PH - 1, pc[1] + rpx); y++) {
367 for (let x = Math.max(0, Math.floor(pc[0] - rpx * cam.ax)); x <= Math.min(PW - 1, pc[0] + rpx * cam.ax); x++) {
368 const nx = (x + 0.5 - pc[0]) / (rpx * cam.ax), ny = (y + 0.5 - pc[1]) / rpx
369 const r2 = nx * nx + ny * ny
370 if (r2 > 1) continue
371 const c = bodyColor(kind, nx, ny, pass * 3.7)
372 const a = Math.min(1, (1 - Math.sqrt(r2)) * rpx * 1.5) // сглаженный край диска
373 const o = (y * PW + x) * 3
374 rgb[o] = c[0] * a; rgb[o + 1] = c[1] * a; rgb[o + 2] = c[2] * a
375 }
376 }
377 }
378 }
379
380 // ── 3. звёзды: точки в покое, лучи от точки схода в прыжке; пыль у камеры — чувство скорости ──
381 const L = streakAt(p)
382 if (!inTunnel) {
383 // В разгоне фиксируем исходные точки; после выхода новое небо больше не скачет назад.
384 const completed = t < FIRST_JUMP ? 0 : Math.floor((t - FIRST_JUMP) / JUMP_EVERY) + (p < 0 || p >= EXIT ? 1 : 0)
385 const starTime = p >= 0 && p < FLASH ? t - p : t
386 const shift = starTime * CRUISE + completed * 777
387 const vp = project([cp[0] + 10_000, cp[1], cp[2]], cam)!
388 const settle = p >= EXIT ? 0.045 * Math.sin((p - EXIT) / 80) * Math.exp(-(p - EXIT) / 240) : 0
389 for (let i = 0; i < STARS.length; i++) {
390 const st = STARS[i]!
391 const x = ((((st.p[0] - shift) % 520) + 780) % 520) - 260
392 const a = project([x, st.p[1], st.p[2]], cam)
393 if (!a || a[0] < -40 || a[0] > PW + 40 || a[1] < -40 || a[1] > PH + 40) continue
394 const tw = 0.75 + 0.25 * noise(i, t / 400)
395 const near = clamp01(80 / a[2])
396 const br = st.b * tw * (1 + L * near * 2)
397 if (p < 0) { add(a[0], a[1], st.tint, br); continue }
398 const dx = a[0] - vp[0], dy = a[1] - vp[1]
399 const hx = a[0] + dx * settle, hy = a[1] + dy * settle
400 add(hx, hy, [0.85, 0.94, 1], br)
401 if (L < 0.004 || (st.b < 0.4 && i % 4)) continue
402 // Голова остаётся на звезде, гаснущий хвост растёт наружу строго по радиусу.
403 const len = L * (0.3 + 2.8 * near)
404 ray(hx, hy, hx + dx * len, hy + dy * len, [0.78, 0.9, 1], br * 0.65, 0)
405 }
406 // пыль: короткие штрихи, проносятся мимо камеры
407 const dshift = t * CRUISE * 1.4
408 for (let i = 0; i < (p < 0 ? DUST.length : 0); i++) {
409 const d = DUST[i]!
410 const x = ((((d[0] - dshift) % 80) + 120) % 80) - 40 + cam.target[0]
411 const a = project([x, d[1], d[2]], cam), b = project([x + 0.735, d[1], d[2]], cam)
412 if (!a || !b || a[2] > 45) continue
413 ray(a[0], a[1], b[0], b[1], [0.6, 0.62, 0.68], 0.35, 0)
414 }
415 }
416
417 // ── 4. корабли: игрок, враги, разрушитель на фоне ──
418 const tick = Math.floor(t / 90) % 3
419 const engine = hexOf(mixC(rgbOf([0xff8a3d, 0xffa64d, 0xffc46b][tick]!), [0.55, 0.75, 1], h))
420 const blue = hexOf(mixC(rgbOf([0x4fb4ff, 0x7fd0ff, 0xb8e8ff][tick]!), WHITE, h * 0.7))
421
422 // разрушитель: огромный, далеко, медленно
423 const destObj: Obj = { pos: [150 - passX * 1.1, 16, -120], yaw: 0.25, pitch: -0.05, roll: 0, scale: 3.6 }
424 if (!inTunnel && kind === 3) scene.draw(meshOf('destroyer'), destObj, cam, engine, blue)
425
426 // волна боя: только в обычном полёте и не впритык к прыжку
427 const k = Math.floor(t / WAVE) + seed * 7919, u = t % WAVE, w0 = t - u
428 const fight = !jumpIn(w0, w0 + WAVE)
429 const torpedo = k % 3 === 2
430 const foeShip: Ship = imperial ? (k % 2 ? 'awing' : 'xwing') : (k % 2 ? 'interceptor' : 'tie')
431 const HIT = 2_700, BOOM = 1_900
432
433 // поза игрока: крен, уклонение от огня, бочка, тряска и рывок в прыжке
434 const open = p < 0 ? 0.24 : p < CHARGE ? 0.24 * (1 - ease(p / CHARGE)) : p < EXIT ? 0 : 0.24 * ease((p - EXIT) / (JUMP_LEN - EXIT))
435 const pose = jumpPose(t)
436 // Перед прыжком автопилот гасит поперечную скорость и выводит корпус на курс.
437 const flight = flightAt(t, fight)
438 const align = p >= 0 ? 1 - ease(p / CHARGE) : 1
439 const settling = p >= EXIT ? Math.sin((p - EXIT) / 110) * Math.exp(-(p - EXIT) / 260) : 0
440 const vibration = p >= 0 && p < FLASH ? Math.pow(clamp01(p / STRETCH), 3) * 0.035 * Math.sin(t / 27) : 0
441 const me: Obj = {
442 pos: [pose.forward, flight.pos[1] * align + vibration, flight.pos[2] * align], scale: pose.scale,
443 yaw: flight.yaw * align, pitch: flight.pitch * align + settling * 0.035,
444 roll: p < 0 ? flight.roll : Math.atan2(Math.sin(flight.roll), Math.cos(flight.roll)) * align,
445 }
446 // свет от взрыва и от событий: подсвечивает корпуса рядом
447 const lights: Light[] = []
448 if (fight && u >= HIT && u < HIT + 900) {
449 lights.push({ p: enemyPath(k, HIT, reach).pos, col: [1, 0.6, 0.25], k: 9 * Math.pow(1 - (u - HIT) / 900, 2) * (torpedo ? 1.6 : 1) })
450 }
451 for (const ev of events) {
452 const age = t - ev.t
453 if (ev.kind === 'torpedo' && age >= 650 && age < 1_300) lights.push({ p: [34, 0, -4], col: [1, 0.6, 0.25], k: 8 * (1 - (age - 650) / 650) })
454 if (ev.kind === 'hit' && age >= 0 && age < 350) lights.push({ p: [2, 2, 3], col: [0.4, 1, 0.4], k: 2.5 * (1 - age / 350) })
455 }
456
457 // поле астероидов: глыбы разного размера медленно крутятся и проплывают мимо
458 if (!inTunnel && kind === 4) {
459 for (let i = 0; i < 26; i++) {
460 const r = 1 + hash(i * 41 + pass) * 3.5
461 const span2 = 260
462 const x = ((((hash(i * 43 + pass) * span2 - t * CRUISE * 0.8) % span2) + span2) % span2) - 90
463 const ap: V = [x, (hash(i * 47 + pass) - 0.5) * 26, -8 - hash(i * 53 + pass) * 70]
464 if (Math.abs(ap[1]) < r + 3 && ap[2] > -14 && Math.abs(ap[0]) < 12) continue // не в корабль
465 scene.draw(meshOf(`rock${i % 7}`), { pos: ap, yaw: t / (900 + i * 70), pitch: t / (1300 + i * 50), roll: i, scale: r }, cam, engine, blue, 1, undefined, lights)
466 }
467 }
468
469 const r2 = r2At(t, me)
470 let myMesh = meshOf(ship, open, r2.head, r2.brace)
471 if (pose.stretch > 1.001) {
472 const stretched = new Mesh()
473 // Растягиваем от хвоста вперёд: хвост не должен пересекать неподвижную камеру.
474 const tail = myMesh.tris.reduce((m, tri) => Math.min(m, tri.a[0], tri.b[0], tri.c[0]), Infinity)
475 const stretch = ([x, y, z]: V): V => [tail + (x - tail) * pose.stretch, y, z]
476 stretched.tris = myMesh.tris.map(tri => ({ ...tri, a: stretch(tri.a), b: stretch(tri.b), c: stretch(tri.c) }))
477 stretched.glows = myMesh.glows.map(g => ({ ...g, p: stretch(g.p) }))
478 stretched.guns = myMesh.guns.map(stretch)
479 myMesh = stretched
480 }
481 const tunnelLit = p >= FLASH && p < EXIT
482 // в туннеле корабль — тёмный силуэт с голубым контровым светом, как на фоне гиперпространства в кино
483 if (!cockpit) scene.draw(myMesh, me, cam, engine, blue, tunnelLit ? 0.12 : 1, tunnelLit ? [0.15, 0.45, 1.1] : undefined, lights)
484
485 let foeObj: Obj | null = null
486 if (fight && u < HIT) {
487 const f = enemyPath(k, u, reach)
488 foeObj = { pos: f.pos, yaw: f.yaw, pitch: 0, roll: f.roll }
489 scene.draw(meshOf(foeShip), foeObj, cam, engine, blue, 1.1, undefined, lights)
490 }
491
492 // ── 5. собрать меши поверх фона ──
493 scene.resolve(rgb)
494 // эффект прячется за кораблём, если корабль ближе
495 const behind = (depth: number) => (x: number, y: number) => {
496 const xi = Math.round(x), yi = Math.round(y)
497 if (xi < 0 || xi >= PW || yi < 0 || yi >= PH) return true
498 return scene.depthAt(xi, yi) < depth
499 }
500
501 // выхлоп: шлейф из каждого сопла назад по курсу, в прыжке длинный и бело-голубой
502 const exhaust = (mesh: Mesh, o: Obj, len: number) => {
503 for (const g of mesh.glows) {
504 const a = toWorld(g.p, o), b = toWorld([g.p[0] - len, g.p[1], g.p[2]], o)
505 const pa = project(a, cam), pb = project(b, cam)
506 if (!pa || !pb) continue
507 const c = rgbOf(g.blue ? blue : engine)
508 ray(pa[0], pa[1], pb[0], pb[1], c, 0.9, 0, behind(pa[2] - 0.3))
509 if (!behind(pa[2] - 0.3)(pa[0], pa[1])) add(pa[0], pa[1], c, tunnelLit ? 0.3 : 0.8) // гало сопла
510 }
511 }
512 if (!cockpit) exhaust(myMesh, me, 1.6 + (tick === 1 ? 0.5 : 0) + h * 12)
513 if (foeObj) exhaust(meshOf(foeShip), foeObj, 1.4)
514 if (pose.point > 0) {
515 const at = project(me.pos, cam)
516 if (at) {
517 add(at[0], at[1], [0.85, 0.95, 1], pose.point * 5)
518 ray(at[0] - 4, at[1], at[0] + 4, at[1], [0.65, 0.85, 1], pose.point, pose.point)
519 }
520 }
521
522 // ── 6. оружие ──
523 const bolts: Bolt[] = []
524 if (fight) {
525 const H = enemyPath(k, HIT, reach).pos
526 const gunAt = (i: number, tt: number) => {
527 const g = myMesh.guns[i % myMesh.guns.length]!
528 return toWorld(g, flightAt(w0 + tt, fight))
529 }
530 // свои залпы: первые мимо, последний в цель (если волна без торпеды)
531 const shots = torpedo ? [1_350, 1_650, 2_000] : [1_350, 1_650, 2_000, 2_400]
532 shots.forEach((ft, i) => {
533 const last = !torpedo && i === shots.length - 1
534 const tgt = enemyPath(k, ft + 300, reach).pos
535 const miss: V = last ? [0, 0, 0] : [15, (hash(k * 31 + i) - 0.5) * 5, (hash(k * 37 + i) - 0.5) * 6]
536 for (const gi of [i * 2, i * 2 + 1]) {
537 bolts.push({ a: gunAt(gi, ft), b: [tgt[0] + miss[0], tgt[1] + miss[1], tgt[2] + miss[2]], t0: ft, t1: ft + (last ? 300 : 850), col: myLaser })
538 }
539 })
540 // ответный огонь: болты врага проходят мимо нас
541 for (const [i, ft] of [[0, 1_050], [1, 1_300], [2, 1_550]] as const) {
542 const from = enemyPath(k, ft, reach).pos
543 bolts.push({ a: from, b: [-30, 2.5 * (i - 1) + 1.5, 4 + i * 2], t0: ft, t1: ft + 700, col: theirLaser })
544 }
545 // протонная торпеда: дугой в цель, искрит, светится
546 if (torpedo && u >= 1_800 && u < HIT) {
547 const s = (u - 1_800) / (HIT - 1_800)
548 const from = gunAt(0, 1_800)
549 const mid: V = [(from[0] + H[0]) / 2, Math.max(from[1], H[1]) + 5, (from[2] + H[2]) / 2]
550 const bez = (q: number) => lerpV(lerpV(from, mid, q), lerpV(mid, H, q), q)
551 for (let j = 0; j < 14; j++) { // искрящий след
552 const pt = bez(Math.max(0, s - j * 0.012))
553 const pj = project([pt[0] + (hash(j + u) - 0.5) * 0.4, pt[1] + (hash(j * 3 + u) - 0.5) * 0.4, pt[2]], cam)
554 if (pj) add(pj[0], pj[1], [1, 0.45, 0.2], 0.7 * (1 - j / 14))
555 }
556 const pt = project(bez(s), cam)
557 if (pt) {
558 add(pt[0], pt[1], [1, 0.95, 0.85], 3)
559 for (const [dx, dy] of [[-1, 0], [1, 0], [0, -1], [0, 1], [-2, 0], [2, 0]]) add(pt[0] + dx!, pt[1] + dy!, [1, 0.35, 0.15], 1.2)
560 }
561 }
562 }
563 // турболазеры разрушителя по далёкой цели
564 if (!inTunnel && kind === 3) {
565 const g = meshOf('destroyer').guns
566 for (let i = 0; i < 3; i++) {
567 const tt = (t + i * 700) % 2_100
568 const from = toWorld(g[(Math.floor((t + i * 700) / 2_100) + i) % g.length]!, destObj)
569 bolts.push({ a: from, b: [from[0] + 60, from[1] + 20, from[2] + 30], t0: t - tt, t1: t - tt + 1_200, col: [0.35, 1, 0.4], abs: true })
570 }
571 }
572 for (const bl of bolts) {
573 const s = ((bl.abs ? t : u) - bl.t0) / (bl.t1 - bl.t0)
574 if (s < 0 || s > 1) continue
575 const dir: V = [bl.b[0] - bl.a[0], bl.b[1] - bl.a[1], bl.b[2] - bl.a[2]]
576 const dl = Math.hypot(...dir) || 1
577 const head = lerpV(bl.a, bl.b, s)
578 const tail: V = [head[0] - (dir[0] / dl) * 3.2, head[1] - (dir[1] / dl) * 3.2, head[2] - (dir[2] / dl) * 3.2]
579 const pa = project(head, cam), pb = project(tail, cam)
580 if (!pa || !pb) continue
581 ray(pa[0], pa[1], pb[0], pb[1], mixC(bl.col, WHITE, 0.45), 1.5, 0.5, behind(pa[2]))
582 }
583
584 // ── 7. взрыв: вспышка, огненный шар из искр, обломки, у торпеды — ударное кольцо ──
585 if (fight && u >= HIT && u < HIT + BOOM) {
586 const a = (u - HIT) / BOOM, sec = (u - HIT) / 1000
587 const c0 = enemyPath(k, HIT, reach).pos
588 const c: V = [c0[0] - sec * 6, c0[1], c0[2]] // взрыв отстаёт: мы летим дальше
589 const pc = project(c, cam)
590 if (pc) {
591 // вспышка: диск с мягким краем, быстро растёт и гаснет
592 const fr = (1.5 + 5 * Math.sqrt(a)) * pc[3] * (torpedo ? 1.4 : 1)
593 const fa = Math.pow(1 - a, 2.5) * (torpedo ? 2.2 : 1.6)
594 for (let y = Math.floor(pc[1] - fr); y <= pc[1] + fr; y++) for (let x = Math.floor(pc[0] - fr * cam.ax); x <= pc[0] + fr * cam.ax; x++) {
595 const d = Math.hypot((x - pc[0]) / cam.ax, y - pc[1]) / (fr || 1)
596 if (d <= 1.4) add(x, y, fire(d * 0.5 + a * 0.5), fa * Math.exp(-d * d * 2.5))
597 }
598 }
599 // искры огненного шара
600 const n = torpedo ? 70 : 46
601 for (let i = 0; i < n; i++) {
602 const th = hash(k * 1000 + i) * Math.PI * 2, ph = Math.acos(2 * hash(k * 1000 + i + 500) - 1)
603 const d = (5 + hash(k * 77 + i) * 11) * sec * (1 - 0.3 * a)
604 const pt = project([c[0] + Math.sin(ph) * Math.cos(th) * d, c[1] + Math.cos(ph) * d, c[2] + Math.sin(ph) * Math.sin(th) * d], cam)
605 if (!pt) continue
606 const life = clamp01(a * (0.8 + hash(i * 9) * 0.6))
607 add(pt[0], pt[1], fire(life * 1.1), 1.4 * (1 - life))
608 }
609 // обломки: тёмные куски с отблеском, разлетаются
610 for (let i = 0; i < 9; i++) {
611 const v: V = [(hash(k * 50 + i) - 0.5) * 14, (hash(k * 51 + i) - 0.5) * 9, (hash(k * 52 + i) - 0.5) * 14]
612 const pt = project([c[0] + v[0] * sec, c[1] + v[1] * sec, c[2] + v[2] * sec], cam)
613 if (!pt) continue
614 const glint = (Math.floor(u / 80) + i) % 4 === 0 ? 0.9 : 0.25
615 add(pt[0], pt[1], [0.8, 0.8, 0.85], glint * (1 - a))
616 }
617 // ударное кольцо: расширяется в наклонной плоскости
618 if (torpedo) {
619 const rr = 1 + 16 * Math.pow(a, 0.6)
620 for (let i = 0; i < 90; i++) {
621 const th = (i / 90) * Math.PI * 2
622 const pt = project([c[0] + Math.cos(th) * rr, c[1] + Math.sin(th) * rr * 0.25 + Math.cos(th) * rr * 0.15, c[2] + Math.sin(th) * rr], cam)
623 if (pt) add(pt[0], pt[1], [0.75, 0.9, 1], 1.5 * Math.pow(1 - a, 1.5))
624 }
625 }
626 }
627
628 // ── 7б. события из работы Claude: инструмент — залп, правка файла — торпеда, ошибка — попадание по нам ──
629 if (p < 0 || p > JUMP_LEN) for (let ei = 0; ei < events.length; ei++) {
630 const ev = events[ei]!, age = t - ev.t
631 if (age < 0 || age > 1_900) continue
632 const aim: V = foeObj ? foeObj.pos : [reach + 25, (hash(ei) - 0.5) * 4, -10]
633 if (ev.kind === 'shot' && age < 450) {
634 // спаренный залп из всех пушек разом
635 for (const g of myMesh.guns.slice(0, 4)) {
636 const from = toWorld(g, me)
637 const s1 = age / 450
638 const head = lerpV(from, [aim[0] + 10, aim[1] + (hash(ei * 3) - 0.5) * 3, aim[2]], s1)
639 const pa = project(head, cam), pb = project(lerpV(from, head, Math.max(0, 1 - 4 / Math.max(4, Math.hypot(head[0] - from[0], head[1] - from[1], head[2] - from[2])))), cam)
640 if (pa && pb) ray(pa[0], pa[1], pb[0], pb[1], mixC(myLaser, WHITE, 0.45), 1.6, 0.5, behind(pa[2]))
641 }
642 }
643 if (ev.kind === 'torpedo') {
644 const tgt: V = [34, 0, -4]
645 const from = toWorld(myMesh.guns[0]!, me)
646 if (age < 650) {
647 const s1 = age / 650
648 const mid: V = [(from[0] + tgt[0]) / 2, from[1] + 1.2, (from[2] + tgt[2]) / 2]
649 const pt = project(lerpV(lerpV(from, mid, s1), lerpV(mid, tgt, s1), s1), cam)
650 if (pt) { add(pt[0], pt[1], [1, 0.95, 0.85], 3); add(pt[0] - 1, pt[1], [1, 0.35, 0.15], 1.5); add(pt[0] + 1, pt[1], [1, 0.35, 0.15], 1.5) }
651 } else {
652 // детонация в пустоте: вспышка и ударное кольцо
653 const a = (age - 650) / 1_250
654 const pc = project(tgt, cam)
655 if (pc) {
656 const fr = (1 + 4 * Math.sqrt(a)) * pc[3]
657 for (let y = Math.floor(pc[1] - fr); y <= pc[1] + fr; y++) for (let x = Math.floor(pc[0] - fr * cam.ax); x <= pc[0] + fr * cam.ax; x++) {
658 const d = Math.hypot((x - pc[0]) / cam.ax, y - pc[1]) / (fr || 1)
659 if (d <= 1.4) add(x, y, fire(d * 0.5 + a * 0.5), 2 * Math.pow(1 - a, 2.5) * Math.exp(-d * d * 2.5))
660 }
661 }
662 const rr = 1 + 14 * Math.pow(a, 0.6)
663 for (let i = 0; i < 80; i++) {
664 const th = (i / 80) * Math.PI * 2
665 const pt = project([tgt[0] + Math.cos(th) * rr, tgt[1] + Math.sin(th) * rr * 0.25, tgt[2] + Math.sin(th) * rr], cam)
666 if (pt) add(pt[0], pt[1], [0.75, 0.9, 1], 1.4 * Math.pow(1 - a, 1.5))
667 }
668 }
669 }
670 if (ev.kind === 'hit' && age < 700) {
671 // болт врага бьёт в корпус: искры с места попадания и короткая вспышка
672 const at = toWorld([0.5, 0.6, 0.4], me)
673 if (age < 160) {
674 const head = lerpV([30, 3, -6], at, age / 160)
675 const pa = project(head, cam), pb = project(lerpV(head, [30, 3, -6], 0.12), cam)
676 if (pa && pb) ray(pa[0], pa[1], pb[0], pb[1], mixC(theirLaser, WHITE, 0.45), 1.8, 0.5)
677 } else {
678 const a = (age - 160) / 540
679 for (let i = 0; i < 24; i++) {
680 const v: V = [(hash(ei * 70 + i) - 0.6) * 9, (hash(ei * 71 + i) - 0.3) * 7, (hash(ei * 72 + i) - 0.5) * 9]
681 const pt = project([at[0] + v[0] * a, at[1] + v[1] * a - 3 * a * a, at[2] + v[2] * a], cam)
682 if (pt) add(pt[0], pt[1], fire(a * 0.9), 1.6 * (1 - a))
683 }
684 const pc = project(at, cam)
685 if (pc && a < 0.4) add(pc[0], pc[1], [1, 1, 0.9], 3 * (1 - a / 0.4))
686 }
687 }
688 }
689
690 // ── 7в. вид из кабины: рама фонаря, прицел, захват цели ──
691 if (cockpit) {
692 const strut = (x0: number, y0: number, x1: number, y1: number) => {
693 const n = Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0) * cam.ax))
694 for (let i = 0; i <= n; i++) {
695 const x = Math.round(lerp(x0, x1, i / n)), y = Math.round(lerp(y0, y1, i / n))
696 for (const dx of [0, 1, 2]) if (x + dx >= 0 && x + dx < PW && y >= 0 && y < PH) {
697 const o = (y * PW + x + dx) * 3
698 rgb[o] = 0.13; rgb[o + 1] = 0.14; rgb[o + 2] = 0.16
699 }
700 }
701 }
702 // две стойки фонаря от нижних углов вверх и нижняя приборная кромка
703 strut(PW * 0.06, PH - 1, PW * 0.3, 0)
704 strut(PW * 0.94, PH - 1, PW * 0.7, 0)
705 for (let x = 0; x < PW; x++) for (let y = PH - Math.max(1, Math.round(PH * 0.08)); y < PH; y++) {
706 const o = (y * PW + x) * 3
707 rgb[o] = 0.1; rgb[o + 1] = 0.11; rgb[o + 2] = 0.12
708 }
709 // прицел: крест в центре
710 const hud: RGB = [0.3, 1, 0.45]
711 const cx = Math.round(cam.cx), cy = Math.round(cam.cy)
712 for (const d of [3, 4, 5]) { add(cx - d * 2, cy, hud, 0.8); add(cx + d * 2, cy, hud, 0.8) }
713 add(cx, cy - 2, hud, 0.8); add(cx, cy + 2, hud, 0.8)
714 // захват: уголки вокруг врага, в момент выстрела краснеют
715 if (foeObj) {
716 const pf = project(foeObj.pos, cam)
717 if (pf) {
718 const lock = u > 2_100
719 const col: RGB = lock ? [1, 0.3, 0.2] : [1, 0.75, 0.2]
720 const r = Math.max(3, 3.2 * pf[3]), rx = r * cam.ax
721 for (const [sx, sy] of [[-1, -1], [1, -1], [-1, 1], [1, 1]] as const) {
722 for (let i = 0; i < 3; i++) { add(pf[0] + sx * rx - sx * i, pf[1] + sy * r, col, 1); add(pf[0] + sx * rx, pf[1] + sy * r - sy * i, col, 1) }
723 }
724 }
725 }
726 }
727
728 // ── 8. вспышки прыжка: вход и выход заливают кадр белым ──
729 let white = 0
730 if (p >= FLASH - 50 && p < FLASH + 180) white = p < FLASH ? ease((p - FLASH + 50) / 50) : 1 - ease((p - FLASH) / 180)
731 else if (p >= EXIT - 80 && p < EXIT + 160) white = p < EXIT ? ease((p - EXIT + 80) / 80) : 1 - ease((p - EXIT) / 160)
732 if (white > 0) for (let i = 0; i < N * 3; i++) rgb[i] = lerp(rgb[i]!, 2.2, white)
733
734 // ── 9. блум и анаморфные блики: яркое расплывается ореолом, огни тянут синие горизонтальные полосы ──
735 bloom(rgb, buf.br, buf.tmp, PW, PH)
736
737 // ── 10. киношная рамка: в прыжке сверху и снизу наезжают чёрные полосы ──
738 if (p >= CHARGE * 0.5 && p < JUMP_LEN - 400) {
739 const k = Math.min(ease((p - CHARGE * 0.5) / 600), 1 - ease((p - JUMP_LEN + 1_000) / 600))
740 const bar = Math.round(k * SY)
741 for (let y = 0; y < bar; y++) for (let x = 0; x < PW; x++) for (const yy of [y, PH - 1 - y]) {
742 const o = (yy * PW + x) * 3
743 rgb[o] = 0; rgb[o + 1] = 0; rgb[o + 2] = 0
744 }
745 }
746
747 return res === 'sext' ? encodeSext(rgb, columns) : encodeQuads(rgb, columns)
748}
749
750// блум: всё ярче порога размывается коробочным фильтром (по x шире — пиксели узкие) и добавляется
751function bloom(rgb: Float32Array, br: Float32Array, tmp: Float32Array, W: number, H: number) {
752 const N = W * H
753 let any = false
754 for (let i = 0; i < N * 3; i++) { const v = rgb[i]! - 0.8; br[i] = v > 0 ? v : 0; if (v > 0) any = true }
755 if (!any) return
756 // скользящее окно: сумма по строке/столбцу за O(1) на пиксель
757 const passX = (src: Float32Array, dst: Float32Array, r: number) => {
758 for (let y = 0; y < H; y++) for (let ch = 0; ch < 3; ch++) {
759 let s = 0
760 for (let x = -r; x <= r; x++) if (x >= 0 && x < W) s += src[(y * W + x) * 3 + ch]!
761 for (let x = 0; x < W; x++) {
762 dst[(y * W + x) * 3 + ch] = s / (2 * r + 1)
763 const xa = x + r + 1, xr = x - r
764 if (xa < W) s += src[(y * W + xa) * 3 + ch]!
765 if (xr >= 0) s -= src[(y * W + xr) * 3 + ch]!
766 }
767 }
768 }
769 const passY = (src: Float32Array, dst: Float32Array, r: number) => {
770 for (let x = 0; x < W; x++) for (let ch = 0; ch < 3; ch++) {
771 let s = 0
772 for (let y = -r; y <= r; y++) if (y >= 0 && y < H) s += src[(y * W + x) * 3 + ch]!
773 for (let y = 0; y < H; y++) {
774 dst[(y * W + x) * 3 + ch] = s / (2 * r + 1)
775 const ya = y + r + 1, yr = y - r
776 if (ya < H) s += src[(ya * W + x) * 3 + ch]!
777 if (yr >= 0) s -= src[(yr * W + x) * 3 + ch]!
778 }
779 }
780 }
781 // анаморфный блик: только очень яркое, длинная горизонтальная полоса с синим отливом
782 for (let i = 0; i < N * 3; i += 3) {
783 const l = (rgb[i]! + rgb[i + 1]! + rgb[i + 2]!) / 3 - 1.2
784 tmp[i] = l > 0 ? l * 0.35 : 0; tmp[i + 1] = l > 0 ? l * 0.55 : 0; tmp[i + 2] = l > 0 ? l : 0
785 }
786 const flare = new Float32Array(tmp)
787 passX(flare, tmp, 14)
788 for (let i = 0; i < N * 3; i++) rgb[i] += tmp[i]! * 0.5
789 passX(br, tmp, 2)
790 passY(tmp, br, 1)
791 passX(br, tmp, 2)
792 passY(tmp, br, 1)
793 for (let i = 0; i < N * 3; i++) rgb[i] += br[i]! * 0.9
794}
795
796// мягкий клип HDR → 0..1: до 0.8 линейно, выше плавно в белый
797const EXPOSURE = 1.2 // общая яркость кадра
798const tone = (v: number) => (v < 0.8 ? Math.max(0, v) : 0.8 + 0.2 * (1 - Math.exp(-(v - 0.8) * 4)))
799
800// четвертьблоки: бит 1 — левый верх, 2 — правый верх, 4 — левый низ, 8 — правый низ
801const QUAD = [0x20, 0x2598, 0x259d, 0x2580, 0x2596, 0x258c, 0x259e, 0x259b, 0x2597, 0x259a, 0x2590, 0x259c, 0x2584, 0x2599, 0x259f, 0x2588]
802const EMPTY = 0.035 // темнее этого — пустота, сквозь неё виден фон терминала
803
804// пиксель HDR → готовый цвет 0..1: экспозиция, сочность, мягкий клип
805function graded(rgb: Float32Array, o: number): RGB {
806 const r0 = rgb[o]! * EXPOSURE, g0 = rgb[o + 1]! * EXPOSURE, b0 = rgb[o + 2]! * EXPOSURE
807 const l0 = (r0 + g0 + b0) / 3
808 return [tone(l0 + (r0 - l0) * 1.15), tone(l0 + (g0 - l0) * 1.15), tone(l0 + (b0 - l0) * 1.15)]
809}
810
811// общий подбор для клетки из n пикселей: пустые → фон терминала, иначе лучшая пара цветов по маске
812function fitCell(px: RGB[], n: number, glyph: (mask: number) => number): [number, number, number] {
813 let any = 0
814 for (let j = 0; j < n; j++) if (Math.max(px[j]![0], px[j]![1], px[j]![2]) > EMPTY) any |= 1 << j
815 const full = (1 << n) - 1
816 if (any === 0) return [0x20, DEF, DEF]
817 if (any !== full) {
818 // часть клетки пустая: зажжённые пиксели одним цветом, фон — терминала
819 let r = 0, g = 0, b = 0, c = 0
820 for (let j = 0; j < n; j++) if (any & (1 << j)) { r += px[j]![0]; g += px[j]![1]; b += px[j]![2]; c++ }
821 return [glyph(any), hexOf([r / c, g / c, b / c]), DEF]
822 }
823 // вся клетка зажжена: перебрать сплошную и все разбиения на две группы (без зеркальных), взять лучшую
824 let best = Infinity, bm = full, bf: RGB = [0, 0, 0], bb: RGB = [0, 0, 0]
825 const half = 1 << (n - 1)
826 for (let m = 0; m < half; m++) {
827 const mask = m === 0 ? full : m
828 let ar = 0, ag = 0, ab = 0, an = 0, br = 0, bg = 0, bbb = 0, bn = 0
829 for (let j = 0; j < n; j++) {
830 const q = px[j]!
831 if (mask & (1 << j)) { ar += q[0]; ag += q[1]; ab += q[2]; an++ } else { br += q[0]; bg += q[1]; bbb += q[2]; bn++ }
832 }
833 const fa: RGB = [ar / an, ag / an, ab / an]
834 const fb: RGB = bn ? [br / bn, bg / bn, bbb / bn] : fa
835 let err = 0
836 for (let j = 0; j < n; j++) {
837 const ref = mask & (1 << j) ? fa : fb, q = px[j]!
838 err += (q[0] - ref[0]) ** 2 + (q[1] - ref[1]) ** 2 + (q[2] - ref[2]) ** 2
839 }
840 if (m === 0) err -= 0.002 // при почти равной ошибке — сплошной блок
841 if (err < best) { best = err; bm = mask; bf = fa; bb = fb }
842 }
843 return [glyph(bm), hexOf(bf), bm === full ? DEF : hexOf(bb)]
844}
845
846// секстанты 2×3: бит 1 — левый верх, 2 — правый верх, 4 — левый середина, 8 — правый середина, 16 — левый низ, 32 — правый низ
847// в блоке U+1FB00 нет пустого, полного и двух половин — они берутся из обычных блоков
848const sextGlyph = (m: number) => {
849 if (m === 0) return 0x20
850 if (m === 63) return 0x2588
851 if (m === 21) return 0x258c
852 if (m === 42) return 0x2590
853 return 0x1fb00 + m - 1 - (m > 21 ? 1 : 0) - (m > 42 ? 1 : 0)
854}
855
856function encodeSext(rgb: Float32Array, columns: number): Uint32Array {
857 const PW = columns * 2
858 const out = new Uint32Array(columns * ROWS * 3)
859 const px: RGB[] = Array.from({ length: 6 }, () => [0, 0, 0] as RGB)
860 for (let row = 0; row < ROWS; row++) for (let cx = 0; cx < columns; cx++) {
861 for (let j = 0; j < 6; j++) px[j] = graded(rgb, ((row * 3 + (j >> 1)) * PW + cx * 2 + (j & 1)) * 3)
862 const [cp, fg, bg] = fitCell(px, 6, sextGlyph)
863 const i = (row * columns + cx) * 3
864 out[i] = cp; out[i + 1] = fg; out[i + 2] = bg
865 }
866 return out
867}
868
869// собрать клетки: на каждые 2×2 пикселя подобрать глиф и два цвета с минимальной ошибкой
870function encodeQuads(rgb: Float32Array, columns: number): Uint32Array {
871 const PW = columns * 2
872 const out = new Uint32Array(columns * ROWS * 3)
873 const px: RGB[] = Array.from({ length: 4 }, () => [0, 0, 0] as RGB)
874 for (let row = 0; row < ROWS; row++) for (let cx = 0; cx < columns; cx++) {
875 for (let j = 0; j < 4; j++) px[j] = graded(rgb, ((row * 2 + (j >> 1)) * PW + cx * 2 + (j & 1)) * 3)
876 const [cp, fg, bg] = fitCell(px, 4, m => QUAD[m]!)
877 const i = (row * columns + cx) * 3
878 out[i] = cp; out[i + 1] = fg; out[i + 2] = bg
879 }
880 return out
881}
882
883// клетки в base64, как просит Raster
884export const encode = (cells: Uint32Array): string => new Uint8Array(cells.buffer).toBase64()
885hooks/three.ts 481 lines1// Мини-3D: low-poly меши кораблей, камера и софтверный растеризатор с z-буфером и сглаживанием.
2// Схема как у termcade (github.com/mlekhi/termcade): треугольники → перспектива → z-буфер → свет → пиксели.
3// Мир: x — курс корабля (вперёд), y — вверх, z — правый борт. Корабль игрока всегда в начале координат.
4
5export type V = [number, number, number]
6// треугольник: цвет 0xRRGGBB, либо ENGINE / BLUE — светящиеся сопла, цвет подставит кадр
7type Tri = { a: V; b: V; c: V; col: number }
8export const ENGINE = -1
9export const BLUE = -2
10
11// меш: треугольники + точки сопел (откуда выхлоп) и пушек (откуда лазер)
12export class Mesh {
13 tris: Tri[] = []
14 glows: { p: V; blue: boolean }[] = []
15 guns: V[] = []
16 // треугольник и четырёхугольник (две половинки)
17 tri(a: V, b: V, c: V, col: number) { this.tris.push({ a, b, c, col }) }
18 quad(a: V, b: V, c: V, d: V, col: number) { this.tri(a, b, c, col); this.tri(a, c, d, col) }
19 // плоский многоугольник веером от первой точки (выпуклый или звёздный относительно неё)
20 poly(ps: V[], col: number) { for (let i = 1; i < ps.length - 1; i++) this.tri(ps[0]!, ps[i]!, ps[i + 1]!, col) }
21 // кусок «трубы» между двумя сечениями одинаковой длины; cap — цвет торца (-3 — без торца)
22 loft(r0: V[], r1: V[], col: number, cap0 = -3, cap1 = -3) {
23 const n = r0.length
24 for (let i = 0; i < n; i++) this.quad(r0[i]!, r0[(i + 1) % n]!, r1[(i + 1) % n]!, r1[i]!, col)
25 if (cap0 !== -3) this.poly(r0, cap0)
26 if (cap1 !== -3) this.poly(r1, cap1)
27 }
28 // прямоугольная призма из сечения в сечение по оси x: [x, cy, cz, полувысота, полуширина]
29 beam(a: number[], b: number[], col: number, capA = col, capB = col) {
30 const rect = ([x, y, z, hy, hz]: number[]): V[] => [[x!, y! - hy!, z! - hz!], [x!, y! + hy!, z! - hz!], [x!, y! + hy!, z! + hz!], [x!, y! - hy!, z! + hz!]]
31 this.loft(rect(a), rect(b), col, capA, capB)
32 }
33 // коробка по двум углам
34 box(x0: number, x1: number, y0: number, y1: number, z0: number, z1: number, col: number) {
35 const cy = (y0 + y1) / 2, cz = (z0 + z1) / 2, hy = (y1 - y0) / 2, hz = (z1 - z0) / 2
36 this.beam([x0, cy, cz, hy, hz], [x1, cy, cz, hy, hz], col)
37 }
38 // тело вращения вокруг оси (0 — x, 1 — y, 2 — z): профиль [радиус, координата вдоль оси], n граней
39 lathe(axis: 0 | 1 | 2, at: V, prof: [number, number][], n: number, col: number, phase = 0, capEnds = true) {
40 const ring = ([r, h]: [number, number]): V[] => Array.from({ length: n }, (_, i) => {
41 const a = phase + (i / n) * Math.PI * 2
42 const u = Math.cos(a) * r, v = Math.sin(a) * r
43 const p: V = axis === 0 ? [h, u, v] : axis === 1 ? [u, h, v] : [u, v, h]
44 return [p[0] + at[0], p[1] + at[1], p[2] + at[2]]
45 })
46 for (let i = 0; i < prof.length - 1; i++) {
47 const last = i === prof.length - 2
48 this.loft(ring(prof[i]!), ring(prof[i + 1]!), col, capEnds && i === 0 ? col : -3, capEnds && last ? col : -3)
49 }
50 }
51 // шар вокруг оси x: n меридианов, m параллелей
52 ball(at: V, r: number, col: number, n = 10, m = 6) {
53 const prof: [number, number][] = []
54 for (let i = 0; i <= m; i++) { const a = (i / m) * Math.PI; prof.push([Math.max(0.001, Math.sin(a) * r), -Math.cos(a) * r]) }
55 this.lathe(0, at, prof, n, col, 0, false)
56 }
57 // применить преобразование ко всему, что добавлено начиная с отметки
58 map(mark: { t: number; g: number; u: number }, f: (v: V) => V) {
59 for (let i = mark.t; i < this.tris.length; i++) {
60 const t = this.tris[i]!
61 t.a = f(t.a); t.b = f(t.b); t.c = f(t.c)
62 }
63 for (let i = mark.g; i < this.glows.length; i++) this.glows[i]!.p = f(this.glows[i]!.p)
64 for (let i = mark.u; i < this.guns.length; i++) this.guns[i] = f(this.guns[i]!)
65 }
66 mark() { return { t: this.tris.length, g: this.glows.length, u: this.guns.length } }
67}
68
69// ── палитра: как на плёнке — тёплый белый, грязно-серый, полосы эскадрилий ──
70const HULL = 0xd9d6cf, HULL2 = 0xb9b6ae, GREY = 0x8a8c90, DARK = 0x45484e, GLASS = 0x1c2633
71const RED = 0xc23a2e, YELLOW = 0xd9a520, R2BLUE = 0x2f5fc4, TIEPANEL = 0x3a404c, TIEFRAME = 0x8a909a, TIEGREY = 0x858a94
72
73// X-wing: open — угол раскрытия S-foil в радианах
74export function xwing(open: number, headYaw = 0, headBrace = 0): Mesh {
75 const m = new Mesh()
76 // фюзеляж: короб сзади, длинный клин носа, красные полосы на носу
77 m.beam([-6, 0, 0, 0.75, 0.8], [-1.2, 0, 0, 0.85, 0.85], HULL, GREY)
78 m.beam([-1.2, 0, 0, 0.85, 0.85], [6.6, -0.15, 0, 0.28, 0.32], HULL, HULL, GREY)
79 m.beam([2.2, -0.05, 0, 0.6, 0.64], [2.9, -0.07, 0, 0.56, 0.6], RED)
80 m.beam([3.3, -0.08, 0, 0.53, 0.57], [3.7, -0.09, 0, 0.5, 0.54], RED)
81 // кабина: тёмный фонарь с перемычкой
82 m.beam([-1.6, 0.95, 0, 0.12, 0.55], [1.4, 0.6, 0, 0.05, 0.35], GLASS)
83 m.box(-0.3, -0.1, 0.8, 1.15, -0.5, 0.5, GREY)
84 // R2-D2 утоплен в гнездо за фонарём: видны плечи и купол, ноги внутри фюзеляжа.
85 // Крупные синие панели и тёмный глаз читаются и после четвертьблоков.
86 m.lathe(1, [-2.6, 0.82, 0], [[0.57, 0], [0.57, 0.12], [0.49, 0.16]], 10, DARK)
87 m.lathe(1, [-2.6, 0.96, 0], [[0.47, 0], [0.47, 0.38]], 10, 0xe3e6e8)
88 m.box(-2.14, -2.1, 1.01, 1.28, -0.25, 0.25, R2BLUE)
89 m.box(-3.1, -3.06, 1.04, 1.2, -0.3, 0.3, R2BLUE)
90 const headMark = m.mark()
91 m.lathe(1, [0, 0, 0], [[0.5, 0], [0.5, 0.12], [0.46, 0.3], [0.32, 0.48], [0.001, 0.55]], 12, 0xbfcbd6)
92 m.lathe(1, [0, 0, 0], [[0.505, 0], [0.505, 0.1]], 12, R2BLUE)
93 // Четыре широких сектора на куполе; без мелких точек и случайного блеска.
94 for (let i = 0; i < 4; i++) {
95 const a = i * Math.PI / 2 + 0.18, b = a + 0.7
96 const ring = (r: number, y: number, th: number): V => [r * Math.cos(th), y, r * Math.sin(th)]
97 m.quad(ring(0.465, 0.3, a), ring(0.465, 0.3, b), ring(0.325, 0.48, b), ring(0.325, 0.48, a), R2BLUE)
98 }
99 m.box(0.38, 0.51, 0.16, 0.36, -0.24, 0.24, R2BLUE) // рамка основного глаза
100 m.box(0.5, 0.55, 0.18, 0.34, -0.15, 0.15, 0x08121e) // оптика, не светящийся фонарь
101 m.box(-0.52, -0.47, 0.13, 0.28, -0.15, 0.15, 0x273c69) // задний проектор
102 m.map(headMark, ([x, y, z]) => {
103 const co = Math.cos(headYaw), si = Math.sin(headYaw)
104 const hx = x * co + z * si, hz = -x * si + z * co
105 const cb = Math.cos(headBrace), sb = Math.sin(headBrace)
106 return [-2.6 + hx * cb - y * sb, 1.34 + hx * sb + y * cb, hz]
107 })
108 // четыре крыла: строятся справа-сверху, потом наклоняются и отражаются
109 for (const up of [1, -1]) for (const side of [1, -1]) {
110 const k = m.mark()
111 m.quad([-5.6, 0, 0.8], [-1.6, 0, 0.8], [-2.8, 0, 5.4], [-5.2, 0, 5.4], HULL2)
112 m.quad([-5.6, -0.14, 0.8], [-5.2, -0.14, 5.4], [-2.8, -0.14, 5.4], [-1.6, -0.14, 0.8], HULL2)
113 m.box(-4.4, -3.2, 0.0, 0.05, 3.6, 5.2, RED)
114 m.lathe(0, [0, up * 0.55, 1.55], [[0.5, -5.9], [0.58, -5.4], [0.58, -1.6], [0.35, -0.9]], 8, GREY, Math.PI / 8)
115 m.lathe(0, [0, up * 0.55, 1.55], [[0.4, -5.95], [0.4, -5.92]], 8, ENGINE, Math.PI / 8)
116 m.glows.push({ p: [-6, up * 0.55, 1.55], blue: false })
117 m.lathe(0, [0, 0, 5.55], [[0.2, -5], [0.2, 0.5]], 6, DARK)
118 m.lathe(0, [0, 0, 5.55], [[0.09, 0.5], [0.09, 5.6], [0.15, 5.7], [0.15, 6.2]], 6, GREY)
119 m.guns.push([6.3, 0, 5.55])
120 const c = Math.cos(open), s = Math.sin(open)
121 m.map(k, ([x, y, z]) => [x, y * c + z * s * up, (-y * s * up + z * c) * side])
122 }
123 return m
124}
125
126// Y-wing: кабина-капсула впереди, перекладина и две длинные гондолы двигателей
127export function ywing(): Mesh {
128 const m = new Mesh()
129 m.beam([-1.5, 0, 0, 0.8, 0.9], [3.2, 0, 0, 0.75, 0.85], HULL, GREY)
130 m.beam([3.2, 0, 0, 0.75, 0.85], [5.6, -0.2, 0, 0.3, 0.4], HULL, HULL, GREY)
131 m.beam([1.4, 0.1, 0, 0.78, 0.88], [2.0, 0.1, 0, 0.78, 0.88], YELLOW) // жёлтая полоса Золотой эскадрильи
132 m.beam([2.6, 0.55, 0, 0.25, 0.6], [4.3, 0.4, 0, 0.08, 0.45], GLASS)
133 m.lathe(1, [3.0, 0.8, 0], [[0.3, 0], [0.25, 0.35], [0.001, 0.4]], 6, DARK) // ионная турель
134 m.box(-6.5, -1.5, -0.35, 0.35, -0.45, 0.45, 0x9a9890) // хребет без обшивки
135 m.box(-4.5, -3.2, -0.4, 0.4, -4.2, 4.2, HULL2) // перекладина крыла
136 m.lathe(1, [-3.6, 0.4, 0], [[0.38, 0], [0.38, 0.3], [0.001, 0.5]], 8, 0xdfe4ea) // астродроид
137 for (const side of [1, -1]) {
138 const z = side * 4.2
139 m.lathe(0, [0, 0, z], [[0.45, -7.4], [0.62, -6.9], [0.62, -1.2], [0.5, 0.2], [0.3, 0.8]], 8, HULL2, Math.PI / 8)
140 m.lathe(0, [0, 0, z], [[0.5, -7.45], [0.5, -7.42]], 8, ENGINE, Math.PI / 8)
141 m.box(-6.6, -5.9, -0.66, 0.66, z - 0.66, z + 0.66, DARK) // кольцо сопла
142 m.glows.push({ p: [-7.5, 0, z], blue: false })
143 }
144 m.guns.push([5.8, -0.2, 0.2], [5.8, -0.2, -0.2])
145 return m
146}
147
148// A-wing: плоский клин с двумя бортовыми двигателями и красными полосами
149export function awing(): Mesh {
150 const m = new Mesh()
151 const top: V[] = [[4.6, 0.35, 0], [-3.2, 0.55, 2.4], [-3.4, 0.55, 0], [-3.2, 0.55, -2.4]]
152 const bot: V[] = [[4.6, -0.2, 0], [-3.2, -0.35, 2.4], [-3.4, -0.35, 0], [-3.2, -0.35, -2.4]]
153 m.poly([top[0]!, top[1]!, top[2]!], HULL); m.poly([top[0]!, top[2]!, top[3]!], HULL)
154 m.poly([bot[0]!, bot[1]!, bot[2]!], HULL2); m.poly([bot[0]!, bot[2]!, bot[3]!], HULL2)
155 m.quad(top[0]!, top[1]!, bot[1]!, bot[0]!, HULL2); m.quad(top[0]!, top[3]!, bot[3]!, bot[0]!, HULL2)
156 m.quad(top[1]!, top[3]!, bot[3]!, bot[1]!, GREY)
157 // красные шевроны на носу
158 for (const s of [1, -1]) m.poly([[3.6, 0.42, 0], [1.2, 0.47, s * 0.9], [0.4, 0.49, s * 1.25], [2.9, 0.44, 0]], RED)
159 m.beam([-0.6, 0.6, 0, 0.3, 0.55], [1.6, 0.45, 0, 0.05, 0.3], GLASS)
160 for (const s of [1, -1]) {
161 m.lathe(0, [0, 0.05, s * 2.55], [[0.42, -4.4], [0.55, -4.0], [0.55, -0.8], [0.25, 0.3]], 8, HULL2, Math.PI / 8)
162 m.lathe(0, [0, 0.05, s * 2.55], [[0.42, -4.45], [0.42, -4.42]], 8, ENGINE, Math.PI / 8)
163 m.glows.push({ p: [-4.5, 0.05, s * 2.55], blue: false })
164 m.guns.push([0.5, -0.1, s * 2.95])
165 }
166 return m
167}
168
169// TIE-истребитель: шар-кабина с круглым окном, пилоны, две шестигранные панели
170export function tie(): Mesh {
171 const m = new Mesh()
172 cockpit(m)
173 for (const side of [1, -1]) {
174 const k = m.mark()
175 m.lathe(2, [0, 0, 0], [[0.55, 1.2], [0.42, 1.8], [0.42, 3.3], [0.75, 3.6]], 8, 0x5b6069)
176 m.lathe(2, [0, 0, 0], [[0.6, 3.55], [4.3, 3.55], [4.3, 3.8], [0.6, 3.8]], 6, TIEPANEL, Math.PI / 2)
177 m.lathe(2, [0, 0, 0], [[4.15, 3.5], [4.45, 3.5], [4.45, 3.85], [4.15, 3.85]], 6, TIEFRAME, Math.PI / 2)
178 for (let i = 0; i < 6; i++) spoke(m, Math.PI / 2 + (i / 6) * Math.PI * 2, 4.2)
179 m.map(k, ([x, y, z]) => [x, y, z * side])
180 }
181 m.guns.push([1.4, -0.75, 0.35], [1.4, -0.75, -0.35])
182 return m
183}
184
185// TIE-перехватчик: та же кабина, панели-кинжалы с вырезом спереди, пушки на остриях
186export function interceptor(): Mesh {
187 const m = new Mesh()
188 cockpit(m)
189 const blade: [number, number][] = [[-0.5, 0], [0.6, 0.7], [3.6, 4.3], [-0.6, 4.0], [-1.7, 0.9], [-1.7, -0.9], [-0.6, -4.0], [3.6, -4.3], [0.6, -0.7]]
190 for (const side of [1, -1]) {
191 const k = m.mark()
192 m.lathe(2, [0, 0, 0], [[0.55, 1.2], [0.42, 1.8], [0.42, 3.1], [0.7, 3.4]], 8, 0x5b6069)
193 for (const z of [3.4, 3.62]) {
194 const ps = blade.map(([x, y]) => [x, y, z] as V)
195 // веер от центра: точки 1..8 по кругу, замыкаем последней с первой
196 for (let i = 1; i < ps.length; i++) m.tri(ps[0]!, ps[i]!, ps[i === ps.length - 1 ? 1 : i + 1]!, TIEPANEL)
197 }
198 for (let i = 1; i < blade.length; i++) {
199 const [x0, y0] = blade[i]!, [x1, y1] = blade[i === blade.length - 1 ? 1 : i + 1]!
200 m.quad([x0, y0, 3.38], [x1, y1, 3.38], [x1, y1, 3.64], [x0, y0, 3.64], TIEFRAME)
201 }
202 for (const a of [Math.PI * 0.27, -Math.PI * 0.27, Math.PI * 0.62, -Math.PI * 0.62]) spoke(m, a, 3.4, 3.36, 3.66)
203 m.guns.push([3.7, 4.3, 3.5], [3.7, -4.3, 3.5])
204 m.map(k, ([x, y, z]) => [x, y, z * side])
205 }
206 return m
207}
208
209// общая кабина TIE: шар, окно-восьмиугольник, два ионных сопла сзади
210function cockpit(m: Mesh) {
211 m.ball([0, 0, 0], 1.55, TIEGREY, 12, 8)
212 m.lathe(0, [0, 0, 0], [[0.95, 1.2], [0.95, 1.32], [0.75, 1.42]], 8, 0x3a3e46, Math.PI / 8)
213 m.lathe(0, [0, 0, 0], [[0.62, 1.43], [0.001, 1.45]], 8, GLASS, Math.PI / 8)
214 for (const z of [-0.45, 0.45]) {
215 m.lathe(0, [0, 0, z], [[0.22, -1.62], [0.22, -1.5]], 6, ENGINE)
216 m.glows.push({ p: [-1.65, 0, z], blue: false })
217 }
218}
219
220// ребро панели TIE от центра под углом a длиной r, с обеих сторон панели
221function spoke(m: Mesh, a: number, r: number, z0 = 3.48, z1 = 3.87) {
222 const ex = Math.cos(a) * r, ey = Math.sin(a) * r
223 const nx = -Math.sin(a) * 0.09, ny = Math.cos(a) * 0.09
224 for (const z of [z0, z1]) m.quad([nx, ny, z], [ex + nx, ey + ny, z], [ex - nx, ey - ny, z], [-nx, -ny, z], TIEFRAME)
225}
226
227// Сокол тысячелетия: диск, жвалы, кабина-труба по борту, тарелка радара, голубая дуга двигателя
228export function falcon(): Mesh {
229 const m = new Mesh()
230 m.lathe(1, [0, 0, 0], [[0.001, 0.72], [2.2, 0.66], [3.7, 0.5], [4.6, 0.18], [4.75, -0.05], [4.55, -0.3], [3.6, -0.55], [0.001, -0.62]], 24, 0xc9c7c0, 0, false)
231 // пластины обшивки по верху: тёмные секторы, как грязные заплатки на модели
232 for (let i = 0; i < 6; i++) {
233 const a0 = (i / 6) * Math.PI * 2 + 0.3, a1 = a0 + 0.35
234 const p = (r: number, a: number, y: number): V => [Math.cos(a) * r, y, Math.sin(a) * r]
235 m.quad(p(2.4, a0, 0.67), p(3.6, a0, 0.53), p(3.6, a1, 0.53), p(2.4, a1, 0.67), 0x9c9a92)
236 }
237 for (const z of [1, -1]) m.beam([2.8, 0, z * 1.05, 0.3, 0.62], [7.4, 0, z * 1.0, 0.24, 0.55], 0xbebcb4, GREY, DARK)
238 m.box(3.0, 4.2, -0.3, 0.1, -0.45, 0.45, DARK)
239 m.beam([1.0, 0.05, -3.6, 0.32, 0.55], [3.0, 0.05, -4.35, 0.3, 0.4], 0xbebcb4)
240 m.lathe(0, [0, 0.05, -4.55], [[0.48, 1.2], [0.52, 4.4], [0.42, 5.2], [0.2, 5.55]], 8, 0xc9c7c0, 0, true)
241 m.lathe(0, [0, 0.05, -4.55], [[0.43, 5.18], [0.22, 5.54]], 8, GLASS)
242 m.lathe(1, [0, 0, 0], [[0.7, 0.68], [0.6, 0.95], [0.001, 1.0]], 10, GREY)
243 m.box(0.2, 1.6, 0.85, 0.95, -0.22, -0.12, DARK)
244 m.box(0.2, 1.6, 0.85, 0.95, 0.12, 0.22, DARK)
245 m.lathe(1, [-0.6, 0, 2.6], [[0.12, 0.6], [0.12, 1.05], [0.95, 1.2], [0.001, 1.35]], 10, 0xd6d4cc)
246 for (let i = 0; i <= 8; i++) {
247 const a = Math.PI * (0.78 + (i / 8) * 0.44)
248 const a2 = Math.PI * (0.78 + ((i + 1) / 8) * 0.44)
249 const p = (r: number, y: number, aa: number): V => [Math.cos(aa) * r, y, Math.sin(aa) * r]
250 if (i < 8) m.quad(p(4.8, -0.15, a), p(4.8, 0.2, a), p(4.8, 0.2, a2), p(4.8, -0.15, a2), BLUE)
251 if (i % 2 === 0) m.glows.push({ p: [Math.cos(a) * 4.85, 0.02, Math.sin(a) * 4.85], blue: true })
252 }
253 m.guns.push([0.9, 1.0, 0], [7.5, 0, 1], [7.5, 0, -1])
254 return m
255}
256
257// Звёздный разрушитель для фона: клин, ступенчатая надстройка, мостик с двумя шарами, синие сопла
258export function destroyer(): Mesh {
259 const m = new Mesh()
260 const C = 0xa7aab0, C2 = 0x878a91
261 const nose: V = [16, 0, 0], l: V = [-10, 0, 8.5], r: V = [-10, 0, -8.5], keel: V = [-10, -3.2, 0], keelN: V = [16, -0.4, 0]
262 m.tri(nose, l, r, C) // верхняя палуба
263 m.quad(nose, keelN, keel, l, C2); m.quad(nose, keelN, keel, r, C2) // днище к килю
264 m.poly([l, r, keel], 0x5d6067) // корма
265 // траншея по палубе и ступени надстройки
266 m.box(-6, 12, 0.0, 0.18, -0.35, 0.35, 0x6d7076)
267 m.box(-10, -1, 0, 1.1, -4.2, 4.2, C)
268 m.box(-9.6, -4, 1.1, 2.0, -2.8, 2.8, C)
269 m.box(-9.2, -6.5, 2.0, 2.9, -1.6, 1.6, C)
270 m.box(-8.7, -7.9, 2.9, 4.4, -0.45, 0.45, C2) // шея мостика
271 m.box(-9.0, -7.6, 4.4, 4.9, -2.6, 2.6, C) // мостик
272 for (const z of [-1.6, 1.6]) m.ball([-8.3, 5.3, z], 0.42, 0xbfc2c8, 6, 4)
273 for (const z of [-2.4, 0, 2.4]) {
274 m.lathe(0, [0, 0.4, z], [[0.75, -10.15], [0.75, -10.1]], 8, BLUE)
275 m.glows.push({ p: [-10.3, 0.4, z], blue: true })
276 }
277 // турболазеры вдоль борта: точки, откуда бьют зелёные залпы
278 for (const s of [1, -1]) for (const x of [-3, 2, 7]) m.guns.push([x, 0.2, s * (8.5 - (x + 10) * 8.5 / 26)])
279 return m
280}
281
282// астероид: шар, вершины которого сдвинуты шумом — бугристая глыба; seed — своя форма
283export function asteroid(seed: number): Mesh {
284 const m = new Mesh()
285 m.ball([0, 0, 0], 1, 0x6e655c, 9, 6)
286 const h = (x: number) => { const v = Math.sin(x * 12.9898 + seed * 78.233) * 43758.5453; return v - Math.floor(v) }
287 // одинаковые точки сдвигаются одинаково: швов между гранями нет
288 m.map({ t: 0, g: 0, u: 0 }, ([x, y, z]) => {
289 const k = 0.7 + 0.5 * h(Math.round(x * 50) * 3 + Math.round(y * 50) * 7 + Math.round(z * 50) * 13)
290 return [x * k * 1.25, y * k * 0.9, z * k]
291 })
292 return m
293}
294
295// ── камера и проекция ──
296
297export type Cam = {
298 target: V // куда смотрит, мировые координаты
299 azim: number; elev: number; roll: number // откуда смотрит: вокруг вертикали, сверху, завал горизонта
300 dist: number // расстояние до цели
301 fy: number // пикселей на единицу по вертикали на расстоянии цели
302 ax: number // во сколько раз пиксель уже, чем выше: 2 у четвертьблоков, 4/3 у секстантов
303 cx: number; cy: number // где цель на экране, в пикселях
304}
305// поза объекта в мире: где стоит, как повёрнут, во сколько раз больше
306export type Obj = { pos: V; yaw: number; pitch: number; roll: number; scale?: number }
307
308// повернуть точку модели позой объекта и поставить в мир
309export function toWorld(p: V, o: Obj): V {
310 const k = o.scale ?? 1
311 let [x, y, z] = [p[0] * k, p[1] * k, p[2] * k]
312 let c = Math.cos(o.roll), s = Math.sin(o.roll);
313 [y, z] = [y * c - z * s, y * s + z * c]
314 c = Math.cos(o.pitch); s = Math.sin(o.pitch);
315 [x, y] = [x * c - y * s, x * s + y * c]
316 c = Math.cos(o.yaw); s = Math.sin(o.yaw);
317 [x, z] = [x * c + z * s, -x * s + z * c]
318 return [x + o.pos[0], y + o.pos[1], z + o.pos[2]]
319}
320
321// мировая точка → система камеры: X вправо, Y вверх, Z к зрителю (камера в Z = dist)
322export function toCam(p: V, c: Cam): V {
323 let x = p[0] - c.target[0], y = p[1] - c.target[1], z = p[2] - c.target[2]
324 let co = Math.cos(c.azim), si = Math.sin(c.azim);
325 [x, z] = [x * co + z * si, -x * si + z * co]
326 co = Math.cos(c.elev); si = Math.sin(c.elev);
327 [y, z] = [y * co - z * si, y * si + z * co]
328 co = Math.cos(c.roll); si = Math.sin(c.roll);
329 [x, y] = [x * co - y * si, x * si + y * co]
330 return [x, y, z]
331}
332
333// обратный поворот: направление из системы камеры в мир (для лучей туннеля)
334export function camDirToWorld(d: V, c: Cam): V {
335 let [x, y, z] = d
336 let co = Math.cos(-c.roll), si = Math.sin(-c.roll);
337 [x, y] = [x * co - y * si, x * si + y * co]
338 co = Math.cos(-c.elev); si = Math.sin(-c.elev);
339 [y, z] = [y * co - z * si, y * si + z * co]
340 co = Math.cos(-c.azim); si = Math.sin(-c.azim);
341 [x, z] = [x * co + z * si, -x * si + z * co]
342 return [x, y, z]
343}
344
345// мировая позиция камеры
346export const camPos = (c: Cam): V => {
347 const d = camDirToWorld([0, 0, c.dist], c)
348 return [c.target[0] + d[0], c.target[1] + d[1], c.target[2] + d[2]]
349}
350
351const NEAR = 0.6
352// проекция точки системы камеры в пиксели экрана: [x, y, глубина, масштаб] или null за камерой
353export function projCam(q: V, c: Cam): [number, number, number, number] | null {
354 const depth = c.dist - q[2]
355 if (depth < NEAR) return null
356 const k = (c.dist / depth) * c.fy
357 return [c.cx + q[0] * k * c.ax, c.cy - q[1] * k, depth, k]
358}
359export const project = (p: V, c: Cam) => projCam(toCam(p, c), c)
360
361// ── растеризация мешей в общий z-буфер с под-пикселями ──
362
363export const SS = 2 // 2×2 под-пикселя на пиксель
364export type Light = { p: V; col: [number, number, number]; k: number }
365const LIGHT: V = (() => { const v: V = [-0.35, 0.75, 0.55]; const l = Math.hypot(...v); return [v[0] / l, v[1] / l, v[2] / l] })()
366
367
368// буфер сцены: под-пиксели с глубиной и цветом; одна штука на кадр, все меши в неё
369export class Scene {
370 w: number; h: number; W: number; H: number
371 zb: Float32Array; cb: Uint32Array
372 constructor(w: number, h: number) {
373 this.w = w; this.h = h
374 this.W = w * SS; this.H = h * SS
375 this.zb = new Float32Array(this.W * this.H).fill(Infinity)
376 this.cb = new Uint32Array(this.W * this.H)
377 }
378
379 // обнулить буфер для нового кадра (буферы живут между кадрами: меньше мусора)
380 reset() { this.zb.fill(Infinity) }
381
382 // нарисовать меш объекта o камерой c; tint — общая яркость, env — цвет контрового света окружения,
383 // lights — точечные источники (взрывы, лазеры): позиция, цвет 0..1, сила
384 draw(mesh: Mesh, o: Obj, c: Cam, engine: number, blue: number, tint = 1, env?: [number, number, number], lights: Light[] = []) {
385 const { W, H } = this
386 const cp = camPos(c)
387 mesh.tris.forEach((t, ti) => {
388 const wa = toWorld(t.a, o), wb = toWorld(t.b, o), wc = toWorld(t.c, o)
389 // нормаль в мире, развёрнутая к камере: полигоны двусторонние
390 const ux = wb[0] - wa[0], uy = wb[1] - wa[1], uz = wb[2] - wa[2]
391 const vx = wc[0] - wa[0], vy = wc[1] - wa[1], vz = wc[2] - wa[2]
392 let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx
393 const nl = Math.hypot(nx, ny, nz) || 1
394 nx /= nl; ny /= nl; nz /= nl
395 let ex = cp[0] - wa[0], ey = cp[1] - wa[1], ez = cp[2] - wa[2]
396 const el = Math.hypot(ex, ey, ez) || 1
397 ex /= el; ey /= el; ez /= el
398 let ndv = nx * ex + ny * ey + nz * ez
399 if (ndv < 0) { nx = -nx; ny = -ny; nz = -nz; ndv = -ndv }
400 let col: number
401 if (t.col === ENGINE) col = engine
402 else if (t.col === BLUE) col = blue
403 else {
404 // Ламберт + блик по Блинну + контровой свет по краю; рябь по граням — панели обшивки
405 const lam = Math.max(0, nx * LIGHT[0] + ny * LIGHT[1] + nz * LIGHT[2])
406 let hx = LIGHT[0] + ex, hy = LIGHT[1] + ey, hz = LIGHT[2] + ez
407 const hl = Math.hypot(hx, hy, hz) || 1
408 const spec = Math.pow(Math.max(0, (nx * hx + ny * hy + nz * hz) / hl), 28) * 0.45
409 const rim = Math.pow(1 - ndv, 3) * 0.22
410 const grain = 0.9 + 0.12 * (((ti * 2654435761) >>> 0) % 997) / 997
411 const base = ((0.3 + 0.95 * lam + rim) * grain + spec) * tint
412 let lr = base, lg = base, lb = base
413 if (env) { const e = Math.pow(1 - ndv, 2) * 1.4; lr += env[0] * e; lg += env[1] * e; lb += env[2] * e }
414 for (const L of lights) {
415 const dx = L.p[0] - wa[0], dy = L.p[1] - wa[1], dz = L.p[2] - wa[2]
416 const d = Math.hypot(dx, dy, dz) || 1
417 const k = Math.max(0, (nx * dx + ny * dy + nz * dz) / d) * L.k / (1 + d * d * 0.01)
418 lr += L.col[0] * k; lg += L.col[1] * k; lb += L.col[2] * k
419 }
420 const ch = (sh: number, f: number) => Math.min(255, Math.round(((t.col >> sh) & 255) * f))
421 col = (ch(16, lr) << 16) | (ch(8, lg) << 8) | ch(0, lb)
422 }
423 const A = project(wa, c), B = project(wb, c), C = project(wc, c)
424 if (!A || !B || !C) return
425 const ax = A[0] * SS, ay = A[1] * SS, bx = B[0] * SS, by = B[1] * SS, cx = C[0] * SS, cy = C[1] * SS
426 const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
427 if (Math.abs(area) < 1e-6) return
428 const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)))
429 const x1 = Math.min(W - 1, Math.ceil(Math.max(ax, bx, cx)))
430 const y0 = Math.max(0, Math.floor(Math.min(ay, by, cy)))
431 const y1 = Math.min(H - 1, Math.ceil(Math.max(ay, by, cy)))
432 const bias = t.col < 0 ? 0.05 : 0 // сопла чуть выигрывают z-тест у корпуса вокруг
433 for (let y = y0; y <= y1; y++) {
434 const py = y + 0.5
435 for (let x = x0; x <= x1; x++) {
436 const px = x + 0.5
437 const w0 = ((bx - px) * (cy - py) - (by - py) * (cx - px)) / area
438 const w1 = ((cx - px) * (ay - py) - (cy - py) * (ax - px)) / area
439 const w2 = 1 - w0 - w1
440 if (w0 < 0 || w1 < 0 || w2 < 0) continue
441 const z = w0 * A[2] + w1 * B[2] + w2 * C[2] - bias
442 const i = y * W + x
443 if (z < this.zb[i]!) { this.zb[i] = z; this.cb[i] = col }
444 }
445 }
446 })
447 }
448
449 // свернуть под-пиксели поверх фонового буфера rgb (float 0..1+, 3 канала на пиксель)
450 resolve(rgb: Float32Array) {
451 const { W, w, h } = this
452 for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
453 let r = 0, g = 0, b = 0, n = 0
454 for (let sy = 0; sy < SS; sy++) for (let sx = 0; sx < SS; sx++) {
455 const i = (y * SS + sy) * W + x * SS + sx
456 if (this.zb[i] === Infinity) continue
457 const c = this.cb[i]!
458 r += (c >> 16) & 255; g += (c >> 8) & 255; b += c & 255; n++
459 }
460 if (!n) continue
461 // корпус в тени не должен становиться «пустотой» терминала: минимальная яркость
462 const lift = Math.max(0, 14 - Math.max(r, g, b) / n)
463 r += lift * n; g += lift * n; b += lift * n * 1.2
464 const a = n / (SS * SS), o = (y * w + x) * 3
465 rgb[o] = rgb[o]! * (1 - a) + (r / n / 255) * a
466 rgb[o + 1] = rgb[o + 1]! * (1 - a) + (g / n / 255) * a
467 rgb[o + 2] = rgb[o + 2]! * (1 - a) + (b / n / 255) * a
468 }
469 }
470
471 // глубина ближайшего под-пикселя в пикселе (для того, чтобы эффекты прятались за кораблём)
472 depthAt(x: number, y: number) {
473 let d = Infinity
474 for (let sy = 0; sy < SS; sy++) for (let sx = 0; sx < SS; sx++) {
475 const v = this.zb[(y * SS + sy) * this.W + x * SS + sx]!
476 if (v < d) d = v
477 }
478 return d
479 }
480}
481