# COINS — 3D coins for any website

**For the AI agent (Claude Code, Codex, Cursor or similar).** The person has attached this file, usually together with an SVG file. They want an animated hero for their website: a long row of metal 3D coins made from their SVG that drifts sideways and reacts to the cursor. First they tune it in a settings page in their browser. Then they paste the settings back to you, and you turn them into code for their site.

The settings page is already written. It is the HTML at the very end of this file, between a line `<<<<<<<< COIN-STUDIO-HTML` and a line `>>>>>>>> COIN-STUDIO-HTML`. It is long (74 085 characters). These instructions end at line 129: don't read past that line. **Do not read the page into the chat, retype it, rewrite it or "improve" it.** Copy it out with a script.

Talk to the person in the language of their message. If they wrote nothing, use Russian, since the settings panel is in Russian. Keep messages short and free of jargon. Do one step at a time.

## Step 1. Find the files

- **This file.** Find its path on disk: the person attached it or dropped it into the chat. If you only have its text, look for `coins-prompt.md` in the working folder, then on the Desktop, then in Downloads.
- **The SVG.** It was attached alongside this file or is in the working folder. If there are several, ask which one. If there is none, ask for one. Until it arrives you can still open the page: it starts with a built-in dollar coin.

## Step 2. Check the SVG

Open the SVG as text and check it. Do not redraw or "fix" it yourself.

- The scene uses only **filled** shapes. The largest filled area becomes the coin body. Shapes in other colours on top of it become relief, like the symbol on a coin.
- A single colour gives a flat figure. Holes are fine.
- Strokes without fill, `<text>` and raster `<image>` are ignored.

If the SVG has only strokes or text, tell the person how to fix it in Figma, then export SVG again:

1. Select the layer.
2. Choose **Outline stroke** (⌥⌘O / Ctrl+Alt+O).
3. Turn text into outlines.
4. Flatten.

## Step 3. Make and open the settings page

1. Make a folder `coin-studio` in the folder you are working in (your current directory or open project). If you can't write there, use the Desktop or a temp folder.
2. Write `coin-studio/index.html` with a script:
   1. Take the text between the two marker lines, without the marker lines themselves.
   2. Check it: it starts with `<!doctype html>`, ends with `</html>`, and its SHA-256 (UTF-8, `\n` line endings) is `f758fe881cea83684783fbd870fd41834954519643b35b13a1521f0812b88926`. If the hash doesn't match, extract it again. Don't repair it by hand.
   3. Replace the line `<!--@@SVG@@-->` with the full text of the SVG file. Change nothing else.
3. Open the page in the person's default browser. The copy button needs a real browser, not a preview:
   - macOS: `open coin-studio/index.html`
   - Windows: `start "" "coin-studio\index.html"`
   - Linux: `xdg-open coin-studio/index.html`

   If you have no shell, or the command fails (sandbox, remote machine), give the person the absolute address of the file, like `file:///Users/name/site/coin-studio/index.html` or `file:///C:/Users/name/site/coin-studio/index.html`. Tell them to paste it into the address bar of Chrome, Safari, Edge or Firefox. If the file is on a machine they can't reach, give them the file to save.

Python example (put in the real paths you found in step 1):

```python
from pathlib import Path
import hashlib
prompt = Path("/path/to/coins-prompt.md").read_text(encoding="utf-8")
html = prompt.rsplit("\n<<<<<<<< COIN-STUDIO-HTML\n", 1)[1].rsplit("\n>>>>>>>> COIN-STUDIO-HTML", 1)[0]
assert hashlib.sha256(html.encode("utf-8")).hexdigest() == "f758fe881cea83684783fbd870fd41834954519643b35b13a1521f0812b88926"
svg = Path("/path/to/shape.svg").read_text(encoding="utf-8")
html = html.replace("<!--@@SVG@@-->", svg.strip(), 1)
out = Path("coin-studio/index.html"); out.parent.mkdir(exist_ok=True); out.write_text(html, encoding="utf-8")
```

Node works the same way. The page needs internet: three.js loads from a CDN.

Then explain the page in a few lines:

- The **«Настройки анимации»** panel is on the right. Click its title to open it.
- **Вид**: colours, metal and background. **Свет**: lighting. **Форма**: size, thickness and bevel; another SVG can be loaded there or dropped onto the page. **Рельеф** shows up if the SVG has two or more colours. **Рифлёный торец**: the ribbed coin edge. **Ряд**: count, spacing, speed and position. **Механика первого экрана** and **Курсор**: how the coins react.
- The background is transparent by default (checkerboard), so the site's own background will show through. To set a colour instead, untick **«прозрачный фон»**.
- **«Сбросить»** in the panel header returns everything to the start.
- When it looks right, they press **«Скопировать настройки»** at the bottom of the panel and paste the result into this chat.

## Step 4. When the settings come back

They paste a JSON object with many keys, including `g8` and `svg`. `svg` is the shape that was on screen when they copied, and it can differ from the file they gave you. Always use the pasted one. Save the JSON as is to `coin-studio/settings.json`. Then ask, in one short message, only the questions below they haven't answered yet:

1. **Where will it go?** Tilda, Framer, Webflow, WordPress, a plain HTML site, React / Next.js, Vue / Nuxt, or something else.
2. **How?** As the full-screen background of the first screen with their content on top (the default), or as a block of a set height.
3. **What goes on top?** Their own headline and button, or they will add them later.

## Step 5. Build the code for the site

Start from `coin-studio/index.html` and change it with a script:

1. Delete everything from the line with `/*@@PANEL-START@@*/` to the line with `/*@@PANEL-END@@*/`, including both lines. That is the panel, colour picker and file upload. The site doesn't need them.
2. Delete the line `import GUI from 'lil-gui';` and the `"lil-gui"` entry in the import map. It is the last entry, so also remove the comma at the end of the line before it.
3. Replace `/*@@SETTINGS@@*/` with `window.SCENE_OVERRIDES = <the pasted JSON>;`.
   - Its `svg` key overrides the SVG slot, so empty the `coin-svg` script.
   - Only if the JSON has no `svg` key, keep the SVG in the slot.
4. Replace the demo page's `<style>` block (checkerboard, page background, `section` rules) with your own small one for the canvas and its wrapper. Remove the empty `<section class="hero">`. The scene still adds a class `bg-clear` to `<html>`. Without the demo CSS it does nothing.
5. Fit the canvas `#scene` to the target.
   - The scene sizes itself to the canvas, so the canvas can sit anywhere. Use `position: fixed; inset: 0` for a page background, or `position: absolute; inset: 0` inside a `position: relative` block with a set height.
   - Put the person's content above it with a higher `z-index`. The scene listens to the pointer on the whole window, so text and buttons on top don't block the effect.
   - With `bgTransparent: true` the canvas is see-through. Otherwise it is painted with `bg`.
6. Keep everything else as it is: the scene code, three.js 0.170.0 from the CDN and the import map. The import map must come before the module script.
7. The page is one screen, so you need nothing for scrolling. The coins stay a row, and scrolling only speeds them up for a moment.

For a site builder, give a fragment with no `<html>`, `<head>` or `<body>`, in this order:

```html
<div class="coins-hero"><canvas id="scene"></canvas></div>
<style>/* wrapper and canvas sizes */</style>
<script type="importmap">{ "imports": { "three": "…", "three/addons/": "…" } }</script>
<script type="text/plain" id="coin-svg"></script>
<script>window.SCENE_OVERRIDES = { … };</script>
<script type="module">/* the scene code, unchanged */</script>
```

For a plain HTML site, it can also be a whole page.

Platform notes. Check the current limits of the platform if you can:

- **Plain HTML:** one file, or a block to paste into the page, with the import map placed before any module script.
- **Tilda:** for coins behind their own headline, use a Zero Block. Add an HTML element, paste the fragment, make it fill the block (window width, 100% height) and put it at the bottom layer. Their text and buttons are ordinary Zero Block elements above it. For a block of coins only, use an HTML block (T123) with a wrapper of a set height. Scripts may not run in the editor preview, so check on the published page. Check the current size limit of the element: the fragment is about 50–60 KB.
- **Framer:** Embed → HTML. Stretch it to the section.
- **Webflow:** a Code Embed. It has a character limit (50,000 when this was written). If the code is longer, host the standalone page as a file and embed it with an `<iframe>`.
- **WordPress:** a Custom HTML block.
- **React / Next.js / Vue:** a small component that renders the canvas and loads the scene script once on the client, using `useEffect`, `next/script` or `onMounted`. Don't port the scene to npm packages.
- **Fallback:** if a platform strips module scripts or import maps, use the standalone page in an `<iframe>`. Tell the person that the cursor effect then works only over the frame.

Then check the result:

- No markers are left.
- `SCENE_OVERRIDES` is valid.
- If you can open a browser, open the result and check that the console has no errors.

Save the code as `coin-studio/coins-<platform>.html`, for example `coins-tilda.html`, and give the person its path with short steps on where to paste it. If you can run commands, also try to put it on their clipboard (`pbcopy` / `clip` / `xclip` / `wl-copy`). Say it's copied only if the command succeeded. Don't paste tens of kilobytes into the chat unless they ask.

If something goes wrong, check these first:

- **A blank page** is usually no internet (the CDN) or a broken SVG. Look at the console.
- **The built-in dollar coin instead of their shape** means the SVG couldn't be read. Go back to step 2.

---

Below is the settings page, the payload for step 3.

```html
<<<<<<<< COIN-STUDIO-HTML
<!doctype html>
<!-- Coin Studio — 3D-монеты для сайта. Автор: Виктор Богут, @bogutvictor -->
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coin Studio — настройка монет</title>
<style>
  :root { --bg: #000514; --muted: #56607a; }
  html, body { margin: 0; background: var(--bg); color: #e8ecf5; font-family: system-ui, -apple-system, sans-serif; }
  /* прозрачный фон в демо — шахматка, как в Figma */
  html.bg-clear, html.bg-clear body { background: #2a2a30 repeating-conic-gradient(#1e1e22 0 25%, #2a2a30 0 50%) 0 0 / 24px 24px; }
  /* Сцена закреплена под страницей: экраны прокручиваются поверх неё, а ряд букв
     по мере скролла сгибается в кольцо */
  #scene { position: fixed; inset: 0; width: 100%; height: 100vh; height: 100lvh; display: block; z-index: 0; }
  section { position: relative; z-index: 1; height: 100vh; height: 100svh; pointer-events: none; }
  .next { display: flex; align-items: center; padding: 0 6vw; }
  .next h2 { margin: 0; max-width: 34vw; font-size: clamp(28px, 3.6vw, 56px); line-height: 1.05; font-weight: 600; color: #e8ecf5; }
  .next p { margin: 16px 0 0; max-width: 30vw; font-size: 14px; color: var(--muted); }
</style>
<script type="importmap">
{
  "imports": {
    "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
    "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/",
    "lil-gui": "https://cdn.jsdelivr.net/npm/lil-gui@0.19.2/dist/lil-gui.esm.js"
  }
}
</script>
</head>
<body>
<canvas id="scene"></canvas>
<!-- SVG-фигура для монет: вставляется вместо строки ниже -->
<script type="text/plain" id="coin-svg">
<!--@@SVG@@-->
</script>
<script>/*@@SETTINGS@@*/</script>
<section class="hero">
</section>


<script type="module">
import * as THREE from 'three';
import { SVGLoader } from 'three/addons/loaders/SVGLoader.js';
import { toCreasedNormals } from 'three/addons/utils/BufferGeometryUtils.js';
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
import { RectAreaLightUniformsLib } from 'three/addons/lights/RectAreaLightUniformsLib.js';
import GUI from 'lil-gui';

// ---------- Формы из SVG ----------
// Встроенные формы. Свою можно загрузить кнопкой в панели или перетащить SVG-файл на страницу.
// Если в SVG несколько цветов: самый большой по площади — тело, остальные — рельеф.
const PRESETS = {
  'B': `<svg viewBox="0 0 374 297" xmlns="http://www.w3.org/2000/svg"><path fill="#000" d="M0 296.277V0H246.898C331.719 0 357.604 32.256 357.604 69.2907V72.0782C357.604 111.9 322.56 129.024 300.26 132.21C330.923 136.59 373.931 154.112 373.931 205.084V209.067C373.931 258.048 344.064 296.277 247.296 296.277H0ZM217.031 69.2907H107.52V112.299H217.031C239.73 112.299 246.898 103.538 246.898 91.1929V90.3964C246.898 77.6533 239.332 69.2907 217.031 69.2907ZM224.996 176.412H107.52V223.801H224.996C253.668 223.801 258.446 211.058 258.446 199.908V198.315C258.446 186.766 253.668 176.412 224.996 176.412Z"/></svg>`,
  'Монета ₽': `<svg width="700" height="700" viewBox="0 0 700 700" xmlns="http://www.w3.org/2000/svg"><circle cx="350" cy="350" r="350" fill="#212121"/><path d="M404.605 413.595H295.89V433.108H442.436V467.355H295.89V502H188.37V467.355H153.725V433.108H188.37V413.595H153.725V380.542H188.37V205.723H404.605C514.912 205.723 543.584 247.138 543.584 305.676V310.853C543.584 369.79 513.718 413.595 404.605 413.595ZM295.89 281.385V337.932H394.649C423.719 337.932 432.082 325.189 432.082 309.659V308.862C432.082 294.526 423.719 281.385 394.649 281.385H295.89Z" fill="#777777"/></svg>`,
  'Монета $': `<svg width="1304" height="1304" viewBox="0 0 1304 1304" xmlns="http://www.w3.org/2000/svg"><circle cx="652" cy="652" r="652" fill="#D9D9D9"/><path d="M498.823 513.248V515.035C498.823 542.736 514.907 568.651 608.734 573.118V461.42C512.227 465.888 498.823 483.759 498.823 513.248ZM808.899 790.261V787.58C808.899 755.411 796.388 735.752 694.519 728.603V857.28C797.282 850.132 808.899 818.856 808.899 790.261ZM694.519 1073.53H608.734V1004.72C280.787 997.574 246.83 861.748 246.83 775.964V770.602H497.929C500.61 793.835 505.971 846.557 608.734 856.387V726.816L573.884 725.923C317.424 721.455 255.766 626.734 255.766 518.609V510.567C255.766 402.443 324.573 324.7 608.734 320.232V251.426H694.519V321.126C998.34 325.594 1043.02 433.718 1043.02 526.652V532.013H798.176C793.708 508.78 781.197 473.036 694.519 463.207V575.799L730.263 576.693C992.085 583.842 1054.64 661.584 1054.64 781.325V792.048C1054.64 897.492 1001.91 1000.25 694.519 1004.72V1073.53Z" fill="black"/></svg>`,
};

// ---------- Настройки (их же крутит панель справа) ----------
// Раскладка ряда и камера повторяют референс: длинный ряд вдоль X, все буквы
// повёрнуты на один и тот же угол и стоят «домино» — пластина за пластиной.
const P = {
  color: '#061cc1',  // тёмный синий: металл почти чёрный, цвет проявляется в переливах и на рёбрах
  flashColor: '#5d43df',
  // Материал и свет — по схеме референса: гладкий металл, отражающий фото настоящей студии (HDRI),
  // плюс большой мягкий прямоугольный свет и один направленный
  roughness: 0.31,
  anisotropy: 0,     // шлифовка без штрихов: блик вытягивается вдоль одного направления (0 — гладкий металл)
  anisoRot: 90,      // направление шлифовки, °
  clearcoat: 0, coatRough: 0.2, // прозрачный лак поверх металла: отражает цветной блик без окраски в цвет монеты
  iridescence: 0, iridIOR: 1.3, iridMin: 120, iridMax: 420, // радужная плёнка: перелив цвета в зависимости от угла
  accentColor: '#ff6a1a', accentGlow: 0, // тёплый цветной блик в студии (как оранжевый отсвет на клавишах)
  accentAz: 25, accentEl: 0, accentWidth: 0.35, // положение блика — относительно того, куда смотрят лица монет: так он ложится на часть ряда
  studioFill: 1,     // яркость фона светлой студии (0 — тёмная студия, только софтбоксы)
  envIntensity: 0.35,
  hdri: 'soft',
  faceGlow: 1.45,     // яркость перелива по лицам
  faceWidth: 0.32,   // ширина перелива: меньше — контрастнее, больше — ровнее
  envRotX: 0, envRotY: 0, envRotZ: 0,
  softColor: '#ffffff', softIntensity: 30.7, softAz: 74, softEl: -49, softW: 11.8, softH: 4,
  keyColor: '#000000', keyIntensity: 2, keyAz: -99, keyEl: -44,
  bg: '#000514',
  bgTransparent: true, // прозрачный фон: сквозь сцену виден фон сайта
  toneMapping: 'aces', // как яркий свет сжимается в цвета экрана: neutral — без сдвига оттенка, aces — киношный (синие блики уходят в розовый), agx — мягкий
  exposure: 0.85,

  shape: 'Монета $',      // форма из встроенных (или своя, загруженная из SVG)

  // Рельеф из второго цвета SVG (например, ₽ на монете)
  reliefMode: 'emboss', // emboss — выпуклый, deboss — вдавленный, flat — без рельефа
  reliefDepth: 0.12,     // высота / глубина рельефа
  reliefBoth: true,     // рельеф с обеих сторон, как на монете
  reliefColor: '#0526e6',

  // Рифление торца, как на ребре монеты
  ribs: true, 
  ribCount: 119,     // сколько рёбер по всему контуру
  ribDepth: 0.013,    // глубина канавок
  ribRound: 1.45,       // форма ребра: меньше — широкие плоские, больше — острые

  size: 3.05,         // высота фигуры
  depth: 0.36,        // толщина (без фаски)
  bevel: 0.035,      // фаска
  crease: 50,        // углы мягче этого сглаживаются, острее — остаются гранью, °
  count: 68,         // сколько букв в ряду (видно ~10, остальные за краями)
  spacing: 1.74,      // шаг по X. B шире «8» из референса, поэтому шаг вдвое больше
  yaw: -33,          // поворот всех букв вокруг вертикали, °
  speed: 1.46,       // скорость ряда, единиц в секунду
  x: 0, y: -0.25, z: -10.3,
  arch: 2,        // лёгкая волна по высоте
  curve: 33,         // радиус изгиба ряда (больше — прямее)
  recede: -0.003,    // края ряда подтягиваются к зрителю

  // Второй экран: средняя часть ряда сгибается в почти замкнутое кольцо
  ringSpan: 346,     // угол дуги, °: 360 — полное кольцо
  ringLen: 56.5,       // длина согнутой части ряда (≈ 23 буквы); за её концами буквы тают
  ringScale: 1.32,   // во сколько раз уменьшается вся композиция в кольце
  ringX: 10, ringY: -8.9, ringZ: -11, // где центр кольца: правее центра экрана и глубже
  ringBoost: 1.5,    // насколько ярче свет на кольце (оно дальше от зрителя)

  // Третий экран: кольцо раскрывается в ряд, ряд уходит волной вверх
  row3X: 0, row3Y: -1.5, row3Z: -3.2, row3Scale: 0.9, // где встаёт раскрытый ряд
  unbendPart: 0.55,  // какую часть перехода занимает раскрытие кольца
  exitStart: 0.3,    // с какого момента перехода ряд начинает уходить вверх
  exitHeight: 16,    // насколько высоко улетают буквы
  exitStagger: 0.6,  // запаздывание правых букв относительно левых — это и есть волна
  exitSpread: 12,    // ширина ряда, по которой разложено запаздывание
  exitTilt: 10,      // качание букв на взлёте, °
  exitAfter: false,  // true — на третьем экране ряд остаётся, а уходит только при дальнейшей прокрутке
  exitDir: 1,        // 1 — уходят вверх, -1 — вниз
  mech: 'gr8',      // механика первого экрана: own — простая, gr8 — живая (змейка за курсором, пинок, рябь по клику, появление)
  endMorph: 1.74,
  transition3: 'unbend', // 2 → 3 экран: drift — кольцо целиком плавно уплывает в правый верхний угол; unbend — раскрывается в ряд и улетает волной
  ring3X: 15, ring3Y: 13.5, ring3Z: -11, ring3Scale: 1.32, // где кольцо стоит на третьем экране (drift)       // до какого места доигрывается переход на последнем экране: 2 — монеты улетели целиком, ~1.8 — часть осталась в правом верхнем углу

  lightColor: '#ffffff',
  lightIntensity: 28,
  lightDepth: 6.4,   // насколько свет ближе к зрителю, чем ряд

  hoverRadius: 0.36, // доля ширины экрана
  hoverLift: 1.9,
  hoverTilt: 10,      // наклон в своей плоскости, °
  kick: 0.4,
  scrollBoost: 2.2,
  parallax: 0.031,
};
// страница, куда встроена сцена, может поменять настройки до старта
if (window.SCENE_OVERRIDES) Object.assign(P, window.SCENE_OVERRIDES);
const SLOT_SVG = (() => { const t = document.getElementById('coin-svg')?.textContent || ''; return t.includes('<svg') ? t.trim() : null; })();
const START_SVG = P.svg || SLOT_SVG; delete P.svg; delete P.g8;

const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
const DEG = Math.PI / 180, TAU = Math.PI * 2;

// ---------- Рендер ----------
const canvas = document.getElementById('scene');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' });
renderer.setClearColor(0x000000, 0);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
const TONE = { neutral: THREE.NeutralToneMapping, aces: THREE.ACESFilmicToneMapping, agx: THREE.AgXToneMapping };
function applyTone() { renderer.toneMapping = TONE[P.toneMapping]; renderer.toneMappingExposure = P.exposure; }
applyTone();

const scene = new THREE.Scene();
const BG = new THREE.Color(P.bg);
scene.background = P.bgTransparent ? null : BG;
document.documentElement.classList.toggle('bg-clear', !!P.bgTransparent);
const CAM_Z = 16, VFOV_MIN = 22.9, HFOV = 39.6;
const camera = new THREE.PerspectiveCamera(VFOV_MIN, 16 / 9, 0.1, 200);
camera.position.set(0, 0, CAM_Z);

// Окружение — то, что отражает металл.
// По умолчанию — «мягкая студия»: сфера, на которой нарисованы только размытые световые
// пятна (гауссовы, без единого края). Отражать в ней нечего, кроме плавных переходов,
// поэтому на торцах и лицах нет ни полос, ни линий — только переливы.
// Для сравнения можно включить настоящие фото студий (HDRI, CC0, Poly Haven), но в них
// есть лампы и рамы софтбоксов, и на изогнутых торцах они видны полосками.
const HDRIS = {
  'Мягкая студия (без линий)': 'soft',
  'Светлая студия (алюминий)': 'alu',
  'Фото: маленькая студия 09': 'studio_small_09',
  'Фото: маленькая студия 03': 'studio_small_03',
  'Фото: фотостудия': 'brown_photostudio_02',
};
const pmrem = new THREE.PMREMGenerator(renderer);
function setEnv(env) { scene.environment?.dispose(); scene.environment = env; }

function lobeStudio(lobes, base) {
  // base: [цвет сверху, у горизонта, снизу] — плавный фон студии; lobes — размытые софтбоксы
  const MAXL = 8;
  while (lobes.length < MAXL) lobes.push([new THREE.Vector3(0, 1, 0), '#000000', 0, 1]);
  const mat = new THREE.ShaderMaterial({
    side: THREE.BackSide,
    uniforms: {
      dirs: { value: lobes.map(l => l[0]) },
      cols: { value: lobes.map(l => new THREE.Color(l[1]).multiplyScalar(l[2])) },
      widths: { value: lobes.map(l => l[3]) },
      top: { value: new THREE.Color(base[0]) }, mid: { value: new THREE.Color(base[1]) }, bot: { value: new THREE.Color(base[2]) },
    },
    vertexShader: `varying vec3 vDir; void main(){ vDir = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
    fragmentShader: `
      uniform vec3 dirs[8]; uniform vec3 cols[8]; uniform float widths[8]; uniform vec3 top; uniform vec3 mid; uniform vec3 bot;
      varying vec3 vDir;
      void main(){
        vec3 d = normalize(vDir);
        vec3 c = d.y > 0.0 ? mix(mid, top, smoothstep(0.0, 1.0, d.y)) : mix(mid, bot, smoothstep(0.0, 1.0, -d.y));
        for (int i = 0; i < 8; i++) {
          float a = acos(clamp(dot(d, dirs[i]), -1.0, 1.0));
          c += cols[i] * exp(-(a * a) / (widths[i] * widths[i]));
        }
        gl_FragColor = vec4(c, 1.0);
      }`,
  });
  const s = new THREE.Scene();
  s.add(new THREE.Mesh(new THREE.SphereGeometry(10, 96, 48), mat));
  const env = pmrem.fromScene(s, 0).texture;
  mat.dispose();
  return env;
}
// Куда смотрят отражения лиц: нормаль буквы, отражённый луч от камеры к ряду
function faceDir() {
  const n = new THREE.Vector3(Math.sin(P.yaw * DEG), 0, Math.cos(P.yaw * DEG));
  const d = new THREE.Vector3(0, P.y, P.z - CAM_Z).normalize();
  return d.clone().sub(n.clone().multiplyScalar(2 * d.dot(n))).normalize();
}
const sph = (az, el) => new THREE.Vector3(Math.sin(az * DEG) * Math.cos(el * DEG), Math.sin(el * DEG), Math.cos(az * DEG) * Math.cos(el * DEG));
// цветной блик: направление отражения лиц, повёрнутое на accentAz по горизонтали и accentEl по вертикали
function accentDir() {
  const f = faceDir();
  const az = Math.atan2(f.x, f.z) / DEG + P.accentAz, el = Math.asin(Math.max(-1, Math.min(1, f.y))) / DEG + P.accentEl;
  return sph(az, el);
}
function makeSoftStudio() {
  const face = faceDir();
  return lobeStudio([
    [face.clone().add(new THREE.Vector3(0, 0.45, 0)).normalize(), '#dfe7ff', P.faceGlow, P.faceWidth], // перелив по лицам: сверху светлее
    [new THREE.Vector3(0.1, 1, 0.35).normalize(), '#ffffff', 2.2, 0.6],  // большой верхний софтбокс — блик на фасках
    [new THREE.Vector3(0.9, -0.1, 0.45).normalize(), '#8fb0ff', 1.4, 0.5], // холодный контровой справа
    [new THREE.Vector3(-0.2, -1, 0.3).normalize(), '#3550c8', 0.7, 0.9],  // синий отсвет снизу
    [accentDir(), P.accentColor, P.accentGlow, P.accentWidth],
  ], ['#010103', '#010103', '#010103']);
}
// Светлая студия, как на фото шлифованного алюминия: светло-серый фон, большие мягкие
// софтбоксы сверху и сбоку, тёмный пол — отсюда серебристые переливы на торцах
// и спокойные сатиновые лица. Плюс тёплый цветной блик (accent).
function makeAluStudio() {
  const face = faceDir();
  return lobeStudio([
    [face.clone().add(new THREE.Vector3(0, 0.35, 0)).normalize(), '#ffffff', P.faceGlow * 1.2, Math.max(P.faceWidth, 0.45)], // светлое лицо
    [new THREE.Vector3(0, 1, 0.2).normalize(), '#ffffff', 2.6, 0.55],     // верхний софтбокс
    [new THREE.Vector3(-0.9, 0.25, 0.3).normalize(), '#f2f2f5', 1.6, 0.45], // боковой слева
    [new THREE.Vector3(0.85, 0.2, -0.4).normalize(), '#e8e9ee', 1.1, 0.4], // контровой справа сзади
    [new THREE.Vector3(0, -0.2, 1).normalize(), '#9a9ca3', 0.6, 0.7],     // мягкий фронт
    [accentDir(), P.accentColor, P.accentGlow, P.accentWidth], // цветной блик
  ], ['#8e9097', '#4a4c52', '#0c0c0f'].map(c => '#' + new THREE.Color(c).multiplyScalar(P.studioFill).getHexString()));
}

function loadHdri() {
  if (P.hdri === 'soft') { setEnv(makeSoftStudio()); return; }
  if (P.hdri === 'alu') { setEnv(makeAluStudio()); return; }
  new RGBELoader().load(`https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/${P.hdri}_1k.hdr`, tex => {
    tex.mapping = THREE.EquirectangularReflectionMapping;
    setEnv(pmrem.fromEquirectangular(tex).texture);
    tex.dispose();
  });
}
loadHdri();
scene.environmentIntensity = P.envIntensity;
function applyEnvRotation() { scene.environmentRotation.set(P.envRotX * DEG, P.envRotY * DEG, P.envRotZ * DEG); }
applyEnvRotation();

// Свет ставим по азимуту и высоте относительно центра ряда
const ROW_C = new THREE.Vector3(P.x, P.y, P.z);
function placeLight(light, az, el, dist) {
  light.position.set(
    ROW_C.x + Math.sin(az * DEG) * Math.cos(el * DEG) * dist,
    ROW_C.y + Math.sin(el * DEG) * dist,
    ROW_C.z + Math.cos(az * DEG) * Math.cos(el * DEG) * dist,
  );
}

// Большой мягкий прямоугольный свет сверху-спереди: широкий плавный блик по лицам
RectAreaLightUniformsLib.init();
const soft = new THREE.RectAreaLight(P.softColor, P.softIntensity, P.softW, P.softH);
function applySoft() {
  soft.color.set(P.softColor); soft.intensity = P.softIntensity;
  soft.width = P.softW; soft.height = P.softH;
  placeLight(soft, P.softAz, P.softEl, 12);
  soft.lookAt(ROW_C);
}
applySoft();
scene.add(soft);

// Направленный «ключ» снизу сбоку — подсвечивает фаски и торцы
const key = new THREE.DirectionalLight(P.keyColor, P.keyIntensity);
key.target.position.copy(ROW_C);
scene.add(key, key.target);
function applyKey() { key.color.set(P.keyColor); key.intensity = P.keyIntensity; placeLight(key, P.keyAz, P.keyEl, 10); }
applyKey();

const cursorLight = new THREE.PointLight(P.lightColor, P.lightIntensity, 0, 2);
scene.add(cursorLight);

// ---------- Геометрия фигуры ----------
// Фигура берётся из SVG. Если в нём два цвета и больше: цвет с самой большой
// площадью — это тело фигуры, всё остальное — рельеф на её лицевой стороне
// (например, монета и знак рубля на ней).

// Там, где контур образует острый внутренний клюв (стык «животов» B), фаска
// выворачивается и пересекает сама себя — отсюда полосы и светлый клин.
// Скругляем такой клюв маленькой дугой: на глаз форма та же, а фаска ложится гладко.
function filletSharp(src, r, minTurnDeg = 120) {
  const pts = src.filter((p, i) => i === 0 || p.distanceTo(src[i - 1]) > 1e-6);
  if (pts.length > 2 && pts[0].distanceTo(pts[pts.length - 1]) < 1e-6) pts.pop();
  const n = pts.length, remove = new Set(), inserts = new Map();
  for (let i = 0; i < n; i++) {
    const a = pts[(i - 1 + n) % n], b = pts[i], c = pts[(i + 1) % n];
    const d1 = b.clone().sub(a).normalize(), d2 = c.clone().sub(b).normalize();
    const turn = Math.acos(THREE.MathUtils.clamp(d1.dot(d2), -1, 1)) / DEG;
    if (turn < minTurnDeg) continue; // обычные углы остаются острыми
    const walk = dir => {
      let j = i, acc = 0;
      for (;;) {
        const k = (j + dir + n) % n;
        acc += pts[j].distanceTo(pts[k]); j = k;
        if (acc >= r || k === i) return j;
        remove.add(j);
      }
    };
    const j1 = walk(-1), j2 = walk(1);
    remove.add(i);
    // плавный «нос»: кубическая кривая, касательная к контуру с обеих сторон
    const p1 = pts[j1], p2 = pts[j2];
    const t1 = p1.clone().sub(pts[(j1 - 1 + n) % n]).normalize();
    const t2 = pts[(j2 + 1) % n].clone().sub(p2).normalize();
    const h = r * 0.6;
    const arc = new THREE.CubicBezierCurve(p1.clone(), p1.clone().addScaledVector(t1, h), p2.clone().addScaledVector(t2, -h), p2.clone());
    inserts.set(j1, arc.getPoints(48).slice(1, -1));
  }
  const out = [];
  for (let i = 0; i < n; i++) {
    if (!remove.has(i)) out.push(pts[i]);
    if (inserts.has(i)) out.push(...inserts.get(i));
  }
  return out;
}

// Рифление, как на ребре монеты: контур равномерно переразбиваем и прорезаем
// внутрь канавками. Между канавками — выпуклые скруглённые рёбра.
// round: 0.3 — широкие плоские рёбра и узкие канавки, 1 — круглые, 3 — острые.
function reeded(src, count, depth, round) {
  const pts = src.slice();
  if (THREE.ShapeUtils.isClockWise(pts)) pts.reverse(); // дальше считаем, что обход против часовой
  const n = pts.length, cum = [0];
  for (let i = 1; i <= n; i++) cum.push(cum[i - 1] + pts[i - 1].distanceTo(pts[i % n]));
  const len = cum[n], M = Math.max(512, Math.round(count) * 10), out = []; // 10 точек на ребро: сглаживание нормалей делает его круглым
  let j = 0;
  const at = d => {
    while (cum[j + 1] < d) j++;
    const k = (d - cum[j]) / Math.max(cum[j + 1] - cum[j], 1e-9);
    return pts[j].clone().lerp(pts[(j + 1) % n], k);
  };
  const samples = [];
  for (let i = 0; i < M; i++) samples.push(at((i / M) * len));
  for (let i = 0; i < M; i++) {
    const prev = samples[(i - 1 + M) % M], next = samples[(i + 1) % M];
    const t = next.clone().sub(prev).normalize();
    const outward = new THREE.Vector2(t.y, -t.x); // для обхода против часовой — наружу
    const phi = ((i / M) * count) % 1;
    const bump = Math.pow(Math.max(0, 1 - (2 * phi - 1) ** 2), round); // 1 — вершина ребра, 0 — дно канавки
    out.push(samples[i].clone().addScaledVector(outward, depth * (bump - 1)));
  }
  return out;
}

// Разбор SVG на тело и рельеф
let FIG = null; // { body: [Shape], relief: [Shape], islands: [Shape], cx, cy, h, w }
function parseFigure(svgText) {
  const data = new SVGLoader().parse(svgText);
  const groups = new Map(); // цвет → фигуры
  for (const p of data.paths) {
    const fill = p.userData?.style?.fill;
    if (!fill || fill === 'none' || fill === 'transparent') continue;
    p.userData.style.fillRule = 'evenodd'; // внутренние «окна» — дырки
    const list = groups.get(fill) || [];
    list.push(...SVGLoader.createShapes(p));
    groups.set(fill, list);
  }
  if (!groups.size) throw new Error('В SVG нет залитых фигур');
  const area = shs => shs.reduce((s, sh) => s + Math.abs(THREE.ShapeUtils.area(sh.extractPoints(32).shape)), 0);
  const sorted = [...groups.entries()].sort((a, b) => area(b[1]) - area(a[1]));
  const body = sorted[0][1];
  const relief = sorted.slice(1).flatMap(([, shs]) => shs);
  // габариты тела — по ним масштаб и центр
  const box = new THREE.Box2();
  for (const sh of body) for (const v of sh.extractPoints(64).shape) box.expandByPoint(v);
  const c = box.getCenter(new THREE.Vector2()), sz = box.getSize(new THREE.Vector2());
  FIG = { body, relief, colors: sorted.map(([c]) => c), cx: c.x, cy: c.y, w: sz.x, h: sz.y };
}

const toPts = (sh, div = 128) => sh.extractPoints(div);
const FILLET = 10; // радиус скругления острых клювов, в пикселях исходного SVG

// Контуры в «пикселях» SVG; масштаб применяем после выдавливания
function figureShapes(s, ribsOn) {
  const ribDepthPx = P.ribDepth / s;
  const reliefOuters = [], islands = [], reliefShapes = [];
  for (const sh of FIG.relief) {
    const { shape, holes } = toPts(sh);
    const outer = filletSharp(shape, FILLET);
    reliefOuters.push(outer);
    const rs = new THREE.Shape(outer);
    rs.holes = holes.map(h => new THREE.Path(filletSharp(h, FILLET)));
    reliefShapes.push(rs);
    // «окна» внутри знака (например, в петле ₽) — это снова тело фигуры
    for (const h of holes) islands.push(new THREE.Shape(filletSharp(h, FILLET)));
  }
  const bodyShapes = FIG.body.map(sh => {
    const { shape, holes } = toPts(sh, ribsOn ? 256 : 128);
    let outer = filletSharp(shape, FILLET);
    if (ribsOn) outer = reeded(outer, P.ribCount, ribDepthPx, P.ribRound);
    const out = new THREE.Shape(outer);
    out.holes = holes.map(h => new THREE.Path(filletSharp(h, FILLET)));
    // если рельеф есть, тело под ним прорезано насквозь, а сам рельеф встаёт «пробкой»
    if (P.reliefMode !== 'flat') for (const r of reliefOuters) out.holes.push(new THREE.Path(r));
    return out;
  });
  // «плоский» режим: второй цвет игнорируем, фигура — одним телом
  if (P.reliefMode === 'flat') return { bodyShapes, reliefShapes: [] };
  return { bodyShapes: bodyShapes.concat(islands), reliefShapes };
}

// Буквы стоят параллельными пластинами. Расстояние между соседними пластинами
// по нормали = шаг × |sin(поворот)|. Если фигура толще — соседки врезаются друг в друга,
// поэтому общую толщину (с выпуклым рельефом) ограничиваем этим зазором.
function maxThickness() { return P.spacing * Math.abs(Math.sin(P.yaw * DEG)) * 0.9; }

function extrude(shapes, thick, bevel, s, segments = 8) {
  bevel = Math.min(bevel, thick * 0.3);
  return new THREE.ExtrudeGeometry(shapes, {
    depth: Math.max(thick - 2 * bevel, 1e-4) / s,
    bevelEnabled: bevel > 0,
    bevelThickness: bevel / s,
    bevelSize: bevel / s,
    // фаска уходит внутрь контура, а не наружу: снаружи у острых мест она налезала бы сама на себя
    bevelOffset: -bevel / s,
    bevelSegments: segments,
    curveSegments: 1, // контуры уже из готовых точек
  });
}

// ExtrudeGeometry затеняет каждую грань плоско — отсюда «ребристые» скругления.
// Сглаживаем нормали там, где соседние грани сходятся под малым углом, острые углы оставляем.
// Лица — строго плоские, иначе по ним проступает сетка треугольников.
function finish(g) {
  const out = toCreasedNormals(g, P.crease * DEG);
  g.dispose();
  const pos = out.attributes.position, nor = out.attributes.normal;
  const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
  for (let i = 0; i < pos.count; i += 3) {
    a.fromBufferAttribute(pos, i); b.fromBufferAttribute(pos, i + 1); c.fromBufferAttribute(pos, i + 2);
    const fn = b.sub(a).cross(c.sub(a)).normalize();
    if (Math.abs(fn.z) > 0.9999) for (let k = 0; k < 3; k++) nor.setXYZ(i + k, 0, 0, Math.sign(fn.z));
  }
  nor.needsUpdate = true;
  return out;
}

// SVG смотрит вниз по Y: зеркалим Y и Z (две оси — без вывернутых нормалей),
// центрируем по телу фигуры
function place(g, s) {
  g.translate(-FIG.cx, -FIG.cy, 0);
  g.scale(s, -s, -s);
  return g;
}

function buildGeometries() {
  const s = P.size / FIG.h;
  const ribsOn = P.ribs && P.ribCount >= 3 && P.ribDepth > 0;
  const hasRelief = FIG.relief.length > 0 && P.reliefMode !== 'flat';
  const sides = P.reliefBoth ? 2 : 1;
  const raise = hasRelief && P.reliefMode === 'emboss' ? P.reliefDepth * sides : 0;
  const thick = Math.max(0.05, Math.min(P.depth + 2 * P.bevel, maxThickness() - raise));
  let bevel = P.bevel;
  if (ribsOn) {
    // вершина ребра должна быть круглее фаски, иначе фаска на ней ломается
    const pitch = (2 * (FIG.w + FIG.h) * s) / P.ribCount; // примерный шаг рёбер
    const tipRadius = pitch * pitch / (8 * Math.max(P.ribRound, 0.05) * Math.max(P.ribDepth, 1e-4));
    bevel = Math.min(bevel, tipRadius * 0.5);
  }
  const { bodyShapes, reliefShapes } = figureShapes(s, ribsOn);

  // с рифлением контур очень подробный — фаске хватает 3 шагов, иначе геометрия раздувается
  const body = place(extrude(bodyShapes, thick, bevel, s, ribsOn ? 3 : 8), s);
  body.computeBoundingBox();
  const zMid = (body.boundingBox.max.z + body.boundingBox.min.z) / 2;
  body.translate(0, 0, -zMid);
  const front = thick / 2, back = -thick / 2;

  let relief = null;
  if (hasRelief) {
    // «пробка» в прорези тела: выпуклая торчит над лицом, вдавленная утоплена
    // вдавленный рельеф не может быть глубже, чем позволяет толщина
    const D = P.reliefMode === 'deboss' ? Math.min(P.reliefDepth, thick * 0.4 / sides) : P.reliefDepth;
    const d = P.reliefMode === 'emboss' ? D : -D;
    const zFront = front + d, zBack = P.reliefBoth ? back - d : back;
    const rb = Math.min(P.bevel * 0.6, D * 0.45);
    relief = place(extrude(reliefShapes, zFront - zBack, rb, s), s);
    relief.computeBoundingBox();
    relief.translate(0, 0, zFront - relief.boundingBox.max.z);
    relief = finish(relief);
  }
  return { body: finish(body), relief };
}

// Гладкий металл без текстур: цвет задаёт каждой букве ряд (instanceColor)
// dithering — лёгкий шум против «ступенек» в плавных тёмных переливах
const material = new THREE.MeshPhysicalMaterial({ color: 0xffffff, metalness: 1, roughness: P.roughness, dithering: true, anisotropy: P.anisotropy, anisotropyRotation: P.anisoRot * DEG,
  clearcoat: P.clearcoat, clearcoatRoughness: P.coatRough, iridescence: P.iridescence, iridescenceIOR: P.iridIOR, iridescenceThicknessRange: [P.iridMin, P.iridMax] });

// ---------- Инстансы и их состояние ----------
// Две группы с одинаковыми положениями: тело фигуры и рельеф (у рельефа свой цвет)
let mesh, reliefMesh = null, N, st;
let customSvg = START_SVG; // SVG пользователя: из слота coin-svg, из настроек или загруженный в панели

function makeInstanced(geo) {
  const m = new THREE.InstancedMesh(geo, material, N);
  m.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
  m.frustumCulled = false;
  for (let i = 0; i < N; i++) m.setColorAt(i, new THREE.Color(P.color));
  scene.add(m);
  return m;
}

function buildMesh() {
  for (const m of [mesh, reliefMesh]) if (m) { scene.remove(m); m.geometry.dispose(); m.dispose(); }
  if (!FIG) {
    try { parseFigure(customSvg ?? PRESETS[P.shape]); }
    catch (err) { console.warn('SVG не прочитался, показываю встроенную монету:', err); customSvg = null; parseFigure(PRESETS[P.shape]); }
  }
  N = Math.round(P.count);
  const { body, relief } = buildGeometries();
  mesh = makeInstanced(body);
  reliefMesh = relief ? makeInstanced(relief) : null;
  st = {
    lift: new Float32Array(N), tilt: new Float32Array(N),
    kickY: new Float32Array(N), kickV: new Float32Array(N),
    spin: new Float32Array(N), spinV: new Float32Array(N),
    flash: new Float32Array(N), cd: new Float32Array(N), prevU: new Float32Array(N).fill(-1),
  };
}
buildMesh();
window.P = P; window.rebuild = buildMesh; // для подстройки из консоли
window.T = { scene, camera, material, soft, key, applySoft, applyKey, applyEnvRotation, loadHdri };

// Положение точки ряда по координате вдоль него
function linePoint(x, out) {
  const a = x / P.curve;
  return out.set(
    P.x + Math.sin(a) * P.curve,
    P.y + P.arch * Math.cos(x * 0.14),
    P.z - (1 - Math.cos(a)) * P.curve - P.recede * x * x,
  );
}

// ---------- Ввод ----------
const mouse = { x: 0, y: 0, vx: 0, vy: 0, px: 0, py: 0, active: false, seen: false };
const lightTarget = new THREE.Vector3(0, 0, P.z + P.lightDepth);
function setPointer(e) {
  const r = canvas.getBoundingClientRect();
  mouse.x = ((e.clientX - r.left) / r.width) * 2 - 1;
  mouse.y = -((e.clientY - r.top) / r.height) * 2 + 1;
  if (!mouse.seen) { mouse.px = mouse.x; mouse.py = mouse.y; mouse.seen = true; }
  mouse.active = true;
}
addEventListener('pointermove', setPointer, { passive: true });
addEventListener('pointerdown', setPointer, { passive: true });
document.addEventListener('pointerleave', () => { mouse.active = false; });
addEventListener('blur', () => { mouse.active = false; });

let boost = 0, lastScroll = scrollY;
const addBoost = d => { boost = Math.min(boost + d * 0.004 * P.scrollBoost, 1.6 * P.scrollBoost); };
addEventListener('wheel', e => addBoost(Math.abs(e.deltaY)), { passive: true });
addEventListener('scroll', () => { addBoost(Math.abs(scrollY - lastScroll)); lastScroll = scrollY; }, { passive: true });

// ---------- Размер ----------
// Как в референсе: вертикальный угол обзора не меньше заданного,
// а на узких экранах держим горизонтальный — ряд не обрезается по бокам
function resize() {
  const w = canvas.clientWidth, h = canvas.clientHeight;
  if (!w || !h) return; // вкладка скрыта: размер 0 дал бы NaN в камере и «сломал» все буквы
  renderer.setSize(w, h, false);
  camera.aspect = w / h;
  const vFromH = 2 * Math.atan(Math.tan(HFOV * DEG / 2) / camera.aspect) / DEG;
  camera.fov = Math.max(VFOV_MIN, vFromH);
  camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(canvas);
resize();

// ---------- Кадр ----------
const AX_X = new THREE.Vector3(1, 0, 0), AX_Y = new THREE.Vector3(0, 1, 0), AX_Z = new THREE.Vector3(0, 0, 1);
const p = new THREE.Vector3(), m4 = new THREE.Matrix4();
const q = new THREE.Quaternion(), qa = new THREE.Quaternion(), qb = new THREE.Quaternion();
const sc = new THREE.Vector3(), proj = new THREE.Vector3(), tmpC = new THREE.Color();
const cBase = new THREE.Color(), cFlash = new THREE.Color(), cRelief = new THREE.Color();
const smooth = (a, b, x) => { const k = Math.min(Math.max((x - a) / (b - a), 0), 1); return k * k * (3 - 2 * k); };

const anchor = new THREE.Vector3(), ring1 = new THREE.Vector3(), row3 = new THREE.Vector3(), ring3 = new THREE.Vector3(), lineP = new THREE.Vector3(), tmpV = new THREE.Vector3();
const rotQ = new THREE.Quaternion(), localUp = new THREE.Vector3();
let slide = 0, visible = true, morph = 0;
// ---- Живая механика (mech: 'gr8') ----
// змейка: монеты под курсором поднимаются и выходят вперёд (гаусс по X экрана, сглаживание 4.5);
// пинок: при быстром движении мыши — подброс и поворот вокруг вертикали, соседи тянутся цепочкой;
// рябь: клик по монете запускает волну вдоль ряда; волна от скролла; появление при загрузке;
// параллакс — лёгкий наклон всей ленты за курсором.
const G8C = { snakeLift: 0.95, snakeFwd: 1.25, snakeWidth: 1, snakeFollow: 4.5, snakeGlow: 0,
  kickRadius: 0.35, kickMin: 0.8, kickMax: 8, kickSpin: 14, kickLift: 7, kickFlash: 7, flashGlow: 2.2, flashDecay: 2.5,
  maxSpin: 0.6, spinStep: 0.12, spinStiff: 40, spinDamp: 7, liftStiff: 30, liftDamp: 6,
  scrollMax: 3, scrollLift: 7, scrollSpin: 3, scrollFlash: 0.6, waveFreq: 0.35, waveSpeed: 5,
  rippleSpeed: 40, rippleLift: 1.4, rippleSpin: 1.1, clickFlash: 1,
  introDelay: 0.2, introDur: 1, introStagger: 0.8, introDrop: 2.5, introFwd: 1, introFlip: 20, introScale: 0.8,
  parallax: 0.015, unit: 1.2 };
// страница может поменять параметры механики GR8 (SCENE_OVERRIDES.g8)
if (window.SCENE_OVERRIDES?.g8) Object.assign(G8C, window.SCENE_OVERRIDES.g8);
const MAXN = 512;
const g8 = { t: 0, intro: 0, cx: 0, v: 0, dir: 1, s: 0, ls: null, lx: 0, ly: 0, tx: 0, ty: 0, ripples: [],
  sx: new Float32Array(MAXN).fill(9), sy: new Float32Array(MAXN).fill(9), spin: new Float32Array(MAXN), spinV: new Float32Array(MAXN),
  lift: new Float32Array(MAXN), liftV: new Float32Array(MAXN), flash: new Float32Array(MAXN) };
let downX = 0, downY = 0;
addEventListener('pointerdown', e => { downX = e.clientX; downY = e.clientY; }, { passive: true });
addEventListener('pointerup', e => {
  if (P.mech !== 'gr8' || (e.pointerType && e.pointerType !== 'mouse' && e.pointerType !== 'pen')) return;
  if (e.target.closest && e.target.closest('.lil-gui, a, button, input, textarea, select, label')) return;
  if (Math.hypot(e.clientX - downX, e.clientY - downY) > 6) return;
  const cr = canvas.getBoundingClientRect();
  const x = ((e.clientX - cr.left) / cr.width * 2 - 1) * camera.aspect, y = -((e.clientY - cr.top) / cr.height) * 2 + 1;
  let best = -1, bd = 0.04;
  for (let i = 0; i < N; i++) { const d = (g8.sx[i] - x) ** 2 + (g8.sy[i] - y) ** 2; if (d < bd) { bd = d; best = i; } }
  if (best >= 0) g8.ripples.push({ i0: best, t: 0, hit: new Uint8Array(N) });
}, { passive: true });
function gr8Frame(dt) {
  const C = G8C;
  g8.t += dt; g8.intro += dt;
  const ax = mouse.active ? mouse.x * camera.aspect : 0;
  g8.cx += (ax - g8.cx) * (1 - Math.exp(-dt * C.snakeFollow));
  // скорость мыши и направление
  const vx = (mouse.x - g8.lx) * camera.aspect / Math.max(dt, 1e-3), vy = (mouse.y - g8.ly) / Math.max(dt, 1e-3);
  g8.lx = mouse.x; g8.ly = mouse.y;
  g8.v += (Math.hypot(vx, vy) - g8.v) * (1 - Math.exp(-dt * 20));
  if (Math.abs(vx) > 0.2) g8.dir = vx > 0 ? 1 : -1;
  // скорость скролла в экранах в секунду
  const sc = scrollY / (innerHeight || 1);
  if (g8.ls === null) g8.ls = sc;
  const sv = Math.max(-C.scrollMax, Math.min(C.scrollMax, (sc - g8.ls) / Math.max(dt, 1e-3))); g8.ls = sc;
  g8.s += (sv - g8.s) * (1 - Math.exp(-dt * 8));
  // рябь по клику
  for (let r = g8.ripples.length - 1; r >= 0; r--) {
    const rp = g8.ripples[r]; rp.t += dt; let alive = false;
    for (let i = 0; i < N; i++) {
      if (rp.hit[i]) continue;
      const d = Math.abs(i - rp.i0);
      if (rp.t * C.rippleSpeed >= d) { rp.hit[i] = 1; const f = 1 - Math.min(1, d / N) * 0.6; g8.liftV[i] += C.rippleLift * f; g8.spinV[i] += C.rippleSpin * f; g8.flash[i] = Math.min(1, g8.flash[i] + C.clickFlash * f * (1 - d / N)); }
      else alive = true;
    }
    if (!alive) g8.ripples.splice(r, 1);
  }
  // наклон всей ленты за курсором
  const tf = 1 - Math.exp(-dt * 3);
  g8.tx += ((mouse.active ? mouse.y : 0) * C.parallax - g8.tx) * tf;
  g8.ty += ((mouse.active ? mouse.x : 0) * C.parallax - g8.ty) * tf;
  for (const m of [mesh, reliefMesh]) if (m) m.rotation.set(-g8.tx, g8.ty, 0);
}
window.D = { force: null, get morph() { return morph; }, get st() { return st; } };
{ const f = new URLSearchParams(location.search).get('morph'); if (f !== null) D.force = +f; } // ?morph=1 — сразу кольцо (для кадров в макеты)
new IntersectionObserver(([e]) => { visible = e.isIntersecting; }).observe(canvas);

// Прогресс скролла «в экранах». Если на странице есть блоки с data-scene-stop,
// считаем по ним: верх 1-го блока — 0, 2-го — 1, 3-го — 2, конец страницы — последнее значение.
// Иначе — просто высота окна на экран (страница b-hero).
const stopEls = document.querySelectorAll('[data-scene-stop]');
function scrollProgress(vh) {
  if (stopEls.length < 2) return 0; // один экран: ряд остаётся рядом и при прокрутке
  const stops = [...stopEls].map(el => el.getBoundingClientRect().top + scrollY);
  const end = Math.max(document.documentElement.scrollHeight - vh, stops[stops.length - 1] + 1);
  stops.push(end);
  for (let i = 0; i < stops.length - 1; i++) {
    if (scrollY < stops[i + 1]) return i + Math.max(0, (scrollY - stops[i]) / (stops[i + 1] - stops[i]));
  }
  return stops.length - 1;
}

const clock = new THREE.Clock();
function frame() {
  requestAnimationFrame(frame);
  const dt = Math.min(clock.getDelta(), 1 / 30);
  if (!visible) return;

  // скорость мыши (экранов в секунду), сглаженная
  const ivx = (mouse.x - mouse.px) / Math.max(dt, 1e-3), ivy = (mouse.y - mouse.py) / Math.max(dt, 1e-3);
  mouse.vx += (ivx - mouse.vx) * Math.min(1, dt * 20);
  mouse.vy += (ivy - mouse.vy) * Math.min(1, dt * 20);
  mouse.px = mouse.x; mouse.py = mouse.y;
  const mSpeed = Math.hypot(mouse.vx * camera.aspect, mouse.vy);

  // ряд едет вправо и зациклен: буква, ушедшая за правый край, возвращается слева
  boost *= Math.exp(-dt * 1.8);
  const L = N * P.spacing;
  slide = (slide + dt * P.speed * (reduceMotion ? 0.15 : 1) * (1 + boost) / L) % 1;

  // камера: едва заметный параллакс
  const own = P.mech !== 'gr8';
  const tx = own && mouse.active ? mouse.x * P.parallax * 16 : 0, ty = own && mouse.active ? mouse.y * P.parallax * 8 : 0;
  camera.position.x += (tx - camera.position.x) * Math.min(1, dt * 2);
  camera.position.y += (ty - camera.position.y) * Math.min(1, dt * 2);
  camera.updateMatrixWorld();

  // свет за курсором: точка на луче из камеры, чуть ближе ряда
  if (mouse.active) {
    proj.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(camera.position).normalize();
    const dist = (camera.position.z - (P.z + P.lightDepth)) / Math.max(-proj.z, 0.1);
    lightTarget.copy(camera.position).addScaledVector(proj, dist);
  }
  cursorLight.position.lerp(lightTarget, Math.min(1, dt * 6));
  cursorLight.intensity += ((mouse.active ? P.lightIntensity : P.lightIntensity * 0.2) - cursorLight.intensity) * Math.min(1, dt * 3);

  cBase.set(P.color); cFlash.set(P.flashColor); cRelief.set(P.reliefColor);
  const kickOn = !reduceMotion && P.kick > 0 && mouse.active && mSpeed > 1.0;
  const yawQ = new THREE.Quaternion().setFromAxisAngle(AX_Y, P.yaw * DEG);

  // ---- изгиб в кольцо по скроллу ----
  // Прогресс скролла в экранах: 0 — первый экран, 1 — второй, 2 — третий.
  // Сглаживаем, чтобы при рывке колесом форма догоняла плавно.
  const vh = innerHeight || 1; // в скрытой вкладке высота окна бывает 0 — без защиты получится NaN
  let target = D.force ?? scrollProgress(vh);
  if (D.force == null && target > 1) target = 1 + (target - 1) * (P.endMorph - 1); // последний экран доигрывает переход только до endMorph
  if (D.force != null) morph = D.force; // для отладки: D.force = 0…2 задаёт состояние без скролла
  morph += (target - morph) * Math.min(1, dt * (reduceMotion ? 20 : 4));
  if (!Number.isFinite(morph)) morph = target;
  const ease = t => { t = Math.min(Math.max(t, 0), 1); return t * t * (3 - 2 * t); };
  const toRing = ease(morph);            // 1 → 2 экран: прямой ряд сгибается в кольцо
  const p2 = Math.min(Math.max(morph - 1, 0), 1);
  // 2 → 3 экран: кольцо раскрывается обратно в ряд, ряд уходит волной.
  // exitAfter: на третьем экране ряд остаётся целиком, а уходит только дальше (morph 2 → 3)
  const drift = P.transition3 === 'drift';
  const unbend = drift ? 0 : P.exitAfter ? ease(p2) : ease(p2 / P.unbendPart);
  const exit = drift ? 0 : P.exitAfter ? Math.min(Math.max(morph - 2, 0), 1) : Math.min(Math.max((p2 - P.exitStart) / (1 - P.exitStart), 0), 1);
  // drift: кольцо не разгибается, а плавно, с замедлением в конце, уезжает в угол — без петли
  const d3 = drift ? p2 * p2 * (3 - 2 * p2) : 0;
  const e = toRing * (1 - unbend);       // сколько сейчас «кольца»

  // Ряд гнётся как гибкая лента: средняя часть длиной ringLen становится дугой
  // с одинаковой кривизной, концы продолжаются по касательной. Длина ряда
  // не меняется, поэтому буквы не наезжают друг на друга.
  const span = P.ringSpan * DEG, Lb = P.ringLen, R1 = Lb / span;
  const kap = e * span / Lb;
  const ringS = 1 + (P.ringScale - 1) * toRing;
  const S = (ringS + (P.row3Scale - ringS) * unbend) * (1 - d3) + P.ring3Scale * d3;
  anchor.set(P.x, P.y, P.z).lerp(ring1.set(P.ringX, P.ringY + P.ringScale * R1, P.ringZ), toRing)
    .lerp(row3.set(P.row3X, P.row3Y, P.row3Z), unbend)
    .lerp(ring3.set(P.ring3X, P.ring3Y + P.ring3Scale * R1, P.ring3Z), d3);
  // свет и студия переезжают вместе с композицией: кольцо дальше и повёрнуто иначе,
  // без этого оно уходит в темноту
  ROW_C.set(P.x, P.y, P.z).lerp(ring1.set(P.ringX, P.ringY, P.ringZ), toRing).lerp(row3, unbend).lerp(ring3.set(P.ring3X, P.ring3Y, P.ring3Z), d3);
  placeLight(soft, P.softAz, P.softEl, 12); soft.lookAt(ROW_C);
  placeLight(key, P.keyAz, P.keyEl, 10); key.target.position.copy(ROW_C);
  scene.environmentIntensity = P.envIntensity * (1 + P.ringBoost * e);
  soft.intensity = P.softIntensity * (1 + P.ringBoost * e);
  // хвосты за концами дуги тают на кольце и возвращаются, когда оно раскрывается
  const tailFade = 1e9 + (2 * P.spacing - 1e9) * smooth(0.25, 0.6, e);
  const G8 = P.mech === 'gr8';
  if (G8) gr8Frame(dt);
  const C8 = G8C, snakeW = G8 ? 1 - toRing : 0; // змейка работает только на первом экране
  const introOn = G8 && !reduceMotion && g8.intro < C8.introDelay + C8.introStagger + C8.introDur;
  const kickPtr = G8 && !introOn && mouse.active && g8.v > C8.kickMin ? Math.min(C8.kickMax, g8.v - C8.kickMin) * dt : 0;
  const kickScroll = G8 && !introOn ? g8.s * dt : 0;

  for (let i = 0; i < N; i++) {
    const u = G8 ? ((i / N - slide) % 1 + 1) % 1 : (i / N + slide) % 1; // в живой механике лента едет влево
    if (st.prevU[i] >= 0 && Math.abs(u - st.prevU[i]) > 0.5) { // буква перепрыгнула с правого края на левый — сбрасываем её состояние
      st.lift[i] = st.tilt[i] = st.kickY[i] = st.kickV[i] = st.spin[i] = st.spinV[i] = st.flash[i] = 0;
    }
    st.prevU[i] = u;

    const x = u * L - L * 0.42;

    // точка на согнутой ленте: дуга с кривизной kap, дальше — прямой хвост
    const h = Lb / 2, sa = Math.max(-h, Math.min(h, x)), rest = x - sa;
    const theta = -kap * sa;
    let bx = sa, by = 0;
    if (kap > 1e-6) { bx = Math.sin(kap * sa) / kap; by = (Math.cos(kap * sa) - 1) / kap; }
    bx += rest * Math.cos(theta); by += rest * Math.sin(theta);
    // на первом экране добавляются лёгкая волна и изгиб прямого ряда
    linePoint(x, lineP).sub(tmpV.set(P.x + x, P.y, P.z)).multiplyScalar(1 - e);
    p.set(anchor.x + S * bx, anchor.y + S * by, anchor.z).add(lineP);
    const fade = 1 - smooth(0, tailFade, Math.abs(rest));
    rotQ.setFromAxisAngle(AX_Z, theta);
    localUp.set(0, 1, 0).applyQuaternion(rotQ);

    // уход волной: буквы слева взлетают раньше, справа — позже, и по ряду бежит волна.
    // Сдвиг — только вверх в плоскости буквы, поэтому соседки не задевают друг друга
    let sway = 0;
    if (exit > 0) {
      const delay = Math.min(Math.max((x + P.exitSpread) / (2 * P.exitSpread), 0), 1) * P.exitStagger;
      const k = Math.min(Math.max((exit * (1 + P.exitStagger) - delay), 0), 1);
      const rise = k * k * k; // разгон: сначала медленно, потом быстро
      p.addScaledVector(localUp, P.exitDir * rise * P.exitHeight * S);
      sway = Math.sin(k * Math.PI) * P.exitTilt * DEG; // качнуться на взлёте
    }

    let sv = 0, introK = 1;
    if (G8) {
      // появление: слева направо монеты падают сверху, выходят вперёд и доворачиваются
      if (introOn) {
        const xs = Math.min(Math.max((g8.sx[i] / camera.aspect + 1) / 2, 0), 1);
        const x01 = Math.min(Math.max((g8.intro - C8.introDelay - xs * C8.introStagger) / C8.introDur, 0), 1);
        introK = 1 - Math.pow(1 - x01, 3);
        const r = 1 - introK;
        p.y -= r * C8.introDrop; p.z += r * C8.introFwd;
        if (x01 <= 0) introK = -1; // ещё не появилась
      }
      proj.copy(p).project(camera);
      g8.sx[i] = proj.z < 1 ? proj.x * camera.aspect : 99; g8.sy[i] = proj.y;
      if (snakeW > 0.001) { const d = (g8.sx[i] - g8.cx) / C8.snakeWidth; sv = snakeW * Math.exp(-d * d); }
      if (kickPtr) {
        const kx = (g8.sx[i] - mouse.x * camera.aspect) / C8.kickRadius, ky = (g8.sy[i] - mouse.y) / C8.kickRadius;
        const kw = Math.exp(-(kx * kx + ky * ky));
        if (kw > 0.02) { const f = kickPtr * kw * P.kick / 0.4; g8.spinV[i] += f * C8.kickSpin * g8.dir; g8.liftV[i] += f * C8.kickLift; g8.flash[i] = Math.min(1, g8.flash[i] + f * C8.kickFlash); }
      }
      if (kickScroll) {
        const ph = Math.sin(i * C8.waveFreq - g8.t * C8.waveSpeed);
        g8.liftV[i] += kickScroll * C8.scrollLift * ph; g8.spinV[i] += kickScroll * C8.scrollSpin * ph;
        g8.flash[i] = Math.min(1, g8.flash[i] + Math.abs(kickScroll * ph) * C8.scrollFlash);
      }
      g8.flash[i] *= Math.exp(-dt * C8.flashDecay);
      g8.spinV[i] = (g8.spinV[i] - g8.spin[i] * C8.spinStiff * dt) * Math.exp(-dt * C8.spinDamp);
      g8.spin[i] = Math.max(-C8.maxSpin, Math.min(C8.maxSpin, g8.spin[i] + g8.spinV[i] * dt));
      if (i > 0) { // соседи поворачиваются цепочкой — не больше spinStep друг от друга
        const lo = g8.spin[i - 1] - C8.spinStep, hi = g8.spin[i - 1] + C8.spinStep;
        if (g8.spin[i] < lo || g8.spin[i] > hi) { g8.spin[i] = g8.spin[i] < lo ? lo : hi; g8.spinV[i] = g8.spinV[i - 1]; }
      }
      g8.liftV[i] = (g8.liftV[i] - g8.lift[i] * C8.liftStiff * dt) * Math.exp(-dt * C8.liftDamp);
      g8.lift[i] += g8.liftV[i] * dt;
    }

    // влияние курсора — по расстоянию на экране, в долях ширины
    proj.copy(p).project(camera);
    const dx = (proj.x - mouse.x) / 2, dy = (proj.y - mouse.y) / 2 / camera.aspect;
    const infl = !G8 && mouse.active ? 1 - smooth(0, P.hoverRadius, Math.hypot(dx, dy * 0.5)) : 0;

    // наведение: приподнять и чуть наклонить. Всё — в плоскости самой буквы,
    // поэтому соседки никогда не врезаются друг в друга
    const k = Math.min(1, dt * 6);
    st.lift[i] += (infl * P.hoverLift - st.lift[i]) * k;
    const side = Math.max(-1, Math.min(1, dx / P.hoverRadius * 2)); // слева от курсора наклон в одну сторону, справа — в другую
    st.tilt[i] += (infl * P.hoverTilt * DEG * side - st.tilt[i]) * k;

    // резкий проход: подбросить вверх, качнуть, вспыхнуть
    st.cd[i] = Math.max(0, st.cd[i] - dt);
    if (!G8 && kickOn && infl > 0.3 && st.cd[i] === 0) {
      const power = Math.min(mSpeed / 5, 1) * P.kick * infl;
      st.kickV[i] += 7 * power;
      st.spinV[i] += 9 * power * (mouse.vx >= 0 ? -1 : 1);
      st.flash[i] = Math.min(1, st.flash[i] + power * 1.2);
      st.cd[i] = 0.45;
    }
    st.kickV[i] += (-30 * st.kickY[i] - 6 * st.kickV[i]) * dt;
    st.kickY[i] += st.kickV[i] * dt;
    st.spinV[i] += (-40 * st.spin[i] - 7 * st.spinV[i]) * dt;
    st.spin[i] += st.spinV[i] * dt;
    st.spin[i] = Math.max(-0.6, Math.min(0.6, st.spin[i]));
    st.flash[i] *= Math.exp(-dt * 2.5);

    // ориентация: поворот вдоль изгиба ленты, общий поворот ряда,
    // наклон и качание в плоскости буквы. Подъём — тоже в её плоскости
    // («вверх» для буквы на кольце — от центра кольца)
    if (G8) {
      const U = C8.unit * S;
      q.copy(rotQ).multiply(yawQ).multiply(qa.setFromAxisAngle(AX_Y, g8.spin[i])).multiply(qb.setFromAxisAngle(AX_Z, sway));
      if (introOn && introK < 1) q.premultiply(qb.setFromAxisAngle(AX_X, (1 - Math.max(introK, 0)) * C8.introFlip * DEG));
      p.addScaledVector(localUp, g8.lift[i] * U);
      p.y += sv * C8.snakeLift * U; p.z += sv * C8.snakeFwd * U;
    } else {
      q.copy(rotQ).multiply(yawQ).multiply(qa.setFromAxisAngle(AX_Z, st.tilt[i] + st.spin[i] + sway));
      p.addScaledVector(localUp, (st.lift[i] + st.kickY[i]) * S);
    }

    let s = smooth(0, 0.03, u) * smooth(1, 0.97, u) * fade * S;
    if (G8 && introOn) s *= introK < 0 ? 0 : C8.introScale + (1 - C8.introScale) * introK;
    sc.set(s, s, s);
    m4.compose(p, q, sc);
    mesh.setMatrixAt(i, m4);

    if (G8) {
      const fl = Math.min(g8.flash[i], 1) * 0.85, glow = 1 + sv * C8.snakeGlow;
      mesh.setColorAt(i, tmpC.copy(cBase).lerp(cFlash, fl).multiplyScalar(glow));
      if (reliefMesh) { reliefMesh.setMatrixAt(i, m4); reliefMesh.setColorAt(i, tmpC.copy(cRelief).lerp(cFlash, fl).multiplyScalar(glow)); }
    } else {
      const fl = Math.min(st.flash[i], 1) * 0.85;
      tmpC.copy(cBase).lerp(cFlash, fl);
      mesh.setColorAt(i, tmpC);
      if (reliefMesh) {
        reliefMesh.setMatrixAt(i, m4);
        reliefMesh.setColorAt(i, tmpC.copy(cRelief).lerp(cFlash, fl));
      }
    }
  }
  for (const m of [mesh, reliefMesh]) if (m) { m.instanceMatrix.needsUpdate = true; m.instanceColor.needsUpdate = true; }

  renderer.render(scene, camera);
}
frame();

/*@@PANEL-START@@*/
// ---------- Панель настроек ----------
const INIT = structuredClone({ P, G8C }); // с чем открылась страница — к этому возвращает «Сбросить»
const gui = new GUI({ title: 'Настройки анимации' });
// Оформление: тёмная панель, шрифт Geologica, скруглённые плашки,
// акцентный оранжевый (#F64A00) — на кнопке «Скопировать настройки»
document.head.insertAdjacentHTML('beforeend', `
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Geologica:wght@300;400;500&display=swap" rel="stylesheet">
<style>
  /* переменные задаём и вложенным разделам — иначе lil-gui возвращает им свою тему */
  .lil-gui.root.desk, .lil-gui.root.desk .lil-gui {
    --width: 320px; --background-color: #141416; --text-color: #ececef; --title-background-color: #141416; --title-text-color: #ececef;
    --widget-color: #2a2a30; --hover-color: #313138; --focus-color: #35353c; --number-color: #ececef; --string-color: #ececef;
    --font-family: 'Geologica', -apple-system, system-ui, sans-serif; --font-family-mono: 'Geologica', -apple-system, system-ui, sans-serif;
    --font-size: 12.5px; --input-font-size: 12.5px; --padding: 6px; --spacing: 6px; --widget-height: 30px; --title-height: 44px;
    --widget-padding: 0 0 0 10px; --widget-border-radius: 10px; --checkbox-size: 16px; --name-width: 46%; --slider-knob-width: 3px; --scrollbar-width: 6px;
  }
  .lil-gui.root.desk {
    top: 16px; right: 16px; max-height: calc(100vh - 32px); display: flex; flex-direction: column;
    border-radius: 22px; border: 1px solid rgba(255,255,255,.08); box-shadow: 0 24px 70px rgba(0,0,0,.55); overflow: hidden; font-weight: 300;
  }
  .lil-gui.root.desk > .title { flex: none; color: #ececef; font-weight: 400; font-size: 15px; padding: 0 18px; border-bottom: 1px solid rgba(255,255,255,.07); }
  .lil-gui.root.desk.closed > .title { border-bottom: 0; }
  .lil-gui.root.desk.closed > .copy-bar { display: none; }
  .lil-gui.root.desk > .title { position: relative; }
  .lil-gui.root.desk .reset-btn { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); width: auto; height: 28px; padding: 0 12px; line-height: 26px;
    border-radius: 9px; border: 1px solid rgba(255,255,255,.08); background: #2a2a30; color: #ececef; cursor: pointer;
    font: 400 12.5px 'Geologica', system-ui, sans-serif; transition: background .18s; }
  .lil-gui.root.desk .reset-btn:hover { background: #35353c; }
  .lil-gui.root.desk.closed .reset-btn { display: none; }
  .lil-gui.root.desk > .children { flex: 1; overflow-y: auto; padding: 8px 8px 4px; background: #141416; }
  /* разделы — скруглённые плашки чуть светлее панели */
  .lil-gui.root.desk .lil-gui:not(.root) { background: #1e1e22; border-radius: 16px; margin: 0 0 8px; border: 0; }
  .lil-gui.root.desk .lil-gui:not(.root) > .title { background: transparent; color: #ececef; border-radius: 16px; font-weight: 400; font-size: 13px; padding-left: 14px; height: 40px; line-height: 40px; }
  .lil-gui.root.desk .lil-gui:not(.root) > .children { padding: 0 8px 8px; border-left: 0; margin-left: 0; }
  .lil-gui.root.desk .controller { border-radius: 10px; padding: 0 2px; min-height: 34px; }
  .lil-gui.root.desk .controller .name { color: #9d9da6; }
  .lil-gui.root.desk input, .lil-gui.root.desk select, .lil-gui.root.desk .slider, .lil-gui.root.desk .display { border-radius: 10px !important; border: 1px solid rgba(255,255,255,.06); box-shadow: none; }
  .lil-gui.root.desk .slider .fill { border-right-color: #F64A00; background: rgba(246,74,0,.18); border-radius: 10px 0 0 10px; }
  .lil-gui.root.desk .controller.function button { border-radius: 12px; background: #2a2a30; color: #ececef; border: 1px solid rgba(255,255,255,.06); font-weight: 400; height: 34px; }
  .lil-gui.root.desk .controller.function button:hover { background: #313138; }
  /* кнопка копирования — внизу панели, всегда на виду */
  .lil-gui.root.desk > .copy-bar { flex: none; padding: 10px 10px 12px; background: #141416; border-top: 1px solid rgba(255,255,255,.07); }
  .lil-gui.root.desk > .copy-bar button {
    width: 100%; height: 48px; border: 0; border-radius: 16px; cursor: pointer;
    background: #F64A00; color: #fff; font: 400 14px 'Geologica', system-ui, sans-serif; letter-spacing: .01em; transition: background .18s, transform .18s;
  }
  .lil-gui.root.desk > .copy-bar button:hover { background: #ff5a14; }
  .lil-gui.root.desk > .copy-bar button:active { transform: scale(.98); }
  .lil-gui.root.desk input[type=checkbox] { border-radius: 5px !important; }
  .lil-gui.root.desk .controller.color .display { overflow: hidden; }
  .lil-gui.root.desk .controller.color input[type=text] { text-transform: lowercase; flex: none; width: 66px; padding-left: 8px; }
  .lil-gui.root.desk .children::-webkit-scrollbar-thumb { border-radius: 6px; }
  /* окно выбора цвета */
  .cpick { position: fixed; z-index: 10000; width: 248px; padding: 12px; box-sizing: border-box; background: #141416; color: #ececef;
    border: 1px solid rgba(255,255,255,.08); border-radius: 20px; box-shadow: 0 24px 70px rgba(0,0,0,.55);
    font: 300 12.5px 'Geologica', system-ui, sans-serif; display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; user-select: none; }
  .cpick[hidden] { display: none; }
  .cpick .cp-sv { position: relative; height: 160px; border-radius: 14px; cursor: crosshair; touch-action: none; }
  .cpick .cp-hue { position: relative; height: 14px; border-radius: 7px; cursor: pointer; touch-action: none;
    background: linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00); }
  .cpick .cp-knob { position: absolute; width: 16px; height: 16px; border-radius: 50%; border: 2px solid #fff; box-sizing: border-box;
    transform: translate(-50%, -50%); box-shadow: 0 1px 4px rgba(0,0,0,.5); pointer-events: none; }
  .cpick .cp-hue .cp-knob { top: 50%; }
  .cpick .cp-row { display: flex; gap: 8px; align-items: center; }
  .cpick .cp-sw { flex: none; width: 34px; height: 34px; border-radius: 10px; border: 1px solid rgba(255,255,255,.1); box-sizing: border-box; }
  .cpick .cp-hex { flex: 1; min-width: 0; display: flex; align-items: center; height: 34px; padding: 0 10px; border-radius: 10px; background: #2a2a30;
    border: 1px solid rgba(255,255,255,.06); box-sizing: border-box; color: #9d9da6; }
  .cpick .cp-hex input { flex: 1; min-width: 0; border: 0; outline: 0; background: none; color: #ececef; font: inherit; font-weight: 400;
    width: 100%; text-transform: lowercase; letter-spacing: .04em; padding: 0 0 0 4px; }
  .cpick .cp-drop { flex: none; width: 34px; height: 34px; border-radius: 10px; border: 1px solid rgba(255,255,255,.06); background: #2a2a30;
    color: #ececef; display: grid; place-items: center; cursor: pointer; padding: 0; }
  .cpick .cp-drop:hover { background: #313138; }
  .cpick .cp-drop svg { width: 16px; height: 16px; }
</style>`);
gui.domElement.classList.add('desk');
gui.close(); // при открытии страницы панель свёрнута
const fLook = gui.addFolder('Вид');
fLook.addColor(P, 'color').name('цвет');
fLook.addColor(P, 'flashColor').name('цвет вспышки');
fLook.add(P, 'roughness', 0.05, 0.8, 0.01).name('шероховатость').onChange(v => material.roughness = v);
fLook.add(P, 'anisotropy', 0, 1, 0.01).name('шлифовка').onChange(v => material.anisotropy = v);
fLook.add(P, 'anisoRot', 0, 180, 1).name('шлифовка: направление').onChange(v => material.anisotropyRotation = v * DEG);
fLook.add(P, 'clearcoat', 0, 1, 0.01).name('лак (цветной блик виден)').onChange(v => material.clearcoat = v);
fLook.add(P, 'coatRough', 0, 0.6, 0.01).name('лак: мягкость').onChange(v => material.clearcoatRoughness = v);
fLook.add(P, 'iridescence', 0, 1, 0.01).name('радужный перелив').onChange(v => material.iridescence = v);
fLook.add(P, 'iridIOR', 1, 2.3, 0.01).name('перелив: сила').onChange(v => material.iridescenceIOR = v);
fLook.add(P, 'iridMin', 0, 800, 5).name('перелив: от').onChange(v => material.iridescenceThicknessRange = [v, P.iridMax]);
fLook.add(P, 'iridMax', 0, 1200, 5).name('перелив: до').onChange(v => material.iridescenceThicknessRange = [P.iridMin, v]);
fLook.addColor(P, 'accentColor').name('тёплый блик: цвет').onFinishChange(loadHdri);
fLook.add(P, 'accentGlow', 0, 8, 0.05).name('тёплый блик: яркость').onFinishChange(loadHdri);
fLook.add(P, 'accentAz', -180, 180, 1).name('тёплый блик: азимут').onFinishChange(loadHdri);
fLook.add(P, 'accentEl', -90, 90, 1).name('тёплый блик: высота').onFinishChange(loadHdri);
fLook.add(P, 'accentWidth', 0.05, 1.2, 0.01).name('тёплый блик: размер').onFinishChange(loadHdri);
fLook.add(P, 'studioFill', 0, 1.5, 0.01).name('светлая студия: яркость фона').onFinishChange(loadHdri);
fLook.add(P, 'envIntensity', 0, 3, 0.05).name('блики').onChange(v => scene.environmentIntensity = v);
fLook.add(P, 'hdri', HDRIS).name('студия').onChange(loadHdri);
fLook.add(P, 'faceGlow', 0, 4, 0.05).name('перелив на лицах').onFinishChange(loadHdri);
fLook.add(P, 'faceWidth', 0.1, 1.5, 0.01).name('перелив: ширина').onFinishChange(loadHdri);
fLook.add(P, 'envRotX', -180, 180, 1).name('студия: наклон').onChange(applyEnvRotation);
fLook.add(P, 'envRotY', -180, 180, 1).name('студия: поворот').onChange(applyEnvRotation);
fLook.add(P, 'envRotZ', -180, 180, 1).name('студия: крен').onChange(applyEnvRotation);
const fLight = gui.addFolder('Свет');
fLight.addColor(P, 'softColor').name('мягкий: цвет').onChange(applySoft);
fLight.add(P, 'softIntensity', 0, 40, 0.1).name('мягкий: яркость').onChange(applySoft);
fLight.add(P, 'softAz', -180, 180, 1).name('мягкий: азимут').onChange(applySoft);
fLight.add(P, 'softEl', -90, 90, 1).name('мягкий: высота').onChange(applySoft);
fLight.add(P, 'softW', 1, 30, 0.1).name('мягкий: ширина').onChange(applySoft);
fLight.add(P, 'softH', 1, 30, 0.1).name('мягкий: высота панели').onChange(applySoft);
fLight.addColor(P, 'keyColor').name('ключ: цвет').onChange(applyKey);
fLight.add(P, 'keyIntensity', 0, 15, 0.05).name('ключ: яркость').onChange(applyKey);
fLight.add(P, 'keyAz', -180, 180, 1).name('ключ: азимут').onChange(applyKey);
fLight.add(P, 'keyEl', -90, 90, 1).name('ключ: высота').onChange(applyKey);
fLight.close();
fLook.add(P, 'toneMapping', { 'Нейтральный (без сдвига цвета)': 'neutral', 'ACES (киношный)': 'aces', 'AgX (мягкий)': 'agx' }).name('тонмаппинг').onChange(applyTone);
fLook.add(P, 'exposure', 0.2, 3, 0.01).name('экспозиция').onChange(applyTone);
function applyBg() {
  BG.set(P.bg); scene.background = P.bgTransparent ? null : BG;
  document.body.style.background = P.bgTransparent ? '' : P.bg;
  document.documentElement.classList.toggle('bg-clear', P.bgTransparent);
  bgCtl.enable(!P.bgTransparent);
}
const bgCtl = fLook.addColor(P, 'bg').name('фон').onChange(applyBg);
fLook.add(P, 'bgTransparent').name('прозрачный фон').onChange(applyBg);
bgCtl.enable(!P.bgTransparent);
const fShape = gui.addFolder('Форма');
fShape.add(P, 'size', 1, 8, 0.05).name('высота').onFinishChange(buildMesh);
fShape.add(P, 'depth', 0.05, 1.5, 0.01).name('толщина').onFinishChange(buildMesh);
fShape.add(P, 'bevel', 0, 0.2, 0.005).name('фаска').onFinishChange(buildMesh);
fShape.add(P, 'crease', 0, 90, 1).name('сглаживание граней').onFinishChange(buildMesh);

// Своя форма: кнопка в панели или SVG-файл, перетащенный на страницу.
// Загруженные SVG копятся в списке. Переключатель «форма» появляется, только когда их два и больше,
// а раздел «Рельеф» — только когда в текущем SVG есть второй цвет.
const uploads = {}; // имя файла → текст SVG
if (customSvg) uploads['Ваш SVG'] = customSvg;
let shapeCtl = null;
function useSvg(text) {
  const prev = FIG;
  try { parseFigure(text); customSvg = text; buildMesh(); }
  catch (err) { FIG = prev; alert('Не получилось прочитать SVG: ' + err.message); return false; }
  syncRelief();
  return true;
}
async function addSvgFile(f) {
  const text = await f.text();
  let name = f.name.replace(/\.svg$/i, '') || 'SVG';
  while (uploads[name] && uploads[name] !== text) name += ' ·';
  if (!useSvg(text)) return;
  uploads[name] = text;
  syncShapeList(name);
}
function syncShapeList(current) {
  if (shapeCtl) { shapeCtl.destroy(); shapeCtl = null; }
  const names = Object.keys(uploads);
  if (names.length < 2) return;
  shapeCtl = fShape.add({ svg: current }, 'svg', names).name('форма').onChange(n => useSvg(uploads[n]));
  loadCtl.domElement.after(shapeCtl.domElement); // сразу под кнопкой загрузки
}
const picker = Object.assign(document.createElement('input'), { type: 'file', accept: '.svg,image/svg+xml', multiple: true });
picker.addEventListener('change', async () => { for (const f of picker.files) await addSvgFile(f); picker.value = ''; });
const loadCtl = fShape.add({ load() { picker.click(); } }, 'load').name('Загрузить свой SVG…');
fShape.$children.prepend(loadCtl.domElement);
Object.assign(window.T, {
  setShape: v => { P.shape = v; customSvg = null; FIG = null; buildMesh(); syncRelief(); },
  useSvg,
});
addEventListener('dragover', e => e.preventDefault());
addEventListener('drop', async e => {
  e.preventDefault();
  for (const f of e.dataTransfer.files) if (f.name.toLowerCase().endsWith('.svg')) await addSvgFile(f);
});

const fRelief = gui.addFolder('Рельеф');
function syncRelief() { fRelief.show(!!FIG && FIG.relief.length > 0); }
fRelief.add(P, 'reliefMode', { 'Выпуклый': 'emboss', 'Вдавленный': 'deboss', 'Без рельефа': 'flat' }).name('рельеф').onChange(buildMesh);
fRelief.add(P, 'reliefDepth', 0.01, 0.4, 0.005).name('высота / глубина').onFinishChange(buildMesh);
fRelief.add(P, 'reliefBoth').name('с обеих сторон').onChange(buildMesh);
fRelief.addColor(P, 'reliefColor').name('цвет рельефа');
syncRelief();

const fRibs = gui.addFolder('Рифлёный торец');
fRibs.add(P, 'ribs').name('включить').onChange(buildMesh);
fRibs.add(P, 'ribCount', 12, 400, 1).name('количество рёбер').onFinishChange(buildMesh);
fRibs.add(P, 'ribDepth', 0.005, 0.15, 0.001).name('глубина канавок').onFinishChange(buildMesh);
fRibs.add(P, 'ribRound', 0.2, 3, 0.05).name('форма: плоские ↔ острые').onFinishChange(buildMesh);
const fRow = gui.addFolder('Ряд');
fRow.add(P, 'count', 20, 140, 1).name('количество').onFinishChange(buildMesh);
fRow.add(P, 'spacing', 0.3, 3, 0.01).name('шаг').onFinishChange(buildMesh);
fRow.add(P, 'yaw', -90, 90, 1).name('поворот букв').onFinishChange(() => { buildMesh(); loadHdri(); });
fRow.add(P, 'speed', 0, 4, 0.01).name('скорость');
fRow.add(P, 'y', -5, 3, 0.05).name('высота ряда');
fRow.add(P, 'z', -12, 6, 0.1).name('глубина ряда');
fRow.add(P, 'arch', 0, 2, 0.01).name('волна');
fRow.add(P, 'curve', 8, 200, 1).name('изгиб (радиус)');
fRow.add(P, 'recede', -0.1, 0.1, 0.001).name('края к зрителю');
const fG8 = gui.addFolder('Механика первого экрана');
fG8.add(G8C, 'snakeLift', 0, 3, 0.01).name('змейка: подъём');
fG8.add(G8C, 'snakeFwd', 0, 4, 0.01).name('змейка: вперёд');
fG8.add(G8C, 'snakeWidth', 0.2, 3, 0.01).name('змейка: ширина');
fG8.add(G8C, 'snakeFollow', 0.5, 15, 0.1).name('змейка: скорость за курсором');
fG8.add(G8C, 'snakeGlow', 0, 3, 0.01).name('змейка: свечение');
fG8.add(G8C, 'kickRadius', 0.05, 1, 0.01).name('пинок: радиус');
fG8.add(G8C, 'kickSpin', 0, 40, 0.5).name('пинок: поворот');
fG8.add(G8C, 'kickLift', 0, 20, 0.5).name('пинок: подброс');
fG8.add(G8C, 'maxSpin', 0, 1.5, 0.01).name('макс. поворот');
fG8.add(G8C, 'spinStep', 0, 0.6, 0.01).name('цепочка соседей');
fG8.add(G8C, 'rippleSpeed', 5, 120, 1).name('рябь по клику: скорость');
fG8.add(G8C, 'rippleLift', 0, 5, 0.05).name('рябь: подброс');
fG8.add(G8C, 'introDrop', 0, 8, 0.1).name('появление: падение');
fG8.add(G8C, 'introStagger', 0, 3, 0.05).name('появление: волна');
fG8.add(G8C, 'introDur', 0.2, 3, 0.05).name('появление: длительность');
fG8.add({ replay() { g8.intro = 0; } }, 'replay').name('Проиграть появление');
fG8.add(G8C, 'parallax', 0, 0.08, 0.001).name('наклон за курсором');
fG8.close();
const fMouse = gui.addFolder('Курсор');
fMouse.addColor(P, 'lightColor').name('цвет света').onChange(v => cursorLight.color.set(v));
fMouse.add(P, 'lightIntensity', 0, 400, 1).name('яркость света');
fMouse.add(P, 'lightDepth', -3, 10, 0.1).name('свет ближе / дальше');
fMouse.add(P, 'hoverRadius', 0.03, 0.5, 0.01).name('радиус');
fMouse.add(P, 'hoverLift', 0, 3, 0.01).name('подъём');
fMouse.add(P, 'hoverTilt', 0, 30, 1).name('наклон');
fMouse.add(P, 'kick', 0, 2.5, 0.05).name('сила пинка');
fMouse.add(P, 'scrollBoost', 0, 8, 0.1).name('ускорение скроллом');
fMouse.add(P, 'parallax', 0, 0.1, 0.001).name('параллакс');
// ---- Выбор цвета ----
// Системное окно цвета в Chrome открывается в RGB и не стилизуется, поэтому своё:
// поле насыщенности/яркости, полоса оттенка, HEX и пипетка (где браузер её умеет).
{
  const cp = document.createElement('div');
  cp.className = 'cpick'; cp.hidden = true;
  cp.innerHTML = `
    <div class="cp-sv"><i class="cp-knob"></i></div>
    <div class="cp-hue"><i class="cp-knob"></i></div>
    <div class="cp-row">
      <span class="cp-sw"></span>
      <label class="cp-hex"><span>#</span><input maxlength="7" spellcheck="false" autocomplete="off"></label>
      <button type="button" class="cp-drop" title="Пипетка: взять цвет с экрана">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 5.5l4 4"/><path d="M17 3a2.1 2.1 0 013 3l-2.5 2.5-3-3z"/><path d="M14.5 6.5L5 16v3h3l9.5-9.5"/></svg>
      </button>
    </div>`;
  document.body.appendChild(cp);
  const sv = cp.querySelector('.cp-sv'), svKnob = sv.firstElementChild;
  const hue = cp.querySelector('.cp-hue'), hueKnob = hue.firstElementChild;
  const sw = cp.querySelector('.cp-sw'), hexIn = cp.querySelector('.cp-hex input'), drop = cp.querySelector('.cp-drop');
  if (!('EyeDropper' in window)) drop.remove();

  let ctl = null, H = 0, S = 0, V = 0;
  const toHex = (h, s, v) => {
    const f = n => { const k = (n + h / 60) % 6; return v - v * s * Math.max(0, Math.min(k, 4 - k, 1)); };
    return [f(5), f(3), f(1)].map(x => Math.round(x * 255).toString(16).padStart(2, '0')).join('');
  };
  const fromHex = hex => {
    const n = parseInt(hex, 16), r = (n >> 16 & 255) / 255, g = (n >> 8 & 255) / 255, b = (n & 255) / 255;
    const mx = Math.max(r, g, b), d = mx - Math.min(r, g, b);
    let h = 0;
    if (d) h = mx === r ? ((g - b) / d) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;
    return [(h * 60 + 360) % 360, mx ? d / mx : 0, mx];
  };
  function paint(skipText) {
    const hex = toHex(H, S, V);
    sv.style.background = `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${H} 100% 50%))`;
    svKnob.style.left = `calc(8px + ${S} * (100% - 16px))`; svKnob.style.top = `calc(8px + ${1 - V} * (100% - 16px))`;
    svKnob.style.background = '#' + hex;
    hueKnob.style.left = `calc(7px + ${H / 360} * (100% - 14px))`; hueKnob.style.background = `hsl(${H} 100% 50%)`;
    sw.style.background = '#' + hex;
    if (!skipText) hexIn.value = hex;
    return hex;
  }
  const push = skipText => { const hex = paint(skipText); if (ctl) ctl.setValue('#' + hex); };
  const finish = () => { if (ctl) ctl._callOnFinishChange(); };

  function drag(el, onMove) {
    el.addEventListener('pointerdown', e => {
      el.setPointerCapture(e.pointerId);
      const move = ev => { const r = el.getBoundingClientRect(), ix = el === hue ? 7 : 8, iy = el === hue ? 0 : 8;
        onMove(Math.min(1, Math.max(0, (ev.clientX - r.left - ix) / (r.width - 2 * ix))), Math.min(1, Math.max(0, (ev.clientY - r.top - iy) / (r.height - 2 * iy)))); push(); };
      move(e);
      el.onpointermove = move;
      el.onpointerup = () => { el.onpointermove = el.onpointerup = null; finish(); };
    });
  }
  drag(sv, (x, y) => { S = x; V = 1 - y; });
  drag(hue, x => { H = Math.min(x * 360, 359.9); });
  hexIn.addEventListener('input', () => {
    const v = hexIn.value.replace(/[^0-9a-f]/gi, '');
    const hex = v.length === 3 ? v.replace(/./g, c => c + c) : v;
    if (hex.length === 6) { [H, S, V] = fromHex(hex); push(true); }
  });
  hexIn.addEventListener('change', () => { paint(); finish(); });
  hexIn.addEventListener('focus', () => hexIn.select());
  drop.addEventListener('click', async () => {
    try { const { sRGBHex } = await new EyeDropper().open(); [H, S, V] = fromHex(sRGBHex.slice(1)); push(); finish(); } catch {}
  });

  function open(c) {
    ctl = c; [H, S, V] = fromHex(c.$input.value.slice(1)); paint();
    cp.hidden = false;
    const r = c.$display.getBoundingClientRect(), panel = gui.domElement.getBoundingClientRect();
    const w = cp.offsetWidth, h = cp.offsetHeight;
    cp.style.left = Math.max(12, panel.left - w - 12) + 'px';
    cp.style.top = Math.min(innerHeight - h - 12, Math.max(12, r.top + r.height / 2 - h / 2)) + 'px';
  }
  const close = () => { if (!cp.hidden) { cp.hidden = true; ctl = null; } };
  for (const c of gui.controllersRecursive()) {
    if (c.$input?.type !== 'color') continue;
    c.$input.addEventListener('click', e => { e.preventDefault(); cp.hidden || ctl !== c ? open(c) : close(); });
  }
  addEventListener('pointerdown', e => { if (!cp.hidden && !cp.contains(e.target) && !e.target.closest('.controller.color .display')) close(); }, true);
  addEventListener('keydown', e => { if (e.key === 'Escape') close(); });
  gui.onOpenClose(g => { if (g === gui && g._closed) close(); });
}
{
  // «Сбросить» в шапке панели: все ползунки возвращаются к значениям, с которыми открылась страница
  const reset = document.createElement('button'); reset.type = 'button'; reset.className = 'reset-btn'; reset.textContent = 'Сбросить';
  reset.addEventListener('pointerdown', e => e.stopPropagation());
  reset.addEventListener('keydown', e => e.stopPropagation());
  reset.addEventListener('click', e => {
    e.stopPropagation();
    gui.reset();
    Object.assign(P, structuredClone(INIT.P)); Object.assign(G8C, structuredClone(INIT.G8C));
    gui.controllersRecursive().forEach(c => c.updateDisplay());
    reset.textContent = 'Сброшено ✓'; setTimeout(() => { reset.textContent = 'Сбросить'; }, 1400);
  });
  gui.$title.appendChild(reset);
  // запасной путь, если браузер не дал доступ к буферу: окно с выделенным текстом
  function showCopyBox(text) {
    const box = document.createElement('div');
    box.style.cssText = 'position:fixed;inset:0;z-index:10001;display:grid;place-items:center;background:rgba(0,0,0,.6)';
    box.innerHTML = `<div style="width:min(560px,90vw);padding:16px;border-radius:20px;background:#141416;color:#ececef;font:300 13px Geologica,system-ui,sans-serif;display:grid;gap:10px">
      <div>Браузер не дал скопировать автоматически. Текст выделен — нажмите Cmd+C (Ctrl+C) и вставьте в чат.</div>
      <textarea readonly style="height:300px;border-radius:12px;border:1px solid rgba(255,255,255,.08);background:#1e1e22;color:#ececef;font:12px ui-monospace,monospace;padding:10px"></textarea>
      <button type="button" style="height:38px;border:0;border-radius:12px;background:#F64A00;color:#fff;font:inherit;cursor:pointer">Готово</button></div>`;
    const ta = box.querySelector('textarea'); ta.value = text;
    box.querySelector('button').onclick = () => box.remove();
    document.body.appendChild(box); ta.focus(); ta.select();
  }
  const bar = document.createElement('div'); bar.className = 'copy-bar';
  const btn = document.createElement('button'); btn.type = 'button'; btn.textContent = 'Скопировать настройки';
  btn.addEventListener('click', async () => {
    const text = JSON.stringify({ ...P, g8: G8C, ...(customSvg ? { svg: customSvg } : {}) }, null, 2);
    try { await navigator.clipboard.writeText(text); btn.textContent = 'Скопировано ✓'; }
    catch { btn.textContent = 'Скопируйте вручную'; showCopyBox(text); }
    setTimeout(() => { btn.textContent = 'Скопировать настройки'; }, 1600);
  });
  bar.appendChild(btn); gui.domElement.appendChild(bar);
}
fMouse.close();
// ?clean — чистый кадр для макетов: без панели, подсказки и текста экранов
if (new URLSearchParams(location.search).has('clean')) {
  gui.hide();
  document.querySelectorAll('section').forEach(el => el.style.visibility = 'hidden');
}
/*@@PANEL-END@@*/
</script>
</body>
</html>
>>>>>>>> COIN-STUDIO-HTML
```
