Claude Code skill that makes launch videos, ads and music videos from one line: idea, script, visuals, voice, music, edit and review, then a review room where your notes make the next take
HTML agent-skillsai-agentsai-skillai-videoclaudeclaude-codeclaude-skillslaunch-videomotion-designmotion-graphicsmusic-videovideo-generation
Take One: a Claude Code skill that makes a short film from one line
Tal Siach68c60d57a183
diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..879df49--- /dev/null+++ b/.gitignore@@ -0,0 +1,3 @@+.DS_Store+node_modules/+*.logdiff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..b28164e--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Tal Siach++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/LICENSES/ClaudeAnimationBase-LICENSE-MIT.txt b/LICENSES/ClaudeAnimationBase-LICENSE-MIT.txtnew file mode 100644index 0000000..1215a85--- /dev/null+++ b/LICENSES/ClaudeAnimationBase-LICENSE-MIT.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 John Heibel++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/LICENSES/anidoodle-LICENSE-Apache-2.0.txt b/LICENSES/anidoodle-LICENSE-Apache-2.0.txtnew file mode 100644index 0000000..9fb19f7--- /dev/null+++ b/LICENSES/anidoodle-LICENSE-Apache-2.0.txt@@ -0,0 +1,204 @@+Copyright 2026 Alex Greenshpun+++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/LICENSES/anidoodle-NOTICE.txt b/LICENSES/anidoodle-NOTICE.txtnew file mode 100644index 0000000..cae6e32--- /dev/null+++ b/LICENSES/anidoodle-NOTICE.txt@@ -0,0 +1,17 @@+anidoodle+Copyright 2026 Alex Greenshpun++This product includes software developed as an original work,+licensed under the Apache License, Version 2.0.++Third-party material++skills/anidoodle/engine/assets/refs/vangogh-almond-blossom.jpg+ Vincent van Gogh, Almond Blossom (1890), Van Gogh Museum, Amsterdam.+ Public domain (the author died in 1890; a faithful reproduction of a two-dimensional+ public-domain work). Downloaded from Wikimedia Commons:+ https://commons.wikimedia.org/wiki/File:Vincent_van_Gogh_-_Almond_blossom_-_Google_Art_Project.jpg+ Kept byte-identical to the download (sha256+ 6f640dcd79def4223bf16569fd29ca5e37ee9d6cde2670958636e259e2a1c9d0). Full provenance:+ skills/anidoodle/engine/assets/refs/PROVENANCE.json. It is not covered by the Apache+ License grant above; it carries no copyright.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..14737b8--- /dev/null+++ b/README.md@@ -0,0 +1,144 @@+<p align="center">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="assets/logo/take-one-logo.svg">+ <img src="assets/logo/take-one-logo-on-light.svg" alt="Take One" height="72">+ </picture>+</p>++<h3 align="center">A whole creative studio in one skill</h3>++<p align="center">Type one line in Claude Code. Get a finished short film.</p>++<!-- THE FILM GOES HERE.+ Edit this file on github.com and drag the film onto this spot. GitHub turns the file into a player.+ Then put this line under it:+ <p align="center"><sub>Take One made this film, and the headphone ad inside it. The brand is made up. Sound on.</sub></p>+-->++## Install (once)++The easy way: paste this into Claude Code and it does the rest.++```+Install the Take One skill: clone https://github.com/talsiach/take-one into ~/.claude/skills/take-one, then run bash ~/.claude/skills/take-one/scripts/doctor.sh and tell me what is missing.+```++Or do it yourself in a terminal:++```bash+npx skills add talsiach/take-one -g -a claude-code+bash ~/.claude/skills/take-one/scripts/doctor.sh+```++The second line checks your machine and says what is missing and what each piece is for. After that, Claude Code knows the skill in every session. A plain `git clone https://github.com/talsiach/take-one ~/.claude/skills/take-one` works too.++You need Claude Code, Node 18 or later, Google Chrome and ffmpeg. So far it has been run on macOS only.++## How to work with it++### 1. Say what you want++In Claude Code (a new session, if one was open while you installed):++```+/take-one a 30 second launch video for <your product>+```++One line is enough. You can also ask in plain words ("make me a launch video for my app") and Claude picks the skill up by itself. The name with the slash is the sure way.++It helps to add, in the same message:++- **The site** of the product or brand. It reads the look and the real lines from there.+- **A reference**, if you have a style or a direction in mind: a video file, a picture, or a link to something you love. It studies the reference first and builds to that.+- **What you already have**: a logo, screenshots, photos, a song.+- **Where it will be posted** (X, LinkedIn, Instagram). That sets the length and the shape.++### 2. Choose how to work++It answers with what it understood, the rough size of the job, and one question: run through to a finished first take, or work in stages with you.++- **Run.** It goes all the way to a finished, reviewed film. It stops only for the pitch, for a cost you have not approved, and for a login only you can do.+- **In stages.** It stops and shows you the idea and the storyboard, the look on a few real frames, the first full cut and the final.++For a first try, pick something real and small and let it run.++### 3. Say yes to the pitch++Before it builds anything you get one message: the idea in a sentence, the storyboard with times, and the ways to make the film, best first, each with its price.++- **Code only.** Every frame is drawn in code. Free.+- **Code with real-looking pictures** from an image model.+- **Code with pictures and moving shots** from a video model, for the few moments that need them.++It asks once which paid services are fine with you and whether you have a cap. Nothing paid is needed: with no budget it makes the best film the free way allows, and says what the paid way would have added.++The look comes from your project, not from a menu. For a product or a brand it builds the film from the brand's own type, colours, pictures and lines. For an app or a site it can use the real product: you log in, it works the product in Chrome and captures it. For a song or a story it offers two or three illustrated looks that fit, or learns a new one from your reference.++### 4. Watch it come together++While it works, each job posts one line when it finishes, so you can step in.++| | Job | What it does |+|---|---|---|+| 1 | Strategist | studies your brand |+| 2 | Creative director | finds the idea |+| 3 | Writer | shapes the story |+| 4 | Voice director | casts the voice |+| 5 | Art director | picks the look |+| 6 | Storyboard artist | draws every shot |+| 7 | Cinematographer | shoots every frame |+| 8 | Composer | writes the music |+| 9 | Sound designer | adds every sound |+| 10 | Editor | cuts it to the beat |+| 11 | Reviewer | scores the cut, and sends it back when it is not good enough |+| 12 | Social copywriter | writes the posts |++They are jobs, not twelve agents: one session does most of them, and long films split the build. The reviewer is always fresh eyes: it never saw the work, it scores the finished cut, and under the bar the film goes back, three rounds at most.++### 5. Get the film++- A finished MP4 at 1080p and 60 frames a second, with sound, on your Desktop or in Downloads.+- The posts that go out with it, for X and LinkedIn.+- The reviewer's score and the open problems. It does not report a pass that did not happen.++### 6. Give notes, get the next take++Type your notes in the chat, or open the review room it gives you (a page on your own computer), click on a frame and leave the note there. Each round of notes becomes the next take.++If you keep your own taste in a file (a `TASTE.md`, a voice guide, an agent that answers as you), point to it. The skill brings it into the room before the pitch, at the words and at the review.++## What it costs++- **Your Claude usage.** A 30 second film built in one session is roughly 0.4 to 0.7 million tokens and one to two hours. Longer films cost more; splitting the build across agents is faster and costs several times more. These are estimates; it tells you the size before it starts.+- **Credits, only if you say yes.** The code-only way is free. Pictures and moving shots (it knows Higgsfield, with Nano Banana, Seedance and Kling), a voice (ElevenLabs) and music (Suno) are used through accounts you already have. It reads the real price first and asks. None of them is required.++## What to expect++Proven on real films: the one-line start, the brand study from a live site, the pitch, the code build, real-looking pictures from an image model, a recorded voice, a song-service track fitted by measurement, code-made sound effects, the quality gate, the fresh-reviewer loop and delivery. Proven on one film, through many rounds: notes pinned in the review room becoming the next take. Proven on a few films only: moving shots from a video model. Done once, and scored 7 out of 10 by its own reviewers: a vertical version. Not tried yet: a computer that is not a Mac.++Without moving shots, a film built on pictures of people tops out at about 7 out of 10 with its own reviewers. They say so, and the skill reports that score as it is.++The film at the top took many takes and its owner's notes. The people and the moving shots in the ad came from paid picture and video services, the voice from a voice service and the music from a song service. One line on the free way gives you a finished film too, drawn in code. It will not have filmed-looking people like that ad.++It is slow, and it is strongest for product and brand films.++## Safe to run++- Everything is made on your own machine. No tracking and no analytics. It goes online only to read the sites you point it at, to load fonts, and to use a paid service you said yes to.+- It asks before anything that costs money or credits, with the real price. Your answer at the pitch covers what you agreed to; anything beyond it is asked again.+- Its local pages (the one that draws the frames and the review room) answer your computer only, not the network.+- It never asks for a password or a card.++## Inside the repo++`SKILL.md` is the entry point. `references/` holds the craft (timing, words, sound, brand, the checks before the first cut, the reviewer's brief, the illustrated looks). `scripts/` holds the tools (machine check, frames, export, quality gate, text audit, sound check, review room).++## Credits++Code and ideas adapted from open work are listed in `THIRD_PARTY.md`, with their licences in `LICENSES/`. Films and posts that taught the skill something are credited, with links to their makers, in `examples/INDEX.md`. Nothing of theirs is copied here.++## Licence++MIT. See `LICENSE`. The few files adapted from anidoodle stay under the Apache License 2.0; they are listed in `THIRD_PARTY.md`.++The Take One name and logo are not part of that licence. Use the skill freely, and build on it. Please do not ship a changed copy under the same name or logo.diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..330fbd6--- /dev/null+++ b/SKILL.md@@ -0,0 +1,247 @@+---+name: take-one+description: Turn a short request into a finished short film rendered from code, working like a studio team of twelve jobs (strategist, creative director, writer, voice director, art director, storyboard artist, cinematographer, composer, sound designer, editor, reviewer, social copywriter). For launch and product videos, explainers, music videos, brand and story films. It learns the brand from its site, pitches the best route first (code, real-looking pictures, moving shots from a video model) with prices, asks whether to run to a finished first take or work in stages, always asks before spending money, credits or heavy usage, has a fresh reviewer score the cut against a bar, and takes notes on frames in a local review room.+---++# Take One++Short films rendered from code: a web page draws every frame as a pure function of time, headless Chrome captures the frames, ffmpeg makes the MP4. This is how the Opus 5.5 videos that spread on X were made (a music video, a product explainer, a fight game built from four images). The model is capable of stunning work here; what separates great from mediocre is the process around it: a look that fits the project, a real idea, a storyboard timed for the viewer, and honest self-review.++## The goal++The most mind-blowing result the user can get. Opus directs, illustrates and renders; for most styles it needs nothing else. Specialist tools (image, video, music, sound models) are for what Opus can't make: photorealism, real faces, footage, audio. Offer them when the idea needs them; the user decides.++## How it runs++One line is enough to start. The first reply is short: say in one sentence what you understood they want, then ask one plain question (in the message, not a dialog) and wait for the answer:++> Do you want me to run with this to a finished first take, or work in stages with you?++With the question, say what it will cost, so they choose knowing it (see Cost below). If their message already answers it ("just make it", "get to work", or they ask to see each step), do not ask it again: say which way you are going, give the rough size, and ask only for the go on that. The first reply may carry one more question, only if the answer changes what film gets made (which company a name means, what the product actually is). Everything else you would have asked (format, where it posts, who audits the brand) you decide, state in a line and mark as yours.++- **Run.** Go through to a finished, reviewed film, led by their line and their intent. Decide what a person would have been asked, mark every choice that is yours as yours, and keep inside what they said: no claim, number, link, name or theme they did not give. On a run you stop at exactly these points and nowhere else:+ 1. the first reply (the go on the rough size);+ 2. the pitch (step 3): the route, its total cost, which tools and plans they have, and whether the build is one session or split across agents. One message, one answer;+ 3. a spend that the pitch answer did not cover, a total about to go over what they agreed, or a rebuild from scratch;+ 4. a login only they can do.+ Everything a person would otherwise be shown on the way (the test picture, the character's motion, the cut before moving shots are paid for) you judge yourself, in the same order, and say what you decided. Moving shots are still paid for only after the picture cut passes your own review.+- **In stages.** Stop and show at each stage, and wait for a yes or edits: the idea and storyboard (step 3), the look on a few real frames (the stills gate in step 4), the first full cut, the final.++Either way the first take is not the last word. When it is delivered, say how to give notes (step 7), and treat notes as the next take, not as a failure.++### Cost: always stop and ask++This holds in both ways of working, and "run" does not waive it.++- **Money and credits.** Before any paid image, video, voice or music generation, download or upscale (Higgsfield, Seedance, Kling, Suno, ElevenLabs and the like): read the real price, say it with what it buys, and wait for a yes on that number. A yes covers that spend only. If they give a cap, keep a running total in `spend.md` and say what is left after each batch (`references/services.md`). The choice of route (code only, pictures, moving shots) is theirs and is offered best first at the pitch (step 3); with no budget, make the best film the free route allows and say what the paid route would have added.+- **Inference.** The build itself uses the person's Claude usage. Say the rough size before starting and before any step that multiplies it: one session making a 30 s film is roughly 0.4 to 0.7 million tokens and one to two hours. Scale it with the length, add for a brand or competitor study, and say it is an estimate. One session can build a film of up to about a minute; splitting it across agents is faster and costs several times more, so offer both at the pitch with the sizes. Each fresh reviewer is small next to the build and is part of the size you quote, not a new question. Ask before a rebuild from scratch.++### The team++The work is twelve jobs. They are jobs, not twelve agents: one session does most of them, long films split the build across agents (step 4), and the reviewer is always fresh eyes. The point of naming them is that each one owns a decision and hands something on, so nothing gets skipped because the film already looks fine.++When a job finishes, post one short line that starts with its name and says what it decided ("Strategist: for founders on X, one takeaway: ..."), so the person watches the film come together and can step in. These lines are the studio the person was promised, so they are not optional on a run: on one long run the maker did all twelve jobs and posted almost none of the lines, and the person saw three hours of status notes instead of a team at work. A job the film does not need is skipped; say so in a word.++| Job | Owns | Hands on | Where |+|---|---|---|---|+| Strategist | who it is for, where it posts, the one takeaway; for a brand, its measured look and real lines; for a product, how its closest competitors present themselves | the brief and the brand pack | steps 1 and 1b, `references/brand-brief.md`, `references/brand-pass.md` |+| Creative director | the one idea and the payoff | the idea in a sentence | step 3; for a launch or product film, `references/launch-film.md` |+| Writer | every word, spoken and on screen, written to be understood on one hearing | the script with times | step 3, `references/words.md` |+| Voice director | whether there is a voice, who it is, how it reads | the placed voice track | `references/voice.md` |+| Art director | the look: from the brand for a brand film, from the style gallery for a song or a story | the style file or brand pack the build follows | step 2 |+| Storyboard artist | every shot: time, what happens, what the viewer must read | the storyboard | step 3 |+| Cinematographer | every frame: framing, camera, motion, and which shots need a real picture or a moving one | the built shots | step 4, `references/motion-kit.md`, `references/real-shots.md` |+| Composer | the music, and where its beats and silences fall | the track and its beat map | step 6, `references/audio.md`, `references/music-engine.md` |+| Sound designer | a sound for every visual event | the effects plan | `references/audio.md` |+| Editor | the cut on the beat, the pace, the final mix | the exported film | steps 4 and 6, `references/pipeline.md` |+| Reviewer | the score of the exported cut against the bar, and what goes back | the score, the three worst problems, a pass or a return | step 5, `references/quality-checklist.md` |+| Social copywriter | the words that go out with the film | the post captions | step 7, `references/captions.md` |++### The owner's taste (optional)++The team's judgment is general. Some people bring their own: a taste file, a voice guide, notes from earlier films, an agent that answers as them. When they point to one, or a `TASTE.md` sits in the project, or such an agent is available, it is in the room at three points:++1. **Before the pitch:** which idea it would back, and what it would cut from the storyboard.+2. **At the words:** every spoken and on-screen line read against it.+3. **At the review:** its verdict on the exported cut, next to the fresh reviewer's. The fresh reviewer still gives the score, because the taste knows the owner and the reviewer stands in for a stranger.++Where it disagrees with a general rule in this skill, it wins; where the person disagrees with it, the person wins. Say in the job lines where it changed something. When there is none, do not invent one. After a delivery with notes, offer to save what the person's notes taught as `TASTE.md`, so their next film starts from it.++## Why these rules exist (lessons from real attempts)++- **Nice is not enough.** A clean LinkedIn UI parody, a code-drawn watch, a 2-minute product explainer: all "good", none stopped the scroll. What worked had one idea, a strong look, a character or face, and a payoff.+- **The viewer sees it once, at full speed, on a phone, often muted.** Timing and legibility fail far more often than drawing does.+- **The person's name is on it.** Never add a theme, joke, character or target they didn't ask for (a surprise opponent character once derailed a whole project). Offer ideas, mark yours as yours, let them choose.+- **Claims must be true.** "One prompt" and "one-shotted" only if literally so. Hand edits are fine; the caption just says so.+- **Never cover the main character's face.** Panels, boards, cards, slams and captions go in the free space around the hero, never on her face (hairline to chin). A 9:16 recompose of an app-builder music video dropped a report panel right over her face, and the same film had type grazing her chin and nose. Keep a face box per photo and run the face audit for every aspect ratio you deliver (`references/pipeline.md`). Tracking brackets may frame a face; nothing solid sits on it.+- **A muted viewer must be able to follow.** On a spoken-word music video, showing only key words ("the work", "hand it off") looked sharp and a stranger could not follow the film; a full review round went on putting the short lines back, big and in the picture. Short spoken or sung lines go on screen whole (`references/words.md`).+- **A vertical version is a recompose, not a crop.** Every shot gets its own framing and layout, and the free space moves, so everything placed for 16:9 must be re-checked in 9:16 (`references/vertical.md`).+- **The user's reference is the style.** A brief written by another tool (another AI tool, ChatGPT) is an input, not the look. The first pilot of an app-builder music video followed a helper's toned-down brief ("limited panels, no countdowns") and came out as a flat brand page; the user's reference was a dense editorial HUD film ("this was my inspiration and style"). Put the reference and the brief side by side; where they disagree on the look, the reference wins or you ask. But keep the brief's brand facts: the other tool's brand audit (palette, fonts, lines) is why the final film looked 1:1 like the brand's own marketing video.++## From good to mind-blowing (what actually moved the score)++An app-builder music video was built with code plus 21 free stills and scored an honest 7/10 against its reference. These are the gaps that held it there and the levers that close them. Plan them at the pitch, not after the render.+- **Show, don't tell: the real product is the star (product videos).** A code-redrawn copy of the UI is telling; the real product doing the thing is showing, and it reads as "this is real" in the first second. The first pitch for a whiteboard-product film redrew the product's canvas in code; the user's note: "if you tell the story with show don't tell it can be amazing for product-related videos." A physical product has nothing to log into: its star is the brand's own product pictures from its site, used as they are and as the reference for any generated picture of it in the world (`references/real-shots.md`), never a code redraw of the object. For a product that lives on a screen, default to the real-product route (`references/real-product.md`): the user signs up or logs in (their email, their verification), Claude drives the product in Chrome to build the story's content for real, captures high-res screenshots and short screen recordings of each beat, and code adds only what the product can't: camera, cursor characters, type, sound, the payoff. Headlines then caption what the viewer is already seeing instead of explaining it.+- **What's inside the product tells the story.** A real product showing only text is still telling. Fill it with the story's visuals (photos, faces, product shots, screens) the way the brand's own marketing shots do, and answer the hook visually in the first reveal (`references/real-product.md`).+- **Motion where the viewer looks.** Stills that zoom, shake and cut cap a photoreal film at about 7; the reference's footage moved. Put real motion on the 4-6 hero moments: short video-model clips (price them), code-animated characters, or at minimum burst frames (`references/styles/editorial-hud.md`). Tell the user this ceiling when they choose the asset route.+- **Music drives the edit.** Cut on the song's measured beat grid, land hook words exactly when they're sung, and put the story's turns on the song's silences. A song written from the film's own lines beats an instrumental bed; the user loved hearing the story sung (`references/audio.md`).+- **Sound design by default.** Hits on every visual event (flash pops, flap clatter, key clicks, the send, the logo). Code knows every frame, so they land exactly. Offer them in the pitch; don't leave them for later.+- **Score it against the reference before the user does.** Frames side by side with the reference, a 1-10 score, and the three biggest gaps either closed or priced. The user will ask "how do you score it?"; have the answer and the plan.+- **Details viewers feel without naming them:** a punchy grade (no milky whites), no still held past about 4 s without a cut or burst, faces always clear, UI sitting exactly in its screen, the brand's real fonts, colors and logo.++## The workflow++**If the film launches a product, an app, a brand or a feature, read `references/launch-film.md` before the pitch.** **If the user brings a song and wants a clip for it, follow `references/music-video.md`** (song map, section storyboard, chapters) alongside these steps.++### 1. Brief (quick)+Get, from the conversation or with at most one question: the **subject** (what the video is about), **who it's for / where it posts** (X, LinkedIn, IG; this sets length and aspect), and **any assets** (logo, product screenshots, photos, a song, a character). If the video is about a brand or product, start from a brand audit (the user's, e.g. a research pack from another AI tool, or your own) and build the brand pack from the real assets (`references/brand.md`): real font files, computed colors, exact logo paths, the brand's own devices and lines. The user's favorite thing about the app-builder video was that it was 100% on brand. For a product, offer the real-product route up front: can the user log in (or sign up for a free plan) so Claude can drive and capture the real product? If the user gave a reference video or link, study it first (see step 2b).++**1b. Brand brief + guidelines: required whenever a product or brand is involved.** Three pages, three jobs: `brand-brief.md` is what the pack must hold, `brand-pass.md` is how to pull it from the live site, `brand.md` is how to stay on it in the build. On a run, or when the person is away, audit the site yourself. Before pitching, get a brand brief and brand guidelines pack (`references/brand-brief.md`): either the user runs the ready prompt through another AI tool, or Claude audits the live site itself. It must hold the measured palette, fonts, exact lines, motifs, official campaigns, an asset register and a claims check. This is what made the app-builder film look 1:1 like the brand's own marketing. No build starts without it.++**1c. What is true today: check it yourself, before the pitch.** When the request names a feature, a number or a claim ("it works with agents", "twice as fast", "free forever"), look for it on the product's own site and help pages, and write three lines in the brief: what the product really does today, what the request says, and the gap. If the claim is not there, say so in the first lines of the pitch and ask the one question that settles it: does it exist, is it coming, or is this a spec film for a direction? Do not build on a feature you could not find without that answer. Every screen that shows something the product does not do yet is an illustration: say which ones in the delivery note, so nobody posts it as a product capture. On one product ad the requested feature was nowhere on the brand's site; four cold readers marked the storyboard down because it "felt invented", and one question to the owner (it was a coming feature) settled what three rounds of rewriting could not.++Then pin down **the one takeaway**: the single sentence a viewer should remember ("Sound for every hour."). Watch for brief traps that produce long, dense, forgettable videos, and gently push back on them:+- **Many goals at once** ("introduce us, explain the product, how it works, the innovation, why it's disruptive"). Pick one; the rest go in the caption or a second video.+- **Long length for a feed** (2+ minutes for an explainer). Offer 30-45 s; keep long only for story films or art pieces.+- **"Show off the motion design"** as a goal. Craft serves the message; it isn't the message.+- **"Explain how it works, but keep the secret sauce."** Don't draw a vague mechanism. Show the **effect** instead: before vs. after, the pain vs. the relief, many things becoming one.++### 2. The look+For a brand, a product or a launch, the look comes from the brand (step 1b) and the idea, not from this menu: say which look you chose and why, and move on. For a song, a story or an open subject, open the gallery so they can see the styles, name the two or three that fit and your pick in plain text, and let them choose. On a run, pick and say so.++**The part that explains the product is where a film gets called "AI-looking".** Before designing it, read `references/directed-look.md`: choose the way of explaining that fits the film's goal (the page lists the ways real launch films use), show the real thing each step made instead of an invented picture of it, turn a list into one picture that changes, and only then style it (ban the default look by name, numbers instead of adjectives).++**The gallery shows only our own renders, never frames from other people's videos** (reference videos are kept in a study folder outside the skill). Every card carries the one-story preview pack: THE PAPER BOAT, the same two frames (A: setting out at first light, boat lower-left heading right; B: the storm peak, one big diagonal wave from upper right) rendered by us in that style. Sources live in assets/previews-src/<id>/boat.html with the shared brief at assets/previews-src/BOAT-BRIEF.md and renderer snap.mjs (needs a node_modules symlink beside it with playwright-core, see .gitignore). When adding a style: write the style file, add the card, render the two boat frames from the brief before the card ships; the render doubles as the style file's proof that it works.++```bash+open ~/.claude/skills/take-one/assets/gallery.html+```++| Style | File | Best for |+|---|---|---|+| Watercolor character | `references/styles/watercolor.md` | stories, music videos, anything with a character and a journey |+| Clean kinetic explainer | `references/styles/explainer.md` | a product or idea in 15-30s, SaaS, launches |+| Image-to-game cinematic | `references/styles/image-game.md` | "the model built a game from my images", featuring a real person |+| Manifesto film | `references/styles/manifesto.md` | announcing a company, initiative or thesis: fact, story, turn, numbered vision, callback |+| Dark premium explainer | `references/styles/dark-premium.md` | serious tech/AI concepts, B2B, investor-facing |+| Editorial HUD film | `references/styles/editorial-hud.md` | brand films and art pieces: model-generated fashion footage + code HUD overlay |+| Broadcast title sequence | `references/styles/title-sequence.md` | lineups, comparisons, multi-feature launches, event openers; beat-locked kinetic type |+| Kinetic lyric video | `references/styles/kinetic-lyric.md` | music videos where the words are the visuals; Hebrew/RTL notes inside |+| 3D teaching song | `references/styles/teaching-song.md` | a song that teaches a book/course/product, lyrics demonstrated in a 3D world of the subject |+| Painterly glow music video | `references/styles/painterly-glow.md` | emotional songs: Van Gogh brushstroke skies, a glowing figure, symbolic scenes |+| Cinematic animated short | `references/styles/animated-short.md` | wordless emotional stories, 1-3 min, letterboxed, story pitched and approved first |+| Monochrome launch film | `references/styles/monochrome-launch.md` | fintech/crypto/premium-tool launches: pure b/w section inversions, liquid chrome, quant charts with live counters, one gold moment |+| Crayon storybook | `references/styles/crayon-storybook.md` | history/science "X in under a minute", kids' subjects, family films; the safe choice when characters must move a lot (imperfection is the aesthetic) |+| Paper cut-out | `references/styles/paper-cutout.md` | songs, histories, warm brand stories; layered paper with real shadows, puppet-pivot motion |+| Pixel art film | `references/styles/pixel-art.md` | nostalgia, game-flavored spots, lofi loops; hard grid, dithered palettes, sprites on ticks |+| Hand-drawn sketchbook | `references/styles/sketchbook.md` | intimate stories and build-up explainers; self-drawing line and hatching |+| Glossy chrome showreel | `references/styles/chrome-showreel.md` | launches and brand stings; liquid metal on poster fields, beat-locked vignettes |+| ASCII / CRT terminal | `references/styles/ascii-terminal.md` | dev-tool launches, technical audiences; character-density scenes, prompts as narration |+| Ink wash (sumi-e) | `references/styles/ink-wash.md` | contemplative, heritage, calm-authority pieces; brush dilutions, negative space, one seal |+| Animator's pencil test | `references/styles/pencil-test.md` | craft/process reveals, character reveals; perform, freeze and dissect the motion, APPROVED stamp; doubles as the character motion test |+| Riso pop | `references/styles/riso-pop.md` | satire, meme-dense music videos, AI commentary; three-ink halftone overprint, mascot protagonist, one gag per line |++Read only the chosen style's file. It holds the design system, the engine, and the style-specific rules. For a brand, a product or a launch you do not choose from this table at all: the brand sets the type, the colours and the pictures (`references/brand-pass.md`), and a style file is at most a reference for structure and motion.++**2b. A new style from a reference.** If the user brings a video they love that fits none of these, reverse-engineer it: extract a contact sheet (`scripts/contact-sheet.sh <video>`), read a few full frames, and write down its design system (background, accent, fonts and their jobs, texture, motion, pacing, beat length). Build to that. If it's good, offer to save it as a new style file in `references/styles/` and add it to the gallery.+To save it as a style, follow `references/adapt-a-style.md`: analyze 2-3 frames with `scripts/analyze-style.mjs`, look before trusting numbers, write the recipe in the style-file format with provenance, prove it with the two PAPER BOAT frames, then add the gallery card and the `examples/INDEX.md` row.++### 3. Pitch: the idea, the storyboard and the route+Run `references/concept-check.md` on the leading idea first, and `references/page-or-picture.md` on its storyboard (for every shot: a page or a picture, something happening or something shown) (retell it in three sentences, the three answers a stranger must get, words off, the defaults that have already failed, the one image). It is the cheapest place to catch a film nobody wants to watch: two films that passed every technical check were both rejected as having nothing to say.++Before any code, show the user:+- **The one idea** in a sentence, and the payoff (the moment people rewatch or share).+- **The words, timed, before the storyboard.** If the film will have a voice, write every spoken line first and count it: about two words a second plus the gaps between lines. The shot times in the storyboard come from that count. A voice written after the storyboard moved one film from a pitched 33 seconds to 41, and every shot had to be re-timed twice.+- **The storyboard**: a table of shots with times, what happens, the read(s) the viewer must get, any on-screen words, and the transition out.+- **Length and format** (default 15-40 s, 16:9 for X, add 4:5 or 9:16 for LinkedIn/IG if asked).+- **The route, best first** (read `references/toolbox.md`). First decide what would make the best film for this subject as if cost did not matter, and pitch that. It is usually a mix: code for type, motion, the product's screens and the finishing; real-looking pictures where the film needs people, places or the product out in the world; and moving shots from a video model on the few hero moments. Then lay out the routes, one line each, with what the film looks like on that route, its expected ceiling and its price read from the real price list:+ 1. **Code plus pictures plus moving shots** (a video model such as Seedance or Kling): costs credits; say how many shots and the total.+ 2. **Code plus pictures only** (an image model): free when the person has an unlimited plan (Nano Banana in the Higgsfield web UI with Unlimited on) or brings the images from their own ChatGPT using prompts you write; the pictures get motion from code.+ 3. **Code only**, in the style that suits the idea best: free.+ For a product that lives on a screen, whichever of the three is chosen is built on captures of the real product (`references/real-product.md`): free, and it needs their login and Claude in Chrome. Say so with the routes.+ Recommend the one you believe in and say why, then ask the one services question from `references/services.md`: which services are OK to use and whether there is a cap. The person decides both; for every "no" that page gives the other way to make the film. Do not quietly fall back to the free or code-only route because it is free: a person who is never offered the better film cannot choose it. Code only is the right pitch when it is the best look for the idea (an illustrated story, kinetic type, a product that lives on a screen) or when the person says code only. If they have no budget, pitch the best film that no money can make, and say what the paid route would have added. Never spend credits without a yes on the number.+- **Music at the pitch.** For a product or launch film, or when they asked only for "music", pitch an instrumental: a Suno instrumental (they generate it from your prompt, or you drive their logged-in account with their yes on the cost) or a bed composed in code, free. For a story or a film built on its words, the default is sung: offer a Suno song whose lyrics are the film's own lines (story sung, hook words on the beats), with an instrumental as the fallback (a Suno instrumental, or a bed composed in code with `scripts/music.mjs`, fitted to the film's exact length). On a whiteboard-product film the user had to ask why the song had no sung lyrics; the sung version then drove the whole edit. Sound effects alone read as "no sound" to a viewer.+- For comedy: the lines or gags, each tied to a moment. A line is funny when it **contradicts what's happening on screen** (a knocked-out salesman still asking "So... next Tuesday?"), not when it's just a familiar phrase.++- **The expected ceiling of each asset route**, in one line each (e.g. "code + free stills: strong, about 7/10 against this reference; + 5 video clips for the hero moments: about 9, costs N credits"). The user picks the ambition knowing the price.++- **The format** (read `references/formats.md`): a linear film is not the only shape. When it fits, offer an interactive artifact filmed in use, a one-continuous-zoom piece, a "the film draws itself" reveal, a model-vs-model duel, or production receipts in the caption (measure tokens/hours/cost during the build so the receipts are real).++Offer 2-3 ideas if the subject is open. In stages, wait for a yes or edits on all of it: this checkpoint is cheap, rebuilding a finished film is not. On a run, post the idea and storyboard as a note, marked as your choices, and wait only for the route and its cost; if the best route is free, say so and keep going.++Put the pitch in a normal message and let the user read it before asking anything. A question dialog sent right after it can cover it ("did you show me something? I didn't see"); ask follow-ups in plain text or after they've seen the storyboard.++### 3a. The storyboard, drawn+After the yes on the pitch and before the build, the storyboard artist draws every shot: one rough frame per shot, in order, on one sheet. A table says what happens; a drawn frame shows whether the shot works, and fixing a frame on the sheet costs seconds.+- **Pictures route:** a quick pencil sketch per shot from the image model, in the framing of the final shot, at its cheapest or free setting (it is part of the services question, `references/services.md`). The cinematographer then makes the real picture from each approved sketch, keeping its composition.+- **Code route:** a blockout frame per shot rendered from the page: the ground, the big shapes, where the type sits. No polish.+- Tile them with `scripts/storyboard-sheet.sh <frames folder> storyboard.png` and show the sheet. In stages, wait for a yes or edits. On a run, read it yourself the way a stranger would, fix what does not read, and post the sheet with the storyboard artist's line.++### 3b. Character department (any film with a character who moves)+Before any scene is animated, build the character properly and get the user's approval on motion, not stills: a real skeleton (fixed bone lengths, joint limits, 2-bone IK for arms and legs, foot planting), drawn head views and hand shapes (never procedurally bent faces or fingers), a pose library of the poses the film needs, and short motion tests (walk cycle, sit/stand, reach and grip, the film's key actions). Animators then use only approved poses and motions. Lesson from a song clip: stills approved, film failed, because animators improvised limbs on a loose figure and joints twisted in motion. Keep code characters stylized.++### 4. Build+Set up a project folder from the style's engine (the style file says how; a brand film with no style file starts from `bash scripts/new-canvas-project.sh <dir>`), then build shot by shot. Have the music and its beat map before building, so the cut follows it (the music part of step 6). Every frame must be a pure function of time `t` (seeded randomness only), so frames can render in parallel and out of order.++- For films over about a minute or with many chapters, and for shorter ones when the person chose the split at the pitch, split into chapter files and brief parallel subagents with a shared guide (the P(doom) video did this: one guide, one storyboard, one chapter per agent, shared files read-only).+- For epic pieces (music videos, 1-3 min films) where the user can let it run for hours with tools and a budget, use the overnight-run method in `references/overnight-run.md`: a rich voice-style brief, a proven base repo, an image model for designs, a video model for reference motion that gets redrawn in code (rotoscoping), sound design, and explicit self-review loops. Agree the budget first.+- Timing rules, all styles, from `references/timing.md`. Read it before building. The short version: list the reads per shot, one read at a time, fast actions but held meanings, lead the eye, let the reads set the length, hold the final payoff long enough to land. All motion runs on springs (`springs.js`, presets in timing.md); linear motion never. Moves that read as designed (log-space zooms, beat punches, shared elements across handoffs, flood circles): `references/motion-kit.md`.+- **Stills gate before the first full export. This is the storyboard drawn.** Render one frame per storyboard beat (`node frames.mjs 0 <beat times>`), read every one at full size and on the 360 px sheet, and fix what's wrong in the stills. Composition, type size, contrast and on-brand colour are all visible in a still, and a still costs seconds where an export costs minutes. No full export until every beat's still is right. Run `node <skill>/scripts/text-audit.mjs` from the film folder (it measures every word the film draws: too small for a phone, up too briefly to read, parked in a corner, held too long) and fix every FAIL. Then walk `references/before-the-first-cut.md` on those stills (phone width, the first second, people on screen, states that agree, payoffs that hold, nothing on what matters): it is the list of things fresh reviewers kept finding after the export.++### 5. Review: your own pass, then fresh eyes+The review is of an exported file with its sound, so render and mix first (step 6), then come back here. For a real brand or product, run the brand pass first (`references/brand-pass.md`): their typeface, colors, logo SVGs, headline and CTA pulled from the live site. Render contact sheets and full frames and actually look at them (`scripts/frames.mjs`, see `references/pipeline.md`). Then walk `references/quality-checklist.md`. If the film has a main character, run the face audit (`scripts/audit-faces.mjs`) in every aspect ratio and fix every overlap before anyone sees it. Then score the critique rubric in `references/quality-checklist.md`: hook in the first 2 s, readability at 360 px, motion quality, variety (something new every 2-4 s), composition, data accuracy and sound sync, each 1-10; name the 3 worst problems with timestamps, fix them, and loop until every axis is 8+. Read a 12-frame strip around each fast move (whips, handoffs, floods): that is where text blurs and floods read as flashes. Then the bar check: put your frames next to the reference's, score it 1-10, and close the three biggest gaps (or price them for the user). Fix and re-render until it passes; re-render only the shots you changed (`references/pipeline.md`). The first render is never the one to show.++**Then fresh eyes: the reviewer is never the maker.** The maker scores its own work too high. Build the pack with `scripts/review-pack.sh` and hand it over with the brief in `references/reviewer-brief.md`. Hand the exported cut to a new agent that has seen none of the work (no conversation, no storyboard, no code, no earlier score): the contact sheet and full frames at every beat, the strips around fast moves, the sound report (it cannot hear), the words spoken with their times, who the film is for and where it posts. It retells the film in a sentence, scores the rubric and names the three worst problems with times. Its score is the score. The bar is 8 on every axis. Under the bar the film goes back: fix, re-export, and give it to another new reviewer, because one that saw the last cut is anchored. Three rounds at most; if it is still under, stop and deliver it with the score and the open problems, since the idea or the asset route may be the limit and that is the person's call. Never say it passed when it did not. If no second agent is available, say plainly that the score is your own.++**Score honestly, from the exported MP4.** Scrub the actual file at every story beat at full size before giving a number, and list the known flaws with it. On a whiteboard-product film the maker scored its own cut 9/10, and the user then found a blurry, pixelated product label and a headline stamped over live content, both visible on first watch. A score is a claim; check it like one.++### 6. Render + sound+Export at 1920x1080, 60 fps (`scripts/export.mjs`; for anything over about 20 s use `scripts/render-parallel.sh`, which renders pieces side by side, restarts a piece whose browser never starts, and checks the frame count); the final master of smooth-motion styles (kinetic, explainer, title, chrome, mono) with `SUB=8` subframe motion blur, never for stepped art (pixel, pencil test, crayon boil); see `references/pipeline.md`. Music: a user-supplied track or a Suno prompt from `references/audio.md`; cut it so the drop and the silence land on story beats (`scripts/mux-audio.sh`). Hit sound effects are a big quality lever for action pieces; offer them.++### 7. Deliver+Put the MP4 somewhere obvious (Desktop or Downloads), named plainly (`<name>.mp4` is take one; each round of the person's notes makes `<name>-v2.mp4`, take two, then v3), open it, and give:+- what's in it, shot by shot, in two or three lines+- **the post copy, written out in the delivery message and saved as `POSTS.md` in the project**: one post for X and one for LinkedIn at least, per `references/captions.md` (the brand's own launch posts when the film is for a brand, the maker's post when it is their own work). This is the social copywriter's job and it is never skipped or deferred: a delivery that says "captions not written yet" is not a delivery. On one run the film went out with a score, a spend report and a review room, and no copy; the person's first note was that the posts were missing+- an honest one-line note on what was one prompt vs. hand-tweaked+- the reviewer's score, whose it is, and the known flaws+- how to give notes, both ways: type them in the chat, or pin them on frames in the review room, open on this cut (`references/review-room.md`): they click on a frame and leave a note there. Notes are the next take: read each one with its snapshot, answer it in a new cut, and send that cut back through the reviewer++## Files++- `assets/gallery.html` + `assets/previews/` : the style menu+- `assets/logo/` : the Take One mark (a film slate, arm lifted, a 1) and the logo with its name, as vector files: `take-one-mark.svg`, `take-one-logo.svg` (name beside the mark) and `take-one-logo-stacked.svg` (name under it), each with an `-on-light` twin. The plain files are for dark grounds. The review room and the README use them; use these files wherever the skill's own name appears and never redraw the mark+- `references/styles/*.md` : one file per style+- `references/timing.md` : timing for the viewer (all styles), spring presets+- `references/motion-kit.md` : log-space zooms, beat punches, shared-element handoffs, flood circles, seek-compatible libraries+- `references/vertical.md` : 9:16 recompose (one timeline, two layouts, where things go)+- `references/brand-brief.md` : the required brand brief + guidelines pack (what it holds, the research prompt)+- `references/brand.md` : staying 100% on brand (real fonts, computed colors, exact logo paths, faithful UI)+- `references/quality-checklist.md` : the bar before showing anything+- `references/before-the-first-cut.md` : the checks to walk on the stills, before any export+- `references/page-or-picture.md` : the storyboard check that catches a slideshow before it is built+- `scripts/text-audit.mjs` : measures the words a film draws (size at phone width, time on screen, corners, edges, faces)+- `references/video-models.md` : read a video model's limits live; dated notes on the models we have used+- `references/pipeline.md` : render tools, flags, gotchas+- `references/audio.md` : Suno prompts, cutting music to beats, SFX+- `references/music-engine.md` : the code music engine (`scripts/music.mjs`): instrumental beds and loops composed as scores, fitted to any length, deterministic+- `references/captions.md` : the maker's post and the brand's own launch posts+- `references/launch-film.md` : the shape of launch and product films+- `references/concept-check.md` : the idea check before anything is built+- `scripts/storyboard-sheet.sh` : the drawn storyboard, one rough frame per shot on one sheet+- `references/words.md` : spoken and on-screen lines+- `references/voice.md` + `scripts/vo.py` : casting, recording and cutting a voice; every cut line checked against its text+- `references/real-shots.md` + `scripts/clip.py`, `scripts/cutseq.py`, `scripts/matte.swift`, `scripts/plate.py` : real-looking pictures, moving shots from a video model, cut-outs, and a still made into a shot with depth (cut-out, filled plate, three layers; free)+- `scripts/songmap.py` : tempo, beats, loudness and silences of a track+- `references/review-room.md` + `scripts/review-room/` : the local page where the person pins notes on frames of a cut+- `references/overnight-run.md` : the 12-hour one-prompt method behind the most viral Opus 5.5 videos+- `references/overnight-brief-template.md` : the fill-in brief for that method (target, look, tools, characters, rotoscope base, zeitgeist, attention, rigor, budget)+- `references/music-video.md` : the song → clip workflow (lyrics, timing, sections, chapters)+- `references/brand-pass.md` : pull the brand's real fonts, colors, logo and CTA from its live site; no invented decoration+- `references/real-product.md` : show don't tell: sign up, build the story in the real product, capture it, composite+- `references/services.md` : paid services: the one question at the pitch, the other way for every "no", how to reach a service, the spend ledger+- `references/toolbox.md` : which tool for which asset (Nano Banana, ChatGPT, Seedance, Suno, ElevenLabs, whisper, demucs), free routes, costs+- `examples/INDEX.md` : work we studied, each credited with a link to its maker and what it taught. Add each new one; never copy the work itself.+- `references/reviewer-brief.md` + `scripts/review-pack.sh` : the fresh reviewer's pack and brief, and what to do when the owner's taste and the reviewer disagree+- `scripts/render-parallel.sh` : render a long film in pieces, three browsers at a time by default+- `scripts/unbundle.py` : unpacker for the frame bundles used when capturing a real product's canvas in the browser (`references/real-product.md`)+- `scripts/` : `serve.mjs`, `frames.mjs`, `export.mjs` (`SUB=N` motion blur), `springs.js` (closed-form springs), `gate.mjs` (determinism, contract, dead air, pops), `audit-faces.mjs`, `mux-audio.sh`, `contact-sheet.sh`, `new-canvas-project.sh`diff --git a/THIRD_PARTY.md b/THIRD_PARTY.mdnew file mode 100644index 0000000..edf9454--- /dev/null+++ b/THIRD_PARTY.md@@ -0,0 +1,35 @@+# Third-party code and credits++What this skill adapts from other people's open work, and what it needs at render time. Licence texts for adapted code are in `LICENSES/`.++The files adapted from anidoodle stay under the Apache License 2.0. Everything else here, including the gallery preview images and the music pieces, is under the MIT licence in `LICENSE`, except the Take One name and logo (see the README).++## Code adapted into this repo++| What | Files here | Upstream | Licence |+|---|---|---|---|+| anidoodle (Alex Greenshpun): code music engine, sound-effect kit, render gate, audio meter, style analyzer, the adapt-a-style method, the ink-wash brush and seal | `scripts/music/*.mjs` and the kit set-up of the pieces in `scripts/music/pieces/`, `scripts/music.mjs`, `scripts/sfx.mjs`, `scripts/gate.mjs`, `scripts/audio-check.mjs`, `scripts/analyze-style.mjs`, `references/music-engine.md`, `references/adapt-a-style.md`, parts of `references/styles/ink-wash.md` and `assets/previews-src/ink/boat.html` (adapted) | github.com/alexgreensh/anidoodle | Apache-2.0: `LICENSES/anidoodle-LICENSE-Apache-2.0.txt`, `LICENSES/anidoodle-NOTICE.txt` |+| Claude Animation Base guide (John Heibel): the "model the viewer" timing rules | `references/timing.md` (prose adapted, credited in its first line) | github.com/JohnHeibel/ClaudeAnimationBase | MIT: `LICENSES/ClaudeAnimationBase-LICENSE-MIT.txt` |++## Ideas credited, no code copied++| What | Where | Upstream | Licence |+|---|---|---|---|+| Closed-form springs, launch-video motion moves, the axes of the review score and the subframe motion-blur filter (Raphael Aubry) | `scripts/springs.js` (own implementation), `references/motion-kit.md`, `references/timing.md`, the rubric in `SKILL.md` and `references/quality-checklist.md`, one filter line in `scripts/export.mjs` | github.com/howseen-ai/claude-motion-design | MIT |+| Asking of every shot whether it is a page or a picture, and measuring a film's text with a script (Tejas Makwana) | `references/page-or-picture.md`, `scripts/text-audit.mjs` (own script; its corner test uses the same thresholds) | github.com/Tejashmakwana/motionmaxxing | Apache-2.0 |+| Banning the default look by name, a number in place of every adjective, and the easing, spring and stagger numbers (Florence, "Opus 5.5 Motion Lab") | `references/directed-look.md`, sections 1 and 3 (own words) | x.com/flxrnc/status/2105311836190978392 | A published guide; ideas only, none of its text or prompts |++## Needed at render time (not shipped here)++- Node 18 or later and `playwright-core` (Apache-2.0), installed per project by `scripts/new-canvas-project.sh`. It drives the Google Chrome already on the machine; no browser is downloaded.+- `ffmpeg` and `ffprobe` on the PATH.+- The watercolor style builds on Claude Animation Base (MIT), cloned into the film's own folder at a fixed commit (`references/styles/watercolor.md`). The 3D styles load three.js (MIT) from a public CDN or install it in the film's own folder, and films load their typefaces from Google Fonts.+- Optional, only when a film needs them: whisper.cpp and demucs (word times and vocal stems for a song), Python 3 with numpy and scipy (`scripts/songmap.py`), and any paid image, video, voice or music service the person chooses. The skill never spends on one without a yes to the price.++## Fonts++No font files ship in this repo. Films load the fonts their brand or style calls for; keep each font's licence with the project that uses it.++## Work we studied++Films and posts that taught something are credited, with links to their makers, in `examples/INDEX.md`. Nothing of theirs is copied here: no frames, no prompts, no code.diff --git a/assets/gallery.html b/assets/gallery.htmlnew file mode 100644index 0000000..b2aac44--- /dev/null+++ b/assets/gallery.html@@ -0,0 +1,60 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Video Styles</title>+<meta name="viewport" content="width=device-width,initial-scale=1">+<style>+:root{--bg:#f6f5f1;--card:#fff;--ink:#141414;--mute:#6b6b6b;--line:#e4e2dc;--acc:#2563eb}+@media (prefers-color-scheme:dark){:root{--bg:#111113;--card:#1a1a1e;--ink:#f2f0ea;--mute:#9a988f;--line:#2a2a30;--acc:#6f9bff}}+*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.5 -apple-system,system-ui,sans-serif;padding:40px 16px}+main{max-width:1100px;margin:0 auto}h1{font-size:40px;margin:0 0 6px;letter-spacing:-.02em}h1 em{font-family:Georgia,serif;font-weight:400;color:var(--acc)}+.sub{color:var(--mute);margin:0 0 32px}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,500px),1fr));gap:20px}+.card{background:var(--card);border:1px solid var(--line);border-radius:18px;overflow:hidden}+.imgs{display:grid;grid-template-columns:1fr 1fr;gap:2px;background:var(--line)}.imgs img{width:100%;aspect-ratio:16/9;object-fit:cover;display:block}+.body{padding:18px 20px 22px}.n{font:600 12px ui-monospace,Menlo,monospace;color:var(--acc);letter-spacing:.06em}+h2{margin:4px 0 6px;font-size:22px}p{margin:0 0 10px;color:var(--mute)}.best{font-size:14px}.best b{color:var(--ink)}+.ref{font-size:13px;color:var(--mute)}+</style></head><body><main>+<h1>Pick a <em>style</em></h1>+<p class="sub">Every video is rendered from code with Claude Opus 5.5. Choose the look, then approve the storyboard.</p>+<div class="grid">+<div class="card"><div class="imgs"><img src="previews/watercolor-a.jpg" alt="The paper boat setting out, watercolor style"><img src="previews/watercolor-b.jpg" alt="The storm peak, watercolor style"></div><div class="body"><div class="n">01</div><h2>Watercolor character</h2><p>Hand-painted brushstrokes and boiling ink lines. A character acts out a small story, like a picture book that moves.</p>+<p class="best"><b>Best for:</b> stories, music videos, anything with a journey.</p><p class="ref">Reference: "I'm Upping My P(doom)" music video</p></div></div>+<div class="card"><div class="imgs"><img src="previews/explainer-a.jpg" alt="The paper boat setting out, explainer style"><img src="previews/explainer-b.jpg" alt="The storm peak, explainer style"></div><div class="body"><div class="n">02</div><h2>Clean kinetic explainer</h2><p>White page, one accent color, giant word-by-word type with one italic word, a dithered mascot, product UI that assembles.</p>+<p class="best"><b>Best for:</b> a product or idea in 15-30 seconds.</p><p class="ref">Reference: a product explainer for a workflow tool</p></div></div>+<div class="card"><div class="imgs"><img src="previews/game-a.jpg" alt="The paper boat setting out, game style"><img src="previews/game-b.jpg" alt="The storm peak, game style"></div><div class="body"><div class="n">03</div><h2>Image-to-game cinematic</h2><p>An image model makes the art, Opus turns it into a real animated (and playable) game. Opens on a "screenshot" that comes alive.</p>+<p class="best"><b>Best for:</b> "the model built a game from my images", starring a real person.</p><p class="ref">Reference: a Mortal Kombat-style fight game (ours)</p></div></div>+<div class="card"><div class="imgs"><img src="previews/dark-a.jpg" alt="The paper boat setting out, dark style"><img src="previews/dark-b.jpg" alt="The storm peak, dark style"></div><div class="body"><div class="n">04</div><h2>Dark premium explainer</h2><p>Near-black, one warm gold accent, a glowing hero object, cinematic light. Short, big type, one idea.</p>+<p class="best"><b>Best for:</b> serious AI and B2B concepts.</p><p class="ref">Reference: an AI infrastructure concept video (fixed: shorter, bigger, higher contrast)</p></div></div>+<div class="card"><div class="imgs"><img src="previews/hud-a.jpg" alt="The paper boat setting out, hud style"><img src="previews/hud-b.jpg" alt="The storm peak, hud style"></div><div class="body"><div class="n">05</div><h2>Editorial HUD film</h2><p>Photoreal fashion-campaign footage of one character (made with an image/video model), with a code-drawn HUD: data panels, tracking brackets, a countdown, a news ticker, giant kinetic words.</p>+<p class="best"><b>Best for:</b> art pieces, brand films, a statement about AI and culture.</p><p class="ref">Reference: an Opus 5.5 film with Midjourney and a moodboard</p></div></div>+<div class="card"><div class="imgs"><img src="previews/title-a.jpg" alt="The paper boat setting out, title style"><img src="previews/title-b.jpg" alt="The storm peak, title style"></div><div class="body"><div class="n">06</div><h2>Broadcast title sequence</h2><p>Beat-locked typography like a sports-season opener: a color world per chapter, split-flap letters, marquee outlines, one signature visual each, HUD with BPM and bar count.</p>+<p class="best"><b>Best for:</b> lineups and comparisons, a launch with several features, a season or event opener.</p><p class="ref">Reference: "THE FRONTIER" (Opus 5.5, 15 minutes)</p></div></div>+<div class="card"><div class="imgs"><img src="previews/short-a.jpg" alt="The paper boat setting out, short style"><img src="previews/short-b.jpg" alt="The storm peak, short style"></div><div class="body"><div class="n">07</div><h2>Cinematic animated short</h2><p>A wordless 1-3 minute story with a real emotional arc: one relationship, one repeated gesture, years passing, a payoff. Letterboxed, soft stylized 3D, moonlit palette.</p>+<p class="best"><b>Best for:</b> stories that make people feel something; a brand's "why"; a tribute.</p><p class="ref">Reference: "Goodnight, Keeper"</p></div></div>+<div class="card"><div class="imgs"><img src="previews/lyric-a.jpg" alt="The paper boat setting out, lyric style"><img src="previews/lyric-b.jpg" alt="The storm peak, lyric style"></div><div class="body"><div class="n">08</div><h2>Kinetic lyric video</h2><p>The words are the visuals: every sung line becomes its own typographic scene with a visual metaphor. Black + one hot accent, a paper-white "technical" world for contrast.</p>+<p class="best"><b>Best for:</b> music videos without characters, songs with strong lines.</p><p class="ref">Reference: a P(doom) lyric video</p></div></div>+<div class="card"><div class="imgs"><img src="previews/glow-a.jpg" alt="The paper boat setting out, glow style"><img src="previews/glow-b.jpg" alt="The storm peak, glow style"></div><div class="body"><div class="n">09</div><h2>Painterly glow music video</h2><p>Moving oil-paint: swirling Van Gogh brushstrokes, deep night blues, one glowing ember-lit figure through symbolic scenes. Dreamlike, emotional.</p>+<p class="best"><b>Best for:</b> turning a song (Suno or yours) into an emotional clip.</p><p class="ref">Reference: a full Suno-style song turned into a clip</p></div></div>+<div class="card"><div class="imgs"><img src="previews/manifesto-a.jpg" alt="The paper boat setting out, manifesto style"><img src="previews/manifesto-b.jpg" alt="The storm peak, manifesto style"></div><div class="body"><div class="n">10</div><h2>Manifesto film</h2><p>A serious idea in 60-90 s: a hard fact, a true story, the turn, the vision as a numbered list, a callback. Black, paper and one signal yellow; photos turned into line art; terminals as proof.</p>+<p class="best"><b>Best for:</b> announcing a company, an initiative, a thesis. B2B and AI.</p><p class="ref">Reference: Thom Wolf / Hugging Face "Open Alignment"</p></div></div>+<div class="card"><div class="imgs"><img src="previews/teach-a.jpg" alt="The paper boat setting out, teach style"><img src="previews/teach-b.jpg" alt="The storm peak, teach style"></div><div class="body"><div class="n">11</div><h2>3D teaching song</h2><p>A song that teaches: each lyric line is demonstrated in a 3D world of the subject, the sung word lights up orange, a recurring chart shows progress.</p>+<p class="best"><b>Best for:</b> turning a book, course, paper or product into a song people rewatch.</p><p class="ref">Reference: "Chasing the Roofline"</p></div></div>+<div class="card"><div class="imgs"><img src="previews/mono-a.jpg" alt="The paper boat setting out, mono style"><img src="previews/mono-b.jpg" alt="The storm peak, mono style"></div><div class="body"><div class="n">12</div><h2>Monochrome launch film</h2><p>Pure black and white, hard section inversions: liquid chrome and dithered matter in the black world, quant charts with live ticking numbers in the white world, icon-scatter storytelling, one gold prestige moment.</p>+<p class="best"><b>Best for:</b> fintech, crypto and premium dev-tool launches; brands with weak or undecided colors.</p><p class="ref">Reference: "Frontier Traders" (Opus 5.5, 20 minutes)</p></div></div>+<div class="card"><div class="imgs"><img src="previews/crayon-a.jpg" alt="The paper boat setting out, crayon style"><img src="previews/crayon-b.jpg" alt="The storm peak, crayon style"></div><div class="body"><div class="n">13</div><h2>Crayon storybook</h2><p>A child's picture book in motion: wobbly blue ballpoint contour, crayon-scribble fills on cream paper, a handwritten caption strip as the timeline, squash-and-stretch critters with one big eye. Imperfection is the aesthetic, so moving characters never break.</p>+<p class="best"><b>Best for:</b> history and science explainers, "X in under a minute", kids' subjects, family films, characters that move a lot.</p><p class="ref">Reference: "The history of dinosaurs" (Sonnet 5.5, square)</p></div></div>+<div class="card"><div class="imgs"><img src="previews/papercut-a.jpg" alt="The paper boat setting out, Paper cut-out"><img src="previews/papercut-b.jpg" alt="The storm peak, Paper cut-out"></div><div class="body"><div class="n">14</div><h2>Paper cut-out</h2><p>Flat cut and torn paper layers with real drop shadows between them, hinge-and-pivot puppet motion, construction-paper colors, fiber fringe on torn edges. Variants: lightbox glow, pop-up book.</p>+<p class="best"><b>Best for:</b> songs, histories, warm brand stories.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/pixel-a.jpg" alt="The paper boat setting out, Pixel art film"><img src="previews/pixel-b.jpg" alt="The storm peak, Pixel art film"></div><div class="body"><div class="n">15</div><h2>Pixel art film</h2><p>A hard pixel grid at tiny logical resolution, per-scene limited palettes, Bayer-dithered skies, sprite characters that snap between frames. Variants: lofi loop, 16-bit RPG, HD-2D, demoscene.</p>+<p class="best"><b>Best for:</b> nostalgia stories, game-flavored product spots, lofi loops.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/sketch-a.jpg" alt="The paper boat setting out, Hand-drawn sketchbook"><img src="previews/sketch-b.jpg" alt="The storm peak, Hand-drawn sketchbook"></div><div class="body"><div class="n">16</div><h2>Hand-drawn sketchbook</h2><p>Pen, pencil and charcoal lines that draw themselves on paper grain, hatching for tone, construction lines left visible, handwritten margin notes, one accent wash.</p>+<p class="best"><b>Best for:</b> intimate stories, explainers that build up, "the film draws itself".</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/chrome-a.jpg" alt="The paper boat setting out, Glossy chrome showreel"><img src="previews/chrome-b.jpg" alt="The storm peak, Glossy chrome showreel"></div><div class="body"><div class="n">17</div><h2>Glossy chrome showreel</h2><p>Studio-lit liquid-metal type and objects on bold poster fields, beat-locked vignettes, hard cuts, extreme easing, persistent HUD with BPM and bar count.</p>+<p class="best"><b>Best for:</b> launches, brand stings, motion-design flexes.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/ascii-a.jpg" alt="The paper boat setting out, ASCII / CRT terminal"><img src="previews/ascii-b.jpg" alt="The storm peak, ASCII / CRT terminal"></div><div class="body"><div class="n">18</div><h2>ASCII / CRT terminal</h2><p>Everything built from monospace characters on a phosphor tube: scenes as character-density fields, scanlines, prompts and log lines as narration, one red alert line allowed.</p>+<p class="best"><b>Best for:</b> dev-tool launches, hacker stories, anything for a technical audience.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/ink-a.jpg" alt="The paper boat setting out, Ink wash (sumi-e)"><img src="previews/ink-b.jpg" alt="The storm peak, Ink wash (sumi-e)"></div><div class="body"><div class="n">19</div><h2>Ink wash (sumi-e)</h2><p>Loaded brush on rice paper, five ink dilutions, bleed halos and flying-white dry strokes, vast negative space, one cinnabar seal stamp. Strokes draw themselves.</p>+<p class="best"><b>Best for:</b> contemplative, heritage and reflective pieces; calm authority.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/penciltest-a.jpg" alt="The paper boat setting out, animator pencil test"><img src="previews/penciltest-b.jpg" alt="The storm peak dissected, animator pencil test"></div><div class="body"><div class="n">20</div><h2>Animator's pencil test</h2><p>An animator's desk test: red clean pencil over blue construction, onion skins, a frame counter on twos and ones. The character performs, the film freezes to dissect the motion with principle labels and a spacing chart, then an APPROVED stamp slams in.</p>+<p class="best"><b>Best for:</b> showing craft and process, character reveals, behind-the-scenes halves of character films.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+<div class="card"><div class="imgs"><img src="previews/riso-a.jpg" alt="The paper boat setting out, riso pop"><img src="previews/riso-b.jpg" alt="The storm peak, riso pop"></div><div class="body"><div class="n">21</div><h2>Riso pop</h2><p>A three-ink risograph world: yellow, fluorescent pink and blue halftone screens overprinting on cream paper, slight misregistration, flat mid-century figures, a mascot protagonist, one satirical gag per line, typewriter captions with strikethroughs.</p>+<p class="best"><b>Best for:</b> satire, internet-culture music videos, memes, AI commentary.</p><p class="ref">Previews: THE PAPER BOAT, rendered by us</p></div></div>+</div></main></body></html>diff --git a/assets/logo/take-one-logo-on-light.svg b/assets/logo/take-one-logo-on-light.svgnew file mode 100644index 0000000..72a92ff--- /dev/null+++ b/assets/logo/take-one-logo-on-light.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -20 476 124" width="952" height="248" role="img" aria-label="Take One"><g transform="translate(0 0)"><rect x="0" y="26" width="100" height="74" rx="16" fill="#d97757"/><g transform="translate(0 24) rotate(-12.03)"><clipPath id="arm"><rect x="0" y="-17" width="100" height="17"/></clipPath><g clip-path="url(#arm)"><rect x="0" y="-17" width="100" height="17" fill="#17110e"/><g fill="#f8f2e3"><path d="M10 -17H22L12 0H0Z"/><path d="M34 -17H46L36 0H24Z"/><path d="M58 -17H70L60 0H48Z"/><path d="M82 -17H94L84 0H72Z"/><path d="M106 -17H118L108 0H96Z"/></g></g></g><path d="M38.2 84.7V77.46H47.38V56.95H38.18V51.5Q40.37 51.34 43.04 50.55Q45.7 49.77 48.33 48.61Q50.95 47.44 53.01 46.2H56.58V77.46H65.25V84.7Z" fill="#17110e"/></g><path d="M147.61 91V46.16H129.97V36.09H177.28V46.16H159.59V91Z M187.28 91.96Q185.19 91.96 182.81 91.49Q180.43 91.01 178.34 89.77Q176.25 88.52 174.95 86.18Q173.65 83.84 173.65 80.12Q173.65 75.71 175.58 72.85Q177.51 69.98 181.05 68.35Q184.59 66.72 189.55 66.06Q194.51 65.39 200.53 65.39V62.25Q200.53 60.43 199.91 59.06Q199.29 57.7 197.84 56.92Q196.38 56.14 193.68 56.14Q191.07 56.14 189.44 56.78Q187.82 57.41 187.11 58.4Q186.41 59.39 186.41 60.58V61.52H175.62Q175.54 61.14 175.54 60.77Q175.54 60.41 175.54 59.9Q175.54 56.23 177.78 53.53Q180.01 50.83 184.09 49.38Q188.16 47.93 193.67 47.93Q199.45 47.93 203.44 49.46Q207.43 50.99 209.53 53.95Q211.63 56.92 211.63 61.37V80.48Q211.63 81.95 212.46 82.65Q213.29 83.35 214.38 83.35H217.01V90.61Q216.17 90.98 214.51 91.44Q212.84 91.9 210.44 91.9Q208.12 91.9 206.31 91.23Q204.51 90.55 203.31 89.29Q202.11 88.03 201.61 86.3H201.12Q199.69 87.95 197.74 89.24Q195.79 90.54 193.21 91.25Q190.63 91.96 187.28 91.96ZM191 83.54Q193.21 83.54 194.99 82.88Q196.76 82.22 197.98 81.06Q199.19 79.89 199.86 78.22Q200.53 76.54 200.53 74.57V72.29Q196.06 72.29 192.52 72.88Q188.97 73.48 186.95 74.93Q184.94 76.38 184.94 78.92Q184.94 80.39 185.64 81.43Q186.35 82.46 187.71 83Q189.08 83.54 191 83.54Z M220.63 91V33.11H231.73V66.42L246.5 48.89H259.49L245.08 65.36L260.2 91H247.5L237.81 73.26L231.73 79.13V91Z M280.73 91.96Q273.82 91.96 269.11 89.6Q264.39 87.24 261.99 82.36Q259.58 77.48 259.58 69.94Q259.58 62.38 261.98 57.53Q264.37 52.68 269.04 50.3Q273.7 47.93 280.52 47.93Q286.93 47.93 291.31 50.22Q295.7 52.52 297.93 57.27Q300.17 62.03 300.17 69.57V72.41H270.87Q270.99 76.11 271.99 78.66Q272.99 81.21 275.12 82.47Q277.25 83.74 280.73 83.74Q282.63 83.74 284.21 83.26Q285.78 82.78 286.92 81.82Q288.06 80.85 288.68 79.42Q289.3 77.98 289.3 76.14H300.17Q300.17 80.09 298.76 83.07Q297.35 86.04 294.75 88.01Q292.15 89.97 288.59 90.97Q285.03 91.96 280.73 91.96ZM271.01 65.39H288.72Q288.72 62.96 288.15 61.23Q287.57 59.51 286.53 58.37Q285.48 57.23 284.01 56.72Q282.53 56.21 280.66 56.21Q277.65 56.21 275.61 57.21Q273.56 58.22 272.48 60.25Q271.39 62.28 271.01 65.39Z M346.86 91.96Q338.13 91.96 331.8 88.85Q325.48 85.75 322.11 79.42Q318.75 73.09 318.75 63.54Q318.75 53.91 322.11 47.63Q325.48 41.34 331.8 38.23Q338.13 35.13 346.86 35.13Q355.68 35.13 361.97 38.23Q368.27 41.34 371.63 47.63Q375 53.91 375 63.54Q375 73.09 371.63 79.42Q368.27 85.75 361.97 88.85Q355.68 91.96 346.86 91.96ZM346.86 82.2Q350.74 82.2 353.7 81.06Q356.65 79.93 358.66 77.71Q360.67 75.5 361.7 72.26Q362.74 69.03 362.74 64.85V62.36Q362.74 58.12 361.7 54.85Q360.67 51.58 358.66 49.37Q356.65 47.16 353.7 46.02Q350.74 44.88 346.86 44.88Q342.98 44.88 340.03 46.02Q337.08 47.16 335.08 49.37Q333.07 51.58 332.07 54.85Q331.07 58.12 331.07 62.36V64.85Q331.07 69.03 332.07 72.26Q333.07 75.5 335.08 77.71Q337.08 79.93 340.03 81.06Q342.98 82.2 346.86 82.2Z M381.82 91V48.89H391.04L391.89 54.66H392.45Q393.94 52.62 395.97 51.1Q397.99 49.59 400.55 48.76Q403.11 47.93 406.12 47.93Q410.34 47.93 413.46 49.46Q416.57 51 418.3 54.27Q420.02 57.54 420.02 62.83V91H408.86V64.62Q408.86 62.57 408.38 61.18Q407.89 59.79 406.97 58.89Q406.05 58 404.7 57.59Q403.36 57.18 401.69 57.18Q399.19 57.18 397.21 58.38Q395.22 59.58 394.07 61.66Q392.92 63.73 392.92 66.45V91Z M447.2 91.96Q440.29 91.96 435.58 89.6Q430.86 87.24 428.46 82.36Q426.05 77.48 426.05 69.94Q426.05 62.38 428.45 57.53Q430.84 52.68 435.51 50.3Q440.17 47.93 446.99 47.93Q453.4 47.93 457.79 50.22Q462.17 52.52 464.4 57.27Q466.64 62.03 466.64 69.57V72.41H437.34Q437.46 76.11 438.46 78.66Q439.46 81.21 441.59 82.47Q443.72 83.74 447.2 83.74Q449.11 83.74 450.68 83.26Q452.25 82.78 453.39 81.82Q454.53 80.85 455.15 79.42Q455.77 77.98 455.77 76.14H466.64Q466.64 80.09 465.23 83.07Q463.82 86.04 461.22 88.01Q458.63 89.97 455.07 90.97Q451.51 91.96 447.2 91.96ZM437.48 65.39H455.19Q455.19 62.96 454.62 61.23Q454.04 59.51 453 58.37Q451.95 57.23 450.48 56.72Q449 56.21 447.13 56.21Q444.12 56.21 442.08 57.21Q440.03 58.22 438.95 60.25Q437.86 62.28 437.48 65.39Z" fill="#17110e"/></svg>diff --git a/assets/logo/take-one-logo-stacked-on-light.svg b/assets/logo/take-one-logo-stacked-on-light.svgnew file mode 100644index 0000000..b7068a6--- /dev/null+++ b/assets/logo/take-one-logo-stacked-on-light.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-216 -20 432 236" width="864" height="472" role="img" aria-label="Take One"><g transform="translate(-50 0)"><rect x="0" y="26" width="100" height="74" rx="16" fill="#d97757"/><g transform="translate(0 24) rotate(-12.03)"><clipPath id="arm"><rect x="0" y="-17" width="100" height="17"/></clipPath><g clip-path="url(#arm)"><rect x="0" y="-17" width="100" height="17" fill="#17110e"/><g fill="#f8f2e3"><path d="M10 -17H22L12 0H0Z"/><path d="M34 -17H46L36 0H24Z"/><path d="M58 -17H70L60 0H48Z"/><path d="M82 -17H94L84 0H72Z"/><path d="M106 -17H118L108 0H96Z"/></g></g></g><path d="M38.2 84.7V77.46H47.38V56.95H38.18V51.5Q40.37 51.34 43.04 50.55Q45.7 49.77 48.33 48.61Q50.95 47.44 53.01 46.2H56.58V77.46H65.25V84.7Z" fill="#17110e"/></g><path d="M-180.36 196V142.19H-201.53V130.1H-144.76V142.19H-165.99V196Z M-132.76 197.15Q-135.27 197.15 -138.12 196.58Q-140.97 196.01 -143.48 194.52Q-146 193.03 -147.56 190.22Q-149.12 187.41 -149.12 182.94Q-149.12 177.66 -146.8 174.22Q-144.49 170.78 -140.24 168.82Q-135.99 166.86 -130.03 166.07Q-124.08 165.27 -116.85 165.27V161.5Q-116.85 159.31 -117.6 157.68Q-118.34 156.04 -120.09 155.11Q-121.83 154.17 -125.07 154.17Q-128.21 154.17 -130.16 154.93Q-132.11 155.69 -132.96 156.88Q-133.8 158.06 -133.8 159.49V160.63H-146.75Q-146.85 160.17 -146.85 159.73Q-146.85 159.29 -146.85 158.68Q-146.85 154.28 -144.16 151.04Q-141.48 147.8 -136.59 146.05Q-131.7 144.31 -125.09 144.31Q-118.15 144.31 -113.37 146.15Q-108.58 147.98 -106.06 151.55Q-103.54 155.11 -103.54 160.45V183.38Q-103.54 185.14 -102.54 185.98Q-101.55 186.82 -100.24 186.82H-97.08V195.53Q-98.08 195.98 -100.09 196.53Q-102.09 197.08 -104.96 197.08Q-107.75 197.08 -109.92 196.27Q-112.08 195.47 -113.52 193.95Q-114.96 192.44 -115.56 190.37H-116.15Q-117.87 192.34 -120.21 193.89Q-122.55 195.44 -125.65 196.3Q-128.74 197.15 -132.76 197.15ZM-128.29 187.05Q-125.64 187.05 -123.51 186.26Q-121.38 185.47 -119.92 184.07Q-118.47 182.67 -117.66 180.66Q-116.85 178.65 -116.85 176.29V173.54Q-122.22 173.54 -126.47 174.26Q-130.73 174.97 -133.15 176.71Q-135.57 178.45 -135.57 181.5Q-135.57 183.27 -134.72 184.51Q-133.88 185.76 -132.24 186.4Q-130.6 187.05 -128.29 187.05Z M-92.74 196V126.53H-79.42V166.51L-61.69 145.46H-46.11L-63.4 165.23L-45.25 196H-60.49L-72.12 174.72L-79.42 181.75V196Z M-20.61 197.15Q-28.91 197.15 -34.57 194.32Q-40.22 191.49 -43.11 185.63Q-46 179.78 -46 170.73Q-46 161.65 -43.12 155.83Q-40.24 150.02 -34.65 147.16Q-29.05 144.31 -20.86 144.31Q-13.17 144.31 -7.91 147.07Q-2.66 149.82 0.03 155.53Q2.71 161.24 2.71 170.28V173.69H-32.45Q-32.3 178.13 -31.11 181.19Q-29.91 184.25 -27.35 185.77Q-24.8 187.29 -20.62 187.29Q-18.33 187.29 -16.44 186.71Q-14.55 186.14 -13.19 184.98Q-11.82 183.82 -11.08 182.1Q-10.33 180.38 -10.33 178.17H2.71Q2.71 182.91 1.02 186.48Q-0.67 190.05 -3.79 192.41Q-6.91 194.76 -11.18 195.96Q-15.45 197.15 -20.61 197.15ZM-32.28 165.27H-11.03Q-11.03 162.35 -11.72 160.28Q-12.4 158.21 -13.66 156.84Q-14.91 155.48 -16.68 154.86Q-18.46 154.25 -20.7 154.25Q-24.32 154.25 -26.77 155.45Q-29.22 156.66 -30.52 159.1Q-31.82 161.53 -32.28 165.27Z M58.74 197.15Q48.26 197.15 40.67 193.42Q33.08 189.7 29.04 182.1Q25.01 174.51 25.01 163.05Q25.01 151.5 29.04 143.95Q33.08 136.4 40.67 132.68Q48.26 128.95 58.74 128.95Q69.32 128.95 76.87 132.68Q84.43 136.4 88.47 143.95Q92.5 151.5 92.5 163.05Q92.5 174.51 88.47 182.1Q84.43 189.7 76.87 193.42Q69.32 197.15 58.74 197.15ZM58.74 185.44Q63.4 185.44 66.94 184.08Q70.48 182.71 72.9 180.06Q75.31 177.4 76.55 173.52Q77.79 169.63 77.79 164.62V161.63Q77.79 156.54 76.55 152.62Q75.31 148.7 72.9 146.05Q70.48 143.39 66.94 142.03Q63.4 140.66 58.74 140.66Q54.08 140.66 50.54 142.03Q47 143.39 44.6 146.05Q42.19 148.7 40.99 152.62Q39.79 156.54 39.79 161.63V164.62Q39.79 169.63 40.99 173.52Q42.19 177.4 44.6 180.06Q47 182.71 50.54 184.08Q54.08 185.44 58.74 185.44Z M100.69 196V145.46H111.76L112.78 152.39H113.45Q115.24 149.94 117.67 148.12Q120.09 146.31 123.17 145.31Q126.24 144.31 129.85 144.31Q134.92 144.31 138.66 146.15Q142.4 148 144.47 151.92Q146.54 155.84 146.54 162.19V196H133.14V164.35Q133.14 161.89 132.56 160.22Q131.98 158.54 130.87 157.47Q129.77 156.4 128.15 155.91Q126.54 155.42 124.53 155.42Q121.53 155.42 119.15 156.86Q116.78 158.3 115.39 160.79Q114.01 163.28 114.01 166.54V196Z M179.15 197.15Q170.86 197.15 165.2 194.32Q159.54 191.49 156.66 185.63Q153.77 179.78 153.77 170.73Q153.77 161.65 156.64 155.83Q159.52 150.02 165.12 147.16Q170.71 144.31 178.9 144.31Q186.59 144.31 191.85 147.07Q197.11 149.82 199.79 155.53Q202.47 161.24 202.47 170.28V173.69H167.31Q167.46 178.13 168.66 181.19Q169.86 184.25 172.41 185.77Q174.97 187.29 179.14 187.29Q181.43 187.29 183.32 186.71Q185.21 186.14 186.58 184.98Q187.94 183.82 188.69 182.1Q189.43 180.38 189.43 178.17H202.47Q202.47 182.91 200.78 186.48Q199.09 190.05 195.98 192.41Q192.86 194.76 188.59 195.96Q184.31 197.15 179.15 197.15ZM167.48 165.27H188.74Q188.74 162.35 188.05 160.28Q187.36 158.21 186.11 156.84Q184.85 155.48 183.08 154.86Q181.31 154.25 179.07 154.25Q175.45 154.25 173 155.45Q170.55 156.66 169.25 159.1Q167.94 161.53 167.48 165.27Z" fill="#17110e"/></svg>diff --git a/assets/logo/take-one-logo-stacked.svg b/assets/logo/take-one-logo-stacked.svgnew file mode 100644index 0000000..8126611--- /dev/null+++ b/assets/logo/take-one-logo-stacked.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-216 -20 432 236" width="864" height="472" role="img" aria-label="Take One"><g transform="translate(-50 0)"><rect x="0" y="26" width="100" height="74" rx="16" fill="#d97757"/><g transform="translate(0 24) rotate(-12.03)"><clipPath id="arm"><rect x="0" y="-17" width="100" height="17"/></clipPath><g clip-path="url(#arm)"><rect x="0" y="-17" width="100" height="17" fill="#ecebe8"/><g fill="#17110e"><path d="M10 -17H22L12 0H0Z"/><path d="M34 -17H46L36 0H24Z"/><path d="M58 -17H70L60 0H48Z"/><path d="M82 -17H94L84 0H72Z"/><path d="M106 -17H118L108 0H96Z"/></g></g></g><path d="M38.2 84.7V77.46H47.38V56.95H38.18V51.5Q40.37 51.34 43.04 50.55Q45.7 49.77 48.33 48.61Q50.95 47.44 53.01 46.2H56.58V77.46H65.25V84.7Z" fill="#17110e"/></g><path d="M-180.36 196V142.19H-201.53V130.1H-144.76V142.19H-165.99V196Z M-132.76 197.15Q-135.27 197.15 -138.12 196.58Q-140.97 196.01 -143.48 194.52Q-146 193.03 -147.56 190.22Q-149.12 187.41 -149.12 182.94Q-149.12 177.66 -146.8 174.22Q-144.49 170.78 -140.24 168.82Q-135.99 166.86 -130.03 166.07Q-124.08 165.27 -116.85 165.27V161.5Q-116.85 159.31 -117.6 157.68Q-118.34 156.04 -120.09 155.11Q-121.83 154.17 -125.07 154.17Q-128.21 154.17 -130.16 154.93Q-132.11 155.69 -132.96 156.88Q-133.8 158.06 -133.8 159.49V160.63H-146.75Q-146.85 160.17 -146.85 159.73Q-146.85 159.29 -146.85 158.68Q-146.85 154.28 -144.16 151.04Q-141.48 147.8 -136.59 146.05Q-131.7 144.31 -125.09 144.31Q-118.15 144.31 -113.37 146.15Q-108.58 147.98 -106.06 151.55Q-103.54 155.11 -103.54 160.45V183.38Q-103.54 185.14 -102.54 185.98Q-101.55 186.82 -100.24 186.82H-97.08V195.53Q-98.08 195.98 -100.09 196.53Q-102.09 197.08 -104.96 197.08Q-107.75 197.08 -109.92 196.27Q-112.08 195.47 -113.52 193.95Q-114.96 192.44 -115.56 190.37H-116.15Q-117.87 192.34 -120.21 193.89Q-122.55 195.44 -125.65 196.3Q-128.74 197.15 -132.76 197.15ZM-128.29 187.05Q-125.64 187.05 -123.51 186.26Q-121.38 185.47 -119.92 184.07Q-118.47 182.67 -117.66 180.66Q-116.85 178.65 -116.85 176.29V173.54Q-122.22 173.54 -126.47 174.26Q-130.73 174.97 -133.15 176.71Q-135.57 178.45 -135.57 181.5Q-135.57 183.27 -134.72 184.51Q-133.88 185.76 -132.24 186.4Q-130.6 187.05 -128.29 187.05Z M-92.74 196V126.53H-79.42V166.51L-61.69 145.46H-46.11L-63.4 165.23L-45.25 196H-60.49L-72.12 174.72L-79.42 181.75V196Z M-20.61 197.15Q-28.91 197.15 -34.57 194.32Q-40.22 191.49 -43.11 185.63Q-46 179.78 -46 170.73Q-46 161.65 -43.12 155.83Q-40.24 150.02 -34.65 147.16Q-29.05 144.31 -20.86 144.31Q-13.17 144.31 -7.91 147.07Q-2.66 149.82 0.03 155.53Q2.71 161.24 2.71 170.28V173.69H-32.45Q-32.3 178.13 -31.11 181.19Q-29.91 184.25 -27.35 185.77Q-24.8 187.29 -20.62 187.29Q-18.33 187.29 -16.44 186.71Q-14.55 186.14 -13.19 184.98Q-11.82 183.82 -11.08 182.1Q-10.33 180.38 -10.33 178.17H2.71Q2.71 182.91 1.02 186.48Q-0.67 190.05 -3.79 192.41Q-6.91 194.76 -11.18 195.96Q-15.45 197.15 -20.61 197.15ZM-32.28 165.27H-11.03Q-11.03 162.35 -11.72 160.28Q-12.4 158.21 -13.66 156.84Q-14.91 155.48 -16.68 154.86Q-18.46 154.25 -20.7 154.25Q-24.32 154.25 -26.77 155.45Q-29.22 156.66 -30.52 159.1Q-31.82 161.53 -32.28 165.27Z M58.74 197.15Q48.26 197.15 40.67 193.42Q33.08 189.7 29.04 182.1Q25.01 174.51 25.01 163.05Q25.01 151.5 29.04 143.95Q33.08 136.4 40.67 132.68Q48.26 128.95 58.74 128.95Q69.32 128.95 76.87 132.68Q84.43 136.4 88.47 143.95Q92.5 151.5 92.5 163.05Q92.5 174.51 88.47 182.1Q84.43 189.7 76.87 193.42Q69.32 197.15 58.74 197.15ZM58.74 185.44Q63.4 185.44 66.94 184.08Q70.48 182.71 72.9 180.06Q75.31 177.4 76.55 173.52Q77.79 169.63 77.79 164.62V161.63Q77.79 156.54 76.55 152.62Q75.31 148.7 72.9 146.05Q70.48 143.39 66.94 142.03Q63.4 140.66 58.74 140.66Q54.08 140.66 50.54 142.03Q47 143.39 44.6 146.05Q42.19 148.7 40.99 152.62Q39.79 156.54 39.79 161.63V164.62Q39.79 169.63 40.99 173.52Q42.19 177.4 44.6 180.06Q47 182.71 50.54 184.08Q54.08 185.44 58.74 185.44Z M100.69 196V145.46H111.76L112.78 152.39H113.45Q115.24 149.94 117.67 148.12Q120.09 146.31 123.17 145.31Q126.24 144.31 129.85 144.31Q134.92 144.31 138.66 146.15Q142.4 148 144.47 151.92Q146.54 155.84 146.54 162.19V196H133.14V164.35Q133.14 161.89 132.56 160.22Q131.98 158.54 130.87 157.47Q129.77 156.4 128.15 155.91Q126.54 155.42 124.53 155.42Q121.53 155.42 119.15 156.86Q116.78 158.3 115.39 160.79Q114.01 163.28 114.01 166.54V196Z M179.15 197.15Q170.86 197.15 165.2 194.32Q159.54 191.49 156.66 185.63Q153.77 179.78 153.77 170.73Q153.77 161.65 156.64 155.83Q159.52 150.02 165.12 147.16Q170.71 144.31 178.9 144.31Q186.59 144.31 191.85 147.07Q197.11 149.82 199.79 155.53Q202.47 161.24 202.47 170.28V173.69H167.31Q167.46 178.13 168.66 181.19Q169.86 184.25 172.41 185.77Q174.97 187.29 179.14 187.29Q181.43 187.29 183.32 186.71Q185.21 186.14 186.58 184.98Q187.94 183.82 188.69 182.1Q189.43 180.38 189.43 178.17H202.47Q202.47 182.91 200.78 186.48Q199.09 190.05 195.98 192.41Q192.86 194.76 188.59 195.96Q184.31 197.15 179.15 197.15ZM167.48 165.27H188.74Q188.74 162.35 188.05 160.28Q187.36 158.21 186.11 156.84Q184.85 155.48 183.08 154.86Q181.31 154.25 179.07 154.25Q175.45 154.25 173 155.45Q170.55 156.66 169.25 159.1Q167.94 161.53 167.48 165.27Z" fill="#ecebe8"/></svg>diff --git a/assets/logo/take-one-logo.svg b/assets/logo/take-one-logo.svgnew file mode 100644index 0000000..0907540--- /dev/null+++ b/assets/logo/take-one-logo.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -20 476 124" width="952" height="248" role="img" aria-label="Take One"><g transform="translate(0 0)"><rect x="0" y="26" width="100" height="74" rx="16" fill="#d97757"/><g transform="translate(0 24) rotate(-12.03)"><clipPath id="arm"><rect x="0" y="-17" width="100" height="17"/></clipPath><g clip-path="url(#arm)"><rect x="0" y="-17" width="100" height="17" fill="#ecebe8"/><g fill="#17110e"><path d="M10 -17H22L12 0H0Z"/><path d="M34 -17H46L36 0H24Z"/><path d="M58 -17H70L60 0H48Z"/><path d="M82 -17H94L84 0H72Z"/><path d="M106 -17H118L108 0H96Z"/></g></g></g><path d="M38.2 84.7V77.46H47.38V56.95H38.18V51.5Q40.37 51.34 43.04 50.55Q45.7 49.77 48.33 48.61Q50.95 47.44 53.01 46.2H56.58V77.46H65.25V84.7Z" fill="#17110e"/></g><path d="M147.61 91V46.16H129.97V36.09H177.28V46.16H159.59V91Z M187.28 91.96Q185.19 91.96 182.81 91.49Q180.43 91.01 178.34 89.77Q176.25 88.52 174.95 86.18Q173.65 83.84 173.65 80.12Q173.65 75.71 175.58 72.85Q177.51 69.98 181.05 68.35Q184.59 66.72 189.55 66.06Q194.51 65.39 200.53 65.39V62.25Q200.53 60.43 199.91 59.06Q199.29 57.7 197.84 56.92Q196.38 56.14 193.68 56.14Q191.07 56.14 189.44 56.78Q187.82 57.41 187.11 58.4Q186.41 59.39 186.41 60.58V61.52H175.62Q175.54 61.14 175.54 60.77Q175.54 60.41 175.54 59.9Q175.54 56.23 177.78 53.53Q180.01 50.83 184.09 49.38Q188.16 47.93 193.67 47.93Q199.45 47.93 203.44 49.46Q207.43 50.99 209.53 53.95Q211.63 56.92 211.63 61.37V80.48Q211.63 81.95 212.46 82.65Q213.29 83.35 214.38 83.35H217.01V90.61Q216.17 90.98 214.51 91.44Q212.84 91.9 210.44 91.9Q208.12 91.9 206.31 91.23Q204.51 90.55 203.31 89.29Q202.11 88.03 201.61 86.3H201.12Q199.69 87.95 197.74 89.24Q195.79 90.54 193.21 91.25Q190.63 91.96 187.28 91.96ZM191 83.54Q193.21 83.54 194.99 82.88Q196.76 82.22 197.98 81.06Q199.19 79.89 199.86 78.22Q200.53 76.54 200.53 74.57V72.29Q196.06 72.29 192.52 72.88Q188.97 73.48 186.95 74.93Q184.94 76.38 184.94 78.92Q184.94 80.39 185.64 81.43Q186.35 82.46 187.71 83Q189.08 83.54 191 83.54Z M220.63 91V33.11H231.73V66.42L246.5 48.89H259.49L245.08 65.36L260.2 91H247.5L237.81 73.26L231.73 79.13V91Z M280.73 91.96Q273.82 91.96 269.11 89.6Q264.39 87.24 261.99 82.36Q259.58 77.48 259.58 69.94Q259.58 62.38 261.98 57.53Q264.37 52.68 269.04 50.3Q273.7 47.93 280.52 47.93Q286.93 47.93 291.31 50.22Q295.7 52.52 297.93 57.27Q300.17 62.03 300.17 69.57V72.41H270.87Q270.99 76.11 271.99 78.66Q272.99 81.21 275.12 82.47Q277.25 83.74 280.73 83.74Q282.63 83.74 284.21 83.26Q285.78 82.78 286.92 81.82Q288.06 80.85 288.68 79.42Q289.3 77.98 289.3 76.14H300.17Q300.17 80.09 298.76 83.07Q297.35 86.04 294.75 88.01Q292.15 89.97 288.59 90.97Q285.03 91.96 280.73 91.96ZM271.01 65.39H288.72Q288.72 62.96 288.15 61.23Q287.57 59.51 286.53 58.37Q285.48 57.23 284.01 56.72Q282.53 56.21 280.66 56.21Q277.65 56.21 275.61 57.21Q273.56 58.22 272.48 60.25Q271.39 62.28 271.01 65.39Z M346.86 91.96Q338.13 91.96 331.8 88.85Q325.48 85.75 322.11 79.42Q318.75 73.09 318.75 63.54Q318.75 53.91 322.11 47.63Q325.48 41.34 331.8 38.23Q338.13 35.13 346.86 35.13Q355.68 35.13 361.97 38.23Q368.27 41.34 371.63 47.63Q375 53.91 375 63.54Q375 73.09 371.63 79.42Q368.27 85.75 361.97 88.85Q355.68 91.96 346.86 91.96ZM346.86 82.2Q350.74 82.2 353.7 81.06Q356.65 79.93 358.66 77.71Q360.67 75.5 361.7 72.26Q362.74 69.03 362.74 64.85V62.36Q362.74 58.12 361.7 54.85Q360.67 51.58 358.66 49.37Q356.65 47.16 353.7 46.02Q350.74 44.88 346.86 44.88Q342.98 44.88 340.03 46.02Q337.08 47.16 335.08 49.37Q333.07 51.58 332.07 54.85Q331.07 58.12 331.07 62.36V64.85Q331.07 69.03 332.07 72.26Q333.07 75.5 335.08 77.71Q337.08 79.93 340.03 81.06Q342.98 82.2 346.86 82.2Z M381.82 91V48.89H391.04L391.89 54.66H392.45Q393.94 52.62 395.97 51.1Q397.99 49.59 400.55 48.76Q403.11 47.93 406.12 47.93Q410.34 47.93 413.46 49.46Q416.57 51 418.3 54.27Q420.02 57.54 420.02 62.83V91H408.86V64.62Q408.86 62.57 408.38 61.18Q407.89 59.79 406.97 58.89Q406.05 58 404.7 57.59Q403.36 57.18 401.69 57.18Q399.19 57.18 397.21 58.38Q395.22 59.58 394.07 61.66Q392.92 63.73 392.92 66.45V91Z M447.2 91.96Q440.29 91.96 435.58 89.6Q430.86 87.24 428.46 82.36Q426.05 77.48 426.05 69.94Q426.05 62.38 428.45 57.53Q430.84 52.68 435.51 50.3Q440.17 47.93 446.99 47.93Q453.4 47.93 457.79 50.22Q462.17 52.52 464.4 57.27Q466.64 62.03 466.64 69.57V72.41H437.34Q437.46 76.11 438.46 78.66Q439.46 81.21 441.59 82.47Q443.72 83.74 447.2 83.74Q449.11 83.74 450.68 83.26Q452.25 82.78 453.39 81.82Q454.53 80.85 455.15 79.42Q455.77 77.98 455.77 76.14H466.64Q466.64 80.09 465.23 83.07Q463.82 86.04 461.22 88.01Q458.63 89.97 455.07 90.97Q451.51 91.96 447.2 91.96ZM437.48 65.39H455.19Q455.19 62.96 454.62 61.23Q454.04 59.51 453 58.37Q451.95 57.23 450.48 56.72Q449 56.21 447.13 56.21Q444.12 56.21 442.08 57.21Q440.03 58.22 438.95 60.25Q437.86 62.28 437.48 65.39Z" fill="#ecebe8"/></svg>diff --git a/assets/logo/take-one-mark-on-light.svg b/assets/logo/take-one-mark-on-light.svgnew file mode 100644index 0000000..53f4935--- /dev/null+++ b/assets/logo/take-one-mark-on-light.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -20 110 124" width="220" height="248" role="img" aria-label="Take One"><g transform="translate(0 0)"><rect x="0" y="26" width="100" height="74" rx="16" fill="#d97757"/><g transform="translate(0 24) rotate(-12.03)"><clipPath id="arm"><rect x="0" y="-17" width="100" height="17"/></clipPath><g clip-path="url(#arm)"><rect x="0" y="-17" width="100" height="17" fill="#17110e"/><g fill="#f8f2e3"><path d="M10 -17H22L12 0H0Z"/><path d="M34 -17H46L36 0H24Z"/><path d="M58 -17H70L60 0H48Z"/><path d="M82 -17H94L84 0H72Z"/><path d="M106 -17H118L108 0H96Z"/></g></g></g><path d="M38.2 84.7V77.46H47.38V56.95H38.18V51.5Q40.37 51.34 43.04 50.55Q45.7 49.77 48.33 48.61Q50.95 47.44 53.01 46.2H56.58V77.46H65.25V84.7Z" fill="#17110e"/></g></svg>diff --git a/assets/logo/take-one-mark.svg b/assets/logo/take-one-mark.svgnew file mode 100644index 0000000..b64e7e4--- /dev/null+++ b/assets/logo/take-one-mark.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="-4 -20 110 124" width="220" height="248" role="img" aria-label="Take One"><g transform="translate(0 0)"><rect x="0" y="26" width="100" height="74" rx="16" fill="#d97757"/><g transform="translate(0 24) rotate(-12.03)"><clipPath id="arm"><rect x="0" y="-17" width="100" height="17"/></clipPath><g clip-path="url(#arm)"><rect x="0" y="-17" width="100" height="17" fill="#ecebe8"/><g fill="#17110e"><path d="M10 -17H22L12 0H0Z"/><path d="M34 -17H46L36 0H24Z"/><path d="M58 -17H70L60 0H48Z"/><path d="M82 -17H94L84 0H72Z"/><path d="M106 -17H118L108 0H96Z"/></g></g></g><path d="M38.2 84.7V77.46H47.38V56.95H38.18V51.5Q40.37 51.34 43.04 50.55Q45.7 49.77 48.33 48.61Q50.95 47.44 53.01 46.2H56.58V77.46H65.25V84.7Z" fill="#17110e"/></g></svg>diff --git a/assets/previews-src/.gitignore b/assets/previews-src/.gitignorenew file mode 100644index 0000000..24cd046--- /dev/null+++ b/assets/previews-src/.gitignore@@ -0,0 +1,2 @@+node_modules+*.pngdiff --git a/assets/previews-src/BOAT-BRIEF.md b/assets/previews-src/BOAT-BRIEF.mdnew file mode 100644index 0000000..5084d18--- /dev/null+++ b/assets/previews-src/BOAT-BRIEF.md@@ -0,0 +1,34 @@+# The one-story preview pack: THE PAPER BOAT++Every style card in the gallery shows the SAME tiny story, two frames, rendered by us in that style. This proves the style file works and shows only our own work.++## The story+A small paper boat sets out at first light, meets a storm at sea, and (beyond these two frames) comes home. The boat is a folded paper boat: a hull and a triangular sail-peak, no face, no limbs. It is the protagonist; give it attitude through tilt, position and light, never anatomy.++## The two frames (fixed formula for every style)+- **Frame A — "setting out":** calm water, morning light, the boat lower-left third heading right, horizon visible, a feeling of quiet beginning. Big sky.+- **Frame B — "the storm peak":** the boat small against one big diagonal wave (or the style's equivalent of overwhelming force), dramatic sky, one light source fighting through. The boat still points forward.++## Rules+1. 16:9, render at 1280x720, export JPG quality ~88.+2. Everything drawn in code (canvas/SVG/WebGL). No model images, no photos, no frames from anyone's video, no CSS filters.+3. Deterministic: seeded randomness only; the same code gives the same pixels.+4. Obey YOUR style file completely: its palette, marks, light, type rules, motion grammar (frozen at its most characteristic moment). The boat is translated INTO the style; the style never bends to the boat. Type/captions/HUD only if your style calls for them, and then with the style's real devices.+5. Phone check: both frames must read at 360 px wide. The boat must be findable in under a second in both.+6. Composition is shared across all styles (A: boat lower-left heading right; B: boat small, wave diagonal from upper right) so the gallery reads as one system.++## Render+Write `boat.html` in your style folder: full-window `<canvas id="c">` 1280x720, and `window.drawFrame(which)` where `which` is "a" or "b" draws the complete frame synchronously (or sets window.DONE=true when finished if async). Set `window.READY = true` (or a promise) when loaded. Then:++```bash+cd <your style folder> && NODE_PATH=<dir containing node_modules with playwright-core>/node_modules node ../snap.mjs boat.html+```++which writes `a.png` and `b.png` beside it. Convert your final picks to the gallery files yourself:++```bash+ffmpeg -y -v error -i a.png -q:v 3 <style-id>-a.jpg && ffmpeg -y -v error -i b.png -q:v 3 <style-id>-b.jpg+```++## Self-review before finishing (mandatory)+Look at both frames full size AND at 360 px wide with real eyes. Ask: would a stranger name this style's medium correctly from the frame alone? Is the boat alive (tilt, wake, light) or a pasted icon? Does frame B feel dangerous? Fix and re-render until yes; 2-4 rounds is normal. Your final message must state your honest 1-10 score per frame and what you'd fix next.diff --git a/assets/previews-src/ascii/boat.html b/assets/previews-src/ascii/boat.htmlnew file mode 100644index 0000000..9c5c3a5--- /dev/null+++ b/assets/previews-src/ascii/boat.html@@ -0,0 +1,326 @@+<!doctype html>+<meta charset="utf-8">+<style>html,body{margin:0;padding:0;background:#000}canvas{display:block}</style>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');+const W = 1280, H = 720;++// ---------- grid ----------+const COLS = 160, ROWS = 45; // 8 x 16 px cells+const CW = W / COLS, CH = H / ROWS;+const RAMP = " .:-=+*#%@";+const MONO = "13px Menlo, 'Courier New', monospace";++// amber world+const PH = [255, 176, 0]; // #FFB000+const HOT = [255, 235, 184]; // near-white amber+const RED = [255, 85, 85];++// ---------- deterministic rng ----------+function mulberry32(seed){+ let a = seed >>> 0;+ return function(){+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+// seeded 2D value noise+function makeNoise(seed){+ const r = mulberry32(seed);+ const g = new Float32Array(256*256);+ for (let i=0;i<g.length;i++) g[i]=r();+ const at=(x,y)=>g[((y&255)<<8)|(x&255)];+ return function(x,y){+ const xi=Math.floor(x), yi=Math.floor(y);+ const fx=x-xi, fy=y-yi;+ const sx=fx*fx*(3-2*fx), sy=fy*fy*(3-2*fy);+ const a=at(xi,yi), b=at(xi+1,yi), c=at(xi,yi+1), d=at(xi+1,yi+1);+ return a+(b-a)*sx+(c-a)*sy+(a-b-c+d)*sx*sy;+ };+}++// ---------- luminance scene (square-pixel space 160x90) ----------+const SW = 160, SH = 90;+const sc = document.createElement('canvas'); sc.width=SW; sc.height=SH;+const sx = sc.getContext('2d');+const samp = document.createElement('canvas'); samp.width=COLS; samp.height=ROWS;+const px = samp.getContext('2d');++function g(v){ const c=Math.round(Math.max(0,Math.min(1,v))*255); return `rgb(${c},${c},${c})`; }++// paper boat silhouette in scene space. (x,y)=waterline center, s=width in px+function sceneBoat(x, y, s, rot, v){+ sx.save(); sx.translate(x,y); sx.rotate(rot);+ sx.fillStyle = g(v);+ // hull+ sx.beginPath();+ sx.moveTo(-0.5*s,0); sx.lineTo(0.5*s,0); sx.lineTo(0.3*s,0.26*s); sx.lineTo(-0.3*s,0.26*s);+ sx.closePath(); sx.fill();+ // sail peak+ sx.beginPath();+ sx.moveTo(-0.3*s,-0.02*s); sx.lineTo(0.04*s,-0.58*s); sx.lineTo(0.3*s,-0.02*s);+ sx.closePath(); sx.fill();+ // bow + stern flaps+ sx.beginPath();+ sx.moveTo(-0.5*s,-0.01*s); sx.lineTo(-0.38*s,-0.15*s); sx.lineTo(-0.28*s,-0.01*s); sx.closePath();+ sx.moveTo(0.28*s,-0.01*s); sx.lineTo(0.38*s,-0.15*s); sx.lineTo(0.5*s,-0.01*s); sx.closePath();+ sx.fill();+ sx.restore();+}++function sceneA(){+ const n = makeNoise(101);+ const rnd = mulberry32(7);+ // sky: dawn gradient+ const HOR = 40; // horizon y in scene space+ const sky = sx.createLinearGradient(0,0,0,HOR);+ sky.addColorStop(0, g(0.04)); sky.addColorStop(0.55, g(0.20)); sky.addColorStop(1, g(0.46));+ sx.fillStyle = sky; sx.fillRect(0,0,SW,HOR);+ // sun low on the right: halo then a clean disc+ const sunX=116, sunY=38;+ let rg = sx.createRadialGradient(sunX,HOR,0,sunX,HOR,16);+ rg.addColorStop(0, g(0.8)); rg.addColorStop(0.4, g(0.4)); rg.addColorStop(1,'rgba(0,0,0,0)');+ sx.fillStyle = rg; sx.fillRect(sunX-16, HOR-16, 32, 16);+ // half-risen sun disc sitting on the horizon+ sx.fillStyle = g(1.0);+ sx.beginPath(); sx.arc(sunX, HOR, 5.2, Math.PI, 2*Math.PI); sx.closePath(); sx.fill();+ // thin morning cloud bands+ sx.fillStyle = g(0.26);+ sx.fillRect(16, 22, 36, 1); sx.fillRect(60, 15, 26, 1); sx.fillRect(28, 29, 22, 1);+ sx.fillRect(90, 25, 18, 1); sx.fillStyle = g(0.18); sx.fillRect(46, 26, 12, 1);+ // sea+ const sea = sx.createLinearGradient(0,HOR,0,SH);+ sea.addColorStop(0, g(0.20)); sea.addColorStop(1, g(0.08));+ sx.fillStyle = sea; sx.fillRect(0,HOR,SW,SH-HOR);+ // horizon glint+ sx.fillStyle = g(0.45); sx.fillRect(0,HOR,SW,1);+ // calm wave streaks+ for (let y=HOR+2; y<SH; y+=2){+ const depth=(y-HOR)/(SH-HOR);+ for (let x=0; x<SW; x++){+ const w = n(x*0.09, y*0.35);+ if (w > 0.62){+ sx.fillStyle = g(0.16 + 0.16*(1-depth)*(w-0.62)/0.38);+ sx.fillRect(x,y,1,1);+ }+ }+ }+ // sun glitter path: a coherent shimmering column under the sun+ for (let y=HOR+1; y<SH; y++){+ const depth=(y-HOR)/(SH-HOR);+ const spread = 1.5 + depth*5;+ const wob = (n(3, y*0.3)-0.5)*3*depth;+ for (let k=0;k<3;k++){+ const x = sunX + wob + (rnd()*2-1)*spread;+ if (rnd() < 0.9*(1-depth*0.45)){+ sx.fillStyle = g(0.42 + rnd()*0.3*(1-depth*0.5));+ sx.fillRect(Math.round(x), y, 1+((rnd()<0.4)?1:0), 1);+ }+ }+ }+ // the boat: lower-left third, heading right, slight friendly tilt+ const bx=46, by=66, bs=17;+ // wake trailing left+ sx.fillStyle = g(0.30);+ sx.fillRect(bx-16,by+2,6,1); sx.fillRect(bx-24,by+3,5,1); sx.fillRect(bx-31,by+2,3,1);+ sceneBoat(bx, by, bs, -0.05, 0.98);+ // faint reflection under hull+ sx.fillStyle = g(0.30); sx.fillRect(bx-5, by+5, 11, 1);+ sx.fillStyle = g(0.20); sx.fillRect(bx-3, by+7, 7, 1);+}++function sceneB(){+ const n = makeNoise(555);+ const rnd = mulberry32(31);+ // dark storm sky+ const sky = sx.createLinearGradient(0,0,0,44);+ sky.addColorStop(0, g(0.05)); sky.addColorStop(1, g(0.11));+ sx.fillStyle = sky; sx.fillRect(0,0,SW,44);+ // one light source fighting through, upper left+ let rg = sx.createRadialGradient(24,10,0,24,10,30);+ rg.addColorStop(0, g(0.85)); rg.addColorStop(0.22, g(0.5)); rg.addColorStop(0.55, g(0.2)); rg.addColorStop(1,'rgba(0,0,0,0)');+ sx.fillStyle = rg; sx.fillRect(0,0,64,44);+ // ragged cloud bites eating into the light+ sx.fillStyle = g(0.06);+ sx.fillRect(10, 16, 14, 2); sx.fillRect(26, 20, 16, 2); sx.fillRect(6, 6, 10, 2);+ // diagonal rain streaks+ sx.fillStyle = g(0.17);+ for (let i=0;i<70;i++){+ const x=rnd()*SW, y=rnd()*40, L=3+rnd()*4;+ sx.save(); sx.translate(x,y); sx.rotate(0.5);+ sx.fillRect(0,0,1,L); sx.restore();+ }+ // dark sea base+ const sea = sx.createLinearGradient(0,44,0,SH);+ sea.addColorStop(0, g(0.13)); sea.addColorStop(1, g(0.07));+ sx.fillStyle = sea; sx.fillRect(0,44,SW,SH-44);++ // THE WAVE: towering diagonal wall from upper right down to mid-left+ // crest line: from (158,10) to (46,58)+ const crest = t => ({ x: 158 - 112*t, y: 10 + 48*t*t*0.6 + 48*t*0.4 });+ sx.beginPath();+ sx.moveTo(160, 6);+ for (let t=0;t<=1.001;t+=0.05){ const p=crest(t); sx.lineTo(p.x, p.y); }+ sx.lineTo(46, 90); sx.lineTo(160, 90); sx.closePath();+ sx.save(); sx.clip();+ // wave face: turbulent density with dark churn broken into it+ const n2 = makeNoise(901);+ for (let y=6;y<SH;y++){+ for (let x=44;x<SW;x++){+ let v = 0.30 + 0.42*n(x*0.11, y*0.16) + 0.18*n2(x*0.45, y*0.45);+ if (n2(x*0.2+40, y*0.2) < 0.30) v -= 0.22; // dark churn pockets+ // brighter toward the crest, darker at the base+ const p = (y-6)/(SH-6);+ v += (1-p)*0.10 - p*0.06;+ sx.fillStyle = g(Math.max(0.06, Math.min(0.82, v)));+ sx.fillRect(x,y,1,1);+ }+ }+ sx.restore();+ // crest foam: thick, jagged, brightest thing in the scene after the boat+ for (let t=0;t<=1.001;t+=0.01){+ const p=crest(t);+ const j = (n(t*40, 3)-0.5)*3;+ sx.fillStyle = g(0.86);+ sx.fillRect(Math.round(p.x), Math.round(p.y + j), 2, 2+Math.round(rnd()*2));+ if (rnd()<0.6){ sx.fillStyle=g(0.7); sx.fillRect(Math.round(p.x+rnd()*4-2), Math.round(p.y+j-2), 1, 2); }+ }+ // spray flung off the crest toward the boat+ for (let i=0;i<90;i++){+ const t=rnd(); const p=crest(t);+ sx.fillStyle = g(0.4+rnd()*0.35);+ sx.fillRect(Math.round(p.x - rnd()*10), Math.round(p.y - 2 - rnd()*7), 1, 1);+ }+ // dark trough around the boat so it pops+ rg = sx.createRadialGradient(37,73,0,37,73,24);+ rg.addColorStop(0,'rgba(0,0,0,0.6)'); rg.addColorStop(1,'rgba(0,0,0,0)');+ sx.fillStyle = rg; sx.fillRect(13,49,48,41);+ // storm streaks on near sea+ for (let y=62;y<SH;y+=2){+ for (let x=0;x<50;x++){+ if (n(x*0.15,y*0.4)>0.68){ sx.fillStyle=g(0.18); sx.fillRect(x,y,2,1); }+ }+ }+ // the boat: tiny, bright, tilted up the swell, still pointing forward (right)+ const bx=36, by=73, bs=11;+ sceneBoat(bx, by, bs, -0.22, 1.0);+ sx.fillStyle = g(0.5); sx.fillRect(bx-8,by+2,4,1); // struggling wake+}++// ---------- chrome (real terminal text) ----------+function chromeFor(which){+ if (which==='a') return [+ {r:1, c:2, text:'user@paperboat:~$ sail --heading east', v:0.92, cursor:true},+ {r:2, c:2, text:'[05:41:07] sea: calm wind: 4kt NE vis: good', v:0.45},+ {r:3, c:2, text:'[05:41:09] course locked. godspeed, little one.', v:0.38},+ ];+ return [+ {r:1, c:2, text:'[05:58:03] ALERT: wave 9.2m bearing NE -- brace brace brace', red:true, v:1.0},+ {r:2, c:2, text:'[05:58:04] hull stress 87% heading 090 held', v:0.5},+ {r:3, c:2, text:'user@paperboat:~$ hold --course', v:0.92, cursor:true},+ ];+}++// ---------- character render ----------+const charCv = document.createElement('canvas'); charCv.width=W; charCv.height=H;+const cc = charCv.getContext('2d');+const smallCv = document.createElement('canvas'); smallCv.width=W/4; smallCv.height=H/4;+const scc = smallCv.getContext('2d');++function phColor(v, red){+ if (red) return 'rgb(255,82,82)'; // the one declared exception stays RED+ v = Math.max(0, Math.min(1, v));+ const c = Math.pow(v, 0.85);+ let r,gc,b;+ if (c < 0.7){ const t=c/0.7; r=PH[0]*t; gc=PH[1]*t; b=PH[2]*t; }+ else { const t=(c-0.7)/0.3; r=PH[0]+(HOT[0]-PH[0])*t; gc=PH[1]+(HOT[1]-PH[1])*t; b=PH[2]+(HOT[2]-PH[2])*t; }+ return `rgb(${Math.round(r)},${Math.round(gc)},${Math.round(b)})`;+}++function render(which){+ // 1) scene -> luminance+ sx.fillStyle='#000'; sx.fillRect(0,0,SW,SH);+ (which==='a'?sceneA:sceneB)();+ px.imageSmoothingEnabled = true;+ px.drawImage(sc, 0, 0, COLS, ROWS);+ const data = px.getImageData(0,0,COLS,ROWS).data;++ // 2) build grid+ const jit = mulberry32(which==='a'?11:77);+ const grid = new Array(ROWS);+ for (let r=0;r<ROWS;r++){+ grid[r]=new Array(COLS);+ for (let c=0;c<COLS;c++){+ let v = data[(r*COLS+c)*4]/255;+ v += (jit()-0.5)*(v>0.85 ? 0.04 : 0.11); // phosphor life + band dither+ v = Math.max(0, Math.min(1, v));+ const idx = v<0.045 ? 0 : Math.min(RAMP.length-1, Math.floor(v*RAMP.length));+ grid[r][c] = { ch: RAMP[idx], v, red:false };+ }+ }+ // 3) chrome overwrites scene cells (whole row cleared: a terminal line is a terminal line)+ for (const line of chromeFor(which)){+ for (let c=0;c<COLS;c++) grid[line.r][c] = { ch:' ', v:0, red:false };+ for (let i=0;i<line.text.length;i++){+ const c=line.c+i; if (c>=COLS) break;+ grid[line.r][c] = { ch: line.text[i], v: line.v, red: !!line.red };+ }+ if (line.cursor){+ const c=line.c+line.text.length+1;+ grid[line.r][c] = { ch:'█', v:0.95, red:false };+ }+ }+ // 4) draw characters with barrel curvature per row+ cc.clearRect(0,0,W,H);+ cc.font = MONO; cc.textAlign='center'; cc.textBaseline='middle';+ const K = 0.030;+ for (let r=0;r<ROWS;r++){+ const dy = (r - (ROWS-1)/2) / ((ROWS-1)/2);+ const scale = 1 - K*dy*dy;+ cc.save();+ cc.translate(W/2, 0); cc.scale(scale, 1); cc.translate(-W/2, 0);+ const y = (r+0.5)*CH;+ for (let c=0;c<COLS;c++){+ const cell = grid[r][c];+ if (cell.ch===' ') continue;+ cc.fillStyle = phColor(cell.v, cell.red);+ cc.fillText(cell.ch, (c+0.5)*CW, y);+ }+ cc.restore();+ }+ // 5) composite: bg, bloom, sharp, scanlines, vignette+ ctx.fillStyle = '#0A0806'; ctx.fillRect(0,0,W,H);+ // faint ambient phosphor+ let amb = ctx.createRadialGradient(W/2,H/2,0,W/2,H/2,W*0.62);+ amb.addColorStop(0,'rgba(255,176,0,0.045)'); amb.addColorStop(1,'rgba(255,176,0,0)');+ ctx.fillStyle=amb; ctx.fillRect(0,0,W,H);+ // wide bloom: downscale-upscale+ scc.clearRect(0,0,W/4,H/4);+ scc.imageSmoothingEnabled=true;+ scc.drawImage(charCv,0,0,W/4,H/4);+ ctx.globalCompositeOperation='lighter';+ ctx.imageSmoothingEnabled=true;+ ctx.globalAlpha=0.40; ctx.drawImage(smallCv,0,0,W,H);+ // tight glow: offset ring+ ctx.globalAlpha=0.14;+ for (const [ox,oy] of [[1.5,0],[-1.5,0],[0,1.5],[0,-1.5]]) ctx.drawImage(charCv,ox,oy);+ ctx.globalAlpha=1; ctx.globalCompositeOperation='source-over';+ // sharp layer+ ctx.drawImage(charCv,0,0);+ // scanlines+ ctx.fillStyle='rgba(0,0,0,0.24)';+ for (let y=0;y<H;y+=3) ctx.fillRect(0,y,W,1);+ // vignette+ let vg = ctx.createRadialGradient(W/2,H/2,H*0.35,W/2,H/2,W*0.72);+ vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(0,0,0,0.55)');+ ctx.fillStyle=vg; ctx.fillRect(0,0,W,H);+}++window.drawFrame = function(which){ render(which); };+window.READY = true;+</script>diff --git a/assets/previews-src/chrome/boat.html b/assets/previews-src/chrome/boat.htmlnew file mode 100644index 0000000..c6a4403--- /dev/null+++ b/assets/previews-src/chrome/boat.html@@ -0,0 +1,334 @@+<!doctype html>+<html>+<head><meta charset="utf-8"><style>html,body{margin:0;background:#000}canvas{display:block}</style></head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const CTX = cv.getContext('2d');++// ---------- deterministic rng + helpers ----------+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}}+const clamp=(v,a,b)=>v<a?a:(v>b?b:v);+const mix=(a,b,t)=>a+(b-a)*t;+const sm=(a,b,x)=>{const t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};+const rgb=a=>`rgb(${Math.round(a[0])},${Math.round(a[1])},${Math.round(a[2])})`;+const tint=(a,b,t)=>[mix(a[0],b[0],t),mix(a[1],b[1],t),mix(a[2],b[2],t)];++// palette (style card)+const VERM=[232,68,44], INK=[14,14,16], CREAM=[239,235,224], ULTRA=[50,48,238];+const SKYW=[250,251,255], SILV=[198,205,218], DARKB=[24,27,34], BOUNCE=[92,100,114], DEEP=[35,38,46];++// ---------- HUD chrome ----------+function hud(g, col, idx, tc, barN, prog){+ g.save();+ const c=rgb(col);+ g.strokeStyle=c; g.fillStyle=c; g.lineWidth=2;+ const m=28, L=16;+ for(const [x,y,sx,sy] of [[m,m,1,1],[W-m,m,-1,1],[m,H-m,1,-1],[W-m,H-m,-1,-1]]){+ g.beginPath(); g.moveTo(x,y+L*sy); g.lineTo(x,y); g.lineTo(x+L*sx,y); g.stroke();+ }+ const F='11px Menlo, Consolas, monospace';+ g.textBaseline='middle';+ const sp=(t,x,y)=>{let cx=x;for(const ch of t){g.fillText(ch,cx,y);cx+=g.measureText(ch).width+2.5;}return cx;};+ const tw=t=>{let w=0;for(const ch of t){w+=g.measureText(ch).width+2.5;}return w;};+ g.font='bold '+F;+ let x2=sp('PAPER BOAT',52,49);+ g.globalAlpha=0.72; g.font=F; sp('MOTION REEL - 2026',x2+18,49); g.globalAlpha=1;+ g.font='bold '+F; sp(idx, W-52-tw(idx), 49);+ g.font='bold '+F; sp(tc,52,H-49);+ g.globalAlpha=0.72; g.font=F; sp('60 FPS',52+ (function(){g.font='bold '+F;const v=tw(tc);g.font=F;return v;})() +16, H-49); g.globalAlpha=1;+ g.font='bold '+F;+ const barsTxt='BAR '+barN+'/8';+ const bx=W-52-tw(barsTxt); sp(barsTxt,bx,H-49);+ const sq=8, gap=5; const sxx=bx-4*(sq+gap)-14; const lit=((barN-1)%4)+1;+ for(let i=0;i<4;i++){+ if(i<lit){ g.fillRect(sxx+i*(sq+gap),H-49-sq/2,sq,sq); }+ else { g.globalAlpha=0.55; g.strokeRect(sxx+i*(sq+gap)+0.5,H-49-sq/2+0.5,sq-1,sq-1); g.globalAlpha=1; }+ }+ g.globalAlpha=0.72; g.font=F; sp('128 BPM',sxx-tw('128 BPM')-14,H-49); g.globalAlpha=1;+ g.globalAlpha=0.9; g.fillRect(m,H-30,(W-2*m)*prog,2); g.globalAlpha=1;+ g.restore();+}++// ---------- grain ----------+function grain(g, seed, amt){+ const im=g.getImageData(0,0,W,H), d=im.data, r=mulberry32(seed);+ for(let i=0;i<d.length;i+=4){const n=(r()-0.5)*amt; d[i]+=n; d[i+1]+=n; d[i+2]+=n;}+ g.putImageData(im,0,0);+}++// ---------- faceted chrome paper boat, pointing right ----------+function drawBoat(g, cx, cy, S, rot, warm, rimFromLeft){+ const lg=(x0,y0,x1,y1,stops)=>{const gr=g.createLinearGradient(x0,y0,x1,y1);for(const [t,c] of stops)gr.addColorStop(t,c);return gr;};+ const midT = warm? tint(SILV,VERM,0.30) : tint(SILV,ULTRA,0.26);+ const dkT = warm? tint(DARKB,VERM,0.08): tint(DARKB,ULTRA,0.14);+ const bnT = tint(BOUNCE, warm?VERM:ULTRA, 0.20);+ g.save();+ g.translate(cx,cy); g.rotate(rot); g.scale(S,S);+ g.lineJoin='round';+ const path=p=>{g.beginPath();g.moveTo(p[0][0],p[0][1]);for(let i=1;i<p.length;i++)g.lineTo(p[i][0],p[i][1]);g.closePath();};+ const hull=[[-0.5,-0.075],[-0.1,0.012],[0.1,0.012],[0.5,-0.075],[0.30,0.24],[-0.30,0.24]];+ // hull front facet: mirror ramp with hard break+ path(hull);+ g.fillStyle=lg(0,-0.075,0,0.24,[[0,rgb(SKYW)],[0.28,rgb(midT)],[0.46,rgb(midT)],[0.50,rgb(dkT)],[0.76,rgb(bnT)],[1,rgb(DEEP)]]);+ g.fill();+ // brim fold strip+ path([[-0.5,-0.075],[-0.1,0.012],[0.1,0.012],[0.5,-0.075],[0.47,-0.045],[0.1,0.042],[-0.1,0.042],[-0.47,-0.045]]);+ g.fillStyle=lg(0,-0.075,0,0.05,[[0,rgb(SKYW)],[1,rgb(SILV)]]); g.fill();+ // sail facets+ const apex=[0,-0.56], bl=[-0.27,0.0], br=[0.27,0.0], bm=[0.005,-0.02];+ const bright=lg(-0.27,0,0.27,-0.3,[[0,rgb(SILV)],[0.45,rgb(SKYW)],[0.75,rgb(midT)],[1,rgb(SILV)]]);+ const dark =lg(-0.27,-0.3,0.27,0,[[0,rgb(dkT)],[0.55,rgb(midT)],[1,rgb(dkT)]]);+ path([apex,bl,bm]); g.fillStyle=rimFromLeft?bright:dark; g.fill();+ path([apex,bm,br]); g.fillStyle=rimFromLeft?dark:bright; g.fill();+ g.strokeStyle=rgb(dkT); g.lineWidth=0.008;+ g.beginPath(); g.moveTo(apex[0],apex[1]); g.lineTo(bm[0],bm[1]); g.stroke();+ g.strokeStyle='rgba(24,27,34,0.85)'; g.lineWidth=0.011;+ path([apex,bl,bm,br]); g.stroke();+ path(hull); g.stroke();+ // specular softbox streaks clipped to silhouette+ g.save();+ g.beginPath();+ const sil=[[-0.5,-0.075],[-0.1,0.012],[0.1,0.012],[0.5,-0.075],[0.30,0.24],[-0.30,0.24]];+ g.moveTo(sil[0][0],sil[0][1]); for(let i=1;i<sil.length;i++) g.lineTo(sil[i][0],sil[i][1]); g.closePath();+ g.moveTo(apex[0],apex[1]); g.lineTo(bl[0],bl[1]); g.lineTo(br[0],br[1]); g.closePath();+ g.clip();+ g.rotate(-0.5);+ const st=(x,y,w,h,a)=>{g.globalAlpha=a;g.beginPath();g.roundRect(x,y,w,h,h/2);g.fillStyle='#ffffff';g.fill();};+ st(-0.62,-0.31,1.15,0.030,0.9);+ st(-0.62,-0.235,1.15,0.012,0.4);+ g.restore();+ if(!rimFromLeft===false){} // no-op+ if(!warm){+ // storm rim light on edges facing the upper-left source+ g.strokeStyle='rgba(250,251,255,0.95)'; g.lineWidth=0.016; g.lineCap='round';+ g.beginPath(); g.moveTo(apex[0],apex[1]); g.lineTo(bl[0],bl[1]); g.stroke();+ g.strokeStyle='rgba(250,251,255,0.6)'; g.lineWidth=0.012;+ g.beginPath(); g.moveTo(-0.5,-0.075); g.lineTo(-0.1,0.012); g.stroke();+ }+ g.restore();+}++function boatReflection(g, cx, cy, S, rot, warm, rimFromLeft){+ const off=document.createElement('canvas'); off.width=W; off.height=H;+ const o=off.getContext('2d');+ drawBoat(o,cx,cy,S,rot,warm,rimFromLeft);+ const top=cy+0.10*S;+ g.save();+ for(let i=0;i<80;i++){+ const sy=top+i*3;+ const srcY=cy+0.10*S-(i+1)*3;+ const a=0.30*Math.max(0,1-i/62);+ if(a<=0.005) break;+ const wob=Math.sin(i*0.5)* (1.5+i*0.28);+ g.globalAlpha=a;+ g.drawImage(off,0,srcY,W,3,wob,sy,W,3);+ }+ g.restore();+}++// ================= FRAME A : setting out at first light =================+function frameA(){+ const g=CTX;+ const HOR=380, SUNX=880, SUNY=306, SUNR=52;+ // analytic sky color (also sampled by the sea)+ function skyCol(x,y){+ let r=VERM[0], gg=VERM[1], b=VERM[2];+ const dx=x-SUNX, dy=y-SUNY, d=Math.sqrt(dx*dx+dy*dy);+ if(d<SUNR){ const e=sm(SUNR,SUNR-3,d); r=mix(r,CREAM[0],e); gg=mix(gg,CREAM[1],e); b=mix(b,CREAM[2],e); }+ else { const glow=Math.exp(-(d-SUNR)/95)*0.32; r=mix(r,255,glow); gg=mix(gg,196,glow); b=mix(b,150,glow); }+ return [r,gg,b];+ }+ // sky (drawn)+ g.fillStyle=rgb(VERM); g.fillRect(0,0,W,HOR);+ let grd=g.createRadialGradient(SUNX,SUNY,SUNR,SUNX,SUNY,SUNR+180);+ grd.addColorStop(0,'rgba(255,196,150,0.32)'); grd.addColorStop(1,'rgba(255,196,150,0)');+ g.fillStyle=grd; g.fillRect(0,0,W,HOR);+ g.fillStyle=rgb(CREAM); g.beginPath(); g.arc(SUNX,SUNY,SUNR,0,7); g.fill();+ // liquid-chrome sea: per-pixel reflection of the analytic sky+ const im=g.createImageData(W,H-HOR), d=im.data;+ for(let y=HOR;y<H;y++){+ const dd=y-HOR+1;+ const per=dd/(H-HOR);+ const amp=0.7+per*per*6;+ for(let x=0;x<W;x++){+ // calm mirror: mostly-horizontal wobble, slow drift in x+ const sx1=Math.sin(x*0.004)*2.5, sx2=Math.sin(x*0.009+3)*2.0;+ const w = Math.sin(dd*0.50+sx1) + 0.6*Math.sin(dd*1.25+sx2);+ const ry = HOR - dd*0.70 - w*amp*2.4;+ let c = skyCol(x + Math.sin(x*0.005+dd*0.3)*amp, ry);+ // perspective-scaled metallic bands (log-spaced: tight at horizon, broad near viewer)+ const band=Math.sin(6.4*Math.log(dd+14) + Math.sin(x*0.008+dd*0.01)*1.1 + 0.6);+ const hi=sm(0.74,0.97,band);+ const loF=sm(-0.62,-0.97,band); // 1 when band deeply negative+ const shineT=0.75+0.25*Math.sin(x*0.003+dd*0.004+2.0);+ c=[mix(c[0],SKYW[0],hi*0.60*shineT), mix(c[1],SKYW[1],hi*0.60*shineT), mix(c[2],SKYW[2],hi*0.56*shineT)];+ c=[mix(c[0],DARKB[0],loF*0.72), mix(c[1],DARKB[1],loF*0.72), mix(c[2],DARKB[2],loF*0.70)];+ // silver sheen field: the studio reads in the water+ const sheen=0.09+0.06*Math.sin(x*0.0025+1.2);+ c=[mix(c[0],SILV[0],sheen*(1-loF)), mix(c[1],SILV[1],sheen*(1-loF)), mix(c[2],SILV[2],sheen*(1-loF))];+ // metallic hairlines keep the broad near bands crisp+ const mb=sm(0.90,0.995,Math.sin(28*Math.log(dd+14)+Math.sin(x*0.006)*1.4+1.1))*per*0.5;+ c=[mix(c[0],SKYW[0],mb), mix(c[1],SKYW[1],mb), mix(c[2],SKYW[2],mb*0.95)];+ // contrast push+ c=[(c[0]-128)*1.22+128,(c[1]-128)*1.22+128,(c[2]-128)*1.22+128];+ // sun glitter column, sliced by the same bands+ const sig=24+per*115;+ const gx=x-SUNX+w*amp*5;+ const gl=Math.exp(-(gx*gx)/(2*sig*sig));+ const tw2=clamp(w*1.2+0.45,0,1)*(0.12+0.88*sm(0.0,0.7,band));+ c=[mix(c[0],255,gl*tw2*0.95), mix(c[1],255,gl*tw2*0.92), mix(c[2],255,gl*tw2*0.85)];+ // near-camera sheen so the bottom HUD stays legible+ const nc=sm(636,712,y)*0.55;+ c=[mix(c[0],SILV[0],nc), mix(c[1],SILV[1],nc), mix(c[2],SILV[2],nc)];+ const i4=((y-HOR)*W+x)*4;+ d[i4]=clamp(c[0],0,255); d[i4+1]=clamp(c[1],0,255); d[i4+2]=clamp(c[2],0,255); d[i4+3]=255;+ }+ }+ g.putImageData(im,0,HOR);+ // thin ink horizon rule+ g.fillStyle='rgba(14,14,16,0.8)'; g.fillRect(0,HOR-1,W,2);+ // boat: lower-left third, heading right, slight confident bow-up tilt+ const BX=300, BY=487, BS=210, ROT=-0.055;+ boatReflection(g,BX,BY,BS,ROT,true,false);+ // wake: bright chrome V behind the boat+ g.save();+ g.translate(BX,BY);+ g.strokeStyle='rgba(250,251,255,0.55)'; g.lineWidth=2.4;+ g.beginPath(); g.moveTo(-105,22); g.quadraticCurveTo(-190,34,-268,30); g.stroke();+ g.strokeStyle='rgba(250,251,255,0.30)'; g.lineWidth=1.6;+ g.beginPath(); g.moveTo(-105,30); g.quadraticCurveTo(-200,52,-286,54); g.stroke();+ g.globalAlpha=0.5; g.fillStyle='#FAFBFF';+ g.beginPath(); g.ellipse(0,25,112,7,0,0,7); g.fill();+ g.restore();+ drawBoat(g,BX,BY,BS,ROT,true,false);+ hud(g, INK, '01 - FIRST LIGHT', '00:00:02:16', 2, 0.16);+ grain(g, 7101, 14);+}++// ================= FRAME B : the storm peak =================+function frameB(){+ const g=CTX;+ // field+ g.fillStyle=rgb(INK); g.fillRect(0,0,W,H);+ const LX=252, LY=118;+ // the one light fighting through+ let grd=g.createRadialGradient(LX,LY,0,LX,LY,340);+ grd.addColorStop(0,'rgba(250,251,255,0.95)');+ grd.addColorStop(0.10,'rgba(226,230,244,0.55)');+ grd.addColorStop(0.45,'rgba(90,92,190,0.18)');+ grd.addColorStop(1,'rgba(50,48,238,0)');+ g.fillStyle=grd; g.fillRect(0,0,W,H);+ // light shafts+ g.save(); g.translate(LX,LY);+ for(const [ang,wd,a] of [[0.62,46,0.08],[0.78,22,0.11],[0.50,16,0.07]]){+ g.save(); g.rotate(ang);+ const sh=g.createLinearGradient(0,0,1100,0);+ sh.addColorStop(0,'rgba(250,251,255,'+a+')'); sh.addColorStop(1,'rgba(250,251,255,0)');+ g.fillStyle=sh; g.fillRect(0,-wd/2,1100,wd); g.restore();+ }+ g.restore();+ // wave surface: crest towering upper-right+ const chop=x=> 14*Math.sin(x*0.021+1.7)+8*Math.sin(x*0.043+0.3)+5*Math.sin(x*0.011+4);+ const ys=x=> 620 - 500*Math.pow(x/W,2.3) + chop(x)*(0.4+0.6*x/W);+ // lighting normals from the smooth base curve only (chop in the normal corrugates the shading)+ const ysS=x=> 620 - 500*Math.pow(x/W,2.3);+ const dys=x=>{ const e=6; return (ysS(x+e)-ysS(x-e))/(2*e); };+ // per-column fill+ const im=g.getImageData(0,0,W,H), d=im.data;+ const r0=mulberry32(4242);+ for(let x=0;x<W;x++){+ const yTop=Math.max(0,Math.floor(ys(x)));+ const m=dys(x);+ const nl=Math.sqrt(m*m+1);+ const nx=m/nl, ny=-1/nl; // outward (up) normal of the surface line+ const crestness=sm(500,950,x); // only the towering part gets the big rim+ for(let y=yTop;y<H;y++){+ const depth=y-ys(x);+ // light vector toward the source+ let lx=LX-x, ly=LY-y; const ll=Math.sqrt(lx*lx+ly*ly); lx/=ll; ly/=ll;+ const facing=clamp(nx*lx+ny*ly,0,1);+ // dark liquid-metal base, lit side toward the source; foreground stays pewter-dark+ let base = 0.08 + 0.34*facing*(0.30+0.70*crestness);+ // sharp thin flow bands parallel to the surface (liquid metal striations)+ const ph = depth*0.045 - x*0.0075 + chop(x)*0.06;+ const s1 = Math.sin(ph);+ const bandHi = sm(0.90,0.99,s1); // thin bright silver lines+ const bandLo = sm(0.80,0.97,-s1); // thin extra-dark grooves+ const band2 = sm(0.93,0.995,Math.sin(depth*0.09+x*0.004+2.2))*0.5; // finer secondary lines+ // broad specular sheet where the face aims at the light+ const sheet = Math.pow(facing,6)*Math.exp(-depth*0.006)*(0.25+0.75*crestness);+ // crest rim+ const rim = sm(10,0,depth)*(0.30+0.70*crestness);+ let v = base + sheet*0.55 + rim*0.9;+ let c;+ const silU = tint(SILV,ULTRA,0.30);+ const dkU = tint(DARKB,ULTRA,0.28);+ if(v>0.92) c=SKYW;+ else if(v>0.62){ const t=(v-0.62)/0.30; c=tint(silU,SKYW,t); }+ else if(v>0.50){ const t=(v-0.50)/0.12; c=tint(dkU,silU,t*t); } // HARD break+ else { const t=v/0.50; c=tint([8,8,20], dkU, t); }+ // striations on top+ const bh=(bandHi*0.75+band2)*(0.3+0.7*facing)*(0.35+0.65*crestness);+ c=[mix(c[0],SKYW[0],bh), mix(c[1],SKYW[1],bh), mix(c[2],SKYW[2],bh*0.95)];+ c=[mix(c[0],6,bandLo*0.6), mix(c[1],6,bandLo*0.6), mix(c[2],10,bandLo*0.55)];+ // hot specular core+ const spec=Math.pow(facing,22)*Math.exp(-depth*0.004)*(0.3+0.7*crestness);+ c=[mix(c[0],255,spec*0.9),mix(c[1],255,spec*0.9),mix(c[2],255,spec*0.85)];+ // depth falloff into ink + foreground grounding for the HUD+ const dk=sm(160,420,depth)*0.55 + sm(500,180,x)*sm(0,70,depth)*0.30;+ c=[mix(c[0],INK[0],clamp(dk,0,0.8)),mix(c[1],INK[1],clamp(dk,0,0.8)),mix(c[2],INK[2],clamp(dk,0,0.8))];+ const i4=(y*W+x)*4;+ d[i4]=clamp(c[0],0,255); d[i4+1]=clamp(c[1],0,255); d[i4+2]=clamp(c[2],0,255); d[i4+3]=255;+ }+ }+ g.putImageData(im,0,0);+ // crest foam edge + spray (upper right)+ g.save();+ g.strokeStyle='rgba(250,251,255,0.9)'; g.lineWidth=2.5;+ g.beginPath();+ let started=false;+ for(let x=640;x<W;x+=4){ const y=ys(x)+1; if(!started){g.moveTo(x,y);started=true;} else g.lineTo(x,y); }+ g.stroke();+ const rs=mulberry32(999);+ g.fillStyle='#FAFBFF';+ for(let i=0;i<220;i++){+ const x=740+rs()*540, y=ys(x)-rs()*rs()*160-4;+ const rr=0.6+rs()*rs()*2.6, a=0.2+rs()*0.65;+ g.globalAlpha=a;+ g.beginPath(); g.arc(x-rs()*30, y, rr, 0, 7); g.fill();+ }+ g.globalAlpha=1;+ g.restore();+ // boat: small, climbing, still pointing forward+ const BX=356, BY=595, BS=132, ROT=-0.21;+ // splash at the hull+ g.save(); g.translate(BX,BY);+ g.fillStyle='#FAFBFF';+ g.globalAlpha=0.40; g.beginPath(); g.ellipse(2,14,66,5,-0.06,0,7); g.fill();+ g.globalAlpha=0.55; g.beginPath(); g.ellipse(-18,13,30,3.4,-0.05,0,7); g.fill();+ g.globalAlpha=0.5; g.beginPath(); g.ellipse(40,15,20,2.6,-0.08,0,7); g.fill();+ const rw=mulberry32(313);+ for(let i=0;i<26;i++){+ const a=rw()*Math.PI, rr=20+rw()*46;+ g.globalAlpha=0.2+rw()*0.5;+ g.beginPath(); g.arc(-Math.cos(a)*rr, 12-Math.sin(a)*rr*0.45, 0.8+rw()*1.7, 0, 7); g.fill();+ }+ g.restore();+ drawBoat(g,BX,BY,BS,ROT,false,true);+ hud(g, CREAM, '02 - STORM PEAK', '00:00:12:03', 7, 0.85);+ grain(g, 7102, 16);+}++window.drawFrame=function(which){+ CTX.clearRect(0,0,W,H);+ if(which==='a') frameA(); else frameB();+ window.DONE=true;+};+window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/crayon/boat.html b/assets/previews-src/crayon/boat.htmlnew file mode 100644index 0000000..ca16b8f--- /dev/null+++ b/assets/previews-src/crayon/boat.html@@ -0,0 +1,529 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<style>html,body{margin:0;padding:0;background:#ECE8DC}#c{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++// ---------- seeded RNG ----------+function mulberry32(seed) {+ let a = seed >>> 0;+ return function () {+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+let R = mulberry32(1);+const rnd = (a = 1, b) => (b === undefined ? R() * a : a + R() * (b - a));+const pick = arr => arr[Math.floor(R() * arr.length)];++// ---------- crayon box ----------+const PAPER = '#EFEAD9';+const PEN = '#2B3A7E'; // blue ballpoint+const TEAL = '#2E7F72'; // teal green crayon+const TEAL_D = '#1F5F55'; // pressed harder+const ORANGE = '#E2762B';+const MARIGOLD = '#E8B23A';+const RED = '#C8452E';+const BROWN = '#7A5433';+const BLACK = '#26221F';++// ---------- grain tile (paper tooth, fixed seed => same wax texture every run) ----------+const grainTile = (() => {+ const g = mulberry32(7);+ const t = document.createElement('canvas');+ t.width = t.height = 256;+ const tc = t.getContext('2d');+ const img = tc.createImageData(256, 256);+ // blocky low-res layer for clumping+ const blocks = [];+ for (let i = 0; i < 64 * 64; i++) blocks.push(g());+ for (let y = 0; y < 256; y++) {+ for (let x = 0; x < 256; x++) {+ const i = (y * 256 + x) * 4;+ const fine = g();+ const block = blocks[(y >> 2) * 64 + (x >> 2)];+ let v = 0.45 + 0.55 * (fine * 0.55 + block * 0.45);+ if (g() < 0.10) v *= 0.30; // valleys where the wax skips+ img.data[i] = 0; img.data[i + 1] = 0; img.data[i + 2] = 0;+ img.data[i + 3] = Math.floor(255 * Math.min(1, v));+ }+ }+ tc.putImageData(img, 0, 0);+ return t;+})();++// ---------- crayon layer (draw strokes on scratch, keep only where grain has tooth) ----------+const S = document.createElement('canvas'); S.width = W; S.height = H;+const sc = S.getContext('2d');+const grainPat = sc.createPattern(grainTile, 'repeat');+let target = ctx;+function beginCrayon() { sc.clearRect(0, 0, W, H); target = sc; }+function endCrayon(alpha = 1) {+ sc.globalCompositeOperation = 'destination-in';+ sc.fillStyle = grainPat;+ sc.fillRect(0, 0, W, H);+ sc.globalCompositeOperation = 'source-over';+ ctx.globalAlpha = alpha;+ ctx.drawImage(S, 0, 0);+ ctx.globalAlpha = 1;+ target = ctx;+}++// ---------- polyline helpers ----------+function resample(pts, step) {+ const out = [pts[0]];+ let rest = 0;+ for (let i = 1; i < pts.length; i++) {+ let [x0, y0] = pts[i - 1], [x1, y1] = pts[i];+ const dx = x1 - x0, dy = y1 - y0;+ const len = Math.hypot(dx, dy);+ if (len < 1e-6) continue;+ let d = step - rest;+ while (d <= len) {+ out.push([x0 + dx * d / len, y0 + dy * d / len]);+ d += step;+ }+ rest = len - (d - step);+ }+ out.push(pts[pts.length - 1]);+ return out;+}++// ---------- crayon stroke: pressure varies along, ends fade like wax lifting ----------+function crayon(pts, w, color, opts = {}) {+ const c = target;+ const step = Math.max(2, w * 0.5);+ const rs = resample(pts, step);+ const n = rs.length;+ c.strokeStyle = color;+ c.lineCap = 'round';+ for (let i = 0; i < n - 1; i++) {+ const t = i / (n - 1);+ let press = Math.min(1, t / 0.12 + 0.15, (1 - t) / 0.12 + 0.15);+ if (opts.flat) press = 1;+ if (R() < (opts.skip || 0)) continue; // unfilled patches+ const j = w * 0.14;+ const [x0, y0] = rs[i], [x1, y1] = rs[i + 1];+ c.globalAlpha = press * rnd(0.55, 0.95) * (opts.alpha || 1);+ c.lineWidth = w * rnd(0.7, 1.08);+ c.beginPath();+ c.moveTo(x0 + rnd(-j, j), y0 + rnd(-j, j));+ c.lineTo(x1 + rnd(-j, j), y1 + rnd(-j, j));+ c.stroke();+ }+ c.globalAlpha = 1;+}++// ---------- ballpoint: ONE thin wobbly blue contour, gaps, occasional double-stroke ----------+function pen(pts, opts = {}) {+ const c = target;+ const wob = opts.wobble ?? 2.2;+ const rs = resample(pts, 9);+ const jit = rs.map(([x, y]) => [x + rnd(-wob, wob), y + rnd(-wob, wob)]);+ const passes = (opts.dbl ?? (R() < 0.3)) ? 2 : 1;+ for (let p = 0; p < passes; p++) {+ c.strokeStyle = opts.color || PEN;+ c.lineWidth = opts.w || 2.1;+ c.lineJoin = 'round'; c.lineCap = 'round';+ c.globalAlpha = (p === 0 ? 0.92 : 0.45) * (opts.alpha || 1);+ const off = p === 0 ? 0 : rnd(1.5, 3);+ let drawing = false;+ c.beginPath();+ for (let i = 0; i < jit.length; i++) {+ if (R() < (opts.gap ?? 0.04) && i > 0 && i < jit.length - 1) { drawing = false; continue; } // hand lifted+ const [x, y] = jit[i];+ if (!drawing) { c.moveTo(x + off, y + off); drawing = true; }+ else c.lineTo(x + off, y + off);+ }+ c.stroke();+ }+ c.globalAlpha = 1;+}++// ---------- scribble fill: hatch runs that disobey the boundary ----------+function scribble(insideFn, bbox, angleDeg, spacing, w, color, opts = {}) {+ const a = angleDeg * Math.PI / 180;+ const dx = Math.cos(a), dy = Math.sin(a);+ const px = -dy, py = dx; // perpendicular+ const [x0, y0, x1, y1] = bbox;+ const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;+ const diag = Math.hypot(x1 - x0, y1 - y0) / 2 + 40;+ for (let o = -diag; o <= diag; o += spacing * rnd(0.75, 1.25)) {+ if (R() < (opts.rowSkip || 0)) continue; // whole missing row = unfilled patch+ // sample along the hatch line, gather runs inside the blob+ const runs = [];+ let run = null;+ for (let s = -diag; s <= diag; s += 6) {+ const x = cx + px * o + dx * s, y = cy + py * o + dy * s;+ if (insideFn(x, y)) {+ if (!run) run = [];+ run.push([x, y]);+ } else if (run) { runs.push(run); run = null; }+ }+ if (run) runs.push(run);+ for (const r of runs) {+ if (r.length < 2) continue;+ // overshoot / undershoot: the crayon disobeys the line+ const ov1 = rnd(-w * 0.6, w * 1.3), ov2 = rnd(-w * 0.6, w * 1.3);+ const h = r.map(([x, y]) => [x + rnd(-2.5, 2.5), y + rnd(-2.5, 2.5)]);+ h[0] = [h[0][0] - dx * ov1, h[0][1] - dy * ov1];+ h[h.length - 1] = [h[h.length - 1][0] + dx * ov2, h[h.length - 1][1] + dy * ov2];+ crayon(h, w, color, { skip: opts.skip ?? 0.04, alpha: opts.alpha || 1 });+ }+ }+}++function inPoly(poly) {+ return (x, y) => {+ let inside = false;+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {+ const [xi, yi] = poly[i], [xj, yj] = poly[j];+ if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) inside = !inside;+ }+ return inside;+ };+}++// ---------- sun: concentric orange scribble spiral ----------+function sunSpiral(cx, cy, rMax, turns, w, color) {+ const pts = [];+ const steps = 130;+ for (let i = 0; i <= steps; i++) {+ const t = i / steps;+ const th = t * turns * 2 * Math.PI + 0.6;+ const r = 4 + t * rMax;+ pts.push([cx + Math.cos(th) * r + rnd(-3, 3), cy + Math.sin(th) * r * 0.96 + rnd(-3, 3)]);+ }+ crayon(pts, w, color, { flat: true, alpha: 0.95 });+}++// ---------- hand-drawn caption font (polylines, baseline y=1) ----------+function circGlyph(cx, cy, r, gapAt = 0.9) {+ const pts = [];+ for (let i = 0; i <= 15; i++) {+ const th = gapAt + i / 15 * (2 * Math.PI - 0.35);+ pts.push([cx + Math.cos(th) * r, cy + Math.sin(th) * r]);+ }+ return pts;+}+const GLYPHS = {+ 'a': { w: 0.62, s: [circGlyph(0.28, 0.68, 0.28), [[0.56, 0.42], [0.57, 0.8], [0.6, 1]]] },+ 'd': { w: 0.62, s: [circGlyph(0.28, 0.7, 0.27), [[0.55, 0.02], [0.56, 0.6], [0.58, 1]]] },+ 'y': { w: 0.58, s: [[[0.03, 0.38], [0.16, 0.7], [0.3, 1]], [[0.58, 0.38], [0.4, 0.85], [0.26, 1.22], [0.1, 1.42]]] },+ 'o': { w: 0.6, s: [circGlyph(0.3, 0.68, 0.3)] },+ 'n': { w: 0.6, s: [[[0.06, 0.38], [0.05, 0.7], [0.06, 1]], [[0.06, 0.64], [0.12, 0.44], [0.3, 0.36], [0.48, 0.44], [0.55, 0.64], [0.55, 1]]] },+ 'e': { w: 0.58, s: [[[0.06, 0.66], [0.3, 0.64], [0.52, 0.62], [0.5, 0.45], [0.34, 0.36], [0.16, 0.42], [0.06, 0.62], [0.08, 0.82], [0.22, 0.98], [0.42, 1.0], [0.54, 0.92]]] },+ 't': { w: 0.5, s: [[[0.24, 0.08], [0.24, 0.6], [0.26, 0.9], [0.34, 1.0], [0.47, 0.96]], [[0.02, 0.36], [0.25, 0.35], [0.5, 0.34]]] },+ 'h': { w: 0.6, s: [[[0.06, 0.02], [0.06, 0.5], [0.06, 1]], [[0.06, 0.62], [0.15, 0.42], [0.32, 0.36], [0.48, 0.45], [0.54, 0.64], [0.54, 1]]] },+ 's': { w: 0.5, s: [[[0.45, 0.42], [0.3, 0.35], [0.14, 0.4], [0.1, 0.52], [0.2, 0.62], [0.35, 0.68], [0.42, 0.78], [0.36, 0.92], [0.2, 0.98], [0.05, 0.92]]] },+ 'k': { w: 0.56, s: [[[0.06, 0.02], [0.06, 0.5], [0.06, 1]], [[0.5, 0.38], [0.28, 0.55], [0.08, 0.68]], [[0.2, 0.6], [0.36, 0.8], [0.52, 1]]] },+ 'g': { w: 0.62, s: [circGlyph(0.28, 0.66, 0.27), [[0.55, 0.42], [0.56, 0.85], [0.56, 1.15], [0.5, 1.38], [0.3, 1.45], [0.14, 1.34]]] },+ 'r': { w: 0.46, s: [[[0.06, 0.38], [0.05, 0.7], [0.06, 1]], [[0.06, 0.6], [0.14, 0.43], [0.28, 0.36], [0.41, 0.41]]] },+ 'w': { w: 0.78, s: [[[0.03, 0.38], [0.18, 1], [0.36, 0.55], [0.55, 1], [0.72, 0.38]]] },+ '.': { w: 0.28, s: [[[0.1, 0.93], [0.14, 0.97], [0.11, 1.0]]] },+ ' ': { w: 0.5, s: [] },+};+function caption(text, cx, baseY, size, color = BLACK, w = 4.6) {+ let total = 0;+ for (const ch of text) total += (GLYPHS[ch] ? GLYPHS[ch].w : 0.5) * size + size * 0.16;+ let x = cx - total / 2;+ for (const ch of text) {+ const g = GLYPHS[ch];+ if (g) {+ const rot = rnd(-0.045, 0.045);+ const jy = rnd(-2, 2);+ for (const stroke of g.s) {+ const pts = stroke.map(([gx, gy]) => {+ const lx = gx * size, ly = (gy - 1) * size;+ return [x + lx * Math.cos(rot) - ly * Math.sin(rot),+ baseY + jy + lx * Math.sin(rot) + ly * Math.cos(rot)];+ });+ crayon(pts, w, color, { flat: false, alpha: 0.95 });+ }+ x += g.w * size + size * 0.16;+ } else x += 0.5 * size;+ }+}++// ---------- the paper boat: hull + triangular sail-peak, no face, no limbs ----------+function boat(cx, cy, s, tiltDeg, stormy) {+ const a = tiltDeg * Math.PI / 180;+ const T = ([x, y]) => [cx + (x * Math.cos(a) - y * Math.sin(a)) * s,+ cy + (x * Math.sin(a) + y * Math.cos(a)) * s];+ // hull trapezoid, bow (right) slightly lifted so it points forward+ const hull = [[-1.02, 0.02], [1.06, -0.1], [0.62, 0.5], [-0.58, 0.5], [-1.02, 0.02]].map(T);+ const sail = [[-0.52, 0.02], [0.04, -1.05], [0.58, -0.04]].map(T);+ const fold = [[0.04, -1.05], [0.09, -0.5], [0.1, -0.02]].map(T);+ const gunwale = [[-1.02, 0.02], [0.0, -0.03], [1.06, -0.1]].map(T);++ // the boat is PAPER: knock the sea out behind hull + sail before drawing it+ ctx.fillStyle = PAPER;+ for (const shape of [hull, sail]) {+ ctx.beginPath();+ ctx.moveTo(shape[0][0], shape[0][1]);+ for (let i = 1; i < shape.length; i++)+ ctx.lineTo(shape[i][0] + rnd(-1.5, 1.5), shape[i][1] + rnd(-1.5, 1.5));+ ctx.closePath();+ ctx.fill();+ }++ // hull fill: warm red crayon, strokes overshooting the contour+ beginCrayon();+ const hin = inPoly(hull);+ scribble(hin, [cx - 1.2 * s, cy - 0.2 * s, cx + 1.2 * s, cy + 0.6 * s],+ tiltDeg + rnd(-4, 4), s * 0.16, s * 0.13, RED, { skip: 0.05, rowSkip: 0.08 });+ // a touch of sunlight (or storm-light) catching the sail's leading half+ const litSail = [sail[1], sail[2], T([0.12, -0.02])];+ scribble(inPoly(litSail), [cx - s, cy - 1.1 * s, cx + s, cy + 0.2 * s],+ tiltDeg - 62, s * 0.2, s * 0.1, MARIGOLD, { skip: 0.12, rowSkip: 0.22, alpha: stormy ? 0.85 : 0.55 });+ endCrayon(0.95);++ // blue ballpoint contour, loose+ pen(hull, { wobble: s * 0.03, w: 2.4, dbl: true });+ pen(sail.concat([sail[0]]), { wobble: s * 0.03, w: 2.4, dbl: true });+ pen(fold, { wobble: s * 0.025, w: 1.9, alpha: 0.8 });+ pen(gunwale, { wobble: s * 0.025, w: 1.9, alpha: 0.7 });+}++// ================================================================+// FRAME A — "day one." calm morning, boat lower-left heading right+// ================================================================+function frameA() {+ R = mulberry32(101);+ ctx.fillStyle = PAPER;+ ctx.fillRect(0, 0, W, H);++ const HOR = 424;++ // morning light: loose side-of-crayon marigold strokes, denser near the sun and horizon+ beginCrayon();+ for (let i = 0; i < 15; i++) {+ const nearSun = R() < 0.55;+ const y = nearSun ? rnd(200, HOR - 15) : HOR - rnd(15, 90);+ const xm = nearSun ? rnd(620, 1230) : rnd(90, 1200);+ const len = rnd(70, 260);+ crayon([[xm - len / 2, y + rnd(-4, 4)], [xm, y + rnd(-6, 6)], [xm + len / 2, y + rnd(-4, 4)]],+ rnd(14, 22), MARIGOLD, { skip: 0.12, alpha: rnd(0.22, 0.4) });+ }+ sunSpiral(985, 268, 88, 3.1, 8, ORANGE);+ // few marigold flicks around the sun+ for (let i = 0; i < 8; i++) {+ const th = rnd(0, Math.PI * 2);+ const r0 = 104 + rnd(0, 12), r1 = r0 + rnd(22, 44);+ crayon([[985 + Math.cos(th) * r0, 268 + Math.sin(th) * r0],+ [985 + Math.cos(th) * r1, 268 + Math.sin(th) * r1]], 7, MARIGOLD, { alpha: 0.8 });+ }+ endCrayon(0.95);++ // the sea: teal broad strokes, ragged bottom edge, bare paper band below for the caption+ beginCrayon();+ const seaBottom = x => 596 + Math.sin(x * 0.013 + 2) * 14 + Math.sin(x * 0.037) * 8;+ const inSea = (x, y) => x > -20 && x < W + 20 && y > HOR + 2 + Math.sin(x * 0.02) * 3 && y < seaBottom(x);+ scribble(inSea, [-20, HOR, W + 20, 640], 0.5, 15, 18, TEAL, { skip: 0.05, rowSkip: 0.06 });+ // pressed-harder teal accents+ for (let i = 0; i < 9; i++) {+ const y = rnd(HOR + 20, 585);+ const x0 = rnd(0, 950);+ crayon([[x0, y], [x0 + rnd(90, 260), y + rnd(-4, 4)]], 9, TEAL_D, { alpha: 0.75 });+ }+ // sun's reflection: short orange flicks on the water under the sun+ for (let i = 0; i < 6; i++) {+ const y = HOR + 14 + i * rnd(12, 22);+ const xw = rnd(20, 60);+ crayon([[985 - xw + rnd(-14, 14), y], [985 + xw + rnd(-14, 14), y]], 8, ORANGE, { alpha: 0.7 });+ }+ endCrayon(0.92);++ // ballpoint: horizon + little wave squiggles + two birds+ pen([[55, HOR], [400, HOR + rnd(-3, 3)], [760, HOR + rnd(-3, 3)], [1230, HOR - 2]], { wobble: 2.5, gap: 0.07 });+ for (let i = 0; i < 10; i++) {+ const x = rnd(60, 1150), y = rnd(HOR + 25, 580);+ const wpts = [];+ for (let k = 0; k <= 6; k++) wpts.push([x + k * 11, y + (k % 2 ? -4 : 3)]);+ pen(wpts, { wobble: 1.4, w: 1.8, alpha: 0.6, gap: 0.02 });+ }+ for (const [bx, by] of [[700, 170], [780, 205]]) {+ pen([[bx - 22, by + 4], [bx - 10, by - 6], [bx, by + 2]], { wobble: 1.2, w: 2, alpha: 0.85 });+ pen([[bx, by + 2], [bx + 11, by - 7], [bx + 23, by + 3]], { wobble: 1.2, w: 2, alpha: 0.85 });+ }++ // the boat, lower-left third, heading right, bow a touch up+ boat(365, 505, 92, -4, false);++ // it sits IN the water: a few teal strokes back over the hull bottom + wake+ beginCrayon();+ crayon([[240, 548], [370, 552], [500, 547]], 14, TEAL, { alpha: 0.8 });+ crayon([[275, 560], [460, 562]], 11, TEAL, { alpha: 0.6 });+ endCrayon(0.9);+ pen([[262, 545], [215, 552], [172, 548]], { wobble: 2, w: 1.9, alpha: 0.7 }); // wake+ pen([[250, 558], [200, 566]], { wobble: 2, w: 1.8, alpha: 0.5 });++ // caption strip+ caption('day one.', W / 2, 672, 44);+}++// ================================================================+// FRAME B — "the sky got angry." black-scrubbed sky, one diagonal wave+// ================================================================+function frameB() {+ R = mulberry32(202);+ ctx.fillStyle = PAPER;+ ctx.fillRect(0, 0, W, H);++ const sunC = [195, 148], sunHole = 86;+ const skyEdge = x => (x < 560 ? 300 + (x / 560) * 70 : 370) + Math.sin(x * 0.011 + 1) * 26 + Math.sin(x * 0.031 + 4) * 14;++ // crest of the wave, needed early so the sky stops at it+ const waveTop = [+ [1300, 158], [1150, 172], [1010, 205], [880, 252], [760, 306],+ [640, 362], [540, 408], [470, 436], [420, 452], [388, 474], [378, 500]+ ];+ const waveTopY = x => {+ if (x <= 378) return 1e9;+ for (let i = waveTop.length - 1; i > 0; i--) {+ const [x1, y1] = waveTop[i], [x0, y0] = waveTop[i - 1];+ if (x >= x1 && x <= x0) return y1 + (y0 - y1) * (x - x1) / (x0 - x1);+ }+ return waveTop[0][1];+ };+ const skyBot = x => Math.min(skyEdge(x), waveTopY(x) - 16);++ // catastrophe = black crayon scrubbed over the whole sky, ragged bottom edge,+ // with one hole left where the light fights through+ beginCrayon();+ for (let pass = 0; pass < 2; pass++) {+ for (let y = -8; y < 400; y += rnd(9, 14)) {+ const x0 = rnd(-30, 10), x1 = W + rnd(-10, 30);+ const seg = 60;+ let run = [];+ for (let x = x0; x <= x1; x += seg) {+ const yy = y + rnd(-4, 4);+ const nearEdge = yy > skyBot(x) - rnd(0, 34);+ const inHole = Math.hypot(x - sunC[0], yy - sunC[1]) < sunHole + rnd(-6, 10);+ if (yy > skyBot(x) || inHole || (nearEdge && R() < 0.5)) {+ if (run.length > 1) crayon(run, 21, BLACK, { skip: 0.06, alpha: 0.8, flat: true });+ run = [];+ } else run.push([x, yy]);+ }+ if (run.length > 1) crayon(run, 21, BLACK, { skip: 0.06, alpha: 0.8, flat: true });+ }+ }+ // some angry diagonal scrub on top+ for (let i = 0; i < 16; i++) {+ const x = rnd(-20, W), y = rnd(0, 290);+ if (Math.hypot(x - sunC[0], y - sunC[1]) < sunHole + 50) continue;+ const x2 = x + rnd(60, 170), y2 = y + rnd(18, 55);+ if (y > skyBot(x) - 20 || y2 > skyBot(x2) - 20) continue;+ crayon([[x, y], [x2, y2]], 17, BLACK, { alpha: 0.55 });+ }+ endCrayon(0.96);++ // the one light: small orange sun spiral in the hole + marigold shaft down to the boat+ beginCrayon();+ sunSpiral(sunC[0], sunC[1], 46, 2.6, 7, ORANGE);+ for (let i = 0; i < 6; i++) {+ const th = rnd(0, Math.PI * 2);+ crayon([[sunC[0] + Math.cos(th) * 58, sunC[1] + Math.sin(th) * 58],+ [sunC[0] + Math.cos(th) * (58 + rnd(14, 26)), sunC[1] + Math.sin(th) * (58 + rnd(14, 26))]],+ 6, MARIGOLD, { alpha: 0.85 });+ }+ for (let i = 0; i < 5; i++) {+ const o = (i - 2) * 16;+ crayon([[sunC[0] + 30 + o, sunC[1] + 60], [255 + o + rnd(-8, 8), 330], [305 + o * 0.6 + rnd(-8, 8), 452]],+ 15, MARIGOLD, { alpha: 0.28, skip: 0.1 });+ }+ // the lit patch of water around the boat+ for (let i = 0; i < 5; i++) {+ const y = 496 + i * rnd(8, 14);+ const xm = 315 + rnd(-15, 15), len = rnd(60, 130);+ crayon([[xm - len / 2, y], [xm + len / 2, y + rnd(-4, 4)]], 11, MARIGOLD, { alpha: 0.4 });+ }+ endCrayon(0.95);++ // THE WAVE: one big diagonal mass from upper right, breaking toward the boat+ // the lip: a small open hook, not a tangle+ const curl = [[378, 500], [386, 516], [402, 522], [414, 512]];+ const seaBottom = x => 606 + Math.sin(x * 0.017 + 1) * 12 + Math.sin(x * 0.041) * 7;+ // fill polygon offset DOWN from the crest so a bare-paper foam band survives+ const waveInner = waveTop.map(([x, y]) => [x - 6 + rnd(-4, 4), y + 26 + rnd(-6, 6)]);+ const wavePoly = waveInner.concat([[392, 552], [200, 564], [-20, 558], [-20, 640], [1300, 640]]);+ const inWave = (x, y) => y < seaBottom(x) && inPoly(wavePoly)(x, y);+ const inWaveFull = (x, y) => y < seaBottom(x) && inPoly(waveTop.concat([[392, 540], [-20, 556], [-20, 640], [1300, 640]]))(x, y);++ beginCrayon();+ // body: strokes climb the face, steeper than the crest line+ scribble(inWave, [-20, 140, W + 20, 650], -34, 15, 18, TEAL, { skip: 0.05, rowSkip: 0.05 });+ // pressed-harder streaks low on the face (danger), following the same diagonal+ for (let i = 0; i < 9; i++) {+ const idx = 2 + Math.floor(rnd(0, waveTop.length - 3));+ const [x, y] = waveTop[idx];+ const sx = x + rnd(30, 120), sy = y + rnd(90, 170);+ const ex = sx - rnd(70, 130), ey = sy + rnd(50, 90);+ if (ey > 570 || sy > 570) continue;+ crayon([[sx, sy], [ex, ey]], 11, TEAL_D, { alpha: 0.6 });+ }+ // foam tumble right at the lip: paper-white wax over the teal+ for (let i = 0; i < 5; i++) {+ const x = 398 + rnd(-12, 26), y = 508 + rnd(-6, 22);+ crayon([[x, y], [x + rnd(-22, -8), y + rnd(4, 14)]], 11, '#F6F2E4', { alpha: 0.9 });+ }+ // flat sea left of the wave+ const inFlat = (x, y) => x < 400 && y > 520 + Math.sin(x * 0.03) * 5 && y < seaBottom(x);+ scribble(inFlat, [-20, 500, 420, 640], 2, 14, 16, TEAL, { skip: 0.06, rowSkip: 0.08 });+ endCrayon(0.94);++ // crest contour + curl + foam scallops in ballpoint; foam band = bare paper+ pen(waveTop, { wobble: 3.2, w: 2.4, gap: 0.05, dbl: true });+ pen(curl, { wobble: 2.2, w: 2.4, gap: 0.02, dbl: true });+ for (let i = 1; i < waveTop.length - 3; i++) {+ const [x, y] = waveTop[i];+ pen([[x + 6, y + 8], [x - 4, y + 18], [x - 20, y + 16], [x - 26, y + 26]],+ { wobble: 1.8, w: 2, alpha: 0.8 });+ }+ // spray flicks off the upper crest only (keep the boat's corner clean)+ for (let i = 0; i < 9; i++) {+ const src = waveTop[1 + Math.floor(rnd(0, 6))];+ pen([[src[0] + rnd(-8, 8), src[1] - rnd(4, 10)], [src[0] + rnd(-34, -8), src[1] - rnd(16, 44)]],+ { wobble: 1.3, w: 1.8, alpha: 0.7, gap: 0 });+ }++ // rain: ballpoint diagonal dashes+ for (let i = 0; i < 85; i++) {+ const x = rnd(0, W), y = rnd(30, 470);+ if (Math.hypot(x - sunC[0], y - sunC[1]) < sunHole) continue;+ if (inWaveFull(x, y)) continue;+ pen([[x, y], [x - rnd(8, 15), y + rnd(18, 30)]], { wobble: 0.8, w: 1.7, alpha: 0.55, gap: 0 });+ }++ // the boat: small, in the lit patch, climbing the wave, still pointing forward+ boat(316, 474, 55, -16, true);++ // water over its hull bottom + a hard pitching wake+ beginCrayon();+ crayon([[248, 505], [318, 499], [386, 488]], 12, TEAL, { alpha: 0.85 });+ crayon([[262, 516], [356, 505]], 10, TEAL_D, { alpha: 0.7 });+ endCrayon(0.9);+ pen([[254, 508], [226, 518], [204, 515]], { wobble: 2, w: 1.8, alpha: 0.7 });++ // caption strip+ caption('the sky got angry.', W / 2, 672, 44);+}++window.drawFrame = function (which) {+ if (which === 'a') frameA(); else frameB();+ window.DONE = true;+};+window.READY = true;+</script>+</body>+</html>diff --git a/assets/previews-src/dark/boat.html b/assets/previews-src/dark/boat.htmlnew file mode 100644index 0000000..16a5347--- /dev/null+++ b/assets/previews-src/dark/boat.html@@ -0,0 +1,641 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>Paper Boat — dark premium</title>+<style>+ html,body{margin:0;padding:0;background:#000;}+ #c{display:block;width:1280px;height:720px;}+</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++const PAPER_LIT = '#F4E9D0';++// ---------- seeded PRNG ----------+function mulberry32(a){+ return function(){+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++// ---------- shared pieces ----------+let grainCanvas = null;+function grain(alpha){+ if (!grainCanvas){+ grainCanvas = document.createElement('canvas');+ grainCanvas.width = W; grainCanvas.height = H;+ const gctx = grainCanvas.getContext('2d');+ const img = gctx.createImageData(W, H);+ const r = mulberry32(1234567);+ for (let i = 0; i < img.data.length; i += 4){+ const v = (r() * 255) | 0;+ img.data[i] = v; img.data[i+1] = v; img.data[i+2] = v;+ img.data[i+3] = 255;+ }+ gctx.putImageData(img, 0, 0);+ }+ ctx.save();+ ctx.globalCompositeOperation = 'overlay';+ ctx.globalAlpha = alpha;+ ctx.drawImage(grainCanvas, 0, 0);+ ctx.restore();+}++function vignette(strength){+ const g = ctx.createRadialGradient(W/2, H/2, H*0.35, W/2, H/2, H*1.05);+ g.addColorStop(0, 'rgba(0,0,0,0)');+ g.addColorStop(1, 'rgba(0,0,0,' + strength + ')');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, W, H);+}++function glow(x, y, r, color, a){+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ const g = ctx.createRadialGradient(x, y, 0, x, y, r);+ g.addColorStop(0, color.replace('A)', a + ')'));+ g.addColorStop(0.4, color.replace('A)', (a * 0.4).toFixed(3) + ')'));+ g.addColorStop(0.75, color.replace('A)', (a * 0.12).toFixed(3) + ')'));+ g.addColorStop(1, color.replace('A)', '0)'));+ ctx.fillStyle = g;+ ctx.fillRect(x - r, y - r, r * 2, r * 2);+ ctx.restore();+}+const GOLD_A = 'rgba(245,181,68,A)';+const WARM_A = 'rgba(255,220,150,A)';++// soft-edged cloud puff (no hard ellipse edges)+function puff(x, y, rx, ry, rgb, a, comp){+ ctx.save();+ if (comp) ctx.globalCompositeOperation = comp;+ ctx.translate(x, y);+ ctx.scale(1, ry / rx);+ const g = ctx.createRadialGradient(0, 0, 0, 0, 0, rx);+ g.addColorStop(0, 'rgba(' + rgb + ',' + a + ')');+ g.addColorStop(0.6, 'rgba(' + rgb + ',' + (a * 0.45).toFixed(3) + ')');+ g.addColorStop(1, 'rgba(' + rgb + ',0)');+ ctx.fillStyle = g;+ ctx.beginPath(); ctx.arc(0, 0, rx, 0, Math.PI * 2); ctx.fill();+ ctx.restore();+}++function monoLabel(text, x, y){+ ctx.save();+ ctx.font = '15px "SF Mono", Menlo, "Courier New", monospace';+ ctx.textBaseline = 'alphabetic';+ ctx.fillStyle = 'rgba(244,241,234,0.45)';+ ctx.fillText(text, x, y);+ ctx.fillStyle = 'rgba(245,181,68,0.8)';+ ctx.fillRect(x - 18, y - 11, 8, 2);+ ctx.restore();+}++// ---------- the paper boat ----------+// origin: waterline center. s = half-width of hull in px. rot in radians.+function drawBoat(s, x, y, rot, lightDir, lanternA){+ ctx.save();+ ctx.translate(x, y);+ ctx.rotate(rot);+ ctx.scale(s, s);+ ctx.lineJoin = 'round';++ const hull = () => {+ ctx.beginPath();+ ctx.moveTo(-1, 0);+ ctx.lineTo(-0.52, 0.42);+ ctx.lineTo(0.52, 0.42);+ ctx.lineTo(1, 0);+ ctx.closePath();+ };+ const sail = () => {+ ctx.beginPath();+ ctx.moveTo(-0.44, -0.02);+ ctx.lineTo(0.44, -0.02);+ ctx.lineTo(0.02, -0.92);+ ctx.closePath();+ };++ const hullGrad = ctx.createLinearGradient(-1 * lightDir, 0, 1 * lightDir, 0);+ hullGrad.addColorStop(0, '#6b5f46');+ hullGrad.addColorStop(0.55, '#bfae84');+ hullGrad.addColorStop(1, PAPER_LIT);+ const sailGrad = ctx.createLinearGradient(-0.5 * lightDir, -0.4, 0.5 * lightDir, -0.4);+ sailGrad.addColorStop(0, '#77694d');+ sailGrad.addColorStop(0.55, '#cbbd94');+ sailGrad.addColorStop(1, '#f7ecd2');++ sail();+ ctx.fillStyle = sailGrad;+ ctx.fill();+ // sail center fold: shaded half (away from the light)+ ctx.beginPath();+ ctx.moveTo(0.02, -0.92);+ if (lightDir > 0){ ctx.lineTo(-0.44, -0.02); ctx.lineTo(0.02, -0.02); }+ else { ctx.lineTo(0.44, -0.02); ctx.lineTo(0.02, -0.02); }+ ctx.closePath();+ ctx.fillStyle = 'rgba(20,16,10,0.32)';+ ctx.fill();++ hull();+ ctx.fillStyle = hullGrad;+ ctx.fill();+ // gunwale crease highlight, only on the lit half so it never reads as a blade+ ctx.beginPath();+ if (lightDir > 0){ ctx.moveTo(1, 0); ctx.lineTo(-0.25, 0); }+ else { ctx.moveTo(-1, 0); ctx.lineTo(0.25, 0); }+ ctx.strokeStyle = 'rgba(255,235,190,0.7)';+ ctx.lineWidth = 0.035;+ ctx.stroke();+ ctx.beginPath();+ ctx.moveTo(-0.96, 0.04); ctx.lineTo(0.96, 0.04);+ ctx.strokeStyle = 'rgba(15,12,8,0.45)';+ ctx.lineWidth = 0.03;+ ctx.stroke();++ // gold rim light on the lit edges+ ctx.strokeStyle = 'rgba(245,181,68,0.95)';+ ctx.lineWidth = 0.05;+ ctx.lineCap = 'round';+ ctx.beginPath();+ if (lightDir > 0){+ ctx.moveTo(1, 0); ctx.lineTo(0.52, 0.42);+ ctx.moveTo(0.44, -0.02); ctx.lineTo(0.02, -0.92);+ } else {+ ctx.moveTo(-1, 0); ctx.lineTo(-0.52, 0.42);+ ctx.moveTo(-0.44, -0.02); ctx.lineTo(0.02, -0.92);+ }+ ctx.stroke();++ ctx.restore();++ // lantern at sail peak (world coords) — kept tight so paper still reads+ const px = x + Math.cos(rot) * (0.02 * s) - Math.sin(rot) * (-0.92 * s);+ const py = y + Math.sin(rot) * (0.02 * s) + Math.cos(rot) * (-0.92 * s);+ if (lanternA > 0){+ glow(px, py, s * 0.95, WARM_A, 0.30 * lanternA);+ glow(px, py, s * 0.26, 'rgba(255,240,200,A)', 0.85 * lanternA);+ ctx.save();+ ctx.fillStyle = '#FFE9B8';+ ctx.beginPath();+ ctx.arc(px, py, Math.max(1.6, s * 0.05), 0, Math.PI * 2);+ ctx.fill();+ ctx.restore();+ }+ return { px, py };+}++// ---------- FRAME A : setting out ----------+function frameA(){+ const rnd = mulberry32(20260928);+ ctx.clearRect(0, 0, W, H);++ const HOR = 452;++ // sky: cold night-into-dawn from top, warming faintly near the horizon+ const sky = ctx.createLinearGradient(0, 0, 0, HOR);+ sky.addColorStop(0, '#0B0B10');+ sky.addColorStop(0.62, '#12121a');+ sky.addColorStop(1, '#1d1a20');+ ctx.fillStyle = sky;+ ctx.fillRect(0, 0, W, HOR + 1);++ // low morning sun, right of center, hazy+ const sunX = 905, sunY = HOR - 30;+ glow(sunX, sunY, 460, GOLD_A, 0.14);+ glow(sunX, sunY, 200, GOLD_A, 0.20);+ glow(sunX, sunY, 66, GOLD_A, 0.4);+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ ctx.fillStyle = 'rgba(255,172,66,1)';+ ctx.beginPath(); ctx.arc(sunX, sunY, 14, 0, Math.PI * 2); ctx.fill();+ ctx.restore();++ // soft stratus haze: long low puffs, warm near the sun, cold elsewhere+ for (let i = 0; i < 22; i++){+ const cx = rnd() * (W + 300) - 150;+ const cy = 60 + rnd() * (HOR - 140);+ const rx = 130 + rnd() * 260;+ const ry = 9 + rnd() * 20;+ const near = Math.max(0, 1 - Math.hypot(cx - sunX, (cy - sunY) * 2.4) / 680);+ if (near > 0.2) puff(cx, cy, rx, ry, '245,181,68', 0.035 + near * 0.05, 'lighter');+ else puff(cx, cy, rx, ry, '38,44,58', 0.05 + rnd() * 0.05);+ }+ // one soft dark band crossing the sun (hazy dawn cloud)+ puff(sunX + 30, sunY - 12, 220, 10, '10,10,15', 0.5);++ // horizon+ ctx.save();+ ctx.strokeStyle = 'rgba(244,241,234,0.13)';+ ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(0, HOR); ctx.lineTo(W, HOR); ctx.stroke();+ ctx.restore();++ // sea+ const sea = ctx.createLinearGradient(0, HOR, 0, H);+ sea.addColorStop(0, '#131522');+ sea.addColorStop(0.5, '#0d0e16');+ sea.addColorStop(1, '#07070b');+ ctx.fillStyle = sea;+ ctx.fillRect(0, HOR, W, H - HOR);++ // sun's reflection column: vertical shimmer under the sun, widening toward viewer+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ for (let i = 0; i < 300; i++){+ const t = rnd();+ const yy = HOR + 3 + t * t * (H - HOR - 6);+ const spread = 16 + t * 130;+ const xx = sunX + (rnd() * 2 - 1) * spread;+ const len = 5 + (6 + t * 60) * rnd();+ const a = (1 - t * 0.75) * 0.26;+ ctx.strokeStyle = 'rgba(245,190,90,' + (a * (0.35 + rnd() * 0.65)).toFixed(3) + ')';+ ctx.lineWidth = 1 + t * 2;+ ctx.beginPath();+ ctx.moveTo(xx - len / 2, yy);+ ctx.lineTo(xx + len / 2, yy);+ ctx.stroke();+ }+ ctx.restore();++ // faint cold ambient streaks across the rest of the water+ ctx.save();+ for (let i = 0; i < 110; i++){+ const t = rnd();+ const yy = HOR + 6 + t * t * (H - HOR - 12);+ const xx = rnd() * W;+ const len = 10 + t * 70 * rnd();+ ctx.strokeStyle = 'rgba(107,122,148,' + (0.045 + t * 0.05).toFixed(3) + ')';+ ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(xx - len/2, yy); ctx.lineTo(xx + len/2, yy); ctx.stroke();+ }+ ctx.restore();++ // ---- the boat, lower-left third, heading right, bow lifted a touch+ const bx = 392, by = 570, bs = 88, brot = -0.06;++ glow(bx, by - 30, 260, GOLD_A, 0.065); // soft wide hero halo, no visible edge++ drawBoat(bs, bx, by, brot, +1, 0.8);++ // waterline contact: dark cut where hull sits in water+ ctx.save();+ ctx.fillStyle = 'rgba(5,5,8,0.55)';+ ctx.beginPath();+ ctx.ellipse(bx, by + 38, bs * 0.72, 9, brot, 0, Math.PI * 2);+ ctx.fill();+ ctx.restore();++ // reflection: faint inverted boat+ ctx.save();+ ctx.globalAlpha = 0.15;+ ctx.translate(bx, by + 46);+ ctx.scale(1, -0.5);+ ctx.translate(-bx, -(by + 2));+ drawBoat(bs, bx, by, -brot, +1, 0);+ ctx.restore();++ // gold shimmer beneath + a broken dash-wake trailing behind (left)+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ for (let i = 0; i < 30; i++){+ const yy = by + 48 + rnd() * 80;+ const xx = bx + (rnd() * 2 - 1) * 66;+ const len = 8 + rnd() * 36;+ ctx.strokeStyle = 'rgba(245,181,68,' + (0.06 + rnd() * 0.15).toFixed(3) + ')';+ ctx.lineWidth = 1.4;+ ctx.beginPath(); ctx.moveTo(xx - len/2, yy); ctx.lineTo(xx + len/2, yy); ctx.stroke();+ }+ for (let i = 0; i < 26; i++){+ const t = rnd();+ const xx = bx - bs * 0.9 - t * 260;+ const yy = by + 34 + t * 26 + (rnd() * 2 - 1) * 8;+ const len = 6 + rnd() * 24 * (1 - t * 0.6);+ ctx.strokeStyle = 'rgba(245,181,68,' + ((1 - t) * (0.08 + rnd() * 0.16)).toFixed(3) + ')';+ ctx.lineWidth = 1.6;+ ctx.beginPath(); ctx.moveTo(xx - len/2, yy); ctx.lineTo(xx + len/2, yy); ctx.stroke();+ }+ ctx.restore();++ // air motes in the morning light+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ for (let i = 0; i < 46; i++){+ const xx = rnd() * W, yy = rnd() * HOR;+ const near = Math.max(0, 1 - Math.hypot(xx - sunX, (yy - sunY) * 1.6) / 560);+ ctx.fillStyle = 'rgba(255,220,150,' + (0.025 + near * 0.15 * rnd()).toFixed(3) + ')';+ ctx.beginPath(); ctx.arc(xx, yy, 0.8 + rnd() * 1.3, 0, Math.PI * 2); ctx.fill();+ }+ ctx.restore();++ monoLabel('// 01 · setting out', 66, 64);++ grain(0.10);+ vignette(0.5);+}++// ---------- FRAME B : the storm peak ----------+function frameB(){+ const rnd = mulberry32(9091126);+ ctx.clearRect(0, 0, W, H);++ // base: cold storm dark+ const base = ctx.createLinearGradient(0, 0, 0, H);+ base.addColorStop(0, '#0e0f16');+ base.addColorStop(0.5, '#0b0c12');+ base.addColorStop(1, '#07070a');+ ctx.fillStyle = base;+ ctx.fillRect(0, 0, W, H);++ // churning cloud masses: soft puffs only+ for (let i = 0; i < 70; i++){+ const cx = rnd() * (W + 400) - 200;+ const cy = rnd() * 340 - 40;+ const rx = 120 + rnd() * 260;+ const ry = 34 + rnd() * 70;+ const dark = rnd() < 0.55;+ puff(cx, cy, rx, ry, dark ? '16,19,28' : '36,43,58', 0.06 + rnd() * 0.09);+ }++ // gold break in the clouds, upper-left (source of the one light)+ const gapX = 300, gapY = 70;+ glow(gapX, gapY, 340, GOLD_A, 0.20);+ glow(gapX, gapY, 150, WARM_A, 0.26);+ puff(gapX - 220, gapY + 30, 240, 60, '9,11,17', 0.5);+ puff(gapX + 260, gapY + 12, 280, 66, '9,11,17', 0.5);+ puff(gapX + 20, gapY - 55, 260, 50, '9,11,17', 0.4);++ // distant raging sea behind the wave+ const sea = ctx.createLinearGradient(0, 400, 0, H);+ sea.addColorStop(0, 'rgba(11,12,18,0)');+ sea.addColorStop(0.35, 'rgba(9,10,15,0.85)');+ sea.addColorStop(1, 'rgba(7,7,11,1)');+ ctx.fillStyle = sea;+ ctx.fillRect(0, 400, W, H - 400);+ // distant swell humps on the left, faintly rimmed+ const swells = [+ { x0: -80, y: 470, x1: 420, h: 26 },+ { x0: -40, y: 520, x1: 560, h: 34 }+ ];+ for (const s of swells){+ ctx.save();+ ctx.beginPath();+ ctx.moveTo(s.x0, s.y + 60);+ ctx.quadraticCurveTo((s.x0 + s.x1) / 2, s.y - s.h, s.x1, s.y + 60);+ ctx.closePath();+ ctx.fillStyle = '#0b0d15';+ ctx.fill();+ ctx.strokeStyle = 'rgba(150,165,190,0.045)';+ ctx.lineWidth = 1.2;+ ctx.beginPath();+ ctx.moveTo(s.x0, s.y + 58);+ ctx.quadraticCurveTo((s.x0 + s.x1) / 2, s.y - s.h, s.x1, s.y + 58);+ ctx.stroke();+ ctx.restore();+ }++ // ---- THE WAVE: huge diagonal mass from upper right,+ // concave face and a lip curling over the boat+ const LIP = [640, 330]; // lip tip+ const wavePath = () => {+ ctx.beginPath();+ ctx.moveTo(1330, 190);+ ctx.quadraticCurveTo(1150, 138, 980, 122); // back ridge+ ctx.quadraticCurveTo(878, 112, 790, 150); // shoulder+ ctx.bezierCurveTo(706, 176, 632, 224, LIP[0], LIP[1]); // curl over+ ctx.bezierCurveTo(692, 408, 610, 500, 476, 585); // concave face under the lip+ ctx.quadraticCurveTo(392, 646, 344, 730); // base runs off bottom-left+ ctx.lineTo(1330, 730);+ ctx.closePath();+ };+ wavePath();+ const wgr = ctx.createLinearGradient(560, 240, 1220, 700);+ wgr.addColorStop(0, '#252c40');+ wgr.addColorStop(0.4, '#161b28');+ wgr.addColorStop(1, '#0a0b11');+ ctx.fillStyle = wgr;+ ctx.fill();++ // face texture: streaks following the face + sheen where the light grazes it+ ctx.save();+ wavePath();+ ctx.clip();+ for (let i = 0; i < 120; i++){+ const x0 = 440 + rnd() * 860, y0 = 150 + rnd() * 560;+ const len = 40 + rnd() * 170;+ const cold = rnd() < 0.7;+ ctx.strokeStyle = cold+ ? 'rgba(120,138,168,' + (0.05 + rnd() * 0.09).toFixed(3) + ')'+ : 'rgba(245,181,68,' + (0.03 + rnd() * 0.06).toFixed(3) + ')';+ ctx.lineWidth = 1 + rnd() * 2.2;+ ctx.beginPath();+ ctx.moveTo(x0, y0);+ ctx.quadraticCurveTo(x0 - len * 0.2, y0 + len * 0.5, x0 - len * 0.5, y0 + len);+ ctx.stroke();+ }+ ctx.globalCompositeOperation = 'lighter';+ const sheen = ctx.createLinearGradient(470, 560, 760, 320);+ sheen.addColorStop(0, 'rgba(245,181,68,0.11)');+ sheen.addColorStop(1, 'rgba(245,181,68,0)');+ ctx.fillStyle = sheen;+ ctx.fillRect(360, 220, 480, 500);+ // shadow under the curling lip+ ctx.globalCompositeOperation = 'source-over';+ puff(700, 380, 140, 70, '4,5,8', 0.5);+ ctx.restore();++ // crest rim light: bright around the lip where the light catches it+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ const rim = () => {+ ctx.beginPath();+ ctx.moveTo(1330, 190);+ ctx.quadraticCurveTo(1150, 138, 980, 122);+ ctx.quadraticCurveTo(878, 112, 790, 150);+ ctx.bezierCurveTo(706, 176, 632, 224, LIP[0], LIP[1]);+ };+ for (let pass = 0; pass < 3; pass++){+ rim();+ const along = ctx.createLinearGradient(1200, 150, LIP[0], LIP[1]);+ const peak = [0.16, 0.36, 0.9][pass];+ along.addColorStop(0, 'rgba(160,175,200,' + (0.04 * peak).toFixed(3) + ')');+ along.addColorStop(0.55, 'rgba(245,181,68,' + (0.30 * peak).toFixed(3) + ')');+ along.addColorStop(1, 'rgba(255,232,175,' + (0.95 * peak).toFixed(3) + ')');+ ctx.strokeStyle = along;+ ctx.lineWidth = [15, 6.5, 2.4][pass];+ ctx.lineCap = 'round';+ ctx.stroke();+ }+ // faint continuation of the rim down the concave face+ ctx.beginPath();+ ctx.moveTo(LIP[0], LIP[1]);+ ctx.bezierCurveTo(692, 408, 610, 500, 476, 585);+ ctx.strokeStyle = 'rgba(245,181,68,0.16)';+ ctx.lineWidth = 2.5;+ ctx.stroke();+ ctx.restore();++ // foam boiling at the lip + spray falling toward the boat+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ for (let i = 0; i < 60; i++){+ const t = rnd();+ // along the curl from shoulder to lip tip+ const cx = 790 + (LIP[0] - 790) * t + (rnd() * 2 - 1) * 22;+ const cy = 150 + (LIP[1] - 150) * (t * t) + (rnd() * 2 - 1) * 14;+ const hot = t > 0.55;+ puff(cx, cy, 7 + rnd() * 22, 5 + rnd() * 11,+ hot ? '255,228,175' : '185,198,218', (hot ? 0.13 : 0.07) + rnd() * 0.10, 'lighter');+ }+ // heavy clot right at the tip+ puff(LIP[0] - 4, LIP[1] + 2, 30, 18, '255,232,185', 0.28, 'lighter');+ puff(LIP[0] - 18, LIP[1] + 16, 20, 12, '255,232,185', 0.20, 'lighter');+ // spray falling from the lip toward the boat below+ for (let i = 0; i < 150; i++){+ const t = rnd();+ const xx = LIP[0] - 10 - t * (150 + rnd() * 60) + (rnd() * 2 - 1) * 26;+ const yy = LIP[1] + t * (230 + rnd() * 60) + (rnd() * 2 - 1) * 20;+ const gold = rnd() < 0.55;+ ctx.fillStyle = gold+ ? 'rgba(255,222,155,' + ((0.28 - t * 0.18) * (0.4 + rnd() * 0.6)).toFixed(3) + ')'+ : 'rgba(190,204,224,' + ((0.16 - t * 0.10) * (0.4 + rnd() * 0.6)).toFixed(3) + ')';+ ctx.beginPath();+ ctx.arc(xx, yy, 0.7 + rnd() * 2.0, 0, Math.PI * 2);+ ctx.fill();+ }+ // wind-blown spray off the back ridge+ for (let i = 0; i < 60; i++){+ const t = rnd();+ const cx = 980 + t * 330, cy = 122 + t * 62;+ const d = rnd() * 70;+ ctx.fillStyle = 'rgba(185,200,220,' + (0.04 + rnd() * 0.10).toFixed(3) + ')';+ ctx.beginPath();+ ctx.arc(cx - d * 0.9, cy - d * 0.3 + rnd() * 20, 0.6 + rnd() * 1.6, 0, Math.PI * 2);+ ctx.fill();+ }+ ctx.restore();++ // ---- the ONE light: soft beam from the break, falling on the boat.+ // Drawn on an offscreen so BOTH the sides and the ends fade out softly.+ const bmx0 = gapX, bmy0 = gapY, bmx1 = 470, bmy1 = 600;+ const bc = document.createElement('canvas');+ bc.width = W; bc.height = H;+ const bctx = bc.getContext('2d');+ const mx = (bmx0 + bmx1) / 2, my = (bmy0 + bmy1) / 2;+ let pdx = (bmy1 - bmy0), pdy = -(bmx1 - bmx0);+ const pl = Math.hypot(pdx, pdy); pdx /= pl; pdy /= pl;+ const halfW = 150;+ const cross = bctx.createLinearGradient(mx - pdx * halfW, my - pdy * halfW,+ mx + pdx * halfW, my + pdy * halfW);+ cross.addColorStop(0, 'rgba(245,181,68,0)');+ cross.addColorStop(0.5, 'rgba(245,181,68,0.14)');+ cross.addColorStop(1, 'rgba(245,181,68,0)');+ bctx.fillStyle = cross;+ bctx.beginPath();+ bctx.moveTo(bmx0 - 170, bmy0 - 60);+ bctx.lineTo(bmx0 + 170, bmy0 - 60);+ bctx.lineTo(bmx1 + 310, bmy1 + 90);+ bctx.lineTo(bmx1 - 310, bmy1 + 110);+ bctx.closePath();+ bctx.fill();+ // fade the beam lengthwise (soft birth at the gap, soft death past the boat)+ bctx.globalCompositeOperation = 'destination-in';+ const lng = bctx.createLinearGradient(bmx0, bmy0 - 60, bmx1, bmy1 + 100);+ lng.addColorStop(0, 'rgba(0,0,0,0)');+ lng.addColorStop(0.14, 'rgba(0,0,0,1)');+ lng.addColorStop(0.72, 'rgba(0,0,0,0.85)');+ lng.addColorStop(1, 'rgba(0,0,0,0)');+ bctx.fillStyle = lng;+ bctx.fillRect(0, 0, W, H);+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ ctx.drawImage(bc, 0, 0);+ // dust caught in the beam+ for (let i = 0; i < 40; i++){+ const t = rnd();+ const xx = bmx0 + (bmx1 - bmx0) * t + (rnd() * 2 - 1) * (40 + t * 130);+ const yy = bmy0 + (bmy1 - bmy0) * t + (rnd() * 2 - 1) * 24;+ ctx.fillStyle = 'rgba(255,220,150,' + (0.03 + rnd() * 0.09 * (1 - t)).toFixed(3) + ')';+ ctx.beginPath(); ctx.arc(xx, yy, 0.7 + rnd() * 1.3, 0, Math.PI * 2); ctx.fill();+ }+ ctx.restore();++ // ---- foreground trough in front of the boat+ ctx.save();+ ctx.beginPath();+ ctx.moveTo(0, 616);+ ctx.quadraticCurveTo(200, 584, 430, 610);+ ctx.quadraticCurveTo(590, 630, 770, 688);+ ctx.lineTo(W, 720); ctx.lineTo(0, 720);+ ctx.closePath();+ const fg = ctx.createLinearGradient(0, 584, 0, 720);+ fg.addColorStop(0, '#171b28');+ fg.addColorStop(1, '#050508');+ ctx.fillStyle = fg;+ ctx.fill();+ ctx.clip();+ ctx.globalCompositeOperation = 'lighter';+ for (let i = 0; i < 70; i++){+ const xx = 200 + rnd() * 480, yy = 592 + rnd() * 120;+ const near = Math.max(0, 1 - Math.abs(xx - 450) / 280);+ const len = 6 + rnd() * 26;+ ctx.strokeStyle = 'rgba(245,181,68,' + (0.04 + near * rnd() * 0.20).toFixed(3) + ')';+ ctx.lineWidth = 1.3;+ ctx.beginPath(); ctx.moveTo(xx - len/2, yy); ctx.lineTo(xx + len/2, yy); ctx.stroke();+ }+ ctx.restore();++ // ---- the boat: small under the curling lip, climbing, still pointing forward+ const bx = 455, by = 594, bs = 58, brot = -0.27;+ glow(bx, by - 24, 130, GOLD_A, 0.13);+ drawBoat(bs, bx, by, brot, -1, 0.95);+ // the beam kisses the sail with gold+ glow(bx - bs * 0.16, by - bs * 0.42, bs * 0.8, GOLD_A, 0.12);+ // white water biting at the hull (kept off the paper itself)+ ctx.save();+ ctx.globalCompositeOperation = 'lighter';+ for (let i = 0; i < 20; i++){+ const xx = bx - 52 + rnd() * 112;+ const yy = by + 18 + rnd() * 12 - (xx - bx) * 0.26;+ ctx.fillStyle = 'rgba(215,225,240,' + (0.10 + rnd() * 0.28).toFixed(3) + ')';+ ctx.beginPath(); ctx.arc(xx, yy, 0.8 + rnd() * 2.4, 0, Math.PI * 2); ctx.fill();+ }+ ctx.restore();++ // rain: cold diagonal streaks+ ctx.save();+ ctx.strokeStyle = 'rgba(140,155,180,0.05)';+ ctx.lineWidth = 1;+ for (let i = 0; i < 100; i++){+ const xx = rnd() * (W + 200) - 100, yy = rnd() * H;+ const len = 26 + rnd() * 60;+ ctx.beginPath();+ ctx.moveTo(xx, yy);+ ctx.lineTo(xx - len * 0.42, yy + len);+ ctx.stroke();+ }+ ctx.restore();++ monoLabel('// 02 · the storm', 66, 64);++ grain(0.12);+ vignette(0.58);+}++window.drawFrame = function(which){+ if (which === 'a') frameA(); else frameB();+ window.DONE = true;+};+window.READY = true;+</script>+</body>+</html>diff --git a/assets/previews-src/explainer/boat.html b/assets/previews-src/explainer/boat.htmlnew file mode 100644index 0000000..274edcd--- /dev/null+++ b/assets/previews-src/explainer/boat.html@@ -0,0 +1,345 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<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=Inter+Tight:wght@700;800;900&family=Instrument+Serif:ital@1&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">+<style>+ html,body{margin:0;padding:0;background:#FAFAF8;}+ #c{display:block;width:1280px;height:720px;}+</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');+const W = 1280, H = 720;++// ---------- palette (decided once, never deviate) ----------+const PAPER = '#FAFAF8'; // off-white page+const INK = '#111111'; // black+const GREY = '#8A8A86'; // mid grey+const LGREY = '#D8D8D4'; // hairline grey+const BLUE = '#2563EB'; // the one accent+const BLUED = '#123A9E'; // wave mass on the accent scene+const BLUEDD = '#0C2B78'; // deepest wave shadow++const SANS = '"Inter Tight", "Futura", "Avenir Next", sans-serif';+const SERIF = 'italic "Instrument Serif", "Georgia", serif';+const MONO = '"JetBrains Mono", "Menlo", monospace';++// ---------- deterministic PRNG ----------+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}++// ---------- 8x8 Bayer ordered dithering ----------+const BAYER8 = [+ [ 0,32, 8,40, 2,34,10,42],[48,16,56,24,50,18,58,26],+ [12,44, 4,36,14,46, 6,38],[60,28,52,20,62,30,54,22],+ [ 3,35,11,43, 1,33, 9,41],[51,19,59,27,49,17,57,25],+ [15,47, 7,39,13,45, 5,37],[63,31,55,23,61,29,53,21]+];+// plot `cell`-sized dots where valueFn(x,y) in [0..1] beats the Bayer threshold+function dither(x0,y0,x1,y1,cell,color,valueFn){+ ctx.fillStyle = color;+ for(let y=y0;y<y1;y+=cell){+ for(let x=x0;x<x1;x+=cell){+ const v = valueFn(x,y);+ if(v<=0) continue;+ const t = (BAYER8[(y/cell|0)&7][(x/cell|0)&7]+0.5)/64;+ if(v>t) ctx.fillRect(x,y,cell,cell);+ }+ }+}++// ---------- the paper boat (hull + triangular sail-peak, nothing else) ----------+// local units: hull half-width 60, drawn around (0,0) = waterline at hull top+function drawBoat(s, x, y, rot, opts){+ const o = Object.assign({sail:BLUE, body:'#FFFFFF', line:INK, lw:2.6, fold:LGREY}, opts||{});+ ctx.save();+ ctx.translate(x,y); ctx.rotate(rot*Math.PI/180); ctx.scale(s,s);+ ctx.lineJoin='round'; ctx.lineCap='round';+ // hull: trapezoid, top edge wide with slightly raised tips+ ctx.beginPath();+ ctx.moveTo(-62,-4); ctx.lineTo(62,-4); ctx.lineTo(36,30); ctx.lineTo(-36,30); ctx.closePath();+ ctx.fillStyle=o.body; ctx.fill();+ ctx.strokeStyle=o.line; ctx.lineWidth=o.lw; ctx.stroke();+ // hull fold line+ ctx.beginPath(); ctx.moveTo(-52,2); ctx.lineTo(52,2);+ ctx.strokeStyle=o.fold; ctx.lineWidth=1.4; ctx.stroke();+ // sail-peak: center triangle+ ctx.beginPath();+ ctx.moveTo(-28,-4); ctx.lineTo(28,-4); ctx.lineTo(2,-52); ctx.closePath();+ ctx.fillStyle=o.sail; ctx.fill();+ ctx.strokeStyle=o.line; ctx.lineWidth=o.lw; ctx.stroke();+ // sail fold+ ctx.beginPath(); ctx.moveTo(2,-52); ctx.lineTo(-4,-4);+ ctx.strokeStyle = o.sailFold || 'rgba(255,255,255,0.55)'; ctx.lineWidth=1.6; ctx.stroke();+ ctx.restore();+}++// ---------- shared chrome: mono labels ----------+function monoLabel(text, x, y, color, size, align){+ ctx.save();+ ctx.font = `500 ${size||15}px ${MONO}`;+ ctx.fillStyle = color; ctx.textAlign = align||'left'; ctx.textBaseline='alphabetic';+ ctx.fillText(text, x, y);+ ctx.restore();+}++// rounded rect path+function rr(x,y,w,h,r){+ ctx.beginPath();+ ctx.moveTo(x+r,y); ctx.arcTo(x+w,y,x+w,y+h,r); ctx.arcTo(x+w,y+h,x,y+h,r);+ ctx.arcTo(x,y+h,x,y,r); ctx.arcTo(x,y,x+w,y,r); ctx.closePath();+}++// ---------- conditions card (the UI device, rhymes across frames) ----------+function conditionsCard(x,y,label,big,unit,sub,accent,warn){+ const w=228,h=118;+ ctx.save();+ // soft shadow+ ctx.fillStyle='rgba(17,17,17,0.06)';+ rr(x+3,y+5,w,h,18); ctx.fill();+ ctx.fillStyle='#FFFFFF';+ rr(x,y,w,h,18); ctx.fill();+ ctx.strokeStyle=LGREY; ctx.lineWidth=1; rr(x+0.5,y+0.5,w-1,h-1,18); ctx.stroke();+ ctx.font=`500 12px ${MONO}`; ctx.fillStyle=GREY; ctx.textAlign='left';+ ctx.fillText(label, x+18, y+28);+ ctx.font=`800 40px ${SANS}`; ctx.fillStyle=INK;+ ctx.fillText(big, x+18, y+70);+ const bw = ctx.measureText(big).width;+ ctx.font=`700 18px ${SANS}`; ctx.fillStyle=GREY;+ ctx.fillText(unit, x+18+bw+8, y+70);+ ctx.font=`500 13px ${MONO}`;+ ctx.fillStyle = warn ? INK : GREY;+ ctx.fillText(sub, x+18, y+96);+ if(!warn){+ // blue checkmark+ ctx.strokeStyle=accent; ctx.lineWidth=3; ctx.lineCap='round'; ctx.lineJoin='round';+ ctx.beginPath(); ctx.moveTo(x+w-46,y+66); ctx.lineTo(x+w-37,y+75); ctx.lineTo(x+w-22,y+56); ctx.stroke();+ } else {+ // warning triangle, black+ ctx.fillStyle=INK;+ ctx.beginPath(); ctx.moveTo(x+w-34,y+52); ctx.lineTo(x+w-18,y+78); ctx.lineTo(x+w-50,y+78); ctx.closePath(); ctx.fill();+ ctx.fillStyle='#FFFFFF'; ctx.font=`800 16px ${SANS}`; ctx.textAlign='center';+ ctx.fillText('!', x+w-34, y+75);+ }+ ctx.restore();+}++// =======================================================================+// FRAME A — setting out+// =======================================================================+function frameA(){+ const rnd = mulberry32(7);+ ctx.clearRect(0,0,W,H);+ ctx.fillStyle=PAPER; ctx.fillRect(0,0,W,H);++ const HOR = 452; // horizon y++ // morning sun: thin circle low over the horizon, dithered halo (the 1-bit device)+ const sx=986, sy=318, srad=54;+ dither(sx-150,sy-150,sx+150,Math.min(sy+150,HOR-2),2,'#C2C2BD',(x,y)=>{+ const d=Math.hypot(x-sx,y-sy);+ if(d<srad+6) return 0;+ return Math.max(0, 0.22*(1-(d-srad)/92));+ });+ ctx.beginPath(); ctx.arc(sx,sy,srad,0,7);+ ctx.fillStyle=PAPER; ctx.fill();+ ctx.strokeStyle=INK; ctx.lineWidth=2; ctx.stroke();++ // horizon+ ctx.strokeStyle='#B5B5B0'; ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(0,HOR+0.5); ctx.lineTo(W,HOR+0.5); ctx.stroke();++ // water: sparse engineered ripple dashes, denser near horizon+ ctx.strokeStyle='#C7C7C2'; ctx.lineWidth=1.4; ctx.lineCap='round';+ for(let i=0;i<42;i++){+ const y = HOR+14+Math.pow(rnd(),1.5)*(H-HOR-40);+ const x = 30+rnd()*(W-140);+ const len = 22+rnd()*70*(y-HOR)/(H-HOR);+ ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x+len,y); ctx.stroke();+ }+ // sun path glimmer on the water: short blue-less grey dashes under the sun+ ctx.strokeStyle='#B9B9B4';+ for(let i=0;i<9;i++){+ const y=HOR+12+i*13+rnd()*4;+ const spread = 12+i*7;+ ctx.beginPath(); ctx.moveTo(sx-spread/2+rnd()*8,y); ctx.lineTo(sx+spread/2,y); ctx.stroke();+ }++ // the boat: lower-left third, heading right, bow a touch up+ const bx=330, by=536, bs=1.5;+ // wake: two thin curves trailing left+ ctx.strokeStyle='#AFAFAA'; ctx.lineWidth=1.6;+ ctx.beginPath(); ctx.moveTo(bx-70*bs,by+40); ctx.quadraticCurveTo(bx-170,by+52,bx-268,by+46); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(bx-64*bs,by+52); ctx.quadraticCurveTo(bx-150,by+66,bx-212,by+62); ctx.stroke();+ // reflection: three broken grey dashes under the hull+ ctx.strokeStyle='#C7C7C2'; ctx.lineWidth=2;+ ctx.beginPath(); ctx.moveTo(bx-44,by+56); ctx.lineTo(bx+40,by+56); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(bx-28,by+66); ctx.lineTo(bx+22,by+66); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(bx-12,by+76); ctx.lineTo(bx+8,by+76); ctx.stroke();+ drawBoat(bs,bx,by,-2,{});++ // ---- type: giant sans + the one italic serif word ----+ ctx.textAlign='left'; ctx.textBaseline='alphabetic';+ ctx.font=`800 118px ${SANS}`;+ ctx.fillStyle=INK;+ const t1='set ', tx=88, ty=232;+ ctx.fillText(t1,tx,ty);+ const w1=ctx.measureText(t1).width;+ ctx.font=`400 ${''}132px ${SERIF}`.replace('400 ','');+ ctx.font=`italic 132px "Instrument Serif", Georgia, serif`;+ ctx.fillStyle=BLUE;+ ctx.fillText('sail.',tx+w1+6,ty);+ // small sub-line, engineered+ monoLabel('calm water. first light. day one.', tx+4, ty+44, GREY, 16);++ // chrome+ monoLabel('// 01 — setting out', 40, 52, GREY, 15);+ monoLabel('BOAT 00:00:02:10', W-40, 52, GREY, 15, 'right');+ conditionsCard(1010,556,'// conditions','4','kn','WIND · CALM',BLUE,false);+}++// =======================================================================+// FRAME B — the storm peak (the one full-bleed accent scene)+// =======================================================================+function frameB(){+ const rnd = mulberry32(41);+ ctx.clearRect(0,0,W,H);+ ctx.fillStyle=BLUE; ctx.fillRect(0,0,W,H);++ const boatX=320, boatY=596;++ // one mass: the foreground sea, rising at the right into a claw-wave that+ // overhangs left, lip tip above the boat. Diagonal reads from upper right.+ const seaChop = () => {+ ctx.moveTo(0,606);+ ctx.bezierCurveTo(90,590,170,616,300,600);+ ctx.bezierCurveTo(420,586,540,608,660,586);+ };+ const frontWall = () => { // A up the leaning front, out to the lip tip+ ctx.bezierCurveTo(646,540,628,492,600,440);+ ctx.bezierCurveTo(572,392,540,352,510,334);+ ctx.bezierCurveTo(504,330,497,327,492,326); // lip tip ~(492,326)+ };+ const backEdge = () => { // crest: steep off the lip, one diagonal to top-right+ ctx.bezierCurveTo(500,268,560,208,700,150);+ ctx.bezierCurveTo(860,96,1080,72,1280,88);+ };+ const wavePath = () => {+ ctx.beginPath();+ seaChop(); frontWall(); backEdge();+ ctx.lineTo(W,H); ctx.lineTo(0,H); ctx.closePath();+ };+ wavePath(); ctx.fillStyle=BLUED; ctx.fill();++ // deepest shadow: under the curl, plus depth at the very bottom+ ctx.save(); wavePath(); ctx.clip();+ dither(0,80,W,H,3,BLUEDD,(x,y)=>{+ const d=Math.hypot((x-760)*1.1,y-460);+ const lobe = Math.max(0,0.7*(1-d/370));+ const deep = y>580 ? 0.45*Math.min(1,(y-580)/140) : 0;+ return Math.max(lobe,deep);+ });+ ctx.restore();++ // one light source fighting through: dithered shaft from the sky gap,+ // falling onto the boat. Density fades to zero before the region edges.+ ctx.save();+ ctx.beginPath(); ctx.rect(0,0,W,H); wavePath(); ctx.clip('evenodd');+ dither(100,0,660,600,3,'rgba(255,255,255,0.85)',(x,y)=>{+ const t = y/600; // progress down the shaft+ const cx = 520 + (boatX-520)*t; // centreline drifts onto the boat+ const half = 45 + 70*t; // widens as it falls+ const e = 1 - Math.abs(x-cx)/half;+ if(e<=0) return 0;+ return 0.26 * Math.pow(e,1.6) * (1 - 0.45*t);+ });+ ctx.restore();++ // foam: crisp white edges+ ctx.strokeStyle='#FFFFFF'; ctx.lineCap='round';+ ctx.lineWidth=6;+ ctx.beginPath(); ctx.moveTo(660,586); frontWall(); ctx.stroke(); // breaking front+ ctx.lineWidth=4;+ ctx.beginPath(); ctx.moveTo(492,326); backEdge(); ctx.stroke(); // crest line+ ctx.lineWidth=3.5;+ ctx.beginPath(); seaChop(); ctx.stroke(); // sea surface+ // spray falling off the lip, wind throwing it down-left toward the boat+ ctx.fillStyle='#FFFFFF';+ for(let i=0;i<160;i++){+ const r = Math.pow(rnd(),1.6);+ const px = 492 - r*180*(0.4+0.6*rnd());+ const py = 330 + r*230*rnd() + 8;+ const s = rnd()<0.75?2:3;+ if(px>0&&py<560) ctx.fillRect(px,py,s,s);+ }+ // flecks along the sea chop+ for(let i=0;i<70;i++){+ const px = rnd()*640;+ const py = 600 + (rnd()-0.5)*26 + 8*Math.sin(px/60);+ ctx.fillRect(px,py,2,2);+ }++ // rain: thin diagonal ticks in the sky, kept off the headline block+ ctx.strokeStyle='rgba(255,255,255,0.4)'; ctx.lineWidth=1.4;+ let placed=0;+ while(placed<38){+ const x=rnd()*W, y=rnd()*500;+ if(x>70 && x<600 && y>100 && y<310) continue; // headline zone+ ctx.save(); wavePath(); // skip ticks inside the dark mass upper region+ const inWave = ctx.isPointInPath(x,y);+ ctx.restore();+ if(inWave && y<540){ continue; }+ ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x-11,y+24); ctx.stroke();+ placed++;+ }++ // ---- the boat: small on the chop, under the overhang, still pointing forward ----+ drawBoat(0.8,boatX,boatY,-10,{sail:'#FFFFFF',body:'#FFFFFF',line:INK,lw:3,sailFold:'rgba(17,17,17,0.25)'});+ // white water breaking at the bow and stern+ for(let i=0;i<26;i++){+ const px=boatX-70-rnd()*70, py=boatY+16+rnd()*18;+ ctx.fillRect(px,py,2,2);+ }+ for(let i=0;i<14;i++){+ const px=boatX+46+rnd()*40, py=boatY+12+rnd()*14;+ ctx.fillRect(px,py,2,2);+ }++ // ---- type: the stamp word, slammed at an angle, crisp on plain blue ----+ ctx.save();+ ctx.translate(96,238); ctx.rotate(-5*Math.PI/180);+ ctx.font=`italic 150px "Instrument Serif", Georgia, serif`;+ ctx.fillStyle='#FFFFFF'; ctx.textAlign='left';+ ctx.fillText('storm.',0,0);+ ctx.font=`500 16px ${MONO}`; ctx.fillStyle='rgba(255,255,255,0.9)';+ ctx.fillText('keep the bow forward.',10,44);+ ctx.restore();++ // chrome+ monoLabel('// 02 — the storm', 40, 52, 'rgba(255,255,255,0.9)', 15);+ monoLabel('BOAT 00:00:09:12', W-40, 52, 'rgba(255,255,255,0.9)', 15, 'right');+ conditionsCard(1010,556,'// conditions','41','kn','GUSTS · SEVERE',BLUE,true);+}++window.drawFrame = function(which){+ if(which==='a') frameA(); else frameB();+ window.DONE = true;+};++// wait for the real fonts before declaring ready+Promise.all([+ document.fonts.load('800 118px "Inter Tight"'),+ document.fonts.load('700 18px "Inter Tight"'),+ document.fonts.load('italic 150px "Instrument Serif"'),+ document.fonts.load('500 15px "JetBrains Mono"')+]).then(()=>document.fonts.ready).then(()=>{ window.READY = true; })+ .catch(()=>{ window.READY = true; });+</script>+</body>+</html>diff --git a/assets/previews-src/game/boat.html b/assets/previews-src/game/boat.htmlnew file mode 100644index 0000000..f483b85--- /dev/null+++ b/assets/previews-src/game/boat.html@@ -0,0 +1,752 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>THE CROSSING — game style boat preview</title>+<style>html,body{margin:0;padding:0;background:#000}canvas{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const C = document.getElementById('c');+const X = C.getContext('2d');+const W = 1280, H = 720;++// ---------- deterministic rng ----------+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+let R = mulberry32(1);+const rand=(a=1,b)=>b===undefined?R()*a:a+R()*(b-a);++// ---------- helpers ----------+function lerp(a,b,t){return a+(b-a)*t}+function mix(c1,c2,t){ // c = [r,g,b]+ return 'rgb('+Math.round(lerp(c1[0],c2[0],t))+','+Math.round(lerp(c1[1],c2[1],t))+','+Math.round(lerp(c1[2],c2[2],t))+')';+}+function dab(x,y,w,h,rot,fill,alpha){+ X.save();X.translate(x,y);X.rotate(rot);X.globalAlpha=alpha;X.fillStyle=fill;+ X.beginPath();X.ellipse(0,0,w,h,0,0,Math.PI*2);X.fill();X.restore();X.globalAlpha=1;+}+function rr(x,y,w,h,r){+ X.beginPath();+ X.moveTo(x+r,y);X.arcTo(x+w,y,x+w,y+h,r);X.arcTo(x+w,y+h,x,y+h,r);+ X.arcTo(x,y+h,x,y,r);X.arcTo(x,y,x+w,y,r);X.closePath();+}+const HUD_FONT = "'Avenir Next Condensed','Arial Narrow',sans-serif";+const TITLE_FONT = "'Optima','Palatino',serif";+function text(t,x,y,size,color,opts={}){+ X.save();+ X.font=(opts.weight||'600')+' '+(opts.italic?'italic ':'')+size+'px '+(opts.font||HUD_FONT);+ // note: italic must precede weight in canvas font shorthand; build properly:+ X.font=(opts.italic?'italic ':'')+(opts.weight||'600')+' '+size+'px '+(opts.font||HUD_FONT);+ if(opts.ls) X.letterSpacing=opts.ls+'px';+ X.textAlign=opts.align||'left';+ X.textBaseline=opts.base||'alphabetic';+ if(opts.shadow!==false){X.shadowColor='rgba(0,0,0,0.75)';X.shadowBlur=opts.blur||4;X.shadowOffsetY=1.5;}+ X.globalAlpha=opts.alpha===undefined?1:opts.alpha;+ X.fillStyle=color;+ X.fillText(t,x,y);+ X.restore();X.globalAlpha=1;X.letterSpacing='0px';+}++// ---------- paper boat ----------+// origin = waterline center. s = half hull width-ish scale. heading right.+// clear read: low hull band + tall narrow sail peak, visible gunwale gap.+function boat(x,y,s,tilt,o){+ X.save();X.translate(x,y);X.rotate(tilt);+ // contact shadow on water+ X.globalAlpha=0.35;X.fillStyle=o.shadow||'rgba(20,20,30,1)';+ X.beginPath();X.ellipse(0,0.06*s,1.08*s,0.14*s,0,0,Math.PI*2);X.fill();X.globalAlpha=1;+ // hull (low band)+ X.beginPath();+ X.moveTo(-1.1*s,-0.02*s);+ X.lineTo(-0.72*s,-0.40*s);+ X.lineTo(0.72*s,-0.40*s);+ X.lineTo(1.1*s,-0.02*s);+ X.quadraticCurveTo(0,0.20*s,-1.1*s,-0.02*s);+ X.closePath();+ const g=X.createLinearGradient(-s,0,s,0);+ if(o.rimSide==='right'){g.addColorStop(0,o.hullDark);g.addColorStop(0.55,o.hullMid||o.hullDark);g.addColorStop(1,o.hullLight);}+ else{g.addColorStop(0,o.hullLight);g.addColorStop(0.45,o.hullMid||o.hullDark);g.addColorStop(1,o.hullDark);}+ X.fillStyle=g;X.fill();+ // gunwale (top rim of hull) — bright folded-paper edge+ X.strokeStyle=o.gunwale||o.rim;X.globalAlpha=0.9;X.lineWidth=Math.max(1.2,s*0.045);+ X.beginPath();X.moveTo(-0.72*s,-0.40*s);X.lineTo(0.72*s,-0.40*s);X.stroke();X.globalAlpha=1;+ // sail (tall narrow peak, papery fold: two values split at center)+ X.beginPath();+ X.moveTo(-0.40*s,-0.40*s);X.lineTo(-0.02*s,-1.42*s);X.lineTo(0.40*s,-0.40*s);X.closePath();+ const g2=X.createLinearGradient(-0.4*s,0,0.4*s,0);+ const dk=o.rimSide==='right'?o.sailDark:o.sailLight;+ const lt=o.rimSide==='right'?o.sailLight:o.sailDark;+ g2.addColorStop(0,dk);g2.addColorStop(0.49,dk);g2.addColorStop(0.52,lt);g2.addColorStop(1,lt);+ X.fillStyle=g2;X.fill();+ // center fold crease+ X.strokeStyle=o.fold;X.globalAlpha=0.6;X.lineWidth=Math.max(1,s*0.03);+ X.beginPath();X.moveTo(-0.02*s,-1.42*s);X.lineTo(-0.01*s,-0.40*s);X.stroke();X.globalAlpha=1;+ // rim light on the lit side edges+ X.strokeStyle=o.rim;X.lineWidth=Math.max(1.6,s*0.07);X.globalAlpha=o.rimA;+ X.lineCap='round';+ X.beginPath();+ if(o.rimSide==='right'){+ X.moveTo(-0.02*s,-1.42*s);X.lineTo(0.40*s,-0.40*s);+ X.moveTo(0.72*s,-0.40*s);X.lineTo(1.1*s,-0.02*s);+ }else{+ X.moveTo(-0.02*s,-1.42*s);X.lineTo(-0.40*s,-0.40*s);+ X.moveTo(-0.72*s,-0.40*s);X.lineTo(-1.1*s,-0.02*s);+ }+ X.stroke();X.globalAlpha=1;+ X.restore();+}+function boatSilhouette(x,y,s,tilt,fill,alpha,squash){+ X.save();X.translate(x,y);X.scale(1,-squash);X.rotate(-tilt*0.6);+ X.globalAlpha=alpha;X.fillStyle=fill;+ X.beginPath();+ X.moveTo(-1.1*s,0);X.lineTo(-0.72*s,-0.40*s);X.lineTo(0.72*s,-0.40*s);X.lineTo(1.1*s,0);+ X.quadraticCurveTo(0,0.20*s,-1.1*s,0);X.closePath();X.fill();+ X.beginPath();+ X.moveTo(-0.40*s,-0.40*s);X.lineTo(0,-1.42*s);X.lineTo(0.40*s,-0.40*s);X.closePath();X.fill();+ X.restore();X.globalAlpha=1;+}++// ---------- HUD widgets ----------+function panel(x,y,w,h,border){+ X.save();+ X.fillStyle='rgba(8,12,16,0.52)';+ rr(x,y,w,h,4);X.fill();+ X.strokeStyle=border||'rgba(235,225,200,0.4)';X.lineWidth=1.2;+ rr(x+0.5,y+0.5,w-1,h-1,4);X.stroke();+ // top inner highlight+ X.strokeStyle='rgba(255,255,255,0.09)';X.lineWidth=1;+ X.beginPath();X.moveTo(x+4,y+1.6);X.lineTo(x+w-4,y+1.6);X.stroke();+ X.restore();+}+function bar(x,y,w,h,frac,trailFrac,main,trail){+ X.save();+ X.fillStyle='rgba(6,9,12,0.8)';rr(x,y,w,h,3);X.fill();+ if(trailFrac>0){X.fillStyle=trail;rr(x+1.5,y+1.5,Math.max(0,(w-3)*trailFrac),h-3,2);X.fill();}+ if(frac>0){+ const g=X.createLinearGradient(x,y,x,y+h);+ g.addColorStop(0,main[0]);g.addColorStop(1,main[1]);+ X.fillStyle=g;rr(x+1.5,y+1.5,Math.max(0,(w-3)*frac),h-3,2);X.fill();+ // gloss+ X.fillStyle='rgba(255,255,255,0.22)';+ rr(x+1.5,y+1.5,Math.max(0,(w-3)*frac),(h-3)*0.42,2);X.fill();+ }+ // segment ticks+ X.strokeStyle='rgba(0,0,0,0.35)';X.lineWidth=1;+ for(let i=1;i<10;i++){const tx=x+(w/10)*i;X.beginPath();X.moveTo(tx,y+1.5);X.lineTo(tx,y+h-1.5);X.stroke();}+ X.strokeStyle='rgba(240,232,214,0.65)';X.lineWidth=1.2;+ rr(x+0.5,y+0.5,w-1,h-1,3);X.stroke();+ X.restore();+}+function diamond(x,y,r,fill,stroke){+ X.save();X.translate(x,y);X.rotate(Math.PI/4);+ X.fillStyle=fill;X.fillRect(-r,-r,2*r,2*r);+ if(stroke){X.strokeStyle=stroke;X.lineWidth=1.4;X.strokeRect(-r,-r,2*r,2*r);}+ X.restore();+}+function minimap(cx,cy,r,mode){+ X.save();+ X.beginPath();X.arc(cx,cy,r,0,Math.PI*2);X.clip();+ if(mode==='a'){+ X.fillStyle='#0f2028';X.fillRect(cx-r,cy-r,2*r,2*r);+ // water texture+ for(let i=0;i<90;i++){dab(cx-r+rand(2*r),cy-r+rand(2*r),rand(3,9),rand(1,2),0,'#1a3542',0.35);}+ // far coast blob upper-right+ X.fillStyle='#233b2e';+ X.beginPath();X.moveTo(cx+r*0.2,cy-r);X.quadraticCurveTo(cx+r*0.45,cy-r*0.35,cx+r*1.1,cy-r*0.5);+ X.lineTo(cx+r*1.1,cy-r*1.1);X.closePath();X.fill();+ X.strokeStyle='rgba(120,200,160,0.35)';X.lineWidth=1;+ X.beginPath();X.moveTo(cx+r*0.2,cy-r);X.quadraticCurveTo(cx+r*0.45,cy-r*0.35,cx+r*1.1,cy-r*0.5);X.stroke();+ // dotted route+ X.setLineDash([3,5]);X.strokeStyle='rgba(232,200,122,0.85)';X.lineWidth=1.6;+ X.beginPath();X.moveTo(cx-r*0.42,cy+r*0.44);X.quadraticCurveTo(cx+r*0.05,cy+r*0.05,cx+r*0.5,cy-r*0.42);X.stroke();+ X.setLineDash([]);+ // waypoint+ diamond(cx+r*0.5,cy-r*0.42,4.5,'#f0c860','rgba(255,240,200,0.9)');+ // player arrow+ X.save();X.translate(cx-r*0.42,cy+r*0.44);X.rotate(-Math.PI/4);+ X.fillStyle='#eef4f0';X.beginPath();X.moveTo(0,-7);X.lineTo(5,6);X.lineTo(0,3);X.lineTo(-5,6);X.closePath();X.fill();+ X.restore();+ }else{+ X.fillStyle='#140f12';X.fillRect(cx-r,cy-r,2*r,2*r);+ for(let i=0;i<80;i++){dab(cx-r+rand(2*r),cy-r+rand(2*r),rand(3,8),rand(1,2),0,'#2a1c1e',0.5);}+ // storm spiral+ X.strokeStyle='rgba(216,72,56,0.8)';X.lineWidth=2;+ for(let k=0;k<3;k++){+ X.beginPath();+ for(let a=0;a<Math.PI*1.7;a+=0.1){+ const rr2=(0.15+0.26*k)*r + a*r*0.055;+ const px=cx+Math.cos(a+k*2.1)*rr2, py=cy+Math.sin(a+k*2.1)*rr2;+ if(a===0)X.moveTo(px,py);else X.lineTo(px,py);+ }+ X.stroke();+ }+ dab(cx,cy,5,5,0,'#f0d264',0.9);+ // player arrow being pulled in+ X.save();X.translate(cx-r*0.4,cy+r*0.4);X.rotate(-Math.PI/3.2);+ X.fillStyle='#eef4f0';X.beginPath();X.moveTo(0,-7);X.lineTo(5,6);X.lineTo(0,3);X.lineTo(-5,6);X.closePath();X.fill();+ X.restore();+ }+ X.restore();+ // rings+ X.strokeStyle=mode==='a'?'rgba(235,225,200,0.75)':'rgba(240,120,100,0.85)';+ X.lineWidth=2;X.beginPath();X.arc(cx,cy,r,0,Math.PI*2);X.stroke();+ X.strokeStyle='rgba(255,255,255,0.18)';X.lineWidth=1;+ X.beginPath();X.arc(cx,cy,r-3.5,0,Math.PI*2);X.stroke();+ // N+ text('N',cx,cy-r-6,13,'#e8e2d2',{align:'center',weight:'700',ls:1});+}+function keyPrompt(x,y,key,label,accent){+ X.save();+ X.strokeStyle=accent||'rgba(235,225,200,0.85)';X.lineWidth=1.6;+ X.fillStyle='rgba(8,12,16,0.6)';+ X.beginPath();X.arc(x,y,11,0,Math.PI*2);X.fill();X.stroke();+ text(key,x,y+4.5,13,'#f0ead8',{align:'center',weight:'700'});+ text(label,x+18,y+5,14,'rgba(235,230,215,0.9)',{ls:1.5,weight:'600'});+ X.restore();+}+function grain(n,alpha){+ for(let i=0;i<n;i++){+ const v=rand()<0.5?0:255;+ X.fillStyle='rgba('+v+','+v+','+v+','+alpha+')';+ X.fillRect(rand(W),rand(H),1.2,1.2);+ }+}+function vignette(strength,color){+ const g=X.createRadialGradient(W/2,H/2,H*0.42,W/2,H/2,H*0.85);+ g.addColorStop(0,'rgba(0,0,0,0)');+ g.addColorStop(1,color||('rgba(8,8,16,'+strength+')'));+ X.fillStyle=g;X.fillRect(0,0,W,H);+}++// =========================================================+// FRAME A — "SETTING OUT" (quest start, dawn)+// =========================================================+function frameA(){+ R=mulberry32(20260928);+ const hor=458;+ const sunX=905, sunY=352;++ // sky+ {+ const g=X.createLinearGradient(0,0,0,hor);+ g.addColorStop(0,'#2c3760');+ g.addColorStop(0.42,'#7d6584');+ g.addColorStop(0.66,'#c98d74');+ g.addColorStop(0.85,'#efc188');+ g.addColorStop(1,'#ffe2a6');+ X.fillStyle=g;X.fillRect(0,0,W,hor+2);+ }+ // painterly sky strokes (subtle brushed texture)+ for(let i=0;i<700;i++){+ const t=rand();const y=t*hor;+ const c=t<0.42?mix([60,70,110],[130,105,135],t/0.42):mix([205,145,120],[255,228,170],(t-0.42)/0.58);+ dab(rand(-30,W+30),y,rand(18,70),rand(2,5),rand(-0.06,0.06),c,0.05+rand(0.05));+ }+ // sun glow + disc (soft, hazy dawn sun — no hard spokes)+ X.save();X.globalCompositeOperation='lighter';+ let g=X.createRadialGradient(sunX,sunY,0,sunX,sunY,320);+ g.addColorStop(0,'rgba(255,218,158,0.42)');g.addColorStop(0.4,'rgba(255,190,120,0.14)');g.addColorStop(1,'rgba(255,180,110,0)');+ X.fillStyle=g;X.fillRect(0,0,W,H);+ g=X.createRadialGradient(sunX,sunY,0,sunX,sunY,58);+ g.addColorStop(0,'rgba(255,244,216,0.85)');g.addColorStop(0.5,'rgba(255,226,170,0.5)');g.addColorStop(1,'rgba(255,214,150,0)');+ X.fillStyle=g;X.beginPath();X.arc(sunX,sunY,58,0,Math.PI*2);X.fill();+ X.restore();++ // clouds: long flat dawn stratus, undersides lit; keep the title band clear+ const bands=[[118,1.5],[310,0.9],[362,0.62]];+ for(const[by,sc]of bands){+ for(let k=0;k<4;k++){+ const cx0=rand(-60,W+60), cy0=by+rand(-16,16)*sc;+ const len=rand(140,300)*sc;+ const n=Math.round(rand(22,32));+ for(let i=0;i<n;i++){+ const dx=(rand()-0.5)*2*len, dy=rand(-8,8)*sc*(1-Math.abs(dx)/len*0.5);+ const px=cx0+dx,py=cy0+dy;+ if(by>250&&Math.hypot(px-sunX,py-sunY)<160)continue; // keep the sun clean+ dab(px,py,rand(34,80)*sc,rand(4,8)*sc,rand(-0.02,0.02),'#5c5478',0.09);+ dab(px+10,py+4,rand(26,60)*sc,rand(3,6)*sc,rand(-0.02,0.02),'#f4bd8c',0.11);+ }+ }+ }+ // two gentle light shafts from the sun (soft, wide)+ X.save();X.globalCompositeOperation='lighter';X.translate(sunX,sunY);+ for(const[a,sp]of[[-2.6,0.4],[2.62,0.34]]){+ X.save();X.rotate(a);+ const rg=X.createLinearGradient(0,0,560,0);+ rg.addColorStop(0,'rgba(255,214,150,0.05)');rg.addColorStop(1,'rgba(255,214,150,0)');+ X.fillStyle=rg;+ X.beginPath();X.moveTo(0,0);X.lineTo(600,-600*Math.tan(sp/2));X.lineTo(600,600*Math.tan(sp/2));X.closePath();X.fill();+ X.restore();+ }+ X.restore();++ // sea base+ {+ const g=X.createLinearGradient(0,hor,0,H);+ g.addColorStop(0,'#e9b57f');+ g.addColorStop(0.16,'#a97e83');+ g.addColorStop(0.45,'#5f5b76');+ g.addColorStop(1,'#333c56');+ X.fillStyle=g;X.fillRect(0,hor,W,H-hor);+ }+ // horizon line crispness + far haze+ X.fillStyle='rgba(255,224,166,0.5)';X.fillRect(0,hor-1,W,2);+ {+ const g2=X.createLinearGradient(0,hor,0,hor+70);+ g2.addColorStop(0,'rgba(255,220,160,0.35)');g2.addColorStop(1,'rgba(255,220,160,0)');+ X.fillStyle=g2;X.fillRect(0,hor,W,70);+ }+ // painterly sea dabs+ for(let i=0;i<3400;i++){+ const t=Math.pow(rand(),1.35); // 0=far+ const y=hor+2+t*(H-hor-2);+ const x=rand(-20,W+20);+ const p=0.15+t*1.25;+ const cc=t<0.5?mix([233,181,127],[100,92,124],t/0.5):mix([100,92,124],[66,78,116],(t-0.5)/0.5);+ dab(x,y,rand(7,30)*p,rand(1.2,2.8)*p,rand(-0.02,0.02),cc,0.13+rand(0.12));+ }+ // long swell lines with perspective (gives the sea structure)+ for(let i=0;i<46;i++){+ const t=Math.pow(rand(),1.25);+ const y=hor+10+t*(H-hor-14);+ const p=0.15+t*1.3;+ const len=rand(120,420)*p;+ const x0=rand(-40,W);+ X.strokeStyle='rgba(50,54,86,'+(0.14+rand(0.14))+')';+ X.lineWidth=rand(1,2.6)*p;+ X.beginPath();X.moveTo(x0,y);X.quadraticCurveTo(x0+len*0.5,y+rand(-4,4)*p,x0+len,y+rand(-2,2)*p);X.stroke();+ }+ // warm crest catches+ for(let i=0;i<380;i++){+ const t=Math.pow(rand(),1.1);+ const y=hor+8+t*(H-hor-10);+ const p=0.15+t*1.25;+ dab(rand(W),y,rand(8,26)*p,rand(0.8,1.6)*p,rand(-0.02,0.02),'#c99a86',0.10+rand(0.10));+ }+ // darker trough strokes+ for(let i=0;i<700;i++){+ const t=Math.pow(rand(),1.2);+ const y=hor+6+t*(H-hor-6);+ const p=0.15+t*1.25;+ dab(rand(W),y,rand(10,34)*p,rand(1,2)*p,rand(-0.02,0.02),'#383c5e',0.12+rand(0.10));+ }+ // sun glitter path+ for(let i=0;i<520;i++){+ const t=Math.pow(rand(),0.8);+ const y=hor+3+t*(H-hor-40);+ const spread=14+t*130;+ const x=sunX-40+rand(-spread,spread)*0.9 - t*180; // path drifts toward boat+ const p=0.2+t*1.2;+ const a=0.10+rand(0.28)*(1-t*0.4);+ dab(x,y,rand(4,16)*p,rand(0.8,1.8)*p,0,i%5?'#ffd9a0':'#fff0cc',a);+ }++ // distant sail? no — keep the sea empty, one protagonist.++ // world waypoint marker (objective diamond floating above horizon)+ {+ const wx=986,wy=404;+ X.save();X.globalCompositeOperation='lighter';+ const lg=X.createLinearGradient(0,hor,0,wy-40);+ lg.addColorStop(0,'rgba(240,200,96,0.22)');lg.addColorStop(1,'rgba(240,200,96,0)');+ X.fillStyle=lg;X.fillRect(wx-2,wy-40,4,hor-(wy-40));+ X.restore();+ diamond(wx,wy,7,'#f0c860','rgba(255,244,210,0.95)');+ diamond(wx,wy,11,'rgba(0,0,0,0)','rgba(240,200,96,0.5)');+ text('2.4 km',wx,wy+27,16,'#f4e8c8',{align:'center',weight:'700'});+ }++ // ---- boat ----+ const bx=298,by=556,bs=58,tilt=-0.05;+ // reflection+ boatSilhouette(bx,by+3,bs,tilt,'#8a6540',0.28,0.5);+ for(let i=0;i<26;i++){ // reflection shimmer breaks+ dab(bx+rand(-70,70),by+rand(6,64),rand(8,26),rand(1,2),0,'#8f7788',0.35);+ }+ // wake: gentle V trailing left + ripples+ X.save();X.strokeStyle='rgba(255,236,200,0.4)';X.lineWidth=2;+ X.beginPath();X.moveTo(bx-bs*0.9,by+2);X.quadraticCurveTo(bx-170,by+10,bx-300,by+30);X.stroke();+ X.strokeStyle='rgba(255,236,200,0.25)';+ X.beginPath();X.moveTo(bx-bs*0.9,by+4);X.quadraticCurveTo(bx-160,by+26,bx-280,by+52);X.stroke();+ X.restore();+ for(let i=0;i<14;i++){+ dab(bx+rand(-90,60),by+rand(2,10),rand(10,26),rand(1,2),0,'#ffe4b0',0.22);+ }+ boat(bx,by,bs,tilt,{+ hullDark:'#9a8672',hullMid:'#cbb89e',hullLight:'#f2e2c4',+ sailDark:'#c4ae92',sailLight:'#fff6e0',+ fold:'#5e4c3a',rim:'#ffe9b8',rimA:1.0,rimSide:'right',+ gunwale:'#fff2d4',shadow:'rgba(60,40,50,1)'+ });+ // warm bounce light on water at bow+ dab(bx+bs*0.9,by+5,26,3,0,'#ffdf9e',0.35);++ // scene finish+ grain(5200,0.03);+ vignette(0.30);++ // ---------------- HUD ----------------+ // location title (slam-in frozen)+ {+ const ty=212;+ X.save();+ X.shadowColor='rgba(0,0,0,0.6)';X.shadowBlur=14;+ text('THE CROSSING',W/2,ty,60,'#f6ecd4',{align:'center',font:TITLE_FONT,weight:'700',ls:14,blur:10});+ X.restore();+ // rules + ornaments+ X.strokeStyle='rgba(240,222,180,0.8)';X.lineWidth=1.4;+ X.beginPath();X.moveTo(W/2-250,ty+22);X.lineTo(W/2-30,ty+22);X.moveTo(W/2+30,ty+22);X.lineTo(W/2+250,ty+22);X.stroke();+ diamond(W/2,ty+22,4,'#f0c860','rgba(255,244,210,0.9)');+ text('CHAPTER I — FIRST LIGHT',W/2,ty+48,17,'rgba(244,232,204,0.85)',{align:'center',ls:5,weight:'600'});+ }+ // player plate top-left+ {+ const px=28,py=26;+ panel(px,py,300,74);+ text('PAPER BOAT',px+16,py+26,19,'#f2ead6',{weight:'700',ls:2});+ text('LV 1',px+284,py+26,15,'#f0c860',{align:'right',weight:'700',ls:1});+ bar(px+16,py+36,268,13,1.0,0,['#8fe6b0','#4aa878'],'');+ text('HULL',px+16,py+64,11,'rgba(235,228,210,0.7)',{ls:2,weight:'600'});+ bar(px+52,py+55,180,7,0.85,0,['#f0d47e','#c89b46'],'');+ }+ // minimap top-right+ minimap(1178,96,64,'a');+ // objective bottom-left+ {+ const ox=28,oy=596;+ panel(ox,oy,332,90);+ diamond(ox+24,oy+24,6,'#f0c860','rgba(255,244,210,0.9)');+ text('NEW OBJECTIVE',ox+40,oy+29,14,'#f0c860',{ls:3,weight:'700'});+ text('Cross the Meridian Sea',ox+18,oy+56,23,'#f4efe2',{weight:'600',ls:0.5});+ text('Reach open water 0 / 1',ox+18,oy+78,14,'rgba(235,230,215,0.65)',{ls:1,weight:'600'});+ }+ // key prompts bottom-right+ keyPrompt(1082,662,'E','SET SAIL');+ keyPrompt(1082,690,'Q','CHART');+}++// =========================================================+// FRAME B — "THE STORM PEAK" (boss fight)+// =========================================================+function crestYat(x){+ // diagonal crest from upper-right down toward lower-left+ const pts=[[80,600],[300,492],[560,368],[860,230],[1140,122],[1280,80]];+ if(x<=pts[0][0])return pts[0][1];+ for(let i=0;i<pts.length-1;i++){+ if(x<=pts[i+1][0]){+ const t=(x-pts[i][0])/(pts[i+1][0]-pts[i][0]);+ const tt=t*t*(3-2*t);+ return lerp(pts[i][1],pts[i+1][1],tt);+ }+ }+ return pts[pts.length-1][1];+}+function frameB(){+ R=mulberry32(19770914);+ const gapX=235,gapY=96;++ // sky — bruised storm+ {+ const g=X.createLinearGradient(0,0,0,H);+ g.addColorStop(0,'#12161a');+ g.addColorStop(0.4,'#1c2429');+ g.addColorStop(1,'#0b1013');+ X.fillStyle=g;X.fillRect(0,0,W,H);+ }+ // light gap upper-left+ X.save();X.globalCompositeOperation='lighter';+ let g=X.createRadialGradient(gapX,gapY,0,gapX,gapY,280);+ g.addColorStop(0,'rgba(190,214,220,0.55)');g.addColorStop(0.35,'rgba(150,180,190,0.2)');g.addColorStop(1,'rgba(140,170,180,0)');+ X.fillStyle=g;X.fillRect(0,0,W,H);+ X.restore();+ // heavy cloud dabs+ for(let i=0;i<900;i++){+ const y=Math.pow(rand(),1.6)*360;+ const x=rand(-40,W+40);+ const d=Math.hypot(x-gapX,y-gapY);+ const litT=Math.max(0,1-d/330);+ const base=mix([20,26,30],[38,48,52],rand());+ dab(x,y,rand(30,85),rand(8,20),rand(-0.1,0.1),base,0.12+rand(0.10));+ if(litT>0.05) dab(x+6,y+6,rand(20,55),rand(5,12),rand(-0.1,0.1),'#9db4bc',0.14*litT);+ }+ // roiling cloud bottoms+ for(let i=0;i<260;i++){+ const x=rand(-40,W+40),y=250+Math.pow(rand(),2)*140;+ dab(x,y,rand(30,70),rand(7,14),rand(-0.1,0.1),'#161c20',0.16);+ }+ // light shaft toward the boat+ X.save();X.globalCompositeOperation='lighter';+ for(const[a,w0,w1]of[[0.05,60,190],[0.028,140,360]]){+ X.globalAlpha=1;+ const sg=X.createLinearGradient(0,gapY,0,600);+ sg.addColorStop(0,'rgba(190,214,220,'+a+')');sg.addColorStop(1,'rgba(190,214,220,0)');+ X.fillStyle=sg;+ X.beginPath();+ X.moveTo(gapX-w0/2,gapY);X.lineTo(gapX+w0/2,gapY);+ X.lineTo(gapX+130+w1/2,600);X.lineTo(gapX+130-w1/2,600);X.closePath();X.fill();+ }+ X.restore();++ // distant sea behind wave (left sliver) — soft blend, no hard band+ {+ const g2=X.createLinearGradient(0,300,0,H);+ g2.addColorStop(0,'rgba(24,38,42,0)');g2.addColorStop(0.14,'rgba(24,38,42,0.9)');g2.addColorStop(1,'rgba(9,15,18,1)');+ X.fillStyle=g2;X.fillRect(0,300,W,H-300);+ X.fillStyle='rgba(150,180,185,0.18)';X.fillRect(0,338,240,1.2);+ for(let i=0;i<320;i++){+ const t=rand();const y=345+t*(H-345);+ dab(rand(W),y,rand(8,30)*(0.3+t),rand(1,2.4)*(0.3+t),0,'#22343a',0.14);+ }+ // whitecaps on the open water+ for(let i=0;i<60;i++){+ const t=rand();const y=350+t*(H-350);+ dab(rand(300),y,rand(5,16)*(0.3+t),rand(1,2)*(0.3+t),0,'#7f9a98',0.20);+ }+ }++ // ===== THE WAVE (boss) =====+ X.save();+ X.beginPath();+ X.moveTo(-10,H+10);+ X.lineTo(-10,crestYat(0));+ for(let x=0;x<=W;x+=8)X.lineTo(x,crestYat(x));+ X.lineTo(W+10,crestYat(W));+ X.lineTo(W+10,H+10);X.closePath();+ const wg=X.createLinearGradient(300,650,1150,120);+ wg.addColorStop(0,'#0d181a');+ wg.addColorStop(0.45,'#1d3a3e');+ wg.addColorStop(0.8,'#2e565a');+ wg.addColorStop(1,'#3c6a6a');+ X.fillStyle=wg;X.fill();+ X.clip();+ // broad mass patches first (value structure, not lines)+ const slope=Math.atan2(-1,2.4); // approx crest direction+ for(let i=0;i<220;i++){+ const x=rand(-20,W+20);+ const cy=crestYat(x);+ const depth=rand();+ const y=cy+10+depth*(H-cy);+ if(y>H+30)continue;+ const cc=depth<0.5?mix([46,86,88],[24,46,50],depth*2):mix([24,46,50],[10,20,22],(depth-0.5)*2);+ dab(x,y,rand(60,150),rand(14,34),slope+rand(-0.1,0.1),cc,0.10+rand(0.08));+ }+ // deep shadow just under the crest overhang+ for(let x=40;x<W;x+=10){+ const cy=crestYat(x);+ dab(x+rand(-4,4),cy+rand(14,40),rand(24,60),rand(6,14),slope,'#0c1a1c',0.16+rand(0.10));+ }+ // face streaks along the slope (curved, painterly)+ for(let i=0;i<900;i++){+ const x=rand(-20,W+20);+ const cy=crestYat(x);+ const depth=rand();+ const y=cy+8+depth*(H-cy);+ if(y>H+20)continue;+ const nearCrest=Math.max(0,1-depth*2.2);+ const cc=depth<0.5?mix([62,110,108],[28,56,60],depth*2):mix([28,56,60],[12,22,24],(depth-0.5)*2);+ dab(x,y,rand(14,48),rand(1.6,3.6),slope+rand(-0.08,0.08),cc,0.12+rand(0.10));+ if(nearCrest>0.2&&rand()<0.5)+ dab(x,y,rand(8,26),rand(1,2),slope+rand(-0.05,0.05),'#7ba49e',0.10*nearCrest+rand(0.08));+ }+ // curved water-drag arcs on the face (the wave rolling over itself)+ for(let i=0;i<90;i++){+ const x=rand(200,W);+ const cy=crestYat(x);+ const d0=rand(20,160);+ X.strokeStyle='rgba(120,160,152,'+(0.06+rand(0.10))+')';+ X.lineWidth=rand(1,3);+ X.beginPath();+ X.moveTo(x,cy+d0);+ X.quadraticCurveTo(x-rand(40,90),cy+d0+rand(10,40),x-rand(90,180),cy+d0+rand(50,110));+ X.stroke();+ }+ // foam lace drifting on the lower face (texture for the big teal expanse)+ for(let i=0;i<40;i++){+ const x=rand(360,W+20);+ const cy=crestYat(x);+ const y=cy+rand(90,Math.max(100,H-cy-10));+ if(y>H)continue;+ const n=Math.round(rand(6,14));+ for(let k=0;k<n;k++){+ dab(x+rand(-34,34),y+rand(-10,10),rand(3,10),rand(1,3),slope+rand(-0.2,0.2),'#7ea69e',0.08+rand(0.10));+ }+ }+ // sparse foam runnels sliding down (fewer, softer than before)+ for(let i=0;i<55;i++){+ const x=rand(160,W);+ const cy=crestYat(x);+ const len=rand(26,80);+ X.save();X.translate(x,cy+rand(8,50));X.rotate(slope+1.45+rand(-0.2,0.2));+ X.strokeStyle='rgba(196,220,212,'+(0.08+rand(0.10))+')';X.lineWidth=rand(1,2.2);+ X.beginPath();X.moveTo(0,0);X.quadraticCurveTo(rand(-16,16),len*0.5,rand(-24,24),len);X.stroke();+ X.restore();+ }+ // light shaft catching the face (rim glow from upper-left)+ X.save();X.globalCompositeOperation='lighter';+ const fg=X.createLinearGradient(150,350,650,550);+ fg.addColorStop(0,'rgba(160,190,190,0.16)');fg.addColorStop(1,'rgba(160,190,190,0)');+ X.fillStyle=fg;X.fillRect(0,0,W,H);+ X.restore();+ X.restore(); // unclip++ // crest foam: chunky tumbling clusters, not a thin line+ for(let x=40;x<W;x+=6){+ const cy=crestYat(x);+ const litT=Math.max(0,1-Math.hypot(x-gapX,cy-gapY)/900);+ if(rand()<0.9)dab(x+rand(-5,5),cy+rand(-6,8),rand(5,18),rand(3,8),slope+rand(-0.3,0.3),'#bcd6ca',0.24+rand(0.26)+litT*0.18);+ if(rand()<0.5)dab(x+rand(-7,3),cy-rand(3,16),rand(3,9),rand(2,5),0,'#e2efe4',0.18+rand(0.26));+ }+ // big foam boulders at intervals (tumbling masses)+ for(let i=0;i<16;i++){+ const x=140+i*72+rand(-20,20);+ const cy=crestYat(x);+ const n=Math.round(rand(8,16));+ for(let k=0;k<n;k++){+ dab(x+rand(-26,20),cy+rand(-16,22),rand(6,20),rand(4,12),rand(-0.6,0.6),k%3?'#a8c2b8':'#dcece2',0.20+rand(0.24));+ }+ // foam bits dropping down the face+ for(let k=0;k<6;k++){+ dab(x+rand(-14,6),cy+rand(24,90),rand(2,6),rand(2,5),0,'#b8d2c8',0.18+rand(0.16));+ }+ }+ // spray blown left off the crest+ for(let i=0;i<380;i++){+ const x=rand(100,W);+ const cy=crestYat(x);+ const d=rand(6,90);+ dab(x-d*rand(0.6,1.4),cy-d*rand(0.3,0.8),rand(0.8,2.6),rand(0.8,2.2),0,'#e6f2ec',0.08+rand(0.22)*(1-d/100));+ }+ // motion smears parallel to crest+ X.save();X.globalCompositeOperation='lighter';+ for(let i=0;i<26;i++){+ const x=rand(300,1200);const cy=crestYat(x);+ X.strokeStyle='rgba(220,238,230,'+(0.05+rand(0.07))+')';X.lineWidth=rand(1,3);+ X.beginPath();X.moveTo(x,cy+rand(-4,8));X.lineTo(x-rand(60,160),cy+rand(20,60));X.stroke();+ }+ X.restore();++ // ---- boat: small but unmissable, climbing the base of the wave ----+ const bx=300,by=556,bs=44,tilt=-0.34;+ // dark water window behind the boat so it separates from the foam+ X.save();+ const dw=X.createRadialGradient(bx+14,by-26,0,bx+14,by-26,95);+ dw.addColorStop(0,'rgba(12,26,28,0.75)');dw.addColorStop(0.7,'rgba(12,26,28,0.35)');dw.addColorStop(1,'rgba(12,26,28,0)');+ X.fillStyle=dw;X.fillRect(bx-90,by-130,210,190);+ X.restore();+ // pool of shaft light on the water around the boat+ X.save();X.globalCompositeOperation='lighter';+ const bl=X.createRadialGradient(bx,by-10,0,bx,by-10,130);+ bl.addColorStop(0,'rgba(170,200,200,0.20)');bl.addColorStop(1,'rgba(170,200,200,0)');+ X.fillStyle=bl;X.fillRect(bx-140,by-150,280,290);+ X.restore();+ // churned water + foam ring at hull+ for(let i=0;i<46;i++){+ dab(bx+rand(-64,64),by+rand(-6,16),rand(6,24),rand(2,6),rand(-0.3,0.3),'#cfe2da',0.24+rand(0.22));+ }+ for(let i=0;i<20;i++){+ dab(bx+rand(-44,44),by+rand(-18,-4),rand(2,6),rand(2,5),0,'#eef6f0',0.32);+ }+ boat(bx,by,bs,tilt,{+ hullDark:'#5c6864',hullMid:'#95a29a',hullLight:'#e2eade',+ sailDark:'#707c76',sailLight:'#ffffff',+ fold:'#1a2224',rim:'#f2fffa',rimA:1.0,rimSide:'left',+ gunwale:'#eefaf2',shadow:'rgba(6,12,14,1)'+ });+ // spray whipping off the boat+ for(let i=0;i<14;i++){+ dab(bx-rand(20,70),by-rand(10,50),rand(1,3),rand(1,2),0,'#e6f2ec',0.25);+ }+ // damage popup+ text('-14',bx+86,by-92,27,'#ff6a52',{weight:'800',italic:true,ls:1,align:'center',blur:6});+ text('HULL',bx+86,by-74,11,'rgba(255,150,130,0.8)',{weight:'700',ls:2,align:'center'});++ // rain — driven from upper right+ X.save();+ for(let i=0;i<210;i++){+ const x=rand(-40,W+120),y=rand(-20,H);+ const len=rand(20,48);+ X.strokeStyle='rgba(200,216,218,'+(0.03+rand(0.08))+')';+ X.lineWidth=rand(0.7,1.4);+ X.beginPath();X.moveTo(x,y);X.lineTo(x-len*0.34,y+len);X.stroke();+ }+ // a few close heavy streaks+ for(let i=0;i<14;i++){+ const x=rand(W+100),y=rand(H);const len=rand(80,150);+ X.strokeStyle='rgba(210,226,228,0.12)';X.lineWidth=rand(1.6,2.4);+ X.beginPath();X.moveTo(x,y);X.lineTo(x-len*0.34,y+len);X.stroke();+ }+ X.restore();++ grain(6200,0.035);+ vignette(0.42,'rgba(4,6,10,0.5)');+ // low-HP red edge pulse+ {+ const g2=X.createRadialGradient(W/2,H/2,H*0.40,W/2,H/2,H*0.78);+ g2.addColorStop(0,'rgba(180,30,24,0)');g2.addColorStop(1,'rgba(180,30,24,0.17)');+ X.fillStyle=g2;X.fillRect(0,0,W,H);+ }++ // ---------------- HUD ----------------+ // boss bar top-center+ {+ const bw=540,bxx=W/2-bw/2,byy=74;+ text('THE MAELSTROM',W/2,46,30,'#f2e8d6',{align:'center',font:TITLE_FONT,weight:'700',ls:8,blur:8});+ text('DEVOURER OF SAILS',W/2,64,12,'rgba(240,200,150,0.85)',{align:'center',ls:4,weight:'600'});+ bar(bxx,byy,bw,13,0.76,0.85,['#e05244','#8e1f1a'],'rgba(240,200,96,0.85)');+ diamond(bxx-10,byy+6.5,5,'#f0c860','rgba(255,244,210,0.9)');+ diamond(bxx+bw+10,byy+6.5,5,'#f0c860','rgba(255,244,210,0.9)');+ }+ // SURVIVE slam (frozen mid-slam, with smear echoes)+ {+ X.save();X.translate(W/2,178);X.rotate(-0.025);+ text('SURVIVE',1,6,64,'rgba(200,50,36,0.5)',{align:'center',weight:'800',italic:true,ls:6,shadow:false});+ text('SURVIVE',0,0,64,'#f4f2ec',{align:'center',weight:'800',italic:true,ls:6,blur:12});+ X.restore();+ }+ // player plate top-left — hurt+ {+ const px=28,py=26;+ panel(px,py,300,74,'rgba(240,120,100,0.55)');+ text('PAPER BOAT',px+16,py+26,19,'#f2ead6',{weight:'700',ls:2});+ text('LV 1',px+284,py+26,15,'#f0c860',{align:'right',weight:'700',ls:1});+ bar(px+16,py+36,268,13,0.22,0.47,['#e05244','#8e1f1a'],'rgba(240,200,96,0.8)');+ text('HULL',px+16,py+64,11,'rgba(255,170,150,0.85)',{ls:2,weight:'600'});+ bar(px+52,py+55,180,7,0.18,0,['#f0d47e','#c89b46'],'');+ }+ // minimap top-right — storm swirl+ minimap(1178,96,64,'b');+ // objective bottom-left+ {+ const ox=28,oy=596;+ panel(ox,oy,332,90,'rgba(240,120,100,0.55)');+ diamond(ox+24,oy+24,6,'#e05244','rgba(255,200,180,0.9)');+ text('OBJECTIVE',ox+40,oy+29,14,'#ff9678',{ls:3,weight:'700'});+ text('Survive the Maelstrom',ox+18,oy+56,23,'#f4efe2',{weight:'600',ls:0.5});+ text('Hold together',ox+18,oy+78,14,'rgba(235,230,215,0.65)',{ls:1,weight:'600'});+ text('01:47',ox+312,oy+62,30,'#f0c860',{align:'right',weight:'700',ls:2});+ }+ // brace prompt bottom-right+ {+ const kx=1010,ky=668;+ X.save();+ X.fillStyle='rgba(8,12,16,0.6)';X.strokeStyle='rgba(240,150,120,0.9)';X.lineWidth=1.8;+ rr(kx,ky-16,86,24,4);X.fill();X.stroke();+ text('SPACE',kx+43,ky+1,14,'#f4efe2',{align:'center',weight:'700',ls:2});+ text('BRACE',kx+104,ky+1,17,'#ffb49a',{weight:'700',ls:3});+ X.restore();+ }+}++// ---------- entry ----------+window.drawFrame=function(which){+ X.setTransform(1,0,0,1,0,0);+ X.clearRect(0,0,W,H);+ if(which==='a')frameA();else frameB();+ window.DONE=true;+};+window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/glow/boat.html b/assets/previews-src/glow/boat.htmlnew file mode 100644index 0000000..3f27f41--- /dev/null+++ b/assets/previews-src/glow/boat.html@@ -0,0 +1,526 @@+<!doctype html>+<html>+<head><meta charset="utf-8"><title>glow boat</title>+<style>html,body{margin:0;padding:0;background:#0a1226}canvas{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++// ---------- deterministic rng ----------+function mulberry32(seed){+ let a = seed >>> 0;+ return function(){+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+const lerp = (a,b,t)=>a+(b-a)*t;+const clamp = (v,a,b)=>v<a?a:(v>b?b:v);+const sstep = (a,b,x)=>{ const t=clamp((x-a)/(b-a),0,1); return t*t*(3-2*t); };++// ---------- value noise ----------+function makeNoise(rng){+ const g = new Float64Array(256);+ for(let i=0;i<256;i++) g[i]=rng();+ const perm = new Uint8Array(256);+ for(let i=0;i<256;i++) perm[i]=i;+ for(let i=255;i>0;i--){ const j=Math.floor(rng()*(i+1)); const t=perm[i]; perm[i]=perm[j]; perm[j]=t; }+ const P = i => perm[i & 255];+ function noise2(x,y){+ const ix=Math.floor(x), iy=Math.floor(y);+ const fx=x-ix, fy=y-iy;+ const sx=fx*fx*(3-2*fx), sy=fy*fy*(3-2*fy);+ const v=(a,b)=>g[P(P((ix+a)&255)+((iy+b)&255))];+ return lerp(lerp(v(0,0),v(1,0),sx), lerp(v(0,1),v(1,1),sx), sy);+ }+ function fbm(x,y){+ return noise2(x,y)*0.55 + noise2(x*2.1+13.7,y*2.1+7.3)*0.3 + noise2(x*4.3+41.2,y*4.3+17.9)*0.15;+ }+ return { noise2, fbm };+}++// ---------- vortex field helper ----------+// base: {a: angle, s: strength}; vorts: [{x,y,r,s}] (s>0 counter-clockwise)+function fieldAngle(x,y,base,vorts,noiseFn,noiseScale,noiseAmp){+ let vx = Math.cos(base.a)*base.s, vy = Math.sin(base.a)*base.s;+ for(let i=0;i<vorts.length;i++){+ const o=vorts[i];+ const dx=x-o.x, dy=y-o.y;+ const d2=dx*dx+dy*dy;+ const f=o.s*Math.exp(-d2/(2*o.r*o.r));+ const d=Math.sqrt(d2)+1;+ vx += (-dy/d)*f; vy += (dx/d)*f;+ }+ let a = Math.atan2(vy,vx);+ if(noiseAmp) a += (noiseFn(x*noiseScale,y*noiseScale)-0.5)*2*noiseAmp;+ return a;+}++// ---------- base layer (offscreen painted scene) ----------+const base = document.createElement('canvas');+base.width=W; base.height=H;+const bx = base.getContext('2d');+let baseData = null;++function radial(g,x,y,r,stops){+ const grad=g.createRadialGradient(x,y,0,x,y,r);+ for(const s of stops) grad.addColorStop(s[0],s[1]);+ g.fillStyle=grad; g.fillRect(0,0,W,H);+}++function sampleBase(x,y){+ const xi=clamp(Math.round(x),0,W-1), yi=clamp(Math.round(y),0,H-1);+ const i=(yi*W+xi)*4;+ return [baseData[i],baseData[i+1],baseData[i+2]];+}++// ---------- brush strokes pass ----------+// stratified grid so canvas is fully covered+function strokePass(field, opts, rng){+ const {cell, lenMin, lenMax, wMin, wMax, alpha, jitter, light, curl} = opts;+ ctx.lineCap='round'; ctx.lineJoin='round';+ const cols=Math.ceil(W/cell), rows=Math.ceil(H/cell);+ for(let cyc=0; cyc<(opts.per||1); cyc++){+ for(let gy=0; gy<rows; gy++){+ for(let gx=0; gx<cols; gx++){+ const x0=(gx+rng())*cell, y0=(gy+rng())*cell;+ let c=sampleBase(x0,y0);+ const j=(rng()-0.5)*2*jitter;+ const lt=light?light(x0,y0,rng):1;+ const r=clamp(c[0]*lt+j,0,255), g2=clamp(c[1]*lt+j*0.9,0,255), b=clamp(c[2]*lt+j*0.7,0,255);+ ctx.strokeStyle=`rgba(${r|0},${g2|0},${b|0},${alpha})`;+ ctx.lineWidth=lerp(wMin,wMax,rng());+ const len=lerp(lenMin,lenMax,rng());+ const steps=5;+ const seg=len/steps;+ // walk back half, then forward, so stroke is centered on sample point+ let px=x0, py=y0;+ for(let s=0;s<Math.floor(steps/2);s++){+ const a=field(px,py);+ px-=Math.cos(a)*seg; py-=Math.sin(a)*seg;+ }+ ctx.beginPath(); ctx.moveTo(px,py);+ let bend=(rng()-0.5)*(curl||0);+ let pa=field(px,py);+ for(let s=0;s<steps;s++){+ const a=field(px,py)+bend*s;+ pa=pa+ (a-pa)*0.6;+ px+=Math.cos(pa)*seg; py+=Math.sin(pa)*seg;+ ctx.lineTo(px,py);+ }+ ctx.stroke();+ }+ }+ }+}++// ---------- glow helpers (radial gradients, additive) ----------+function glow(x,y,r,col,a){+ ctx.save();+ ctx.globalCompositeOperation='lighter';+ const g=ctx.createRadialGradient(x,y,0,x,y,r);+ g.addColorStop(0,`rgba(${col},${a})`);+ g.addColorStop(0.35,`rgba(${col},${a*0.45})`);+ g.addColorStop(1,`rgba(${col},0)`);+ ctx.fillStyle=g;+ ctx.fillRect(x-r,y-r,2*r,2*r);+ ctx.restore();+}++// ---------- the paper boat, painted in strokes ----------+// s = hull width in px; heading right; tilt in radians (positive = bow up)+function paintBoat(x,y,s,tilt,rng,stormy){+ ctx.save();+ ctx.translate(x,y);+ ctx.rotate(-tilt);+ ctx.lineCap='round';+ const u=s; // unit++ // --- glow under/behind sail (bloom base) ---+ glow(0,-0.16*u, 1.15*u, '255,150,60', 0.34);+ glow(0,-0.20*u, 0.55*u, '255,190,110', 0.5);++ // --- sail: narrow triangular peak, a fan of glowing strokes ---+ const peak=[0.015*u,-0.47*u];+ const baseL=[-0.17*u,-0.01*u], baseR=[0.20*u,-0.02*u];+ const nSail=8;+ for(let i=0;i<nSail;i++){+ const t=i/(nSail-1);+ const bxp=lerp(baseL[0],baseR[0],t), byp=lerp(baseL[1],baseR[1],t);+ const e=Math.abs(t-0.45)*2.2; // 0 core, ~1 edge+ const ee=clamp(e,0,1);+ const rC=lerp(255,208,ee), gC=lerp(210,104,ee), bC=lerp(130,38,ee);+ ctx.strokeStyle=`rgba(${rC|0},${gC|0},${bC|0},0.95)`;+ ctx.lineWidth=lerp(0.06,0.04,ee)*u*(0.9+rng()*0.25);+ ctx.beginPath();+ ctx.moveTo(bxp+(rng()-0.5)*0.02*u, byp+(rng()-0.5)*0.02*u);+ const mx=lerp(bxp,peak[0],0.5)+(rng()-0.5)*0.035*u;+ const my=lerp(byp,peak[1],0.5)+(rng()-0.5)*0.03*u;+ ctx.quadraticCurveTo(mx,my, peak[0]+(rng()-0.5)*0.025*u, peak[1]+rng()*0.03*u);+ ctx.stroke();+ }+ // soft hot core inside the sail+ ctx.save();+ ctx.globalCompositeOperation='lighter';+ ctx.strokeStyle='rgba(255,232,180,0.55)';+ ctx.lineWidth=0.055*u;+ ctx.beginPath();+ ctx.moveTo(0.012*u,-0.06*u);+ ctx.quadraticCurveTo(0.004*u,-0.28*u, peak[0],peak[1]+0.08*u);+ ctx.stroke();+ ctx.restore();++ // --- hull: folded-paper hull with raised pointed tips ---+ const sternT=[-0.52*u,-0.115*u], bowT=[0.55*u,-0.135*u]; // raised paper points+ const hull=new Path2D();+ hull.moveTo(sternT[0],sternT[1]);+ hull.quadraticCurveTo(-0.20*u,0.035*u, 0.0,0.035*u); // top edge dips to middle+ hull.quadraticCurveTo(0.22*u,0.035*u, bowT[0],bowT[1]); // rises to bow point+ hull.quadraticCurveTo(0.34*u,0.16*u, 0.20*u,0.185*u); // bow underside+ hull.quadraticCurveTo(0,0.21*u,-0.19*u,0.185*u); // keel+ hull.quadraticCurveTo(-0.33*u,0.155*u, sternT[0],sternT[1]);+ ctx.fillStyle='rgba(13,22,42,0.97)';+ ctx.fill(hull);+ // painterly texture strokes inside the hull+ for(let i=0;i<4;i++){+ const t=i/3;+ ctx.strokeStyle=`rgba(${20+t*16+rng()*8|0},${32+t*16|0},${58+t*20|0},0.8)`;+ ctx.lineWidth=lerp(0.055,0.035,t)*u;+ const yy=lerp(0.07,0.16,t)*u;+ ctx.beginPath();+ ctx.moveTo(-0.40*u*(1-t*0.3), yy*0.8);+ ctx.quadraticCurveTo(0, yy+0.045*u, 0.42*u*(1-t*0.3), yy*0.75);+ ctx.stroke();+ }+ // warm rim light along the gunwale (lit by the sail)+ ctx.strokeStyle='rgba(255,158,70,0.9)';+ ctx.lineWidth=0.032*u;+ ctx.beginPath();+ ctx.moveTo(sternT[0]+0.02*u,sternT[1]+0.02*u);+ ctx.quadraticCurveTo(-0.2*u,0.045*u,0,0.045*u);+ ctx.quadraticCurveTo(0.22*u,0.045*u,bowT[0]-0.015*u,bowT[1]+0.02*u);+ ctx.stroke();+ // the two paper points catch the light+ ctx.strokeStyle='rgba(255,196,120,0.95)';+ ctx.lineWidth=0.028*u;+ ctx.beginPath(); ctx.moveTo(bowT[0]-0.09*u,bowT[1]+0.055*u); ctx.lineTo(bowT[0],bowT[1]); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(sternT[0]+0.085*u,sternT[1]+0.055*u); ctx.lineTo(sternT[0],sternT[1]); ctx.stroke();++ ctx.restore();++ // --- embers / sparks rising from the sail ---+ ctx.save();+ ctx.globalCompositeOperation='lighter';+ const nSpark = stormy? 16 : 9;+ for(let i=0;i<nSpark;i++){+ const t=rng();+ const dx = stormy ? (-0.2-1.5*t)*s*(0.5+rng()) : (rng()-0.35)*0.5*s;+ const dy = -0.35*s - t*(stormy?0.9:1.1)*s - rng()*0.2*s;+ const px=x+dx, py=y+dy+0.1*s;+ const rr=(1-t)*0.028*s+1;+ const al=(1-t)*0.85;+ const g=ctx.createRadialGradient(px,py,0,px,py,rr*3);+ g.addColorStop(0,`rgba(255,220,150,${al})`);+ g.addColorStop(0.4,`rgba(255,150,60,${al*0.5})`);+ g.addColorStop(1,'rgba(255,150,60,0)');+ ctx.fillStyle=g;+ ctx.fillRect(px-rr*3,py-rr*3,rr*6,rr*6);+ }+ ctx.restore();+}++// broken shimmering reflection in the water below the boat+function paintReflection(x,y,s,rng,rough){+ ctx.save();+ ctx.globalCompositeOperation='lighter';+ ctx.lineCap='round';+ const n=rough?7:12;+ for(let i=0;i<n;i++){+ const t=i/(n-1);+ const yy=y+0.12*s+t*(rough?0.8:1.5)*s + (rng()-0.5)*0.28*s;+ const ww=(1-t)*(rough?0.4:0.5)*s*(0.25+rng()*0.9);+ const xx=x+(rng()-0.5)*(rough?0.5:0.45)*s*(0.6+t*2);+ ctx.strokeStyle=`rgba(255,${140+rng()*50|0},60,${(0.15+0.85*(1-t))*(rough?0.28:0.38)*(0.5+rng()*0.5)})`;+ ctx.lineWidth=(rough?0.05:0.04)*s*(1-t*0.5)*(0.6+rng()*0.8)+1;+ ctx.beginPath();+ ctx.moveTo(xx-ww/2,yy);+ ctx.quadraticCurveTo(xx,yy+(rng()-0.5)*3,xx+ww/2,yy);+ ctx.stroke();+ }+ ctx.restore();+}++function vignette(strength){+ const g=ctx.createRadialGradient(W/2,H/2,H*0.35,W/2,H/2,H*0.95);+ g.addColorStop(0,'rgba(4,7,18,0)');+ g.addColorStop(1,`rgba(4,7,18,${strength})`);+ ctx.fillStyle=g;+ ctx.fillRect(0,0,W,H);+}++// =========================================================+// FRAME A — setting out: calm dawn, gentle swirls, big sky+// =========================================================+function drawA(){+ const rng=mulberry32(20260928);+ const nz=makeNoise(mulberry32(777));+ const horizon=0.46*H;+ const sun={x:0.78*W,y:horizon-0.035*H};+ const boat={x:0.30*W,y:0.735*H,s:170};++ // ---- base layer ----+ const sky=bx.createLinearGradient(0,0,0,horizon);+ sky.addColorStop(0,'#241d4e'); // violet dusk+ sky.addColorStop(0.45,'#1e3260');+ sky.addColorStop(0.8,'#1c4a6a');+ sky.addColorStop(1,'#2c5f74'); // teal near horizon+ bx.fillStyle=sky; bx.fillRect(0,0,W,horizon);+ const sea=bx.createLinearGradient(0,horizon,0,H);+ sea.addColorStop(0,'#25617a');+ sea.addColorStop(0.35,'#173e58');+ sea.addColorStop(1,'#0a1630');+ bx.fillStyle=sea; bx.fillRect(0,horizon,W,H-horizon);+ // faint pale band along the whole horizon (dawn haze)+ const hz=bx.createLinearGradient(0,horizon-0.06*H,0,horizon+0.05*H);+ hz.addColorStop(0,'rgba(120,170,190,0)');+ hz.addColorStop(0.55,'rgba(150,195,205,0.28)');+ hz.addColorStop(1,'rgba(120,170,190,0)');+ bx.fillStyle=hz; bx.fillRect(0,horizon-0.06*H,W,0.11*H);+ // warm dawn light around the sun, bleeding into sky and sea+ radial(bx,sun.x,sun.y,0.46*W,[[0,'rgba(255,170,80,0.85)'],[0.18,'rgba(240,130,60,0.5)'],[0.5,'rgba(150,80,70,0.18)'],[1,'rgba(0,0,0,0)']]);+ // sun reflection column on the water+ const refl=bx.createLinearGradient(0,horizon,0,H);+ refl.addColorStop(0,'rgba(255,160,70,0.55)');+ refl.addColorStop(0.6,'rgba(220,110,50,0.16)');+ refl.addColorStop(1,'rgba(200,90,40,0)');+ bx.save();+ bx.beginPath();+ bx.moveTo(sun.x-0.035*W,horizon);+ bx.lineTo(sun.x+0.035*W,horizon);+ bx.lineTo(sun.x+0.14*W,H);+ bx.lineTo(sun.x-0.14*W,H);+ bx.closePath();+ bx.fillStyle=refl; bx.fill();+ bx.restore();+ // faint warm pool around the boat (its own lantern-light on the water)+ radial(bx,boat.x,boat.y,0.13*W,[[0,'rgba(255,150,70,0.35)'],[1,'rgba(0,0,0,0)']]);+ baseData=bx.getImageData(0,0,W,H).data;++ // ---- flow field ----+ const skyVorts=[+ {x:0.16*W,y:0.12*H,r:0.13*W,s:2.6},+ {x:0.46*W,y:0.24*H,r:0.10*W,s:-2.2},+ {x:sun.x,y:sun.y-0.04*H,r:0.11*W,s:3.0},+ {x:0.92*W,y:0.08*H,r:0.09*W,s:-1.8},+ ];+ const field=(x,y)=>{+ if(y<horizon+8){+ return fieldAngle(x,y,{a:0.06,s:1},skyVorts,nz.fbm,0.004,0.9);+ }+ // water: horizontal streaks, mild ripple+ const rip=(nz.fbm(x*0.004,y*0.012)-0.5)*0.28;+ return rip + Math.sin(x*0.002+y*0.02)*0.05;+ };++ // ---- paint ----+ ctx.globalCompositeOperation='source-over';+ ctx.drawImage(base,0,0);+ const warmLight=(x,y,r)=>{+ const dx=x-sun.x, dy=y-sun.y;+ const d=Math.sqrt(dx*dx+dy*dy);+ return 1 + 0.22*Math.exp(-d/(0.3*W)) + (r()-0.5)*0.12;+ };+ strokePass(field,{cell:26,lenMin:34,lenMax:60,wMin:7,wMax:12,alpha:0.85,jitter:16,light:warmLight,curl:0.05},rng);+ strokePass(field,{cell:15,lenMin:22,lenMax:42,wMin:4,wMax:7,alpha:0.8,jitter:20,light:warmLight,curl:0.06},rng);+ strokePass(field,{cell:10,lenMin:12,lenMax:26,wMin:2,wMax:4,alpha:0.65,jitter:24,light:warmLight,curl:0.08},rng);++ // sun disc + bloom (additive)+ glow(sun.x,sun.y,0.20*W,'255,170,80',0.55);+ glow(sun.x,sun.y,0.055*W,'255,220,150',0.9);+ glow(sun.x,sun.y,0.022*W,'255,245,215',1);++ // gentle wake behind the boat+ ctx.save();+ ctx.lineCap='round';+ for(let i=0;i<5;i++){+ const t=i/4;+ ctx.strokeStyle=`rgba(140,200,210,${0.35-0.05*i})`;+ ctx.lineWidth=4-t*2;+ ctx.beginPath();+ const y0=boat.y+0.06*boat.s+i*5;+ ctx.moveTo(boat.x-0.5*boat.s-10-i*38, y0+(rng()-0.5)*6);+ ctx.quadraticCurveTo(boat.x-0.3*boat.s-i*20, y0-4, boat.x-0.2*boat.s, y0);+ ctx.stroke();+ }+ ctx.restore();++ paintBoat(boat.x,boat.y,boat.s,0.045,rng,false);+ paintReflection(boat.x,boat.y+0.1*boat.s,boat.s,rng,false);++ vignette(0.5);+}++// =========================================================+// FRAME B — storm peak: one huge diagonal wave, turbulence+// =========================================================+function drawB(){+ const rng=mulberry32(99280926);+ const nz=makeNoise(mulberry32(4242));+ // wave surface: high at the right, low at the left; boat rides its lower slope+ const waveTop=(x)=>{+ const u=x/W;+ return H*(0.80 - 0.60*sstep(0.08,0.92,u)) + Math.sin(u*9+1.2)*8;+ };+ const crest={x:0.865*W,y:waveTop(0.865*W)};+ const curl={x:crest.x-0.045*W,y:crest.y+0.055*H}; // roll center of the breaking crest+ const boat={x:0.30*W,y:waveTop(0.30*W)+0.010*H,s:100};+ const moon={x:0.14*W,y:0.14*H};++ // ---- base layer ----+ const sky=bx.createLinearGradient(0,0,0,H*0.75);+ sky.addColorStop(0,'#120f2e');+ sky.addColorStop(0.5,'#1a1a44');+ sky.addColorStop(1,'#1e2c52');+ bx.fillStyle=sky; bx.fillRect(0,0,W,H);+ // pale moonlight fighting through the storm (cool, dim — amber stays the boat's)+ radial(bx,moon.x,moon.y,0.3*W,[[0,'rgba(190,200,235,0.6)'],[0.25,'rgba(140,150,200,0.25)'],[1,'rgba(0,0,0,0)']]);+ // wave body+ bx.save();+ bx.beginPath();+ bx.moveTo(0,H); bx.lineTo(0,waveTop(0));+ for(let x=0;x<=W;x+=8) bx.lineTo(x,waveTop(x));+ bx.lineTo(W,H); bx.closePath();+ const wg=bx.createLinearGradient(0,0.2*H,0,H);+ wg.addColorStop(0,'#2f7a80'); // lit teal near the crest+ wg.addColorStop(0.4,'#1c4a60');+ wg.addColorStop(1,'#081226'); // abyss+ bx.fillStyle=wg; bx.fill();+ bx.clip();+ // foam pale band along the wave surface+ bx.lineCap='round';+ bx.strokeStyle='rgba(190,230,225,0.75)';+ bx.lineWidth=16;+ bx.beginPath();+ for(let x=0.2*W;x<=W;x+=8){const y=waveTop(x)+8; if(x===0.2*W)bx.moveTo(x,y); else bx.lineTo(x,y);}+ bx.stroke();+ bx.restore();+ // curl shadow under the breaking crest+ radial(bx,curl.x,curl.y+0.03*H,0.10*W,[[0,'rgba(6,12,26,0.8)'],[1,'rgba(0,0,0,0)']]);+ // warm pool: the boat's glow on the black water+ radial(bx,boat.x,boat.y,0.15*W,[[0,'rgba(255,150,65,0.5)'],[0.4,'rgba(230,110,50,0.22)'],[1,'rgba(0,0,0,0)']]);+ baseData=bx.getImageData(0,0,W,H).data;++ // ---- flow field: full turbulence ----+ const skyVorts=[+ {x:0.30*W,y:0.14*H,r:0.12*W,s:3.4},+ {x:0.58*W,y:0.10*H,r:0.10*W,s:-3.2},+ {x:0.12*W,y:0.30*H,r:0.09*W,s:2.8},+ {x:0.80*W,y:0.05*H,r:0.08*W,s:-2.6},+ {x:moon.x,y:moon.y,r:0.08*W,s:3.2},+ ];+ const curlVort=[{x:curl.x,y:curl.y,r:0.085*W,s:9}];+ const field=(x,y)=>{+ const wy=waveTop(x);+ if(y<wy-6){+ return fieldAngle(x,y,{a:Math.PI+0.3,s:0.8},skyVorts,nz.fbm,0.005,1.5);+ }+ // slope direction of the wave face (strokes run along the face)+ const dx=12, slope=Math.atan2(waveTop(x+dx)-waveTop(x-dx),2*dx);+ const depth=sstep(0,0.28*H,y-wy);+ const a=fieldAngle(x,y,{a:slope+Math.PI,s:1.4},curlVort,nz.fbm,0.006,0.5+0.7*depth);+ return a;+ };++ // ---- paint ----+ ctx.globalCompositeOperation='source-over';+ ctx.drawImage(base,0,0);+ const stormLight=(x,y,r)=>{+ const dm=Math.hypot(x-moon.x,y-moon.y);+ const db=Math.hypot(x-boat.x,y-boat.y);+ return 1 + 0.2*Math.exp(-dm/(0.22*W)) + 0.25*Math.exp(-db/(0.13*W)) + (r()-0.5)*0.14;+ };+ strokePass(field,{cell:26,lenMin:38,lenMax:70,wMin:7,wMax:13,alpha:0.85,jitter:15,light:stormLight,curl:0.09},rng);+ strokePass(field,{cell:15,lenMin:26,lenMax:48,wMin:4,wMax:7,alpha:0.8,jitter:20,light:stormLight,curl:0.10},rng);+ strokePass(field,{cell:10,lenMin:14,lenMax:30,wMin:2,wMax:4,alpha:0.65,jitter:26,light:stormLight,curl:0.12},rng);++ // breaking crest: hooked foam strokes curling over, torn spray+ ctx.save();+ ctx.lineCap='round';+ for(let i=0;i<40;i++){+ const t=rng();+ const x0=lerp(0.58*W,0.985*W,t);+ const y0=waveTop(x0)+rng()*14-4;+ const pale=200+rng()*55|0;+ const corner=1-0.55*sstep(0.86,1,t); // calm the very corner+ ctx.strokeStyle=`rgba(${pale-30},${pale},${pale-8},${(0.45+rng()*0.4)*corner})`;+ ctx.lineWidth=(2+rng()*4.5)*lerp(1,0.75,sstep(0.86,1,t));+ // hook: follow surface then curl down-left around the roll center+ ctx.beginPath();+ let px=x0, py=y0;+ ctx.moveTo(px,py);+ let a=Math.atan2(waveTop(x0+10)-waveTop(x0-10),20)+Math.PI;+ const hook=0.12+rng()*0.22;+ const segs=4+Math.floor(rng()*4), segLen=6+rng()*4;+ for(let s2=0;s2<segs;s2++){+ a+=hook;+ px+=Math.cos(a)*segLen; py+=Math.sin(a)*segLen;+ ctx.lineTo(px,py);+ }+ ctx.stroke();+ }+ // spray blown off the crest toward the boat+ ctx.globalCompositeOperation='lighter';+ for(let i=0;i<60;i++){+ const t=rng();+ const px=crest.x-t*0.45*W+(rng()-0.5)*60;+ const py=crest.y-10-t*0.12*H+(rng()-0.5)*50;+ const rr=1+rng()*2.2;+ ctx.fillStyle=`rgba(200,225,230,${0.5*(1-t)})`;+ ctx.beginPath(); ctx.arc(px,py,rr,0,7); ctx.fill();+ }+ ctx.restore();++ // moon: dim silver, fighting through+ glow(moon.x,moon.y,0.14*W,'190,205,240',0.5);+ glow(moon.x,moon.y,0.03*W,'225,232,250',0.85);++ // foam licking the hull+ paintBoat(boat.x,boat.y,boat.s,0.22,rng,true);+ ctx.save();+ ctx.lineCap='round';+ for(let i=0;i<6;i++){+ ctx.strokeStyle=`rgba(185,220,220,${0.45+rng()*0.3})`;+ ctx.lineWidth=2.5+rng()*3;+ const x0=boat.x-0.5*boat.s+rng()*boat.s*0.85;+ const y0=boat.y+0.10*boat.s+rng()*0.08*boat.s;+ ctx.beginPath();+ ctx.moveTo(x0,y0);+ ctx.quadraticCurveTo(x0+8,y0-4-rng()*6,x0+16+rng()*8,y0-1+rng()*4);+ ctx.stroke();+ }+ ctx.restore();+ paintReflection(boat.x,boat.y+0.05*boat.s,boat.s,rng,true);++ vignette(0.62);+}++window.drawFrame=function(which){+ ctx.setTransform(1,0,0,1,0,0);+ ctx.globalCompositeOperation='source-over';+ ctx.clearRect(0,0,W,H);+ bx.setTransform(1,0,0,1,0,0);+ bx.clearRect(0,0,W,H);+ if(which==='a') drawA(); else drawB();+ window.DONE=true;+};+window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/hud/boat.html b/assets/previews-src/hud/boat.htmlnew file mode 100644index 0000000..094e4a8--- /dev/null+++ b/assets/previews-src/hud/boat.html@@ -0,0 +1,644 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<style>html,body{margin:0;padding:0;background:#000}canvas{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');+const ACC = '#FF4A1C';++// ---------- deterministic rng ----------+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}}+let R = mulberry32(1);++const GROTESK = '"Helvetica Neue", Helvetica, Arial, sans-serif';+const MONO = 'Menlo, "SF Mono", monospace';++function clamp(v,a,b){return v<a?a:(v>b?b:v);}++// ---------- boat ----------+// paper boat: hull + triangular sail peak. waterline at local y=0, bow points +x.+function drawBoat(c, x, y, w, tiltDeg, pal){+ const h = w*0.30, sh = w*0.55;+ c.save();+ c.translate(x,y);+ c.rotate(tiltDeg*Math.PI/180);+ // sail (two facets)+ const peak = {x:0, y:-h - sh};+ const sbL = {x:-w*0.20, y:-h*0.94};+ const sbR = {x: w*0.20, y:-h*0.94};+ // left (shadow) facet+ c.beginPath(); c.moveTo(peak.x,peak.y); c.lineTo(sbL.x,sbL.y); c.lineTo(0,-h*0.94); c.closePath();+ c.fillStyle = pal.sailShadow; c.fill();+ // right (light) facet+ c.beginPath(); c.moveTo(peak.x,peak.y); c.lineTo(sbR.x,sbR.y); c.lineTo(0,-h*0.94); c.closePath();+ c.fillStyle = pal.sailLight; c.fill();+ // center crease+ c.beginPath(); c.moveTo(peak.x,peak.y); c.lineTo(0,-h*0.94);+ c.strokeStyle = pal.crease; c.lineWidth = Math.max(1,w*0.008); c.stroke();+ // hull front face+ c.beginPath();+ c.moveTo(-w*0.5, -h); // stern tip+ c.quadraticCurveTo(0, -h*0.80, w*0.5, -h); // gunwale sag+ c.lineTo(w*0.27, 0);+ c.lineTo(-w*0.27, 0);+ c.closePath();+ c.fillStyle = pal.hull; c.fill();+ // hull light wedge (bow side)+ c.beginPath();+ c.moveTo(w*0.5,-h); c.quadraticCurveTo(w*0.22,-h*0.84, 0,-h*0.82);+ c.lineTo(w*0.06,0); c.lineTo(w*0.27,0); c.closePath();+ c.fillStyle = pal.hullLight; c.fill();+ // wet band along waterline+ c.beginPath();+ c.moveTo(-w*0.27,0); c.lineTo(w*0.27,0); c.lineTo(w*0.24,-h*0.14); c.lineTo(-w*0.24,-h*0.14); c.closePath();+ c.fillStyle = pal.wet; c.fill();+ // inner shadow under gunwale+ c.beginPath();+ c.moveTo(-w*0.5,-h); c.quadraticCurveTo(0,-h*0.80, w*0.5,-h);+ c.quadraticCurveTo(0,-h*0.64, -w*0.5,-h);+ c.closePath();+ c.fillStyle = pal.inner; c.fill();+ // rim light on gunwale + sail edge (light side)+ c.strokeStyle = pal.rim; c.lineWidth = Math.max(1,w*0.012);+ c.beginPath(); c.moveTo(w*0.5,-h); c.quadraticCurveTo(w*0.1,-h*0.80, -w*0.1,-h*0.82); c.stroke();+ c.beginPath(); c.moveTo(peak.x,peak.y); c.lineTo(sbR.x,sbR.y); c.stroke();+ c.restore();+}++// ---------- film grain + vignette + crush ----------+function filmPass(strength, vig, rng){+ const img = ctx.getImageData(0,0,W,H);+ const d = img.data;+ const cx = W/2, cy = H/2;+ for(let y=0;y<H;y++){+ const dy=(y-cy)/cy;+ for(let x=0;x<W;x++){+ const i=(y*W+x)*4;+ const dx=(x-cx)/cx;+ const d2=dx*dx*1.06+dy*dy;+ const f=1-vig*d2*0.85;+ const n=(rng()-0.5)*strength;+ d[i] =clamp((d[i] *1.05-6+n)*f,0,255);+ d[i+1]=clamp((d[i+1]*1.05-6+n)*f,0,255);+ d[i+2]=clamp((d[i+2]*1.05-5+n)*f,0,255);+ }+ }+ ctx.putImageData(img,0,0);+}++// ---------- HUD helpers ----------+function mono(sz, alpha, weight){+ ctx.font = (weight||'')+' '+sz+'px '+MONO;+ ctx.fillStyle = 'rgba(235,240,240,'+alpha+')';+}+function edgeFrame(alpha){+ const m=20;+ ctx.strokeStyle='rgba(255,255,255,'+(alpha*0.55)+')';+ ctx.lineWidth=1;+ ctx.strokeRect(m+0.5,m+0.5,W-2*m-1,H-2*m-1);+ ctx.strokeStyle='rgba(255,255,255,'+(alpha*0.45)+')';+ ctx.beginPath();+ for(let x=m;x<=W-m;x+=40){+ const L=(x-m)%200===0?9:5;+ ctx.moveTo(x+0.5,m); ctx.lineTo(x+0.5,m+L);+ ctx.moveTo(x+0.5,H-m); ctx.lineTo(x+0.5,H-m-L);+ }+ for(let y=m;y<=H-m;y+=40){+ const L=(y-m)%200===0?9:5;+ ctx.moveTo(m,y+0.5); ctx.lineTo(m+L,y+0.5);+ ctx.moveTo(W-m,y+0.5); ctx.lineTo(W-m-L,y+0.5);+ }+ ctx.stroke();+ // coordinate numerals along top + left (skip ranges under corner labels)+ mono(8, alpha*0.5);+ ctx.textAlign='center';+ for(const x of [420,620,820]) ctx.fillText(String(x).padStart(4,'0'), x, m+18);+ ctx.textAlign='left';+ for(const y of [220,420]) ctx.fillText(String(y).padStart(4,'0'), m+13, y+3);+}+function brackets(cx,cy,bw,bh,color,double,lw){+ const x0=cx-bw/2, y0=cy-bh/2, x1=cx+bw/2, y1=cy+bh/2, L=15;+ ctx.strokeStyle=color; ctx.lineWidth=lw||1.6;+ const corner=(x,y,sx,sy)=>{ctx.beginPath();ctx.moveTo(x+sx*L,y);ctx.lineTo(x,y);ctx.lineTo(x,y+sy*L);ctx.stroke();};+ corner(x0,y0,1,1);corner(x1,y0,-1,1);corner(x0,y1,1,-1);corner(x1,y1,-1,-1);+ if(double){+ ctx.globalAlpha=0.45;+ const g=6;+ corner(x0-g,y0-g,1,1);corner(x1+g,y0-g,-1,1);corner(x0-g,y1+g,1,-1);corner(x1+g,y1+g,-1,-1);+ ctx.globalAlpha=1;+ }+}+function panelBox(x,y,w,h,border){+ ctx.fillStyle='rgba(6,10,12,0.72)';+ ctx.fillRect(x,y,w,h);+ ctx.strokeStyle=border; ctx.lineWidth=1;+ ctx.strokeRect(x+0.5,y+0.5,w-1,h-1);+}+function chart(x,y,w,h,pts,color){+ ctx.strokeStyle='rgba(255,255,255,0.18)'; ctx.lineWidth=1;+ ctx.beginPath();+ for(let i=0;i<=2;i++){ctx.moveTo(x,y+h*i/2+0.5);ctx.lineTo(x+w,y+h*i/2+0.5);}+ ctx.stroke();+ ctx.strokeStyle=color; ctx.lineWidth=1.4;+ ctx.beginPath();+ pts.forEach((p,i)=>{const px=x+w*i/(pts.length-1), py=y+h*(1-p); i?ctx.lineTo(px,py):ctx.moveTo(px,py);});+ ctx.stroke();+}+function ticker(items, tag, tagBg, warn){+ const y=H-34, h=24;+ ctx.fillStyle='rgba(4,7,9,0.82)';+ ctx.fillRect(20,y,W-40,h);+ ctx.strokeStyle=warn?'rgba(255,74,28,0.65)':'rgba(255,255,255,0.28)';+ ctx.lineWidth=1; ctx.beginPath(); ctx.moveTo(20,y+0.5); ctx.lineTo(W-20,y+0.5); ctx.stroke();+ // tag+ ctx.fillStyle=tagBg; ctx.fillRect(20,y,52,h);+ ctx.font='bold 10px '+MONO; ctx.fillStyle='#0a0d0f'; ctx.textAlign='center';+ ctx.fillText(tag,46,y+16);+ // items+ ctx.textAlign='left';+ let tx=84;+ ctx.font='10px '+MONO;+ for(const it of items){+ if(tx>W-40)break;+ ctx.fillStyle=it.acc?ACC:'rgba(225,232,232,0.78)';+ ctx.fillText(it.t,tx,y+16);+ tx+=ctx.measureText(it.t).width;+ ctx.fillStyle='rgba(225,232,232,0.35)';+ ctx.fillText(' · ',tx,y+16);+ tx+=ctx.measureText(' · ').width;+ }+}+function bigWord(word, x, y, size, align, ghost){+ ctx.save();+ ctx.translate(x,y);+ ctx.scale(0.76,1);+ ctx.font='bold '+size+'px '+GROTESK;+ try{ctx.letterSpacing='6px';}catch(e){}+ ctx.textAlign=align;+ if(ghost){+ ctx.fillStyle='rgba(255,74,28,0.4)';+ ctx.fillText(word, 5/0.76, 0);+ }+ ctx.fillStyle='rgba(250,250,250,0.94)';+ ctx.fillText(word,0,0);+ try{ctx.letterSpacing='0px';}catch(e){}+ ctx.restore();+}+function headline(lines, cap, y0){+ ctx.textAlign='left';+ ctx.font='bold 40px '+GROTESK;+ ctx.fillStyle='rgba(250,250,250,0.96)';+ lines.forEach((l,i)=>ctx.fillText(l,40,y0+i*44));+ const cy=y0+lines.length*44-14;+ ctx.font='11px '+MONO;+ ctx.fillStyle=ACC; ctx.fillText('>',40,cy);+ ctx.fillStyle='rgba(230,235,235,0.72)';+ ctx.fillText(cap,54,cy);+}++// =====================================================================+// FRAME A — setting out+// =====================================================================+function sceneA(){+ R = mulberry32(70);+ const HZ=396, SUNX=880, SUNY=372;+ // sky+ let g=ctx.createLinearGradient(0,0,0,HZ);+ g.addColorStop(0,'#141f33'); g.addColorStop(0.42,'#3d4a63');+ g.addColorStop(0.70,'#7d7373'); g.addColorStop(0.88,'#cf9560'); g.addColorStop(1,'#eec084');+ ctx.fillStyle=g; ctx.fillRect(0,0,W,HZ+2);+ // sun halation+ ctx.globalCompositeOperation='screen';+ g=ctx.createRadialGradient(SUNX,SUNY,0,SUNX,SUNY,340);+ g.addColorStop(0,'rgba(255,190,120,0.34)'); g.addColorStop(1,'rgba(255,190,120,0)');+ ctx.fillStyle=g; ctx.fillRect(0,0,W,H);+ g=ctx.createRadialGradient(SUNX,SUNY,0,SUNX,SUNY,130);+ g.addColorStop(0,'rgba(255,236,200,0.9)'); g.addColorStop(1,'rgba(255,236,200,0)');+ ctx.fillStyle=g; ctx.fillRect(SUNX-160,SUNY-160,320,320);+ ctx.globalCompositeOperation='source-over';+ ctx.fillStyle='#fff3da';+ ctx.beginPath(); ctx.arc(SUNX,SUNY,22,Math.PI,0); ctx.fill(); // half-disc at horizon+ // clouds: dark streaks high, warm-lit streaks low+ ctx.filter='blur(7px)';+ for(let i=0;i<24;i++){+ const cy=30+R()*280, cw=140+R()*340, ch=8+R()*16, cx=R()*W;+ const hi=cy<230;+ ctx.fillStyle=hi?'rgba(24,33,50,'+(0.28+R()*0.3)+')':'rgba(64,56,64,'+(0.25+R()*0.25)+')';+ ctx.beginPath(); ctx.ellipse(cx,cy,cw/2,ch/2,0,0,7); ctx.fill();+ if(!hi){+ ctx.fillStyle='rgba(255,186,120,'+(0.12+R()*0.18)+')';+ ctx.beginPath(); ctx.ellipse(cx+10,cy+ch*0.45,cw*0.42,ch*0.28,0,0,7); ctx.fill();+ }+ }+ ctx.filter='none';+ // sea+ g=ctx.createLinearGradient(0,HZ,0,H);+ g.addColorStop(0,'#d3945f'); g.addColorStop(0.10,'#8f6a5c');+ g.addColorStop(0.30,'#454a58'); g.addColorStop(0.62,'#202c3a'); g.addColorStop(1,'#0e1722');+ ctx.fillStyle=g; ctx.fillRect(0,HZ,W,H-HZ);+ // horizon haze+ g=ctx.createLinearGradient(0,HZ-6,0,HZ+50);+ g.addColorStop(0,'rgba(245,200,150,0.35)'); g.addColorStop(1,'rgba(245,200,150,0)');+ ctx.fillStyle=g; ctx.fillRect(0,HZ-6,W,56);+ // sun glitter column+ for(let i=0;i<420;i++){+ const t=Math.pow(R(),1.4);+ const gy=HZ+4+t*(H-HZ-30);+ const half=10+t*160;+ const off=(R()*2-1);+ const gx=SUNX+off*half*(0.35+0.65*R());+ const edge=Math.pow(1-Math.abs(off),0.7);+ const len=2+t*24+R()*6;+ ctx.fillStyle='rgba(255,'+Math.round(215-t*40)+','+Math.round(165-t*40)+','+((0.10+(1-t)*0.4*R()+0.06)*edge)+')';+ ctx.fillRect(gx-len/2, gy, len, 1+t*1.6);+ }+ // ambient shimmer elsewhere+ for(let i=0;i<260;i++){+ const t=R();+ const gy=HZ+8+Math.pow(t,1.2)*(H-HZ-20);+ const gx=R()*W;+ if(Math.abs(gx-SUNX)<90) continue;+ const len=3+t*22;+ ctx.fillStyle='rgba(190,200,215,'+(0.03+R()*0.09)+')';+ ctx.fillRect(gx,gy,len,1);+ }+ // gentle foreground swells+ ctx.lineWidth=3;+ for(let i=0;i<7;i++){+ const sy=520+i*30+R()*14;+ ctx.strokeStyle='rgba(6,12,20,'+(0.16+i*0.04)+')';+ ctx.beginPath();+ ctx.moveTo(-20,sy);+ ctx.bezierCurveTo(W*0.3,sy-10-R()*8, W*0.6,sy+8+R()*8, W+20,sy-4);+ ctx.stroke();+ }+ // boat + reflection + wake+ const BX=395, BY=566, BW=132;+ // reflection+ ctx.save();+ ctx.translate(BX,BY+4); ctx.scale(1,-0.34); ctx.translate(-BX,-BY);+ ctx.globalAlpha=0.22;+ drawBoat(ctx,BX,BY,BW,-3,{sailShadow:'#2a2f38',sailLight:'#5a5348',crease:'rgba(0,0,0,0.2)',hull:'#33363c',hullLight:'#4a463f',wet:'#20242c',inner:'#191d24',rim:'rgba(0,0,0,0)'});+ ctx.restore();+ // break reflection with water lines+ for(let i=0;i<8;i++){+ const ry=BY+6+i*5+R()*3;+ ctx.strokeStyle='rgba(26,36,48,0.5)'; ctx.lineWidth=2;+ ctx.beginPath(); ctx.moveTo(BX-70+R()*20,ry); ctx.lineTo(BX+70-R()*20,ry); ctx.stroke();+ }+ // wake trailing left+ ctx.strokeStyle='rgba(235,225,205,0.28)'; ctx.lineWidth=2;+ ctx.beginPath(); ctx.moveTo(BX-34,BY+2); ctx.quadraticCurveTo(BX-120,BY+10,BX-230,BY+30); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(BX-30,BY+5); ctx.quadraticCurveTo(BX-110,BY+22,BX-200,BY+52); ctx.stroke();+ ctx.strokeStyle='rgba(235,225,205,0.14)';+ for(let i=0;i<5;i++){+ const wx=BX-70-i*36, wy=BY+10+i*7;+ ctx.beginPath(); ctx.arc(wx,wy,10+i*3,0.2,2.6); ctx.stroke();+ }+ // small bow ripple+ ctx.strokeStyle='rgba(255,225,190,0.4)'; ctx.lineWidth=1.6;+ ctx.beginPath(); ctx.arc(BX+40,BY+3,9,-0.4,2.4); ctx.stroke();+ drawBoat(ctx,BX,BY,BW,-3,{+ sailShadow:'#8d8172', sailLight:'#f4e6cc', crease:'rgba(90,80,66,0.65)',+ hull:'#cdbda2', hullLight:'#efdfc0', wet:'#5c554b', inner:'#7c7365',+ rim:'rgba(255,222,168,0.95)'+ });+ filmPass(9, 0.32, mulberry32(71));+ hudA(BX,BY,BW);+}++function hudA(BX,BY,BW){+ edgeFrame(0.9);+ // top-left small labels+ ctx.textAlign='left';+ mono(11,0.85); ctx.fillText('MODEL 01 · PAPER', 40, 44);+ ctx.fillStyle=ACC; ctx.font='11px '+MONO;+ ctx.fillText('FIRST LIGHT · SS27', 178, 44);+ headline(['Point it at','the horizon.'], ' departure logged · 05:41 local · wind asks nothing yet', 92);+ // top-right stack+ ctx.textAlign='right';+ mono(11,0.85); ctx.fillText('LOOK 01 / 02', W-40, 44);+ mono(11,0.6); ctx.fillText('TC 00:01:04:12', W-40, 60);+ // counter (story clock)+ ctx.font='bold 30px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('07', W-40, 96);+ mono(10,0.7); ctx.fillText('DAYS TO LANDFALL', W-84, 92);+ // giant kinetic word in the sky, right side+ bigWord('DEPART', W-64, 258, 104, 'right', false);+ ctx.textAlign='right'; mono(9,0.5);+ ctx.fillText('[ CUE 01 · SLAM ]', W-70, 278);+ // dotted scan path: planned route to horizon waypoint+ ctx.strokeStyle=ACC; ctx.lineWidth=1.5; ctx.setLineDash([2,7]);+ ctx.beginPath(); ctx.moveTo(BX+72,BY-8);+ ctx.quadraticCurveTo(660,470, 866,398); ctx.stroke();+ ctx.setLineDash([]);+ ctx.beginPath(); ctx.arc(866,398,4,0,7); ctx.stroke();+ ctx.textAlign='left'; ctx.font='9px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('WPT 01 · 6.2 NM', 878, 394);+ // tracking brackets on the boat+ const bcx=BX+2, bcy=BY-48, bw=BW+72, bh=156;+ brackets(bcx,bcy,bw,bh,'rgba(250,250,250,0.92)',false,1.6);+ ctx.fillStyle=ACC;+ ctx.fillRect(bcx-2, bcy-bh/2-2, 4,4);+ // leader + tag (up-left into clear sea)+ ctx.strokeStyle='rgba(250,250,250,0.7)'; ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(bcx-bw/2,bcy-bh/2); ctx.lineTo(BX-170,BY-190); ctx.lineTo(BX-42,BY-190); ctx.stroke();+ ctx.textAlign='left';+ mono(10,0.9); ctx.fillText('OBJ 01 · PAPER BOAT', BX-170, BY-198);+ ctx.fillStyle=ACC; ctx.font='10px '+MONO; ctx.fillText('LOCK 100%', BX-170, BY-176);+ // bottom-left readout block+ const rx=40, ry=596;+ mono(11,0.9); ctx.fillText('32.0853 N · 34.7818 E', rx, ry);+ mono(10,0.7);+ ctx.fillText('HDG 090°E', rx, ry+16);+ ctx.fillStyle=ACC; ctx.fillText('SPD 1.4 KTS', rx+82, ry+16);+ mono(10,0.7); ctx.fillText('SEA STATE 1 · SWELL 0.2 M', rx, ry+32);+ // data panel lower-right+ const px=1030, py=452, pw=210, ph=158;+ panelBox(px,py,pw,ph,'rgba(255,255,255,0.35)');+ ctx.textAlign='left';+ mono(10,0.65); ctx.fillText('DRIFT REPORT', px+12, py+20);+ ctx.strokeStyle='rgba(255,255,255,0.25)';+ ctx.beginPath(); ctx.moveTo(px+12,py+27.5); ctx.lineTo(px+pw-12,py+27.5); ctx.stroke();+ ctx.font='bold 30px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('001', px+12, py+58);+ mono(12,0.55); ctx.fillText('/ 120 SLICES', px+74, py+58);+ const r2=mulberry32(7);+ const pts=[]; for(let i=0;i<24;i++) pts.push(0.30+r2()*0.12);+ chart(px+12,py+72,pw-24,44,pts,ACC);+ mono(9,0.6);+ ctx.fillText('BALLAST OK · CREASES 07 · LEAK 0', px+12, py+134);+ ctx.fillText('MORALE ▲ UNMEASURED', px+12, py+146);+ ticker([+ {t:'FIRST LIGHT INDEX ▲ 1.2%',acc:true},{t:'SWELL 0.2 M'},{t:'GULL SIGHTINGS 0'},+ {t:'PAPER FUTURES ▲ 2.1%',acc:true},{t:'TOKENS BURNED 321,084,500'},+ {t:'HORIZON: CONFIRMED'},{t:'CREW 0'},{t:'CONFIDENCE 100%'},{t:'WIND: ASLEEP'}+ ],'LIVE','#d8dee0',false);+}++// =====================================================================+// FRAME B — the storm peak+// =====================================================================+function sceneB(){+ R = mulberry32(130);+ // sky+ let g=ctx.createLinearGradient(0,0,0,340);+ g.addColorStop(0,'#0a0e11'); g.addColorStop(0.55,'#161e21'); g.addColorStop(1,'#20292b');+ ctx.fillStyle=g; ctx.fillRect(0,0,W,360);+ // base sea (lower-left, below wave)+ g=ctx.createLinearGradient(0,320,0,H);+ g.addColorStop(0,'#18232a'); g.addColorStop(0.5,'#0d151a'); g.addColorStop(1,'#05090c');+ ctx.fillStyle=g; ctx.fillRect(0,320,W,H-320);+ // churning cloud mass+ ctx.filter='blur(9px)';+ for(let i=0;i<30;i++){+ const cy=10+R()*250, cx=R()*W, cw=120+R()*300, ch=26+R()*50;+ ctx.fillStyle='rgba('+(8+Math.round(R()*10))+','+(14+Math.round(R()*10))+','+(15+Math.round(R()*8))+','+(0.35+R()*0.3)+')';+ ctx.beginPath(); ctx.ellipse(cx,cy,cw/2,ch/2,(R()-0.5)*0.3,0,7); ctx.fill();+ }+ ctx.filter='none';+ // the light break, upper-left: one source fighting through+ ctx.globalCompositeOperation='screen';+ g=ctx.createRadialGradient(300,40,10,300,40,260);+ g.addColorStop(0,'rgba(215,230,224,0.5)'); g.addColorStop(1,'rgba(215,230,224,0)');+ ctx.fillStyle=g; ctx.fillRect(0,0,720,360);+ // shaft: nested soft wedges so edges stay soft+ for(const [t0,t1,a] of [[0,1,0.09],[0.18,0.86,0.10],[0.36,0.68,0.11]]){+ g=ctx.createLinearGradient(0,0,0,540);+ g.addColorStop(0,'rgba(200,220,214,'+a+')'); g.addColorStop(1,'rgba(200,220,214,0)');+ ctx.fillStyle=g;+ const x0t=210+t0*210, x1t=210+t1*210, x0b=150+t0*410, x1b=150+t1*410;+ ctx.beginPath(); ctx.moveTo(x0t,-10); ctx.lineTo(x1t,-10); ctx.lineTo(x1b,540); ctx.lineTo(x0b,540); ctx.closePath(); ctx.fill();+ }+ ctx.globalCompositeOperation='source-over';+ // ---- THE WAVE: one big diagonal mass from upper right ----+ const crest=[[1300,150],[1130,172],[955,210],[790,262],[640,318],[520,378],[430,432],[380,470]];+ ctx.beginPath();+ ctx.moveTo(crest[0][0],crest[0][1]);+ for(let i=1;i<crest.length;i++){+ const p=crest[i-1],q=crest[i];+ ctx.quadraticCurveTo((p[0]+q[0])/2+14,(p[1]+q[1])/2-16,q[0],q[1]);+ }+ ctx.lineTo(430,560); ctx.lineTo(1300,760); ctx.closePath();+ g=ctx.createLinearGradient(500,180,1200,700);+ g.addColorStop(0,'#2a3a3c'); g.addColorStop(0.35,'#1b282c'); g.addColorStop(1,'#0a1114');+ ctx.fillStyle=g; ctx.fill();+ ctx.save(); ctx.clip();+ // streaks along the face+ for(let i=0;i<130;i++){+ const t=R();+ const sx=430+t*850, sy=180+t*420+R()*160;+ const len=40+R()*160;+ ctx.strokeStyle='rgba('+(70+Math.round(R()*40))+','+(96+Math.round(R()*40))+','+(96+Math.round(R()*36))+','+(0.05+R()*0.12)+')';+ ctx.lineWidth=1+R()*2;+ ctx.beginPath(); ctx.moveTo(sx,sy);+ ctx.lineTo(sx+len*0.85,sy+len*0.5); ctx.stroke();+ }+ // lit edge of the face near the shaft+ g=ctx.createLinearGradient(380,380,700,300);+ g.addColorStop(0,'rgba(150,180,172,0.28)'); g.addColorStop(1,'rgba(150,180,172,0)');+ ctx.fillStyle=g; ctx.fillRect(380,240,420,320);+ // translucent underlight all along the lip+ ctx.filter='blur(12px)';+ for(let i=1;i<crest.length;i++){+ const p=crest[i-1],q=crest[i];+ const lit=q[0]<760;+ ctx.fillStyle='rgba(96,124,120,'+(lit?0.26:0.14)+')';+ ctx.beginPath();+ ctx.ellipse((p[0]+q[0])/2,(p[1]+q[1])/2+30,Math.hypot(q[0]-p[0],q[1]-p[1])*0.62,20,Math.atan2(q[1]-p[1],q[0]-p[0]),0,7);+ ctx.fill();+ }+ ctx.filter='none';+ // foam veins marbling down the face, densest just under the crest+ for(let i=1;i<crest.length;i++){+ const p=crest[i-1],q=crest[i];+ for(let k=0;k<16;k++){+ const t=R();+ const drop=4+Math.pow(R(),1.8)*150;+ let vx=p[0]+(q[0]-p[0])*t+(R()-0.5)*30;+ let vy=p[1]+(q[1]-p[1])*t+drop;+ const fade=1-drop/170;+ ctx.strokeStyle='rgba(196,212,208,'+((0.05+R()*0.16)*Math.max(0.15,fade))+')';+ ctx.lineWidth=0.8+R()*1.4;+ ctx.beginPath(); ctx.moveTo(vx,vy);+ const segs=3+Math.round(R()*3);+ for(let s2=0;s2<segs;s2++){+ vx+=10+R()*22; vy+=8+R()*18+(R()-0.5)*6;+ ctx.lineTo(vx,vy);+ }+ ctx.stroke();+ }+ }+ ctx.restore();+ // foam along crest+ for(let i=1;i<crest.length;i++){+ const p=crest[i-1],q=crest[i];+ const seg=Math.hypot(q[0]-p[0],q[1]-p[1]);+ const n=Math.round(seg/2.4);+ const lit=q[0]<700;+ for(let k=0;k<n;k++){+ const t=k/n;+ const fx=p[0]+(q[0]-p[0])*t+(R()-0.5)*22;+ const fy=p[1]+(q[1]-p[1])*t+(R()-0.5)*16-R()*10;+ const a=(lit?0.35:0.18)+R()*(lit?0.5:0.3);+ ctx.fillStyle='rgba('+(lit?230:190)+','+(lit?238:205)+','+(lit?234:205)+','+a+')';+ const r=0.8+R()*(lit?3.2:2.4);+ ctx.beginPath(); ctx.arc(fx,fy,r,0,7); ctx.fill();+ }+ // wind-blown spray off crest (to the left)+ for(let k=0;k<Math.round(n/4);k++){+ const t=R();+ const fx=p[0]+(q[0]-p[0])*t, fy=p[1]+(q[1]-p[1])*t;+ const len=8+R()*36;+ ctx.strokeStyle='rgba(205,218,215,'+(0.08+R()*0.22)+')';+ ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(fx,fy);+ ctx.lineTo(fx-len,fy-len*0.35-R()*8); ctx.stroke();+ }+ }+ // churned water + whitecaps lower-left+ for(let i=0;i<90;i++){+ const wx=R()*520, wy=430+R()*260;+ ctx.strokeStyle='rgba(160,180,180,'+(0.05+R()*0.14)+')';+ ctx.lineWidth=1+R()*1.5;+ ctx.beginPath(); ctx.moveTo(wx,wy); ctx.lineTo(wx+14+R()*44,wy+(R()-0.5)*8); ctx.stroke();+ }+ for(let i=0;i<14;i++){+ const wx=40+R()*440, wy=470+R()*210;+ for(let k=0;k<12;k++){+ ctx.fillStyle='rgba(200,214,212,'+(0.1+R()*0.3)+')';+ ctx.beginPath(); ctx.arc(wx+R()*46,wy+(R()-0.5)*8,0.8+R()*1.8,0,7); ctx.fill();+ }+ }+ // boat: small, climbing the face, still pointing forward+ const BX=404, BY=462, BW=62;+ // foam pocket around hull+ for(let k=0;k<50;k++){+ ctx.fillStyle='rgba(210,222,220,'+(0.15+R()*0.4)+')';+ ctx.beginPath(); ctx.arc(BX-30+R()*70,BY+2+(R()-0.5)*10,0.8+R()*2.6,0,7); ctx.fill();+ }+ drawBoat(ctx,BX,BY,BW,-16,{+ sailShadow:'#3c464e', sailLight:'#dbe4e7', crease:'rgba(20,26,30,0.7)',+ hull:'#828d95', hullLight:'#b6c1c7', wet:'#2b3339', inner:'#4a535a',+ rim:'rgba(235,248,244,1)'+ });+ // spray whipping past the boat+ for(let k=0;k<26;k++){+ const sx=BX-50+R()*120, sy=BY-56+R()*70;+ const len=6+R()*22;+ ctx.strokeStyle='rgba(210,224,220,'+(0.08+R()*0.2)+')'; ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(sx,sy); ctx.lineTo(sx-len,sy-len*0.3); ctx.stroke();+ }+ // rain+ for(let i=0;i<200;i++){+ const rx=R()*W, ry=R()*H, len=18+R()*44;+ ctx.strokeStyle='rgba(180,195,195,'+(0.03+R()*0.08)+')';+ ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(rx,ry); ctx.lineTo(rx-len*0.22,ry+len); ctx.stroke();+ }+ filmPass(14, 0.44, mulberry32(131));+ hudB(BX,BY,BW);+}++function hudB(BX,BY,BW){+ edgeFrame(0.9);+ ctx.textAlign='left';+ mono(11,0.85); ctx.fillText('MODEL 01 · PAPER', 40, 44);+ ctx.fillStyle=ACC; ctx.font='11px '+MONO;+ ctx.fillText('FIRST LIGHT · SS27', 178, 44);+ headline(['The sea votes','last.'], ' mayday drafted · not sent · bow still forward', 92);+ // top-right stack+ ctx.textAlign='right';+ mono(11,0.85); ctx.fillText('LOOK 02 / 02', W-40, 44);+ mono(11,0.6); ctx.fillText('TC 00:03:41:02', W-40, 60);+ ctx.font='bold 30px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('06', W-40, 96);+ mono(10,0.7); ctx.fillText('DAYS TO LANDFALL', W-84, 92);+ ctx.fillStyle=ACC; ctx.font='10px '+MONO;+ ctx.fillText('— HOLDING —', W-40, 112);+ // giant word, ghosted double-strike = flashing+ bigWord('HOLD.', W-56, 250, 150, 'right', true);+ ctx.textAlign='right'; mono(9,0.5);+ ctx.fillText('[ CUE 07 · SLAM · REPEAT ]', W-64, 276);+ // warning banner, left-mid free space+ const wx=40, wy=310, ww=286, wh=54;+ panelBox(wx,wy,ww,wh,'rgba(255,74,28,0.9)');+ // hazard ticks on left edge+ ctx.fillStyle=ACC;+ for(let i=0;i<6;i++) ctx.fillRect(wx+4, wy+5+i*8, 10, 4);+ ctx.textAlign='left';+ ctx.font='bold 15px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('⚠ SEA STATE 8 — SEVERE', wx+24, wy+23);+ mono(10,0.75);+ ctx.fillText('WAVE 6.4 M · GUSTS 41 KTS · ADVISE: EXIST', wx+24, wy+41);+ // route lost: dotted line into the wave, X at obscured waypoint+ ctx.strokeStyle='rgba(250,250,250,0.75)'; ctx.lineWidth=1.4; ctx.setLineDash([2,7]);+ ctx.beginPath(); ctx.moveTo(BX+36,BY-16); ctx.quadraticCurveTo(560,360, 668,290); ctx.stroke();+ ctx.setLineDash([]);+ ctx.strokeStyle=ACC; ctx.lineWidth=2;+ ctx.beginPath(); ctx.moveTo(662,284); ctx.lineTo(674,296); ctx.moveTo(674,284); ctx.lineTo(662,296); ctx.stroke();+ ctx.strokeStyle='rgba(255,74,28,0.7)'; ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(672,282); ctx.lineTo(706,240); ctx.stroke();+ ctx.fillStyle='rgba(4,7,9,0.7)'; ctx.fillRect(708,228,118,17);+ ctx.textAlign='left'; ctx.font='9px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('WPT 01 · OBSCURED', 714, 240);+ // tracking brackets: accent, doubled = alarm+ brackets(BX+1,BY-22,BW+58,102,ACC,true,1.8);+ // leader + degraded tag (down-left, in dark water free space)+ ctx.strokeStyle='rgba(255,74,28,0.8)'; ctx.lineWidth=1;+ ctx.beginPath(); ctx.moveTo(BX-(BW+58)/2+1,BY+18); ctx.lineTo(BX-138,BY+84); ctx.lineTo(BX-16,BY+84); ctx.stroke();+ ctx.textAlign='left';+ ctx.fillStyle=ACC; ctx.font='10px '+MONO;+ ctx.fillText('OBJ 01 · TRACK 43%', BX-136, BY+78);+ mono(10,0.8); ctx.fillText('REACQUIRING…', BX-136, BY+98);+ // bottom-left readout+ const rx=40, ry=596;+ mono(11,0.9); ctx.fillText('32.4410 N · 33.9051 E', rx, ry);+ ctx.font='10px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('HDG 090° HOLD', rx, ry+16);+ mono(10,0.7); ctx.fillText('SPD 0.2 KTS', rx+112, ry+16);+ ctx.fillStyle=ACC; ctx.font='10px '+MONO;+ ctx.fillText('SEA STATE 8', rx, ry+32);+ mono(10,0.7); ctx.fillText('· PITCH 24° · ROLL 31°', rx+86, ry+32);+ // capsize panel lower-right, accent border+ const px=1030, py=452, pw=210, ph=158;+ panelBox(px,py,pw,ph,'rgba(255,74,28,0.85)');+ ctx.textAlign='left';+ ctx.font='10px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('CAPSIZE MODEL', px+12, py+20);+ ctx.strokeStyle='rgba(255,74,28,0.4)';+ ctx.beginPath(); ctx.moveTo(px+12,py+27.5); ctx.lineTo(px+pw-12,py+27.5); ctx.stroke();+ ctx.font='bold 30px '+MONO; ctx.fillStyle=ACC;+ ctx.fillText('78%', px+12, py+58);+ mono(12,0.55); ctx.fillText('RISK · LIVE', px+86, py+58);+ const r2=mulberry32(17);+ const pts=[]; for(let i=0;i<24;i++) pts.push(clamp(0.2+i*0.028+(r2()-0.5)*0.3,0.04,0.96));+ chart(px+12,py+72,pw-24,44,pts,ACC);+ mono(9,0.6);+ ctx.fillText('WAVE 6.4 M · SLICE 114 / 120', px+12, py+134);+ ctx.fillStyle=ACC; ctx.font='9px '+MONO;+ ctx.fillText('PAPER INTEGRITY 61% ▼', px+12, py+146);+ ticker([+ {t:'SWELL ▲ 6.4 M',acc:true},{t:'GUSTS 41 KTS'},{t:'PAPER FUTURES ▼ 12.8%',acc:true},+ {t:'MAYDAY DRAFTS 1 · SENT 0'},{t:'GULLS GROUNDED'},{t:'TOKENS BURNED 402,113,776'},+ {t:'INSURANCE: NO'},{t:'CONFIDENCE 61%',acc:true}+ ],'ALRT',ACC,true);+}++window.drawFrame = function(which){+ ctx.setTransform(1,0,0,1,0,0);+ ctx.clearRect(0,0,W,H);+ if(which==='a') sceneA(); else sceneB();+ window.DONE = true;+};+window.READY = true;+</script>+</body>+</html>diff --git a/assets/previews-src/ink/boat.html b/assets/previews-src/ink/boat.htmlnew file mode 100644index 0000000..4d9b0fe--- /dev/null+++ b/assets/previews-src/ink/boat.html@@ -0,0 +1,541 @@+<!doctype html>+<html>+<head><meta charset="utf-8"><title>ink boat</title>+<style>html,body{margin:0;padding:0;background:#f3ede0}canvas{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+// THE PAPER BOAT in ink wash (sumi-e). Recipe informed by anidoodle (Apache-2.0):+// five dilutions, hair-based brush with flying white, bleed halos at slow points,+// baiwen cinnabar seal. Everything below is drawn in code, seeded, deterministic.+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++// ---------- deterministic rng + noise ----------+function mulberry32(seed){+ let a = seed >>> 0;+ return function(){+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}+const clamp = (v,a,b)=>v<a?a:(v>b?b:v);+const lerp = (a,b,t)=>a+(b-a)*t;+function makeNoise(seed){+ const r = mulberry32(seed);+ const g = new Float64Array(512); for(let i=0;i<512;i++) g[i]=r();+ const perm = new Uint8Array(256); for(let i=0;i<256;i++) perm[i]=i;+ for(let i=255;i>0;i--){ const j=Math.floor(r()*(i+1)); const t=perm[i]; perm[i]=perm[j]; perm[j]=t; }+ const P=i=>perm[i&255];+ function n2(x,y){+ const ix=Math.floor(x), iy=Math.floor(y), fx=x-ix, fy=y-iy;+ const sx=fx*fx*(3-2*fx), sy=fy*fy*(3-2*fy);+ const v=(a,b)=>g[P(P((ix+a)&255)+((iy+b)&255))];+ return lerp(lerp(v(0,0),v(1,0),sx), lerp(v(0,1),v(1,1),sx), sy);+ }+ return function fbm(x,y,o){+ o=o||2; let s=0, amp=0.6, f=1, tot=0;+ for(let i=0;i<o;i++){ s+=n2(x*f+i*17.7,y*f+i*31.3)*amp; tot+=amp; amp*=0.5; f*=2.1; }+ return s/tot;+ };+}+const FBM = makeNoise(77);++// ---------- ink: five dilutions of one stick ----------+const JIAO=1, NONG=0.82, ZHONG=0.6, DAN=0.38, QING=0.2;+function hex2rgb(h){ return [parseInt(h.slice(1,3),16),parseInt(h.slice(3,5),16),parseInt(h.slice(5,7),16)]; }+const INK_BLACK=hex2rgb('#0f0d0c'), INK_COOL=hex2rgb('#39414a');+function tone(v){+ const t = clamp(1-v,0,1)*0.85;+ const c = INK_BLACK.map((a,i)=>Math.round(lerp(a,INK_COOL[i],t)));+ return { color:`rgb(${c[0]},${c[1]},${c[2]})`, alpha: clamp(0.08+0.92*Math.pow(clamp(v,0,1),0.95),0,1) };+}+const PAPER = '#f3ede0';++// ---------- geometry ----------+function smoothResample(ctrl, n){+ // catmull-rom through ctrl, resampled to n points+ const pts=[];+ const P=ctrl;+ const seg=24;+ for(let i=0;i<P.length-1;i++){+ const p0=P[Math.max(0,i-1)], p1=P[i], p2=P[i+1], p3=P[Math.min(P.length-1,i+2)];+ for(let k=0;k<seg;k++){+ const t=k/seg, t2=t*t, t3=t2*t;+ pts.push([+ 0.5*((2*p1[0])+(-p0[0]+p2[0])*t+(2*p0[0]-5*p1[0]+4*p2[0]-p3[0])*t2+(-p0[0]+3*p1[0]-3*p2[0]+p3[0])*t3),+ 0.5*((2*p1[1])+(-p0[1]+p2[1])*t+(2*p0[1]-5*p1[1]+4*p2[1]-p3[1])*t2+(-p0[1]+3*p1[1]-3*p2[1]+p3[1])*t3)+ ]);+ }+ }+ pts.push(P[P.length-1].slice());+ // arc-length resample+ const cum=[0];+ for(let i=1;i<pts.length;i++) cum.push(cum[i-1]+Math.hypot(pts[i][0]-pts[i-1][0],pts[i][1]-pts[i-1][1]));+ const len=cum[cum.length-1], out=[];+ let j=0;+ for(let i=0;i<n;i++){+ const s=len*i/(n-1);+ while(j<cum.length-2 && cum[j+1]<s) j++;+ const f=(s-cum[j])/((cum[j+1]-cum[j])||1);+ out.push([lerp(pts[j][0],pts[j+1][0],f), lerp(pts[j][1],pts[j+1][1],f)]);+ }+ return { pts:out, len };+}+function profile(knots){+ return function(t){+ if(t<=knots[0][0]) return knots[0][1];+ for(let i=1;i<knots.length;i++){+ if(t<=knots[i][0]){+ const f=(t-knots[i-1][0])/((knots[i][0]-knots[i-1][0])||1);+ return lerp(knots[i-1][1],knots[i][1],f);+ }+ }+ return knots[knots.length-1][1];+ };+}++// ---------- THE BRUSH: hairs that spend their ink ----------+// b: { ctrl, w, ink, press, load, dry, edge, split, bleed, wet, streak, slow, hairs, seed }+// dry = fraction of the load spent over the WHOLE stroke (0.06 wash stays wet, 1.1 runs dry early)+let OFF=null, OFFX=null;+function brush(b){+ const pre = smoothResample(b.ctrl, 64);+ const n = Math.max(24, Math.min(900, Math.round(pre.len/2.2)));+ const { pts, len } = smoothResample(b.ctrl, n);+ const pr = profile(b.press || [[0,0.8],[0.2,1],[0.8,0.9],[1,0.3]]);+ const T = tone(b.ink);+ const dry = (b.dry==null?0.35:b.dry);+ const split = b.split==null?0.5:b.split;+ const wet = b.wet||0;+ const load0 = b.load==null?1:b.load;+ const edge = b.edge||0;+ const nh = b.hairs || Math.max(10, Math.min(40, Math.round(b.w*1.2)));+ const r = mulberry32(b.seed*7+3);+ const streakV = b.streak?0.75:0.28;+ const hairs=[];+ for(let i=0;i<nh;i++){+ const u = -1 + (2*(i+0.5))/nh + (r()-0.5)*(1.6/nh);+ hairs.push({ u, load: load0*(1+edge*(u*u-0.33))*(1-streakV/2+streakV*r()) });+ }+ const nr = pts.map((_,i)=>{+ const a=pts[Math.max(0,i-1)], q=pts[Math.min(n-1,i+1)];+ const dx=q[0]-a[0], dy=q[1]-a[1], l=Math.hypot(dx,dy)||1;+ return [-dy/l, dx/l];+ });+ const wid = i => b.w * pr(i/(n-1));++ // 1) bleed layer: slow-point halos + feathers + wet-body halo, blurred, multiply+ const bl = b.bleed==null?0.6:b.bleed;+ if(bl>0){+ ctx.save();+ ctx.globalCompositeOperation='multiply';+ ctx.filter = `blur(${(1.4+1.6*Math.min(1.5,bl)+3*wet).toFixed(1)}px)`;+ ctx.fillStyle = T.color; ctx.strokeStyle = T.color; ctx.lineCap='round';+ (b.slow||[]).forEach(([t,s],j)=>{+ const i=Math.round(t*(n-1));+ const r0 = wid(i)*(0.5+0.35*s)+2.5*s;+ const [x,y]=pts[i];+ const rr = mulberry32(b.seed*31+j);+ ctx.globalAlpha = T.alpha*0.34*s*bl;+ ctx.beginPath();+ for(let a=0;a<18;a++){+ const th=(a/18)*Math.PI*2;+ const f=1+(FBM(Math.cos(th)*2+9+b.seed*0.13+j,Math.sin(th)*2+9)-0.5)*0.7;+ const px=x+Math.cos(th)*r0*f, py=y+Math.sin(th)*r0*f;+ a?ctx.lineTo(px,py):ctx.moveTo(px,py);+ }+ ctx.closePath(); ctx.fill();+ // feathers wicking along single fibres+ ctx.lineWidth=0.55;+ const nf = Math.round(10+14*s);+ for(let q2=0;q2<nf;q2++){+ const th=rr()*Math.PI*2, d0=r0*(0.75+rr()*0.3), d1=d0+(2+rr()*7*s);+ ctx.globalAlpha=T.alpha*(0.25+rr()*0.3)*bl;+ ctx.beginPath();+ ctx.moveTo(x+Math.cos(th)*d0, y+Math.sin(th)*d0);+ ctx.lineTo(x+Math.cos(th)*d1, y+Math.sin(th)*d1);+ ctx.stroke();+ }+ });+ // wet-body halo where the brush still had ink+ ctx.globalAlpha = T.alpha*0.16*bl;+ ctx.beginPath();+ const L=[], R=[];+ for(let i=0;i<n;i++){+ const wetness = clamp(load0 - dry*(i/(n-1))*1.2, 0, 1);+ const h=(wid(i)/2)*(0.9+0.25*wetness)+1.6*wetness;+ L.push([pts[i][0]+nr[i][0]*h, pts[i][1]+nr[i][1]*h]);+ R.push([pts[i][0]-nr[i][0]*h, pts[i][1]-nr[i][1]*h]);+ }+ L.concat(R.reverse()).forEach(([x,y],i)=>i?ctx.lineTo(x,y):ctx.moveTo(x,y));+ ctx.closePath(); ctx.fill();+ ctx.restore();+ }++ // 2) the hairs: drawn OPAQUE into an offscreen sheet, then laid down ONCE at the+ // ink's tone (multiply): ink does not stack with itself inside a single stroke.+ if(!OFF){ OFF=document.createElement('canvas'); OFF.width=W; OFF.height=H; OFFX=OFF.getContext('2d'); }+ const k=OFFX;+ k.setTransform(1,0,0,1,0,0); k.clearRect(0,0,W,H);+ k.globalCompositeOperation='source-over'; k.globalAlpha=1;+ k.strokeStyle=T.color; k.lineCap='round'; k.lineJoin='round';+ const tipLen = Math.min(len*0.2, b.w*0.45);+ hairs.forEach((h,hi)=>{+ let run=[];+ const flush=()=>{+ if(run.length>1){+ let w=0; run.forEach(s=>{w+=s.w;}); w/=run.length;+ k.lineWidth=w;+ k.beginPath();+ run.forEach((s,i)=>i?k.lineTo(s.p[0],s.p[1]):k.moveTo(s.p[0],s.p[1]));+ k.stroke();+ }+ run=[];+ };+ for(let i=0;i<n;i++){+ const s=(i/(n-1))*len, t=i/(n-1);+ const rem = h.load - dry*t*(1+0.7*Math.abs(h.u));+ const q = clamp(rem*(b.streak?1.25:2.1),0,1);+ const tipIn = tipLen*Math.pow(Math.abs(h.u),1.6)*(0.8+0.4*h.load);+ const tipOut = tipLen*0.7*Math.pow(Math.abs(h.u),1.6);+ if(s<tipIn || s>len-tipOut){ flush(); continue; }+ const nz = FBM(b.seed*0.13+hi*0.83, s*0.045);+ if(q*1.3 <= nz+0.06){ flush(); continue; } // flying white: the paper won+ const Wd = wid(i);+ const spl = (FBM(b.seed*0.17+hi*0.5, s*0.02+40)-0.5)*split*(1-q)*b.w*0.7;+ const off = h.u*(Wd/2)*(1+0.12*(1-q))+spl;+ run.push({ p:[pts[i][0]+nr[i][0]*off, pts[i][1]+nr[i][1]*off],+ w: Math.max(0.45,(Wd/nh)*2.6*(0.75+0.25*q)) });+ if(run.length>=10){ const keep=run[run.length-1]; flush(); run=[keep]; }+ }+ flush();+ });+ ctx.save();+ ctx.globalCompositeOperation='multiply';+ ctx.globalAlpha = T.alpha*(1-0.35*wet);+ if(wet||b.soft) ctx.filter=`blur(${(0.6+2.6*wet+(b.soft||0)).toFixed(1)}px)`;+ ctx.drawImage(OFF,0,0);+ ctx.restore();+}++// a wet wash: same brush laid into a damp sheet — everything goes soft+function wash(b){ brush(Object.assign({wet:1, split:0.2, dry:0.06, bleed:1.1}, b)); }++// ---------- the paper ----------+function paperGround(){+ ctx.save();+ ctx.setTransform(1,0,0,1,0,0);+ ctx.globalCompositeOperation='source-over';+ ctx.filter='none';+ ctx.fillStyle=PAPER;+ ctx.fillRect(0,0,W,H);+ const r=mulberry32(501);+ ctx.lineCap='round';+ // long fibres laid in the vat+ for(let i=0;i<140;i++){+ const x=r()*W, y=r()*H;+ const a=(FBM(x*0.004,y*0.004)-0.5)*5;+ const L2=14+r()*46, bend=(r()-0.5)*0.5;+ ctx.strokeStyle = r()<0.5 ? '#d9cfbc' : '#fbf7ee';+ ctx.globalAlpha = 0.16+r()*0.2;+ ctx.lineWidth = 0.4+r()*0.6;+ ctx.beginPath();+ ctx.moveTo(x,y);+ ctx.quadraticCurveTo(x+Math.cos(a+bend)*L2*0.5, y+Math.sin(a+bend)*L2*0.5, x+Math.cos(a)*L2, y+Math.sin(a)*L2);+ ctx.stroke();+ }+ // bark flecks never beaten out+ for(let i=0;i<24;i++){+ const x=r()*W, y=r()*H, a=r()*6.28, L2=1.5+r()*4;+ ctx.strokeStyle='#8f806b'; ctx.globalAlpha=0.22+r()*0.28; ctx.lineWidth=0.6+r()*0.5;+ ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x+Math.cos(a)*L2,y+Math.sin(a)*L2); ctx.stroke();+ }+ ctx.restore();+}+function paperGrain(){+ // light tooth over everything+ ctx.save();+ ctx.globalCompositeOperation='multiply';+ const r=mulberry32(909);+ for(let i=0;i<900;i++){+ const x=r()*W, y=r()*H;+ const v=FBM(x*0.02,y*0.02);+ if(v<0.52) continue;+ ctx.fillStyle='#dcd2c0';+ ctx.globalAlpha=(v-0.5)*0.5;+ ctx.fillRect(x,y,1.3,1.3);+ }+ ctx.restore();+}++// ---------- the seal: baiwen, cinnabar, pressed once ----------+function seal(x,y,s){+ const r=mulberry32(900);+ ctx.save();+ ctx.globalCompositeOperation='multiply';+ ctx.globalAlpha=0.92;+ // the block, edge worn uneven+ const off=document.createElement('canvas'); off.width=Math.ceil(s+8); off.height=Math.ceil(s+8);+ const k=off.getContext('2d');+ k.translate(4,4);+ k.fillStyle='#b8352b';+ k.beginPath();+ for(let i=0;i<40;i++){+ const t=i/10, side=Math.floor(t), f=t-side;+ const j=(FBM(i*0.7,side*3.1)-0.5)*2.6;+ const p = side===0?[s*f,j]: side===1?[s+j,s*f]: side===2?[s*(1-f),s+j]:[j,s*(1-f)];+ i?k.lineTo(p[0],p[1]):k.moveTo(p[0],p[1]);+ }+ k.closePath(); k.fill();+ // carving cut into the stone: prints as paper+ k.globalCompositeOperation='destination-out';+ k.lineCap='square'; k.lineJoin='miter';+ const GLYPHS=[+ [[[0.12,0.16],[0.88,0.16]],[[0.5,0.16],[0.5,0.88]],[[0.16,0.46],[0.84,0.46]],[[0.2,0.62],[0.2,0.86],[0.8,0.86],[0.8,0.62]]],+ [[[0.16,0.1],[0.16,0.9]],[[0.16,0.3],[0.86,0.3],[0.86,0.9]],[[0.44,0.3],[0.44,0.7],[0.68,0.7]],[[0.16,0.9],[0.62,0.9]]],+ [[[0.1,0.2],[0.9,0.2]],[[0.3,0.2],[0.3,0.55],[0.7,0.55],[0.7,0.2]],[[0.5,0.55],[0.5,0.9]],[[0.14,0.76],[0.86,0.76]]],+ [[[0.18,0.14],[0.82,0.14],[0.82,0.86],[0.18,0.86],[0.18,0.4],[0.6,0.4],[0.6,0.64],[0.4,0.64]]]+ ];+ const cell=(s-12)/2, order=[[1,0],[1,1],[0,0],[0,1]]; // right column first, top to bottom+ GLYPHS.forEach((gl,gi)=>{+ const ox=6+order[gi][0]*cell, oy=6+order[gi][1]*cell;+ gl.forEach(line=>{+ k.lineWidth=cell*0.13*(0.9+r()*0.25);+ k.beginPath();+ line.forEach(([u,v],i)=>{+ const px=ox+cell*(0.08+u*0.84)+(r()-0.5)*0.8, py=oy+cell*(0.08+v*0.84)+(r()-0.5)*0.8;+ i?k.lineTo(px,py):k.moveTo(px,py);+ });+ k.stroke();+ });+ });+ // inner border and chips+ k.lineWidth=1.6; k.strokeStyle='#000'; k.strokeRect(3.2,3.2,s-6.4,s-6.4);+ for(let i=0;i<3;i++){+ const a=r()*4;+ const px=a<1?a*s:a<2?s:a<3?(a-2)*s:0, py=a<1?0:a<2?(a-1)*s:a<3?s:(a-3)*s;+ k.beginPath(); k.arc(px,py,1.6+r()*2.2,0,6.28); k.fill();+ }+ // paste pressed unevenly: break the red where the stamp met the paper lightly+ for(let i=0;i<120;i++){+ const px=r()*s, py=r()*s;+ const lighter=FBM(px*0.06+3,py*0.06+3);+ if(lighter<0.5) continue;+ k.globalAlpha=(lighter-0.48)*1.1;+ k.beginPath(); k.arc(px,py,0.5+r()*1.4,0,6.28); k.fill();+ k.globalAlpha=1;+ }+ ctx.drawImage(off,x-4,y-4);+ ctx.restore();+}++// ---------- the paper boat (shared geometry, translated into ink) ----------+// hull + triangular sail-peak, no face, no limbs. attitude by tilt and stroke weight.+function boat(x,y,s,tilt,inkMain,seedBase,opts){+ opts=opts||{};+ const c=Math.cos(tilt), sn=Math.sin(tilt);+ const T=(px,py)=>[x+(px*c-py*sn)*s, y+(px*sn+py*c)*s];+ // hull: one confident loaded side-laid drag, bow (right) slightly raised+ brush({ ctrl:[T(-1.05,0.02),T(-0.5,0.13),T(0.15,0.13),T(0.75,0.03),T(1.05,-0.12)],+ w:0.29*s, ink:inkMain, press:[[0,0.4],[0.12,1.05],[0.55,0.95],[0.85,0.8],[1,0.15]],+ load:1.05, dry:opts.dryHull==null?0.5:opts.dryHull, edge:0.35, split:0.75, bleed:0.8, streak:true,+ slow:[[0.03,0.5],[0.97,0.25]], seed:seedBase});+ // bow and stern up-flicks of the folded paper+ brush({ ctrl:[T(-1.02,0.06),T(-1.16,-0.2),T(-1.2,-0.38)], w:0.09*s, ink:inkMain,+ press:[[0,0.9],[0.5,0.7],[1,0.05]], dry:0.25, split:0.5, bleed:0.35, slow:[[0.02,0.3]], hairs:8, seed:seedBase+1});+ brush({ ctrl:[T(1.0,-0.08),T(1.18,-0.3),T(1.24,-0.5)], w:0.09*s, ink:inkMain,+ press:[[0,0.9],[0.5,0.7],[1,0.05]], dry:0.25, split:0.5, bleed:0.35, slow:[[0.02,0.3]], hairs:8, seed:seedBase+2});+ // the sail-peak: two strokes meeting at the point, leaning forward (right)+ brush({ ctrl:[T(-0.55,-0.02),T(-0.25,-0.5),T(0.14,-0.98)], w:0.13*s, ink:inkMain,+ press:[[0,0.85],[0.5,0.95],[1,0.1]], dry:0.3, split:0.6, bleed:0.5, slow:[[0.02,0.4]], hairs:10, seed:seedBase+3});+ brush({ ctrl:[T(0.14,-0.98),T(0.42,-0.55),T(0.62,-0.06)], w:0.115*s, ink:inkMain,+ press:[[0,0.15],[0.4,0.9],[1,0.75]], dry:0.35, split:0.7, bleed:0.4, slow:[[0.96,0.35]], hairs:9, seed:seedBase+4});+ // one pale fold-line inside the sail (the crease of the paper), clear ink+ brush({ ctrl:[T(0.1,-0.9),T(0.05,-0.5),T(-0.02,-0.1)], w:0.045*s, ink:QING,+ press:[[0,0.2],[0.5,0.8],[1,0.1]], dry:0.2, split:0.3, bleed:0.25, slow:[], hairs:5, seed:seedBase+5});+}++// ---------- FRAME A: setting out at first light ----------+function drawA(){+ paperGround();++ // far peaks on the horizon, right side: depth is dilution; mist is where they stop.+ // each peak is one wet flank of the brush: up one side, over, down the other,+ // its foot dissolving into the mist above the water.+ // each hill is built of short side-laid strokes stacked toward its summit+ const hill = (rows, ink0, wet0, seed0) => rows.forEach((row,ri)=>{+ brush({ ctrl:row.c, w:row.w, ink:ink0*(0.9+0.1*(ri/rows.length)),+ press:[[0,0.08],[0.25,0.9],[0.6,1],[1,0.1]],+ load:0.95, dry:0.5, edge:0.15, split:0.6, bleed:0.55, wet:wet0,+ slow:[[0.4,0.3]], hairs:Math.max(8,Math.round(row.w*0.5)), seed:seed0+ri });+ });+ hill([ // the far hill: clear ink, low and long+ { c:[[864,450],[944,442],[1024,446]], w:20 },+ { c:[[906,432],[962,422],[1014,430]], w:17 }+ ], QING*0.8, 0.35, 210);+ hill([ // the near hill: light ink, one summit+ { c:[[982,452],[1074,442],[1166,440],[1252,450]], w:24 },+ { c:[[1042,428],[1114,416],[1194,426]], w:22 },+ { c:[[1092,402],[1134,392],[1180,402]], w:19 }+ ], DAN*0.92, 0.2, 215);+ // the mist at their feet: one pale horizontal breath that swallows the bases+ wash({ ctrl:[[820,452],[1000,446],[1180,450],[1276,448]],+ w:34, ink:QING*0.45, press:[[0,0.1],[0.4,0.9],[1,0.35]],+ slow:[], soft:6, hairs:16, seed:214 });+ // one darker near shoulder at its foot, a single dry side-laid stroke+ brush({ ctrl:[[1120,452],[1180,432],[1236,436],[1276,448]],+ w:18, ink:DAN, press:[[0,0.05],[0.35,1],[0.8,0.7],[1,0.05]],+ load:0.95, dry:0.7, edge:0.3, split:0.9, streak:true, bleed:0.5,+ slow:[[0.35,0.35]], seed:212 });+ // the horizon: one pale resting line where water meets the mist+ brush({ ctrl:[[790,470],[960,466],[1150,468],[1272,470]], w:3.4, ink:QING*0.7,+ press:[[0,0.03],[0.3,0.55],[0.7,0.5],[1,0.03]], dry:0.6, split:0.7, streak:true,+ bleed:0.2, slow:[], hairs:5, seed:213 });++ // the pale sun: a near-clear ring, brushed once, high in the empty sky+ {+ const cx=962, cy=128, R=40, pts=[];+ for(let i=0;i<=10;i++){ const a=-Math.PI/2+i*(Math.PI*2)/10*1.02; pts.push([cx+Math.cos(a)*R, cy+Math.sin(a)*R]); }+ brush({ ctrl:pts, w:7, ink:QING*0.85, press:[[0,0.25],[0.15,0.8],[0.5,0.55],[0.85,0.75],[1,0.1]],+ load:0.9, dry:0.5, split:0.6, bleed:0.45, slow:[[0.02,0.3]], hairs:9, seed:230 });+ }++ // the water: the paper is the water. only a few resting strokes say so.+ brush({ ctrl:[[70,556],[230,552],[400,556]], w:5, ink:QING,+ press:[[0,0.05],[0.3,0.7],[0.7,0.6],[1,0.05]], dry:0.45, split:0.7, streak:true, bleed:0.3, slow:[], hairs:7, seed:240 });+ brush({ ctrl:[[540,586],[700,582],[900,588],[1080,584]], w:4.5, ink:QING*0.8,+ press:[[0,0.05],[0.4,0.6],[1,0.05]], dry:0.5, split:0.7, streak:true, bleed:0.25, slow:[], hairs:6, seed:241 });+ brush({ ctrl:[[860,470],[1000,466],[1140,470]], w:3.5, ink:QING*0.7,+ press:[[0,0.05],[0.5,0.55],[1,0.05]], dry:0.5, split:0.6, streak:true, bleed:0.2, slow:[], hairs:5, seed:242 });++ // THE BOAT: lower-left third, heading right into the morning+ const bx=330, by=520, bs=58, tilt=-0.045;+ boat(bx,by,bs,tilt,NONG,300,{});+ // its reflection: the same idea upside down in clear ink, broken by the water+ ctx.save();+ ctx.translate(bx, by+22); ctx.scale(1,-0.42); ctx.translate(-bx,-(by));+ boat(bx,by,bs,tilt,QING*0.9,320,{dryHull:0.9});+ ctx.restore();+ // the wake: two dry flicks trailing left+ brush({ ctrl:[[bx-120,by+34],[bx-70,by+30],[bx-38,by+29]], w:4, ink:DAN,+ press:[[0,0.05],[0.6,0.7],[1,0.3]], dry:0.5, split:0.8, streak:true, bleed:0.2, slow:[], hairs:6, seed:340 });+ brush({ ctrl:[[bx-88,by+46],[bx-46,by+43],[bx-16,by+44]], w:3.2, ink:DAN*0.8,+ press:[[0,0.05],[0.6,0.6],[1,0.25]], dry:0.55, split:0.8, streak:true, bleed:0.2, slow:[], hairs:5, seed:341 });++ // two birds, far, each one bent stroke+ [[760,120,15],[812,138,11]].forEach(([x,y,w2],i)=>{+ brush({ ctrl:[[x-w2,y+4],[x-w2*0.3,y-3],[x,y],[x+w2*0.3,y-3],[x+w2,y+4]], w:2.6, ink:DAN,+ press:[[0,0.1],[0.25,0.8],[0.5,0.4],[0.75,0.8],[1,0.1]], dry:0.3, split:0.4, bleed:0.2, slow:[], hairs:4, seed:350+i });+ });++ // the seal, stamped last, lower right, balancing the boat+ seal(1176,596,58);+ paperGrain();+}++// ---------- FRAME B: the storm wave as one huge loaded brushstroke ----------+function drawB(){+ paperGround();++ // the storm sky: heavy wet washes crowding from the upper right,+ // one gap of bare paper left where the light fights through (upper left-center)+ wash({ ctrl:[[300,-44],[540,-58],[790,-40],[980,-6]],+ w:96, ink:DAN*0.9, press:[[0,0.2],[0.35,0.85],[0.7,1.0],[1,0.4]],+ slow:[[0.55,0.6]], soft:7, hairs:26, seed:400 });+ wash({ ctrl:[[520,44],[720,26],[900,50]],+ w:52, ink:QING*0.8, press:[[0,0.08],[0.4,0.85],[1,0.3]],+ slow:[[0.5,0.4]], soft:6, hairs:18, seed:401 });+ // rain: dry diagonal hairlines through the dark side+ {+ const r=mulberry32(420);+ for(let i=0;i<3;i++){+ const x0=640+r()*380, y0=30+r()*100, L2=60+r()*70, bendR=(r()-0.5)*22;+ brush({ ctrl:[[x0,y0],[x0-L2*0.3+bendR,y0+L2*0.5],[x0-L2*0.62,y0+L2]], w:2, ink:DAN*(0.55+r()*0.35),+ press:[[0,0.45],[1,0.05]], dry:0.85, split:0.6, streak:true, bleed:0.1, slow:[], hairs:3, seed:430+i });+ }+ }++ // THE WAVE: one huge loaded brushstroke, diagonal from upper right,+ // wet and thunder-dark where it was loaded, breaking into flying white at the crest+ brush({ ctrl:[[1400,96],[1252,178],[1080,246],[900,352],[724,474],[540,580],[330,652]],+ w:96, ink:JIAO, press:[[0,0.55],[0.2,1.08],[0.45,0.95],[0.75,0.78],[1,0.2]],+ load:0.95, dry:0.62, edge:0.45, split:1, streak:true, bleed:0.9,+ slow:[[0.22,0.7],[0.55,0.4]], hairs:34, seed:500 });+ // its underbelly: a second heavy stroke tucked beneath, drier+ brush({ ctrl:[[1210,330],[1030,420],[850,504],[660,584]],+ w:56, ink:NONG, press:[[0,0.25],[0.3,0.95],[1,0.15]],+ load:0.85, dry:0.8, edge:0.4, split:1, streak:true, bleed:0.6,+ slow:[[0.1,0.5]], hairs:24, seed:501 });+ // the crest curling over: the lip hooks up, over and back down toward the boat+ brush({ ctrl:[[1340,152],[1246,110],[1148,98],[1058,110],[1004,148]],+ w:40, ink:NONG, press:[[0,0.45],[0.3,0.95],[0.65,0.75],[1,0.05]],+ load:0.85, dry:0.75, edge:0.5, split:1, streak:true, bleed:0.4,+ slow:[[0.3,0.4]], hairs:17, seed:502 });+ // foam claws raking down off the lip+ [[1010,146,-70],[1076,118,-64],[1140,108,-58]].forEach(([fx,fy,fl],i)=>{+ brush({ ctrl:[[fx,fy],[fx-24,fy-fl*0.5],[fx-58,fy-fl]], w:10, ink:NONG,+ press:[[0,0.7],[0.5,0.5],[1,0.03]], dry:1.05, split:1, streak:true, bleed:0.2,+ slow:[], hairs:7, seed:560+i });+ });+ // spray: dry flicks and thrown dots off the crest+ {+ const r=mulberry32(510);+ for(let i=0;i<9;i++){+ const t=r(), x0=1040-t*330+(r()-0.5)*130, y0=170+t*180+(r()-0.5)*110;+ const a=-2.3+(r()-0.5)*0.7, L2=22+r()*40;+ brush({ ctrl:[[x0,y0],[x0+Math.cos(a)*L2,y0+Math.sin(a)*L2]], w:4+r()*4, ink:NONG,+ press:[[0,0.8],[1,0.02]], dry:1.1, split:1, streak:true, bleed:0.15, slow:[], hairs:5, seed:520+i });+ }+ ctx.save(); ctx.globalCompositeOperation='multiply';+ for(let i=0;i<26;i++){+ const t=r(), x0=1010-t*420+(r()-0.5)*170, y0=150+t*200+(r()-0.5)*140;+ const T2=tone(r()<0.5?NONG:ZHONG);+ ctx.fillStyle=T2.color; ctx.globalAlpha=T2.alpha*(0.4+r()*0.5);+ ctx.beginPath(); ctx.arc(x0,y0,0.8+r()*2.4,0,6.28); ctx.fill();+ }+ ctx.restore();+ }++ // troubled water beneath the boat: heavy short strokes, rising left to right+ brush({ ctrl:[[60,640],[220,624],[400,634],[540,616]], w:26, ink:ZHONG,+ press:[[0,0.1],[0.3,0.9],[0.7,0.8],[1,0.1]], load:0.85, dry:0.8, edge:0.3, split:1, streak:true,+ bleed:0.5, slow:[[0.4,0.4]], hairs:14, seed:530 });+ brush({ ctrl:[[140,686],[330,672],[520,680]], w:20, ink:DAN,+ press:[[0,0.1],[0.4,0.8],[1,0.1]], load:0.8, dry:0.9, split:1, streak:true,+ bleed:0.4, slow:[], hairs:11, seed:531 });++ // the swell the boat rides: one long stroke passing under the hull+ brush({ ctrl:[[96,610],[240,588],[380,578],[520,590],[640,614]], w:16, ink:ZHONG,+ press:[[0,0.05],[0.3,0.75],[0.55,0.9],[0.8,0.6],[1,0.05]],+ load:0.85, dry:0.75, edge:0.3, split:1, streak:true, bleed:0.4,+ slow:[[0.5,0.3]], hairs:10, seed:533 });+ // THE BOAT: small against the wave, climbing it, bow still pointing forward+ const bx=350, by=546, bs=34, tilt=-0.3;+ boat(bx,by,bs,tilt,JIAO,600,{dryHull:0.4});+ // a splash where the hull cuts the water+ brush({ ctrl:[[bx-42,by+26],[bx-16,by+16],[bx+16,by+18]], w:8, ink:NONG,+ press:[[0,0.05],[0.5,0.9],[1,0.1]], dry:0.7, split:1, streak:true, bleed:0.3, slow:[], hairs:8, seed:620 });++ // the seal: same stone, same corner family — upper left, in the light the storm left open+ seal(66,58,52);+ paperGrain();+}++window.drawFrame=function(which){+ ctx.setTransform(1,0,0,1,0,0);+ ctx.globalCompositeOperation='source-over';+ ctx.filter='none';+ ctx.clearRect(0,0,W,H);+ if(which==='a') drawA(); else drawB();+ window.DONE=true;+};+window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/lyric/boat.html b/assets/previews-src/lyric/boat.htmlnew file mode 100644index 0000000..85e7754--- /dev/null+++ b/assets/previews-src/lyric/boat.html@@ -0,0 +1,543 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>lyric — paper boat</title>+<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=Archivo+Black&family=Space+Mono:wght@400;700&family=Playfair+Display:ital,wght@1,500;1,600&display=swap" rel="stylesheet">+<style>+ html,body{margin:0;padding:0;background:#000;}+ #c{display:block;width:1280px;height:720px;}+</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++const ORANGE = '#FF5A1F';+const PAPER = '#f4f2ec';+const PAPER_SHADE = '#c9c5b8';+const INK_BG = '#08080a';++// ---------- deterministic rng ----------+function mulberry32(seed){+ return function(){+ seed |= 0; seed = seed + 0x6D2B79F5 | 0;+ let t = Math.imul(seed ^ seed >>> 15, 1 | seed);+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;+ return ((t ^ t >>> 14) >>> 0) / 4294967296;+ };+}++const GROTESK = '"Archivo Black", Arial Black, sans-serif';+const MONO = '"Space Mono", Menlo, monospace';+const SERIF = '"Playfair Display", Georgia, serif';++// ---------- shared helpers ----------+function hud(topR, botL, botR){+ ctx.save();+ ctx.strokeStyle = 'rgba(255,255,255,0.5)';+ ctx.lineWidth = 1.5;+ const m = 26, L = 20;+ // corner brackets+ const cs = [[m,m,1,1],[W-m,m,-1,1],[m,H-m,1,-1],[W-m,H-m,-1,-1]];+ for(const [x,y,sx,sy] of cs){+ ctx.beginPath();+ ctx.moveTo(x + sx*L, y); ctx.lineTo(x, y); ctx.lineTo(x, y + sy*L);+ ctx.stroke();+ }+ ctx.fillStyle = 'rgba(255,255,255,0.55)';+ ctx.font = '11px ' + MONO;+ ctx.textBaseline = 'alphabetic';+ ctx.textAlign = 'left';+ ctx.fillText('THE PAPER BOAT — LYRIC FILM', m + 34, m + 4);+ ctx.textAlign = 'right';+ ctx.fillText(topR, W - m - 34, m + 4);+ ctx.textAlign = 'left';+ ctx.fillText(botL, m + 34, H - m + 4);+ ctx.textAlign = 'right';+ ctx.fillText(botR, W - m - 34, H - m + 4);+ ctx.restore();+}++function vignette(a){+ ctx.save();+ const g = ctx.createRadialGradient(W/2, H/2, H*0.42, W/2, H/2, H*0.85);+ g.addColorStop(0, 'rgba(0,0,0,0)');+ g.addColorStop(1, 'rgba(0,0,0,' + a + ')');+ ctx.fillStyle = g;+ ctx.fillRect(0,0,W,H);+ ctx.restore();+}++// one row of readable repeated lyric text (the water is made of the words)+function typeRow(phrase, y, size, weight, xoff, waveFn, colorFn){+ ctx.font = weight + ' ' + size.toFixed(1) + 'px ' + MONO;+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';+ let x = xoff, k = 0;+ while(x < W + 20){+ const chs = phrase[k % phrase.length];+ ctx.fillStyle = colorFn(x);+ ctx.fillText(chs, x, y + waveFn(x));+ x += ctx.measureText(chs).width + size*0.12;+ k++;+ }+}++// folded paper boat: hull + triangular sail peak. origin = waterline center.+// scale = full hull width in px. rot in radians (negative = bow up heading right).+function drawBoat(x, y, scale, rot, rim){+ ctx.save();+ ctx.translate(x, y);+ ctx.rotate(rot);+ ctx.scale(scale, scale);+ ctx.lineJoin = 'round';+ // sail (two facets, folded)+ ctx.fillStyle = PAPER;+ ctx.beginPath();+ ctx.moveTo(0, -0.46); ctx.lineTo(-0.26, -0.02); ctx.lineTo(0, -0.02);+ ctx.closePath(); ctx.fill();+ ctx.fillStyle = PAPER_SHADE;+ ctx.beginPath();+ ctx.moveTo(0, -0.46); ctx.lineTo(0.26, -0.02); ctx.lineTo(0, -0.02);+ ctx.closePath(); ctx.fill();+ // hull (front facet bright, tips up)+ ctx.fillStyle = PAPER;+ ctx.beginPath();+ ctx.moveTo(-0.52, -0.06); ctx.lineTo(0.52, -0.06);+ ctx.lineTo(0.30, 0.26); ctx.lineTo(-0.30, 0.26);+ ctx.closePath(); ctx.fill();+ // hull shade strip along top edge+ ctx.fillStyle = PAPER_SHADE;+ ctx.beginPath();+ ctx.moveTo(-0.52, -0.06); ctx.lineTo(0.52, -0.06);+ ctx.lineTo(0.46, 0.02); ctx.lineTo(-0.46, 0.02);+ ctx.closePath(); ctx.fill();+ // fold crease+ ctx.strokeStyle = 'rgba(0,0,0,0.18)';+ ctx.lineWidth = 0.015;+ ctx.beginPath(); ctx.moveTo(0, -0.46); ctx.lineTo(0, -0.02); ctx.stroke();+ // rim light (sun/glow side)+ if(rim){+ ctx.strokeStyle = ORANGE;+ ctx.lineWidth = 0.035;+ ctx.lineCap = 'round';+ if(rim === 'right'){+ ctx.beginPath(); ctx.moveTo(0, -0.46); ctx.lineTo(0.26, -0.02); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(0.52, -0.06); ctx.lineTo(0.30, 0.26); ctx.stroke();+ } else {+ ctx.beginPath(); ctx.moveTo(0, -0.46); ctx.lineTo(-0.26, -0.02); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(-0.52, -0.06); ctx.lineTo(-0.30, 0.26); ctx.stroke();+ }+ }+ ctx.restore();+}++// ============================================================+// FRAME A — setting out+// ============================================================+function frameA(){+ const rnd = mulberry32(7);+ // sky+ const sky = ctx.createLinearGradient(0, 0, 0, 480);+ sky.addColorStop(0, '#060608');+ sky.addColorStop(0.75, '#0b0a0c');+ sky.addColorStop(1, '#17110d');+ ctx.fillStyle = sky; ctx.fillRect(0, 0, W, 480);+ ctx.fillStyle = INK_BG; ctx.fillRect(0, 480, W, H-480);++ const HOR = 470, SUNX = 880;++ // sun glow+ let g = ctx.createRadialGradient(SUNX, HOR-40, 6, SUNX, HOR-40, 240);+ g.addColorStop(0, 'rgba(255,120,50,0.55)');+ g.addColorStop(0.35, 'rgba(255,90,31,0.16)');+ g.addColorStop(1, 'rgba(255,90,31,0)');+ ctx.fillStyle = g; ctx.fillRect(SUNX-260, HOR-300, 520, 320);+ // sun disc+ ctx.fillStyle = ORANGE;+ ctx.beginPath(); ctx.arc(SUNX, HOR-42, 24, 0, Math.PI*2); ctx.fill();+ ctx.fillStyle = 'rgba(255,190,140,0.9)';+ ctx.beginPath(); ctx.arc(SUNX, HOR-42, 13, 0, Math.PI*2); ctx.fill();+ // mono tag hanging off the sun, engineered+ ctx.fillStyle = 'rgba(255,255,255,0.5)';+ ctx.font = '11px ' + MONO;+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';+ ctx.fillText('lightsource_00 · 06:12', SUNX + 48, HOR - 98);+ ctx.strokeStyle = 'rgba(255,255,255,0.3)'; ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(SUNX + 20, HOR - 60); ctx.lineTo(SUNX + 42, HOR - 92); ctx.lineTo(SUNX + 196, HOR - 92); ctx.stroke();++ // ---- the sung line: italic serif, soft moment ----+ const LX = 150, LY = 210;+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';+ // outlined echo+ ctx.strokeStyle = 'rgba(255,255,255,0.18)';+ ctx.lineWidth = 1.2;+ ctx.font = 'italic 600 92px ' + SERIF;+ ctx.strokeText('set out small', LX + 8, LY + 10);+ // main+ ctx.fillStyle = 'rgba(244,242,236,0.96)';+ ctx.fillText('set out small', LX, LY);+ // orange full stop as the single hot punctuation+ const lw = ctx.measureText('set out small').width;+ ctx.fillStyle = ORANGE;+ ctx.beginPath(); ctx.arc(LX + lw + 26, LY - 8, 7, 0, Math.PI*2); ctx.fill();+ // mono annotation under the line+ ctx.fillStyle = 'rgba(255,255,255,0.45)';+ ctx.font = '13px ' + MONO;+ ctx.fillText('[ 00:12.408 ] verse 1 — first light', LX + 4, LY + 44);++ // ---- horizon ruler ----+ ctx.strokeStyle = 'rgba(255,255,255,0.35)';+ ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(0, HOR); ctx.lineTo(W, HOR); ctx.stroke();+ ctx.font = '9px ' + MONO;+ ctx.fillStyle = 'rgba(255,255,255,0.35)';+ for(let x = 40; x < W; x += 40){+ const tall = (x % 200 === 0);+ ctx.beginPath(); ctx.moveTo(x, HOR); ctx.lineTo(x, HOR - (tall ? 8 : 4)); ctx.stroke();+ if(tall) ctx.fillText(String(x/10|0).padStart(3,'0') + '°', x + 3, HOR - 6);+ }++ // ---- type-water: calm rows of the lyric ----+ const phrase = 'set out small · ';+ let y = HOR + 10;+ let rowH = 12, size = 9;+ while(y < H - 14){+ const baseA = 0.11 + rnd()*0.09;+ const xoff = -rnd()*140;+ const wob = 1 + rnd()*1.3;+ const ph = rnd()*Math.PI*2;+ const yy = y;+ // sun glitter path: narrow band under the sun, gently widening+ const band = 40 + (yy - HOR)*0.30;+ typeRow(phrase, yy, size, '400', xoff,+ x => Math.sin(x*0.012 + ph)*wob,+ x => (Math.abs(x - SUNX) < band)+ ? 'rgba(255,110,45,' + Math.min(0.6, baseA + 0.30).toFixed(2) + ')'+ : 'rgba(210,215,225,' + baseA.toFixed(2) + ')');+ y += rowH;+ rowH *= 1.13; size *= 1.085;+ }++ // ---- the boat ----+ const BX = 350, BY = 545, BS = 86;+ // wake: fading type ripples trailing left+ ctx.font = '13px ' + MONO;+ ctx.textAlign = 'left';+ for(let i = 0; i < 9; i++){+ const wx = BX - 55 - i*34, wy = BY + 12 + Math.sin(i*1.1)*2 + i*0.8;+ ctx.fillStyle = 'rgba(230,232,238,' + (0.42 - i*0.045).toFixed(2) + ')';+ ctx.fillText(i % 2 ? '~' : '·', wx, wy);+ }+ // water contact shadow+ ctx.fillStyle = 'rgba(0,0,0,0.5)';+ ctx.beginPath(); ctx.ellipse(BX, BY + 12, 52, 7, 0, 0, Math.PI*2); ctx.fill();+ ctx.strokeStyle = 'rgba(240,240,240,0.5)';+ ctx.lineWidth = 1.4;+ ctx.beginPath(); ctx.ellipse(BX + 4, BY + 13, 58, 6, 0, Math.PI*0.05, Math.PI*0.95); ctx.stroke();+ drawBoat(BX, BY, BS, -0.06, 'right');+ // engineered callout+ ctx.strokeStyle = 'rgba(255,255,255,0.35)';+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(BX + 30, BY - 44); ctx.lineTo(BX + 78, BY - 92); ctx.lineTo(BX + 196, BY - 92);+ ctx.stroke();+ ctx.fillStyle = 'rgba(255,255,255,0.55)';+ ctx.font = '11px ' + MONO;+ ctx.fillText('hull_01 — outbound', BX + 84, BY - 97);++ vignette(0.34);+ hud('00:12.408 / VERSE 1', 'BPM 92 · SEED 7 · CALM 0.2', 'FRAME A / SETTING OUT');+}++// ============================================================+// FRAME B — the storm peak: the words ARE the wave+// ============================================================+// crest curve: quadratic bezier, upper right mass -> breaking tip lower left+const P0 = {x: 1320, y: 128}, PC = {x: 840, y: 150}, P1 = {x: 442, y: 418};+function bez(t){+ const a = (1-t)*(1-t), b = 2*(1-t)*t, c = t*t;+ return { x: a*P0.x + b*PC.x + c*P1.x, y: a*P0.y + b*PC.y + c*P1.y };+}+// u: 0 at tip (left) -> 1 at upper right+function crest(u){ return bez(1-u); }+function crestAngle(u){+ const e = 0.004, p = crest(Math.min(1-e, u)), q = crest(Math.min(1, u+e));+ return Math.atan2(q.y - p.y, q.x - p.x);+}++function lettersAlongCrest(text, dy, mode, alpha, col, s0, s1){+ // walk letters left->right along the crest, offset dy downward+ ctx.save();+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';+ let u = 0.02;+ for(const chs of text){+ const size = s0 + (s1 - s0)*u;+ ctx.font = '900 ' + size.toFixed(0) + 'px ' + GROTESK;+ const w = ctx.measureText(chs).width || size*0.5;+ const p = crest(u);+ const ang = crestAngle(u);+ // curl the lip: first letters pitch forward over the boat+ const curl = u < 0.16 ? -(0.16 - u)/0.16 * 0.55 : 0;+ if(chs !== ' '){+ ctx.save();+ ctx.translate(p.x + Math.sin(ang)*dy, p.y + Math.cos(ang)*dy + dy);+ ctx.rotate(ang + curl);+ if(mode === 'fill'){+ ctx.fillStyle = col; ctx.globalAlpha = alpha;+ ctx.fillText(chs, 0, 0);+ } else {+ ctx.strokeStyle = col; ctx.globalAlpha = alpha; ctx.lineWidth = 1.4;+ ctx.strokeText(chs, 0, 0);+ }+ ctx.restore();+ }+ // arc-length step+ const speed = Math.hypot(crest(u+0.004).x - crest(u).x, crest(u+0.004).y - crest(u).y)/0.004;+ u += ((chs === ' ' ? size*0.42 : w) ) / speed;+ if(u > 1.08) break;+ }+ ctx.restore();+}++function frameB(){+ const rnd = mulberry32(58);+ // storm sky+ const sky = ctx.createLinearGradient(0, 0, 0, H);+ sky.addColorStop(0, '#07070a');+ sky.addColorStop(1, '#050507');+ ctx.fillStyle = sky; ctx.fillRect(0, 0, W, H);++ // faint warped perspective grid in the sky (engineered dread)+ ctx.save();+ ctx.strokeStyle = 'rgba(255,255,255,0.055)';+ ctx.lineWidth = 1;+ const vpx = 250, vpy = -160;+ for(let i = -4; i <= 14; i++){+ ctx.beginPath(); ctx.moveTo(vpx, vpy); ctx.lineTo(i*130 - 200, H); ctx.stroke();+ }+ for(let j = 0; j < 6; j++){+ const yy = 60 + j*j*14;+ ctx.beginPath(); ctx.moveTo(0, yy + 40); ctx.quadraticCurveTo(W*0.4, yy - 30, W, yy + 70); ctx.stroke();+ }+ ctx.restore();++ // one light source fighting through — upper left+ let g = ctx.createRadialGradient(185, 95, 10, 185, 95, 380);+ g.addColorStop(0, 'rgba(255,170,110,0.34)');+ g.addColorStop(0.4, 'rgba(255,110,50,0.12)');+ g.addColorStop(1, 'rgba(255,90,31,0)');+ ctx.fillStyle = g; ctx.fillRect(0, 0, 640, 520);+ // crepuscular streaks+ ctx.save();+ ctx.strokeStyle = 'rgba(255,150,90,0.10)';+ ctx.lineWidth = 3;+ for(let i = 0; i < 5; i++){+ const a = 0.5 + i*0.22;+ ctx.beginPath(); ctx.moveTo(185, 95);+ ctx.lineTo(185 + Math.cos(a)*560, 95 + Math.sin(a)*560); ctx.stroke();+ }+ ctx.restore();++ // ---- churning type-water first (wave sits on top of it) ----+ const phrase = 'hold the line ';+ function churnRows(y0, y1, rH0, s0){+ let y = y0, rowH = rH0, size = s0;+ while(y < y1){+ const baseA = 0.11 + rnd()*0.11;+ const xoff = -rnd()*160;+ const amp = 4 + rnd()*5;+ const ph = rnd()*Math.PI*2;+ const yy = y;+ typeRow(phrase, yy, size, '700', xoff,+ x => Math.sin(x*0.02 + ph)*amp + Math.sin(x*0.006 + ph*2)*amp*0.7 - x*0.012,+ x => (Math.sin(x*0.05 + ph*3) > 0.93)+ ? 'rgba(255,110,45,' + (baseA + 0.18).toFixed(2) + ')'+ : 'rgba(205,212,224,' + baseA.toFixed(2) + ')');+ y += rowH; rowH *= 1.14; size *= 1.10;+ }+ }+ churnRows(512, H - 10, 15, 11);++ // ---- wave body: dark mass filled with outlined echoes of the line ----+ ctx.save();+ ctx.beginPath();+ const tip = crest(0);+ ctx.moveTo(tip.x - 70, tip.y + 90);+ for(let u = 0; u <= 1.001; u += 0.05){+ const p = crest(u);+ ctx.lineTo(p.x, p.y - 46);+ }+ ctx.lineTo(W + 10, -10); ctx.lineTo(W + 10, H + 10);+ ctx.lineTo(660, H + 10);+ ctx.quadraticCurveTo(500, 640, 470, 560);+ ctx.quadraticCurveTo(440, 500, tip.x - 70, tip.y + 90);+ ctx.closePath();+ const bodyG = ctx.createLinearGradient(1200, 100, 450, 500);+ bodyG.addColorStop(0, '#101017');+ bodyG.addColorStop(1, '#0a0a10');+ ctx.fillStyle = bodyG;+ ctx.fill();+ ctx.clip();+ // outlined echo rows = the mass of water is made of the same words+ for(let i = 1; i <= 9; i++){+ const a = 0.20 - i*0.019;+ const col = (i === 2 || i === 5) ? 'rgba(255,90,31,1)' : 'rgba(220,226,238,1)';+ lettersAlongCrest('HOLD THE LINE', i*58, 'stroke', Math.max(0.035, a) * (col.includes('255,90') ? 0.85 : 1), col, 72 - i*2, 122 - i*4);+ }+ ctx.restore();++ // crest edge glow+ ctx.save();+ ctx.strokeStyle = 'rgba(255,120,55,0.5)';+ ctx.lineWidth = 2.5;+ ctx.shadowColor = 'rgba(255,90,31,0.8)';+ ctx.shadowBlur = 14;+ ctx.beginPath();+ for(let u = 0; u <= 1.001; u += 0.03){+ const p = crest(u);+ if(u === 0) ctx.moveTo(p.x, p.y - 46); else ctx.lineTo(p.x, p.y - 46);+ }+ ctx.stroke();+ ctx.restore();++ // ---- THE LINE: huge grotesk letters riding the crest ----+ // echo pass (offset outline)+ ctx.save(); ctx.translate(9, 14);+ lettersAlongCrest('HOLD THE LINE', 0, 'stroke', 0.30, 'rgba(230,234,244,1)', 80, 128);+ ctx.restore();+ // main pass: HOLD in orange (the imperative, by the boat), THE LINE white+ ctx.save();+ ctx.shadowColor = 'rgba(255,90,31,0.55)';+ ctx.shadowBlur = 22;+ lettersAlongCrestSplit();+ ctx.restore();++ // spray: particle burst of glyphs above the crest, dense at the breaking tip+ ctx.save();+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';+ const glyphs = "/\\'·*^`,";+ for(let i = 0; i < 120; i++){+ const u = Math.pow(rnd(), 2.1); // cluster near tip+ const p = crest(u);+ const throwUp = 18 + rnd()*90 + (1-u)*40;+ const gx = p.x + (rnd()-0.5)*130 - (1-u)*50;+ const gy = Math.max(72, p.y - 46 - throwUp*rnd());+ const s = 8 + rnd()*14;+ ctx.font = '700 ' + s.toFixed(0) + 'px ' + MONO;+ const orange = rnd() < 0.3;+ const a = 0.25 + rnd()*0.5;+ ctx.fillStyle = orange ? 'rgba(255,110,45,' + a.toFixed(2) + ')' : 'rgba(235,238,246,' + a.toFixed(2) + ')';+ ctx.save();+ ctx.translate(gx, gy); ctx.rotate((rnd()-0.5)*1.6);+ ctx.fillText(glyphs[(rnd()*glyphs.length)|0], 0, 0);+ ctx.restore();+ }+ ctx.restore();++ // glitch slices across the big word zone+ for(const [sy, sh, dx] of [[160, 14, -15],[238, 9, 11],[330, 12, -9]]){+ ctx.drawImage(cv, 470, sy, 790, sh, 470 + dx, sy, 790, sh);+ ctx.fillStyle = 'rgba(255,90,31,0.10)';+ ctx.fillRect(470, sy, 790, 1);+ }++ // ---- the boat: tiny, climbing, lit by the break in the clouds ----+ const BX = 322, BY = 565, BS = 58;+ // spotlight glow behind the hero+ let bg = ctx.createRadialGradient(BX, BY - 8, 4, BX, BY - 8, 120);+ bg.addColorStop(0, 'rgba(255,150,95,0.36)');+ bg.addColorStop(1, 'rgba(255,90,31,0)');+ ctx.fillStyle = bg;+ ctx.fillRect(BX-120, BY-120, 240, 220);+ // heaving water contact+ ctx.strokeStyle = 'rgba(235,238,246,0.55)';+ ctx.lineWidth = 1.6;+ ctx.beginPath();+ ctx.moveTo(BX - 62, BY + 18);+ ctx.quadraticCurveTo(BX - 20, BY + 4, BX + 16, BY + 14);+ ctx.quadraticCurveTo(BX + 44, BY + 21, BX + 66, BY + 12);+ ctx.stroke();+ ctx.fillStyle = 'rgba(0,0,0,0.55)';+ ctx.beginPath(); ctx.ellipse(BX, BY + 14, 36, 6, -0.1, 0, Math.PI*2); ctx.fill();+ drawBoat(BX, BY, BS, -0.22, 'left');+ // callout+ ctx.strokeStyle = 'rgba(255,255,255,0.4)';+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.moveTo(BX - 24, BY - 24); ctx.lineTo(BX - 78, BY - 66); ctx.lineTo(BX - 218, BY - 66);+ ctx.stroke();+ ctx.fillStyle = 'rgba(255,255,255,0.6)';+ ctx.font = '11px ' + MONO;+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';+ ctx.fillText('hull_01 — holding', BX - 214, BY - 71);+ // warning readout near the wave tip+ ctx.fillStyle = 'rgba(255,110,45,0.85)';+ ctx.font = '700 11px ' + MONO;+ ctx.fillText('▲ WAVE_AMP 9.7 — BRACE', 452, 486);++ // foreground churn rows over the wave base to merge it with the sea+ churnRows(646, H - 6, 26, 20);++ vignette(0.40);+ hud('00:58.216 / CHORUS — PEAK', 'BPM 92 · SEED 58 · SURGE 0.97', 'FRAME B / THE STORM PEAK');+}++// main crest word with per-word color+function lettersAlongCrestSplit(){+ const text = 'HOLD THE LINE';+ ctx.save();+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';+ let u = 0.02, idx = 0;+ for(const chs of text){+ const size = 80 + (128 - 80)*u;+ ctx.font = '900 ' + size.toFixed(0) + 'px ' + GROTESK;+ const w = ctx.measureText(chs).width || size*0.5;+ const p = crest(u);+ const ang = crestAngle(u);+ const curl = u < 0.16 ? -(0.16 - u)/0.16 * 0.55 : 0;+ if(chs !== ' '){+ ctx.save();+ ctx.translate(p.x, p.y);+ ctx.rotate(ang + curl);+ ctx.fillStyle = idx < 4 ? ORANGE : PAPER;+ ctx.fillText(chs, 0, 0);+ ctx.restore();+ }+ const speed = Math.hypot(crest(u+0.004).x - crest(u).x, crest(u+0.004).y - crest(u).y)/0.004;+ u += ((chs === ' ' ? size*0.42 : w)) / speed;+ idx++;+ if(u > 1.08) break;+ }+ ctx.restore();+}++// ---------- harness ----------+window.drawFrame = function(which){+ ctx.setTransform(1,0,0,1,0,0);+ ctx.globalAlpha = 1;+ ctx.clearRect(0,0,W,H);+ ctx.fillStyle = INK_BG; ctx.fillRect(0,0,W,H);+ if(which === 'a') frameA(); else frameB();+ window.DONE = true;+};++const want = [+ '900 100px "Archivo Black"',+ '400 16px "Space Mono"',+ '700 16px "Space Mono"',+ 'italic 600 92px "Playfair Display"'+];+Promise.race([+ Promise.all(want.map(f => document.fonts.load(f))),+ new Promise(r => setTimeout(r, 8000))+]).then(() => { window.READY = true; });+</script>+</body>+</html>diff --git a/assets/previews-src/manifesto/boat.html b/assets/previews-src/manifesto/boat.htmlnew file mode 100644index 0000000..2122da0--- /dev/null+++ b/assets/previews-src/manifesto/boat.html@@ -0,0 +1,572 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>manifesto boat</title>+<style>+ html,body{margin:0;padding:0;background:#111;}+ #c{display:block;width:1280px;height:720px;}+</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++// palette+const BLACK = '#0b0a08';+const PAPER = '#f3eee2';+const YELLOW = '#FFD21F';+const RED = '#e03a2a';++// fonts+const GROTESK = '900 76px "Helvetica Neue", Helvetica, Arial, sans-serif';+const SERIF_I = 'italic 400 26px Georgia, "Times New Roman", serif';+const MONO = '400 15px Menlo, Monaco, monospace';++// deterministic rng+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}}++// ---------- shared drawing helpers ----------++function grain(seed, color, alpha, n){+ const r = mulberry32(seed);+ ctx.save();+ ctx.globalAlpha = alpha;+ ctx.fillStyle = color;+ for(let i=0;i<n;i++){+ const x = r()*W, y = r()*H, s = 0.5 + r()*1.1;+ ctx.fillRect(x, y, s, s);+ }+ ctx.restore();+}++function frameAndBrackets(ink){+ ctx.save();+ ctx.strokeStyle = ink;+ // hairline frame+ ctx.globalAlpha = 0.45;+ ctx.lineWidth = 1;+ ctx.strokeRect(26.5, 26.5, W-53, H-53);+ // corner brackets+ ctx.globalAlpha = 1;+ ctx.lineWidth = 3;+ const L = 26, inset = 26;+ const cs = [[inset,inset,1,1],[W-inset,inset,-1,1],[inset,H-inset,1,-1],[W-inset,H-inset,-1,-1]];+ for(const [x,y,sx,sy] of cs){+ ctx.beginPath();+ ctx.moveTo(x + sx*L, y);+ ctx.lineTo(x, y);+ ctx.lineTo(x, y + sy*L);+ ctx.stroke();+ }+ ctx.restore();+}++function monoLabel(text, x, y, color, align){+ ctx.save();+ ctx.font = MONO;+ ctx.fillStyle = color;+ ctx.textAlign = align || 'left';+ ctx.textBaseline = 'alphabetic';+ if('letterSpacing' in ctx) ctx.letterSpacing = '2px';+ ctx.fillText(text, x, y);+ ctx.restore();+}++// statement: two lines, heavy grotesk caps. line2 gets a yellow highlight bar+// (paper frame) or is set in yellow (black frame).+function statement(l1, l2, x, y, mode){+ ctx.save();+ ctx.font = GROTESK;+ if('letterSpacing' in ctx) ctx.letterSpacing = '1px';+ ctx.textAlign = 'left';+ ctx.textBaseline = 'alphabetic';+ const lh = 84;+ if(mode === 'paper'){+ ctx.fillStyle = BLACK;+ ctx.fillText(l1, x, y);+ // highlight bar behind second line+ const w2 = ctx.measureText(l2).width;+ ctx.fillStyle = YELLOW;+ ctx.fillRect(x-14, y+lh-62, w2+28, 76);+ ctx.fillStyle = BLACK;+ ctx.fillText(l2, x, y+lh);+ } else {+ ctx.fillStyle = PAPER;+ ctx.fillText(l1, x, y);+ ctx.fillStyle = YELLOW;+ ctx.fillText(l2, x, y+lh);+ }+ ctx.restore();+}++function narration(text, x, y, color){+ ctx.save();+ ctx.font = SERIF_I;+ ctx.fillStyle = color;+ ctx.textAlign = 'left';+ ctx.fillText(text, x, y);+ ctx.restore();+}++// paper boat, clean line art. local coords: hull top edge y=0, width ~120.+function boat(x, y, scale, rot, ink, lw){+ ctx.save();+ ctx.translate(x, y);+ ctx.rotate(rot);+ ctx.scale(scale, scale);+ ctx.strokeStyle = ink;+ ctx.lineWidth = lw/scale;+ ctx.lineJoin = 'round';+ ctx.lineCap = 'round';+ // hull: trapezoid with slightly raised end points+ ctx.beginPath();+ ctx.moveTo(-64, -6); // left tip, slightly raised+ ctx.lineTo(-58, 2);+ ctx.lineTo(-36, 34); // bottom left+ ctx.lineTo(36, 34); // bottom right+ ctx.lineTo(58, 2);+ ctx.lineTo(64, -6); // right tip+ ctx.stroke();+ // gunwale line connecting the tips+ ctx.beginPath();+ ctx.moveTo(-64, -6);+ ctx.quadraticCurveTo(0, 1, 64, -6);+ ctx.stroke();+ // sail: center triangle+ ctx.beginPath();+ ctx.moveTo(-27, -1);+ ctx.lineTo(0, -56);+ ctx.lineTo(27, -1);+ ctx.stroke();+ // fold line inside sail+ ctx.beginPath();+ ctx.moveTo(0, -56);+ ctx.lineTo(-4, -2);+ ctx.stroke();+ // hull fold line+ ctx.beginPath();+ ctx.moveTo(-44, 16);+ ctx.lineTo(44, 16);+ ctx.globalAlpha = 0.55;+ ctx.stroke();+ ctx.restore();+}++// ---------- FRAME A : setting out ----------++function drawA(){+ const r = mulberry32(20260928);+ ctx.clearRect(0,0,W,H);+ ctx.fillStyle = PAPER;+ ctx.fillRect(0,0,W,H);+ grain(11, BLACK, 0.05, 2600);++ const horizon = 452;++ // sun: yellow half-disc rising on the horizon, right side (boat heads toward it)+ ctx.save();+ ctx.beginPath();+ ctx.rect(0, 0, W, horizon);+ ctx.clip();+ ctx.fillStyle = YELLOW;+ ctx.beginPath();+ ctx.arc(950, horizon+16, 62, 0, Math.PI*2);+ ctx.fill();+ ctx.strokeStyle = BLACK;+ ctx.lineWidth = 2.5;+ ctx.stroke();+ ctx.restore();+ // sun rays: short line ticks+ ctx.save();+ ctx.strokeStyle = BLACK;+ ctx.lineWidth = 2;+ for(let i=0;i<7;i++){+ const a = Math.PI + Math.PI*(i+1)/8; // upper half+ const r0 = 76, r1 = 92 + (i%2)*8;+ ctx.beginPath();+ ctx.moveTo(950 + Math.cos(a)*r0, horizon+16 + Math.sin(a)*r0);+ ctx.lineTo(950 + Math.cos(a)*r1, horizon+16 + Math.sin(a)*r1);+ ctx.stroke();+ }+ ctx.restore();++ // horizon line+ ctx.strokeStyle = BLACK;+ ctx.lineWidth = 2.5;+ ctx.beginPath();+ ctx.moveTo(60, horizon);+ ctx.lineTo(W-60, horizon);+ ctx.stroke();++ // calm water: sparse horizontal dashes, denser lower+ ctx.save();+ ctx.strokeStyle = BLACK;+ ctx.lineCap = 'round';+ for(let i=0;i<64;i++){+ const t = r();+ const y = horizon + 14 + Math.pow(t, 1.4) * (H - horizon - 70);+ const x = 70 + r()*(W-220);+ const len = 20 + r()*70 * (0.5 + t);+ ctx.globalAlpha = 0.35 + 0.4*t;+ ctx.lineWidth = 1.6 + t*1.4;+ ctx.beginPath();+ ctx.moveTo(x, y);+ ctx.lineTo(x+len, y);+ ctx.stroke();+ }+ ctx.restore();++ // sun glint path on the water: yellow dashes below the sun+ ctx.save();+ ctx.strokeStyle = YELLOW;+ ctx.lineCap = 'round';+ const rg = mulberry32(77);+ for(let i=0;i<12;i++){+ const t = i/12;+ const y = horizon + 18 + t*180;+ const wob = (rg()-0.5)*40*(0.3+t);+ const len = 14 + t*46 + rg()*18;+ ctx.globalAlpha = 0.9 - t*0.35;+ ctx.lineWidth = 3.4;+ ctx.beginPath();+ ctx.moveTo(950 + wob - len/2, y);+ ctx.lineTo(950 + wob + len/2, y);+ ctx.stroke();+ }+ ctx.restore();++ // the boat: lower-left third, heading right, slight confident tilt+ const bx = 330, by = 560;+ boat(bx, by, 1.15, -0.05, BLACK, 3.4);+ // wake: two trailing curves behind (to the left)+ ctx.save();+ ctx.strokeStyle = BLACK;+ ctx.lineCap = 'round';+ ctx.lineWidth = 2.2;+ ctx.globalAlpha = 0.7;+ ctx.beginPath();+ ctx.moveTo(bx-84, by+42);+ ctx.quadraticCurveTo(bx-150, by+52, bx-215, by+46);+ ctx.stroke();+ ctx.globalAlpha = 0.45;+ ctx.beginPath();+ ctx.moveTo(bx-90, by+56);+ ctx.quadraticCurveTo(bx-140, by+66, bx-180, by+62);+ ctx.stroke();+ ctx.restore();+ // waterline under the boat+ ctx.save();+ ctx.strokeStyle = BLACK;+ ctx.lineWidth = 2.6;+ ctx.lineCap = 'round';+ ctx.beginPath();+ ctx.moveTo(bx-58, by+41);+ ctx.quadraticCurveTo(bx, by+48, bx+62, by+41);+ ctx.stroke();+ ctx.restore();++ // type+ statement('IT SET OUT', 'AT FIRST LIGHT.', 72, 168, 'paper');+ narration('No one watched it leave. That was the point.', 74, 316, 'rgba(11,10,8,0.78)');++ // mono meta+ monoLabel('THE PAPER BOAT', 68, 58, BLACK);+ monoLabel('LOG · DAY 01', W-68, 58, BLACK, 'right');+ monoLabel('06:12 · CALM · HEADING E', 68, H-40, BLACK);+ monoLabel('OBSERVED 01/02', W-68, H-40, BLACK, 'right');++ frameAndBrackets(BLACK);+}++// ---------- FRAME B : the storm peak ----------++function drawB(){+ const r = mulberry32(4041);+ ctx.clearRect(0,0,W,H);+ ctx.fillStyle = BLACK;+ ctx.fillRect(0,0,W,H);+ grain(13, PAPER, 0.045, 2200);++ // one light source fighting through: a narrow shaft of yellow hatch lines+ // from the top, converging toward the boat, ends jittered so it dissolves.+ ctx.save();+ ctx.strokeStyle = YELLOW;+ ctx.lineCap = 'round';+ const rl = mulberry32(31);+ const topX0 = 250, topX1 = 400, botX0 = 366, botX1 = 436, botY = 505;+ for(let i=0;i<9;i++){+ const t = i/8;+ const x0 = topX0 + t*(topX1-topX0);+ const x1 = botX0 + t*(botX1-botX0);+ const endT = 0.72 + rl()*0.26;+ ctx.globalAlpha = 0.28 + rl()*0.18;+ ctx.lineWidth = 1.8;+ ctx.beginPath();+ ctx.moveTo(x0, 27);+ ctx.lineTo(x0 + (x1-x0)*endT, 27 + (botY-27)*endT);+ ctx.stroke();+ }+ ctx.restore();++ // storm sky: angry short strokes upper right+ ctx.save();+ ctx.strokeStyle = PAPER;+ ctx.lineCap = 'round';+ for(let i=0;i<36;i++){+ const x = 620 + r()*380;+ const y = 44 + r()*116;+ const len = 26 + r()*70;+ ctx.globalAlpha = 0.16 + r()*0.2;+ ctx.lineWidth = 1.6;+ ctx.beginPath();+ ctx.moveTo(x, y);+ ctx.lineTo(x - len, y + len*0.18);+ ctx.stroke();+ }+ ctx.restore();++ // THE WAVE: one big diagonal mass from upper right, crest undulating down+ // to a curl that hangs OVER the boat.+ function bez(p0,p1,p2,p3,t){+ const u=1-t;+ return [u*u*u*p0[0]+3*u*u*t*p1[0]+3*u*t*t*p2[0]+t*t*t*p3[0],+ u*u*u*p0[1]+3*u*u*t*p1[1]+3*u*t*t*p2[1]+t*t*t*p3[1]];+ }+ // spine: bezier from off-screen upper right down-left, then a spiral curl.+ function spinePts(phase, wob){+ const pts = [];+ const P0=[1330,110], P1=[1050,150], P2=[800,270], P3=[604,388];+ for(let i=0;i<=48;i++){+ const t=i/48;+ const [x,y]=bez(P0,P1,P2,P3,t);+ // normal-ish undulation (mostly vertical)+ pts.push([x + Math.sin(t*16+phase)*wob*0.4, y + Math.sin(t*13+phase)*wob]);+ }+ return pts;+ }+ function curlPts(cx, cy, r0, r1, a0, a1, n){+ const pts=[];+ for(let i=0;i<=n;i++){+ const t=i/n, a=a0+(a1-a0)*t, rr=r0+(r1-r0)*t;+ pts.push([cx+Math.cos(a)*rr, cy+Math.sin(a)*rr]);+ }+ return pts;+ }+ function strokePts(pts){+ ctx.beginPath();+ ctx.moveTo(pts[0][0], pts[0][1]);+ for(let i=1;i<pts.length;i++) ctx.lineTo(pts[i][0], pts[i][1]);+ ctx.stroke();+ }+ const spineMain = spinePts(0, 6); // crest, upper-right -> (604,388)+ const CC = [590, 470]; // curl center, over the boat+ // face of the wave: from crest break down to the wave's foot, lower-left+ const FACE = { p0:[604,388], c:[420,470], p1:[300,724] };+ function facePt(t){+ const u=1-t;+ return [u*u*FACE.p0[0]+2*u*t*FACE.c[0]+t*t*FACE.p1[0],+ u*u*FACE.p0[1]+2*u*t*FACE.c[1]+t*t*FACE.p1[1]];+ }+ function spineYat(x){+ let best = spineMain[0];+ for(const p of spineMain) if(Math.abs(p[0]-x) < Math.abs(best[0]-x)) best = p;+ return best[1];+ }+ function faceXat(y){+ let best = facePt(0);+ for(let i=0;i<=30;i++){ const p=facePt(i/30); if(Math.abs(p[1]-y)<Math.abs(best[1]-y)) best=p; }+ return best[0];+ }+ function bodyPath(){+ ctx.beginPath();+ ctx.moveTo(spineMain[0][0], spineMain[0][1]);+ for(let i=1;i<spineMain.length;i++) ctx.lineTo(spineMain[i][0], spineMain[i][1]);+ ctx.quadraticCurveTo(FACE.c[0], FACE.c[1], FACE.p1[0], FACE.p1[1]);+ ctx.lineTo(W+20, 724);+ ctx.lineTo(W+20, spineMain[0][1]);+ ctx.closePath();+ }++ ctx.save();+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';++ // wave mass: halftone dots, dense at the crest, thinning into the body+ ctx.save();+ bodyPath();+ ctx.clip();+ ctx.fillStyle = PAPER;+ for(let gy=60; gy<724; gy+=13){+ const rowOff = (Math.floor(gy/13)%2) ? 6.5 : 0;+ for(let gx=280+rowOff; gx<W+10; gx+=13){+ const d1 = gx >= 604 ? gy - spineYat(gx) : 1e9;+ const d2 = gy >= 388 ? (gx - faceXat(gy))*1.15 : 1e9;+ const d = Math.min(d1, d2);+ if(d < 0) continue;+ const s = Math.max(0.6, 2.9 - d*0.0052);+ ctx.globalAlpha = Math.max(0.18, 0.85 - d*0.0012);+ ctx.beginPath();+ ctx.arc(gx, gy, s, 0, Math.PI*2);+ ctx.fill();+ }+ }+ ctx.restore();++ // face line the boat climbs+ ctx.strokeStyle = PAPER;+ ctx.lineWidth = 3;+ ctx.globalAlpha = 0.95;+ ctx.beginPath();+ ctx.moveTo(FACE.p0[0], FACE.p0[1]);+ ctx.quadraticCurveTo(FACE.c[0], FACE.c[1], FACE.p1[0], FACE.p1[1]);+ ctx.stroke();++ // the crest: yellow, the one light catching the breaking edge+ ctx.strokeStyle = YELLOW;+ ctx.lineWidth = 5;+ ctx.globalAlpha = 1;+ strokePts(spineMain);++ // the curl: hollow the barrel, then the spiral hanging over the boat+ ctx.fillStyle = BLACK;+ ctx.beginPath();+ ctx.arc(CC[0]-16, CC[1]+2, 42, 0, Math.PI*2);+ ctx.fill();+ ctx.strokeStyle = PAPER;+ ctx.lineWidth = 3;+ ctx.globalAlpha = 0.9;+ strokePts(curlPts(CC[0], CC[1], 70, 34, -1.40, -4.4, 30));+ ctx.strokeStyle = YELLOW;+ ctx.lineWidth = 5;+ ctx.globalAlpha = 1;+ strokePts(curlPts(CC[0], CC[1], 84, 24, -1.40, -5.2, 40));++ // foam claws hooked under the crest and the curl, clawing down-left+ ctx.strokeStyle = PAPER;+ const rc = mulberry32(99);+ for(const ti of [0.18, 0.32, 0.46, 0.60, 0.74, 0.88]){+ const p = spineMain[Math.floor(ti*48)];+ const s = 18 + rc()*12;+ ctx.lineWidth = 2.8;+ ctx.globalAlpha = 0.95;+ ctx.beginPath();+ ctx.moveTo(p[0]+6, p[1]+3);+ ctx.quadraticCurveTo(p[0]-s*0.9, p[1]+s*0.2, p[0]-s*1.2, p[1]+s*1.1);+ ctx.quadraticCurveTo(p[0]-s*1.05, p[1]+s*1.25, p[0]-s*0.85, p[1]+s*1.0);+ ctx.stroke();+ }+ for(const a of [-1.8, -2.5, -3.2]){+ const p = [CC[0]+Math.cos(a)*88, CC[1]+Math.sin(a)*88];+ const s = 14 + rc()*9;+ ctx.lineWidth = 2.6;+ ctx.globalAlpha = 0.95;+ ctx.beginPath();+ ctx.moveTo(p[0]+4, p[1]+4);+ ctx.quadraticCurveTo(p[0]-s, p[1]-s*0.1, p[0]-s*1.15, p[1]+s*0.95);+ ctx.stroke();+ }++ // spray blown off the crest and the curl+ ctx.fillStyle = PAPER;+ for(let i=0;i<90;i++){+ const t = rc();+ const p = spineMain[Math.floor(t*48)];+ ctx.globalAlpha = 0.25 + rc()*0.5;+ const s2 = 1 + rc()*2.2;+ ctx.fillRect(p[0] - rc()*80, p[1] - 8 - rc()*60, s2, s2);+ }+ for(let i=0;i<36;i++){+ ctx.globalAlpha = 0.3 + rc()*0.5;+ const a = -1.2 - rc()*3.6;+ const rr = 96 + rc()*44;+ ctx.fillRect(CC[0]+Math.cos(a)*rr, CC[1]+Math.sin(a)*rr, 1.6, 1.6);+ }+ ctx.restore();++ // rough sea below-left of the boat+ ctx.save();+ ctx.strokeStyle = PAPER;+ ctx.lineCap = 'round';+ const rs = mulberry32(55);+ for(let i=0;i<26;i++){+ const x = 60 + rs()*420;+ const y = 560 + rs()*120;+ const len = 26 + rs()*80;+ ctx.globalAlpha = 0.25 + rs()*0.35;+ ctx.lineWidth = 2;+ ctx.beginPath();+ ctx.moveTo(x, y);+ ctx.quadraticCurveTo(x+len/2, y - 8 - rs()*10, x+len, y);+ ctx.stroke();+ }+ ctx.restore();++ // the boat: small, climbing the wave face under the curl, bow up,+ // still pointing forward. clear a soft halo first so it pops.+ const bx = 396, by = 540;+ ctx.save();+ const halo = ctx.createRadialGradient(bx, by, 12, bx, by, 95);+ halo.addColorStop(0, 'rgba(11,10,8,0.9)');+ halo.addColorStop(1, 'rgba(11,10,8,0)');+ ctx.fillStyle = halo;+ ctx.fillRect(bx-100, by-100, 200, 200);+ ctx.restore();+ boat(bx, by, 0.66, -0.42, PAPER, 3.4);+ // yellow catch-light on the sail edge facing the shaft+ ctx.save();+ ctx.translate(bx, by);+ ctx.rotate(-0.42);+ ctx.scale(0.66, 0.66);+ ctx.strokeStyle = YELLOW;+ ctx.lineWidth = 3.6/0.66;+ ctx.lineCap = 'round';+ ctx.beginPath();+ ctx.moveTo(-27, -1);+ ctx.lineTo(0, -56);+ ctx.stroke();+ ctx.restore();+ // water line the boat sits on+ ctx.save();+ ctx.strokeStyle = PAPER;+ ctx.lineWidth = 2.6;+ ctx.lineCap = 'round';+ ctx.translate(bx, by);+ ctx.rotate(-0.42);+ ctx.beginPath();+ ctx.moveTo(-46, 26);+ ctx.quadraticCurveTo(0, 33, 50, 26);+ ctx.stroke();+ ctx.restore();++ // type+ statement('THE SEA HAD', 'OTHER PLANS.', 72, 168, 'black');+ narration('It kept the heading anyway.', 74, 316, 'rgba(243,238,226,0.85)');++ // mono meta + red alert rule (black chip under the alert so nothing crosses it)+ ctx.fillStyle = BLACK;+ ctx.fillRect(56, H-60, 340, 32);+ monoLabel('THE PAPER BOAT', 68, 58, PAPER);+ monoLabel('LOG · DAY 01', W-68, 58, PAPER, 'right');+ ctx.save();+ ctx.fillStyle = RED;+ ctx.fillRect(68, H-54, 3, 18);+ ctx.restore();+ monoLabel('SWELL 4.6 M · HEADING HELD', 82, H-40, PAPER);+ monoLabel('OBSERVED 02/02', W-68, H-40, PAPER, 'right');++ frameAndBrackets(PAPER);+}++window.drawFrame = function(which){+ if(which === 'a') drawA(); else drawB();+ window.DONE = true;+};+window.READY = true;+</script>+</body>+</html>diff --git a/assets/previews-src/mono/boat.html b/assets/previews-src/mono/boat.htmlnew file mode 100644index 0000000..c9364ee--- /dev/null+++ b/assets/previews-src/mono/boat.html@@ -0,0 +1,362 @@+<!doctype html>+<meta charset="utf-8">+<style>html,body{margin:0;padding:0;background:#000}canvas{display:block}</style>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');+const W = 1280, H = 720;++// ---------- deterministic rng ----------+function mulberry32(seed){+ let a = seed >>> 0;+ return function(){+ a |= 0; a = (a + 0x6D2B79F5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const SANS = "'Helvetica Neue', Helvetica, Arial, sans-serif";+const MONO = "'SF Mono', Menlo, 'Courier New', monospace";++// ---------- the paper boat silhouette ----------+// waterline is local y=0. hull dips below, peaks rise above.+function boatPath(s){+ const p = new Path2D();+ // hull (trapezoid)+ p.moveTo(-0.54*s, 0);+ p.lineTo( 0.54*s, 0);+ p.lineTo( 0.30*s, 0.30*s);+ p.lineTo(-0.30*s, 0.30*s);+ p.closePath();+ // central sail peak+ p.moveTo(-0.34*s, 0.01*s);+ p.lineTo( 0.03*s, -0.64*s);+ p.lineTo( 0.34*s, 0.01*s);+ p.closePath();+ // bow + stern flaps+ p.moveTo(-0.54*s, 0.01*s);+ p.lineTo(-0.41*s, -0.155*s);+ p.lineTo(-0.30*s, 0.01*s);+ p.closePath();+ p.moveTo( 0.30*s, 0.01*s);+ p.lineTo( 0.41*s, -0.155*s);+ p.lineTo( 0.54*s, 0.01*s);+ p.closePath();+ return p;+}+function drawBoat(x, y, s, rot, fill, seamColor, outline){+ ctx.save();+ ctx.translate(x, y); ctx.rotate(rot);+ const p = boatPath(s);+ if (outline){ ctx.lineWidth = outline.w; ctx.strokeStyle = outline.c; ctx.lineJoin='round'; ctx.stroke(p); }+ ctx.fillStyle = fill; ctx.fill(p);+ // paper fold seam inside the sail+ if (seamColor){+ ctx.strokeStyle = seamColor; ctx.lineWidth = Math.max(1, s*0.016);+ ctx.beginPath(); ctx.moveTo(0.03*s, -0.60*s); ctx.lineTo(0.0*s, -0.02*s); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(-0.50*s, 0.0); ctx.lineTo(0.50*s, 0.0); ctx.stroke();+ }+ ctx.restore();+}++// ---------- shared type helpers ----------+function bigWord(word, x, y, color, size){+ ctx.save();+ ctx.font = '600 ' + size + 'px ' + SANS;+ try{ ctx.letterSpacing = (-size*0.03) + 'px'; }catch(e){}+ ctx.fillStyle = color;+ ctx.textBaseline = 'alphabetic';+ ctx.fillText(word, x, y);+ ctx.restore();+}+function mono(txt, x, y, color, size, spacing){+ ctx.save();+ ctx.font = '400 ' + size + 'px ' + MONO;+ try{ ctx.letterSpacing = (spacing==null?1:spacing) + 'px'; }catch(e){}+ ctx.fillStyle = color;+ ctx.fillText(txt, x, y);+ ctx.restore();+}+function dotGrid(x, y, cols, rows, gap, r, color, alpha){+ ctx.save(); ctx.fillStyle = color; ctx.globalAlpha = alpha;+ for (let i=0;i<cols;i++) for (let j=0;j<rows;j++){+ ctx.beginPath(); ctx.arc(x+i*gap, y+j*gap, r, 0, 7); ctx.fill();+ }+ ctx.restore();+}++// =====================================================================+// FRAME A — the white world. quant-terminal morning.+// =====================================================================+function frameA(){+ const R = mulberry32(20260929);+ ctx.fillStyle = '#fff'; ctx.fillRect(0,0,W,H);++ const HORIZON = 440;+ const BX = 358, BY = 556, BS = 118;++ // --- the sea: a stack of thin chart series ---+ let y = HORIZON + 8, gap = 5.0;+ const seaLines = [];+ while (y < H + 14){+ seaLines.push(y);+ y += gap; gap *= 1.062;+ }+ ctx.lineWidth = 1;+ seaLines.forEach((base, idx) => {+ const depth = idx / seaLines.length; // 0 near horizon, 1 near bottom+ const amp = 1.2 + depth*7.5;+ const alpha = 0.10 + depth*0.13;+ ctx.strokeStyle = 'rgba(0,0,0,' + alpha.toFixed(3) + ')';+ ctx.beginPath();+ const ph1 = R()*6.28, ph2 = R()*6.28, drift = (R()-0.5)*0.002;+ for (let x=0; x<=W; x+=8){+ let yy = base + amp*Math.sin(x*0.011 + ph1) + amp*0.5*Math.sin(x*0.031 + ph2) + x*drift;+ // small jagged quant steps on some series+ if (idx % 3 === 0) yy += (Math.floor(x/48)%2 ? 1 : -1) * amp*0.22;+ if (x===0) ctx.moveTo(x,yy); else ctx.lineTo(x,yy);+ }+ ctx.stroke();+ });++ // --- horizon rule ---+ ctx.strokeStyle = 'rgba(0,0,0,0.4)'; ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(0,HORIZON); ctx.lineTo(W,HORIZON); ctx.stroke();+ // sun on the horizon: a small open circle rising (morning), pure line+ ctx.strokeStyle = 'rgba(0,0,0,0.55)'; ctx.lineWidth = 1.5;+ ctx.beginPath(); ctx.arc(930, HORIZON, 26, Math.PI, 0); ctx.stroke();+ mono('first light 05:51', 968, HORIZON - 10, '#999', 10);++ // --- hero series: the boat's course, bold black ---+ const hero = [];+ // behind the boat: choppy walk from off-left up to the boat waterline+ let hx = -20, hy = 596;+ while (hx < BX - 30){+ hero.push([hx, hy]);+ hx += 22 + R()*10;+ const pull = (BY + 4 - hy) * 0.16;+ hy += pull + (R()-0.5)*26;+ }+ hero.push([BX - 28, BY + 3]);+ hero.push([BX + 30, BY + 3]); // flat under the hull+ // ahead of the boat: rising, jagged, confident+ hx = BX + 30; hy = BY + 3;+ while (hx < W + 20){+ hx += 20 + R()*14;+ const trend = -0.062 * (hx - BX);+ hy = BY + trend + (R()-0.5)*20;+ if (R() < 0.1) hy -= 16; // occasional pop+ hero.push([hx, Math.max(hy, HORIZON + 26)]);+ }+ ctx.strokeStyle = '#000'; ctx.lineWidth = 3; ctx.lineJoin = 'miter';+ ctx.beginPath();+ hero.forEach((p,i)=>{ if(i===0) ctx.moveTo(p[0],p[1]); else ctx.lineTo(p[0],p[1]); });+ ctx.stroke();++ // --- dashed crosshair locked on the boat ---+ ctx.save();+ ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.lineWidth = 1; ctx.setLineDash([5,5]);+ ctx.beginPath(); ctx.moveTo(0, BY); ctx.lineTo(W, BY); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(BX, 96); ctx.lineTo(BX, H); ctx.stroke();+ ctx.restore();++ // --- the boat: the one dark shape ---+ drawBoat(BX, BY, BS, -0.055, '#000', 'rgba(255,255,255,0.55)');+ // waterline cut: white slivers across the hull so it sits IN the water+ ctx.save();+ ctx.strokeStyle = '#fff'; ctx.lineWidth = 2.2;+ ctx.beginPath();+ for (let x = BX-70; x <= BX+70; x += 6){+ const yy = BY + 12 + 2.6*Math.sin(x*0.09 + 1.3);+ if (x === BX-70) ctx.moveTo(x,yy); else ctx.lineTo(x,yy);+ }+ ctx.stroke();+ ctx.restore();++ // --- live number callout at the crosshair ---+ const cbx = BX + 26, cby = BY - 180;+ ctx.strokeStyle = 'rgba(0,0,0,0.9)'; ctx.lineWidth = 1;+ ctx.strokeRect(cbx, cby, 176, 52);+ ctx.fillStyle = '#fff'; ctx.fillRect(cbx+1, cby+1, 174, 50);+ mono('$2,071.79', cbx + 14, cby + 24, '#000', 17, 0.5);+ mono('day 001 · heading east', cbx + 14, cby + 41, '#999', 10);+ // tick marker where the crosshair meets the course+ ctx.fillStyle = '#000';+ ctx.beginPath(); ctx.arc(BX, BY, 3.2, 0, 7); ctx.fill();+ ctx.strokeStyle = '#000'; ctx.lineWidth = 1;+ ctx.strokeRect(BX-7, BY-7, 14, 14);++ // --- big split line: "setting ... out" ---+ bigWord('setting', 76, 208, '#000', 118);+ bigWord('out', 858, 348, '#999', 118);++ // --- editorial furniture ---+ mono('the paper boat — a launch film', 78, 62, '#999', 11);+ mono('fig. 01 / departure', 78, 80, '#999', 10);+ ctx.strokeStyle = 'rgba(0,0,0,0.8)'; ctx.lineWidth = 1;+ ctx.beginPath(); ctx.moveTo(78, 94); ctx.lineTo(292, 94); ctx.stroke();+ dotGrid(1082, 56, 10, 5, 10, 1.4, '#000', 0.7);+ mono('calm regime', 1082, 122, '#999', 10);++ // bottom time axis+ for (let i=0;i<8;i++){+ const x = 78 + i*158;+ const mns = 51 + i*12;+ const t = '0' + (5 + Math.floor(mns/60)) + ':' + String(mns%60).padStart(2,'0');+ mono(t, x, 708, '#999', 10);+ ctx.strokeStyle = 'rgba(0,0,0,0.35)';+ ctx.beginPath(); ctx.moveTo(x, 694); ctx.lineTo(x, 699); ctx.stroke();+ }+ // right price ladder+ for (let i=0;i<5;i++){+ const yy = 470 + i*52;+ mono((2074 - i*8).toFixed(1), 1206, yy, '#999', 10);+ }+}++// =====================================================================+// FRAME B — the black world. liquid chrome storm.+// =====================================================================+// wave surface: big diagonal from upper right down to lower left+function surfY(x){+ return 620 - 0.40*x + 46*Math.sin(x*0.0042 + 1.1) + 18*Math.sin(x*0.011 + 3.0)+ + 8*Math.sin(x*0.031 + 0.7) + 4*Math.sin(x*0.067 + 2.2);+}+function frameB(){+ const R = mulberry32(777317);+ ctx.fillStyle = '#000'; ctx.fillRect(0,0,W,H);++ const BXB = 396;+ const BYB = surfY(BXB) - 2;++ const img = ctx.getImageData(0,0,W,H);+ const d = img.data;++ // flow direction of the wave (diagonal, down toward lower-left)+ const th = -0.40, cs = Math.cos(th), sn = Math.sin(th);++ // precompute surface per column+ const S = new Float32Array(W);+ for (let x=0;x<W;x++) S[x] = surfY(x);++ for (let yy=0; yy<H; yy++){+ for (let xx=0; xx<W; xx++){+ const sy = S[xx];+ const depth = yy - sy; // >0 inside the wave+ if (depth < 0) continue; // sky stays pure black; light is halftone, drawn after+ const i = (yy*W + xx)*4;+ // ---- LIQUID CHROME: long molten streaks running down the face ----+ const u = xx*cs - yy*sn; // along the flow+ const w = xx*sn + yy*cs; // across the flow+ const phase =+ w*0.050 ++ 2.1*Math.sin(u*0.0085 + w*0.0032 + 0.6) ++ 1.0*Math.sin(u*0.026 + 1.7) ++ 0.45*Math.sin(w*0.115 + u*0.004);+ const band = Math.sin(phase);+ const spec = Math.pow(Math.max(band, 0), 11);+ const base = 0.035 + 0.085*(0.5 + 0.5*Math.sin(phase*0.7 + 1.0));+ const fade = Math.min(1, Math.max(0.05, 1 - depth/430));+ let lum = base*fade + spec*(0.18 + 0.82*fade)*0.95;+ // bright molten rim at the crest edge+ if (depth < 3.5) lum = 1;+ else if (depth < 15) lum = Math.max(lum, 1 - (depth-3.5)/11.5 * 0.85);+ // calm dark pocket around the boat so the white shape owns its zone+ const pdx = xx-BXB, pdy = yy-BYB;+ const pocket = 1 - 0.88*Math.exp(-(pdx*pdx + pdy*pdy)/(2*105*105));+ lum *= (depth > 14) ? pocket : Math.max(pocket, 0.30);+ const v = Math.max(0, Math.min(255, lum*255));+ d[i] = d[i+1] = d[i+2] = v; d[i+3] = 255;+ }+ }+ ctx.putImageData(img, 0, 0);++ // ---- SKY: one light fighting through, as a coarse halftone dot field ----+ const LX = 500, LY = 130, LR = 170;+ const CELL = 7;+ // keep the captions readable: no dots in these zones+ const keep = [[64,24,340,80],[84,296,330,352]];+ ctx.fillStyle = '#fff';+ for (let gy = Math.floor(CELL/2); gy < H; gy += CELL){+ for (let gx = Math.floor(CELL/2) + ((Math.floor(gy/CELL)%2)?3:0); gx < W; gx += CELL){+ const sy = S[Math.min(W-1, gx)];+ if (gy > sy - 6) continue; // sky only+ if (keep.some(k => gx>k[0] && gx<k[2] && gy>k[1] && gy<k[3])) continue;+ const dx = gx-LX, dy = gy-LY;+ let g = 0.95*Math.exp(-(dx*dx + dy*dy)/(2*LR*LR));+ const rimD = sy - gy; // near the crest, light leaks+ if (rimD < 34) g += 0.24*(1 - rimD/34)*Math.exp(-Math.abs(gx-620)/420);+ g = Math.min(g, 0.9);+ const r = g*2.7;+ if (r < 0.42) continue;+ ctx.beginPath(); ctx.arc(gx, gy, r, 0, 7); ctx.fill();+ }+ }++ // ---- dot-grid rain slanting through the sky ----+ ctx.save();+ for (let k=0;k<110;k++){+ const x0 = R()*W, y0 = R()*H*0.8;+ const n = 4 + Math.floor(R()*8);+ const a0 = 0.2 + R()*0.55;+ for (let j=0;j<n;j++){+ const x = x0 - j*2.8, y = y0 + j*10;+ const xi = Math.max(0, Math.min(W-1, Math.floor(x)));+ if (y > S[xi] - 8) break; // stay in the sky+ ctx.globalAlpha = a0 * (1 - j/n);+ ctx.fillStyle = '#fff';+ ctx.beginPath(); ctx.arc(x, y, 1.3, 0, 7); ctx.fill();+ }+ }+ ctx.restore();++ // ---- spray torn off the crest, upper right ----+ ctx.save();+ ctx.fillStyle = '#fff';+ for (let k=0;k<260;k++){+ const x = 560 + R()*700;+ const xi = Math.max(0, Math.min(W-1, Math.floor(x)));+ const lift = Math.pow(R(), 2.2) * 60;+ const y = S[xi] - 4 - lift;+ if (y < 0) continue;+ ctx.globalAlpha = 0.25 + R()*0.6*(1 - lift/60);+ ctx.beginPath(); ctx.arc(x - lift*0.5, y, 0.9 + R()*1.2, 0, 7); ctx.fill();+ }+ ctx.restore();++ // --- the boat: the one white shape, small, climbing the wave ---+ const bx = BXB;+ const by = BYB + 8; // hull in the water, not perched+ const slope = (surfY(bx+24)-surfY(bx-24))/48;+ const rot = Math.atan(slope) - 0.17; // bow up, still pointing forward+ drawBoat(bx, by, 106, rot, '#fff', 'rgba(0,0,0,0.5)', {w:6, c:'#000'});++ // --- callout: dashed leader + live number ---+ ctx.save();+ ctx.strokeStyle = 'rgba(255,255,255,0.75)'; ctx.lineWidth = 1; ctx.setLineDash([4,5]);+ ctx.beginPath(); ctx.moveTo(bx - 40, by - 52); ctx.lineTo(224, 330); ctx.stroke();+ ctx.restore();+ mono('$1,283.07', 100, 322, '#fff', 17, 0.5);+ mono('day 014 · drawdown −38.2%', 100, 342, '#999', 10);++ // --- big split line: "still ... forward" ---+ bigWord('still', 76, 168, '#fff', 112);+ bigWord('forward', 806, 660, '#999', 112);++ // --- editorial furniture ---+ mono('the paper boat — a launch film', 78, 48, '#999', 11);+ mono('fig. 02 / the storm', 78, 66, '#999', 10);+ dotGrid(1120, 46, 8, 4, 10, 1.4, '#fff', 0.8);+ mono('volatility regime', 1120, 102, '#999', 10);+}++window.drawFrame = function(which){+ if (which === 'a') frameA(); else frameB();+ window.DONE = true;+};+window.READY = true;+</script>diff --git a/assets/previews-src/package.json b/assets/previews-src/package.jsonnew file mode 100644index 0000000..089153b--- /dev/null+++ b/assets/previews-src/package.json@@ -0,0 +1 @@+{"type":"module"}diff --git a/assets/previews-src/papercut/boat.html b/assets/previews-src/papercut/boat.htmlnew file mode 100644index 0000000..fa4540f--- /dev/null+++ b/assets/previews-src/papercut/boat.html@@ -0,0 +1,245 @@+<!doctype html>+<html><head><meta charset="utf-8"><style>html,body{margin:0;background:#111}canvas{display:block}</style></head>+<body><canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W=1280,H=720,ctx=document.getElementById('c').getContext('2d');++/* ---------- deterministic helpers ---------- */+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+function makeNoise(seed,n){const r=mulberry32(seed),v=[];for(let i=0;i<n;i++)v.push(r());return function(t){t=((t%n)+n)%n;const i=Math.floor(t),f=t-i,u=f*f*(3-2*f);return v[i]*(1-u)+v[(i+1)%n]*u}}++/* resample closed polygon at ~step px, return pts + outward normals */+function resample(pts,step){+ const out=[];let per=0;const n=pts.length;+ for(let i=0;i<n;i++){const a=pts[i],b=pts[(i+1)%n];per+=Math.hypot(b[0]-a[0],b[1]-a[1]);}+ const cnt=Math.max(24,Math.round(per/step));const seg=per/cnt;+ let d=0,i=0,a=pts[0],b=pts[1%n],rem=Math.hypot(b[0]-a[0],b[1]-a[1]);+ for(let k=0;k<cnt;k++){+ const target=k*seg;+ while(d+rem<target){d+=rem;i++;a=pts[i%n];b=pts[(i+1)%n];rem=Math.hypot(b[0]-a[0],b[1]-a[1]);}+ const f=rem>0?(target-d)/rem:0;+ out.push([a[0]+(b[0]-a[0])*f,a[1]+(b[1]-a[1])*f]);+ }+ let ar=0;for(let k=0;k<out.length;k++){const p=out[k],q=out[(k+1)%out.length];ar+=p[0]*q[1]-q[0]*p[1];}+ const s=ar>0?-1:1;+ const nor=[];+ for(let k=0;k<out.length;k++){+ const p=out[(k-1+out.length)%out.length],q=out[(k+1)%out.length];+ let dx=q[0]-p[0],dy=q[1]-p[1];const L=Math.hypot(dx,dy)||1;+ nor.push([s*dy/L,-s*dx/L]);+ }+ return{pts:out,nor};+}++/* roughen: displace along outward normals with seeded noise.+ cut: tight wobble. torn: long ragged excursions (low freq) + small chatter. */+function rough(base,opt){+ const{amp=2,step=5,seed=1,freq=0.22,bias=0,oct=0}=opt||{};+ const{pts,nor}=resample(base,step);+ const n1=makeNoise(seed,512),n2=makeNoise(seed+77,512);+ const out=[];+ for(let k=0;k<pts.length;k++){+ let d=(n1(k*freq)-.5)*2*amp+bias;+ if(oct)d+=(n2(k*0.9)-.5)*amp*.55;+ out.push([pts[k][0]+nor[k][0]*d,pts[k][1]+nor[k][1]*d]);+ }+ return out;+}+function path(pts){const p=new Path2D();p.moveTo(pts[0][0],pts[0][1]);for(let i=1;i<pts.length;i++)p.lineTo(pts[i][0],pts[i][1]);p.closePath();return p}++/* ---------- paper texture tiles ---------- */+function grainTile(seed){+ const s=160,cv=document.createElement('canvas');cv.width=cv.height=s;+ const g=cv.getContext('2d'),im=g.createImageData(s,s),r=mulberry32(seed);+ for(let i=0;i<s*s;i++){const v=r()*255|0;im.data[i*4]=v;im.data[i*4+1]=v;im.data[i*4+2]=v;im.data[i*4+3]=255;}+ g.putImageData(im,0,0);return cv;+}+function blotchTile(seed){+ const s=16,cv=document.createElement('canvas');cv.width=cv.height=s;+ const g=cv.getContext('2d'),im=g.createImageData(s,s),r=mulberry32(seed);+ for(let i=0;i<s*s;i++){const v=110+r()*90|0;im.data[i*4]=v;im.data[i*4+1]=v;im.data[i*4+2]=v;im.data[i*4+3]=255;}+ g.putImageData(im,0,0);+ const big=document.createElement('canvas');big.width=big.height=512;+ const gb=big.getContext('2d');gb.imageSmoothingEnabled=true;gb.drawImage(cv,0,0,512,512);return big;+}+const GRAIN=grainTile(11),BLOTCH=blotchTile(23),BLOTCH2=blotchTile(57);++/* ---------- piece renderer ---------- */+let LIGHT=[-1,1]; // global light -> shadow offset dir for free-floating pieces+function drawPiece(o){+ const seed=o.seed||1,depth=o.depth==null?1:o.depth;+ const eo=o.edge==='torn'+ ?{amp:o.amp||9,step:5,seed,freq:o.freq||.09,oct:1}+ :{amp:o.amp||1.6,step:6,seed,freq:.22};+ const main=rough(o.base,eo);+ const mp=path(main);+ let silhouette=mp,fp=null;+ if(o.edge==='torn'&&o.fringe!==false){+ const fr=rough(o.base,{amp:(o.amp||9)*1.1,step:5,seed:seed+31,freq:(o.freq||.09)*1.4,bias:3,oct:1});+ fp=path(fr);silhouette=fp;+ }+ if(!o.noShadow){+ const dir=o.sh||LIGHT;+ const dist=(o.shDist!=null?o.shDist:5+depth*3.5),blur=4+depth*2.4;+ ctx.save();+ ctx.translate(dir[0]*dist,dir[1]*dist);+ ctx.filter='blur('+blur.toFixed(1)+'px)';+ ctx.fillStyle='rgba(40,30,22,'+(o.shadowA!=null?o.shadowA:0.34)+')';+ ctx.fill(silhouette);+ ctx.restore();+ }+ if(fp){ctx.fillStyle=o.fringeColor||'#F0EADB';ctx.fill(fp);}+ ctx.fillStyle=o.color;ctx.fill(mp);+ if(o.tex!==false){+ ctx.save();ctx.clip(fp||mp);+ const pat=ctx.createPattern(GRAIN,'repeat');+ ctx.globalCompositeOperation='multiply';ctx.globalAlpha=0.055;ctx.fillStyle=pat;ctx.fillRect(0,0,W,H);+ ctx.globalCompositeOperation='screen';ctx.globalAlpha=0.045;ctx.fillRect(0,0,W,H);+ const off=(seed*37)%300;+ ctx.globalCompositeOperation='multiply';ctx.globalAlpha=0.10;+ ctx.drawImage(seed%2?BLOTCH:BLOTCH2,-off,-((seed*61)%260),1600,1000);+ ctx.restore();+ }+ return main;+}++/* ---------- shape builders ---------- */+function circle(cx,cy,r,n){n=n||40;const p=[];for(let i=0;i<n;i++){const a=i/n*Math.PI*2;p.push([cx+Math.cos(a)*r,cy+Math.sin(a)*r]);}return p}+function seaStrip(yTop,amp,waves,phase,bottom){+ const p=[];const n=64;+ for(let i=0;i<=n;i++){const x=-40+(W+80)*i/n;+ p.push([x,yTop+Math.sin(i/n*Math.PI*2*waves+phase)*amp]);}+ p.push([W+40,bottom]);p.push([-40,bottom]);+ return p;+}+function rot(pts,cx,cy,ang){const c=Math.cos(ang),s=Math.sin(ang);return pts.map(p=>[cx+(p[0]-cx)*c-(p[1]-cy)*s,cy+(p[0]-cx)*s+(p[1]-cy)*c])}++/* paper boat: hull trapezoid + sail peak + red pennant */+function drawBoat(x,y,s,ang,seedBase,depth,sh){+ const T=p=>rot(p,x,y,ang);+ const hull=T([[x-1.05*s,y-0.34*s],[x+1.05*s,y-0.34*s],[x+0.62*s,y+0.16*s],[x-0.62*s,y+0.16*s]]);+ const band=T([[x-1.05*s,y-0.34*s],[x+1.05*s,y-0.34*s],[x+0.92*s,y-0.18*s],[x-0.92*s,y-0.18*s]]);+ const sail=T([[x,y-1.18*s],[x+0.52*s,y-0.30*s],[x-0.52*s,y-0.30*s]]);+ const flag=T([[x-0.02*s,y-1.16*s],[x+0.36*s,y-1.03*s],[x-0.02*s,y-0.90*s]]);+ drawPiece({base:sail,edge:'cut',color:'#F5EDDA',seed:seedBase+1,depth:depth,amp:1.2,sh:sh});+ drawPiece({base:hull,edge:'cut',color:'#F9F3E3',seed:seedBase+2,depth:depth,amp:1.3,sh:sh});+ drawPiece({base:band,edge:'cut',color:'#E4D8BC',seed:seedBase+3,depth:depth,amp:1.0,shadowA:.14,shDist:2,sh:sh});+ drawPiece({base:flag,edge:'cut',color:'#C8402F',seed:seedBase+4,depth:depth,amp:0.9,shDist:3,sh:sh});+}++/* ---------- FRAME A : setting out, dawn ---------- */+function frameA(){+ LIGHT=[-0.55,0.84]; // sun upper-right -> free pieces shadow down-left+ const BAND=[-0.45,-0.89]; // bands: shadow peeks above their top edge (onto the sheet behind)+ ctx.fillStyle='#F2E3C8';ctx.fillRect(0,0,W,H);+ ctx.save();const pat=ctx.createPattern(GRAIN,'repeat');+ ctx.globalCompositeOperation='multiply';ctx.globalAlpha=.05;ctx.fillStyle=pat;ctx.fillRect(0,0,W,H);+ ctx.globalCompositeOperation='multiply';ctx.globalAlpha=.08;ctx.drawImage(BLOTCH,0,-80,1500,900);ctx.restore();++ const HOR=396;+ // sky bands, top to bottom; each casts up onto the previous+ drawPiece({base:seaStrip(150,10,1.6,1.1,-40).reverse(),edge:'cut',color:'#B9A2BC',seed:101,depth:.8,amp:2,noShadow:true});+ drawPiece({base:seaStrip(258,12,1.9,2.6,140).reverse(),edge:'cut',color:'#E5A184',seed:102,depth:1.0,amp:2,sh:BAND,shDist:7,shadowA:.28});+ drawPiece({base:seaStrip(HOR+6,7,2.2,0.4,248).reverse(),edge:'cut',color:'#F0BE7F',seed:103,depth:1.0,amp:2,sh:BAND,shDist:7,shadowA:.28});++ // sun with radiating cut rays+ const sx=905,sy=286,sr=74;+ for(let i=0;i<14;i++){+ const a=i/14*Math.PI*2+0.12,len=(i%2?1.9:2.6)*sr,wd=0.22;+ const ray=[[sx+Math.cos(a)*sr*1.12,sy+Math.sin(a)*sr*1.12],+ [sx+Math.cos(a+wd)*len*0.62,sy+Math.sin(a+wd)*len*0.62],+ [sx+Math.cos(a)*len,sy+Math.sin(a)*len],+ [sx+Math.cos(a-wd)*len*0.62,sy+Math.sin(a-wd)*len*0.62]];+ drawPiece({base:ray,edge:'cut',color:i%2?'#F6CE79':'#F2B558',seed:200+i,depth:.8,amp:1.2,shadowA:.2});+ }+ drawPiece({base:circle(sx,sy,sr),edge:'cut',color:'#F2A340',seed:230,depth:1.2,amp:1.6});+ drawPiece({base:circle(sx-8,sy-8,sr*0.62),edge:'cut',color:'#F7BC5C',seed:231,depth:.4,amp:1.2,shadowA:.12,shDist:2});++ // small cut clouds+ const cl=(cx,cy,s,sd)=>{+ const b=[[cx-1.5*s,cy+0.32*s],[cx-1.32*s,cy-0.1*s],[cx-0.85*s,cy-0.34*s],[cx-0.35*s,cy-0.52*s],[cx+0.35*s,cy-0.44*s],[cx+0.95*s,cy-0.2*s],[cx+1.5*s,cy+0.05*s],[cx+1.42*s,cy+0.32*s]];+ drawPiece({base:b,edge:'cut',color:'#F7E9CF',seed:sd,depth:1.2,amp:1.8});+ };+ cl(250,150,62,301);cl(1105,120,48,302);cl(620,205,40,303);++ // sea bands, back to front; shadows peek above their wavy top edges+ const SEA=[-0.3,-0.95];+ drawPiece({base:seaStrip(HOR,4,3.2,0,H+40),edge:'cut',color:'#5FA898',seed:401,depth:1.0,amp:1.6,sh:SEA,shDist:7,shadowA:.30});+ // sun glint slivers on the far water+ for(let i=0;i<4;i++){+ const gy=HOR+14+i*13,gw=150-i*28,gx=sx+(i%2?14:-10);+ drawPiece({base:[[gx-gw/2,gy],[gx+gw/2,gy],[gx+gw/2-8,gy+7],[gx-gw/2+6,gy+7]],edge:'cut',color:'#F3C878',seed:420+i,depth:.3,amp:1.2,shadowA:.10,shDist:2});+ }+ drawPiece({base:seaStrip(452,7,2.6,1.3,H+40),edge:'cut',color:'#3E8E8B',seed:402,depth:1.2,amp:1.8,sh:SEA,shDist:8,shadowA:.32});+ drawPiece({base:seaStrip(508,9,2.2,3.9,H+40),edge:'cut',color:'#2F7076',seed:403,depth:1.4,amp:2,sh:SEA,shDist:9,shadowA:.32});++ // the boat, lower-left third heading right; keel dips behind next band+ drawBoat(360,540,95,0.05,500,1.7);+ // foam sliver crossing the waterline+ drawPiece({base:[[264,550],[456,544],[450,560],[272,564]],edge:'cut',color:'#EFE6CE',seed:406,depth:.5,amp:1.6,shadowA:.14,shDist:2});+ // front sea bands overlap the keel+ drawPiece({base:seaStrip(560,11,1.9,5.2,H+40),edge:'cut',color:'#26586B',seed:404,depth:1.6,amp:2.2,sh:SEA,shDist:9,shadowA:.34});+ drawPiece({base:seaStrip(646,13,1.5,2.2,H+40),edge:'cut',color:'#1E4258',seed:407,depth:1.9,amp:2.4,sh:SEA,shDist:10,shadowA:.36});+}++/* ---------- FRAME B : the storm peak ---------- */+function frameB(){+ LIGHT=[0.62,0.79]; // light breaks upper-left -> free pieces shadow down-right+ const RIM=[0.5,-0.87]; // wave sheets: shadow peeks above the torn crest+ ctx.fillStyle='#232A40';ctx.fillRect(0,0,W,H);+ ctx.save();const pat=ctx.createPattern(GRAIN,'repeat');+ ctx.globalCompositeOperation='screen';ctx.globalAlpha=.05;ctx.fillStyle=pat;ctx.fillRect(0,0,W,H);+ ctx.globalCompositeOperation='multiply';ctx.globalAlpha=.16;ctx.drawImage(BLOTCH2,-60,-40,1600,980);ctx.restore();++ // torn gap of dawn light, upper-left+ drawPiece({base:circle(255,140,148,48),edge:'torn',color:'#F4DFA8',seed:601,depth:.4,amp:16,freq:.06,fringeColor:'#F8EFD3',shadowA:.18});+ drawPiece({base:circle(258,146,84,40),edge:'torn',color:'#F9EDC6',seed:602,depth:.2,amp:9,freq:.08,fringe:false,shadowA:.1});++ // torn storm-cloud sheets crowding around the gap+ drawPiece({base:[[-40,-40],[560,-40],[470,40],[210,30],[80,120],[110,250],[330,300],[620,270],[-40,360]],edge:'torn',color:'#2A3352',seed:611,depth:1.2,amp:14,freq:.055,fringeColor:'#A9A4B6',shadowA:.38});+ drawPiece({base:[[340,-40],[1320,-40],[1320,230],[1010,190],[800,235],[600,160],[460,180],[430,70],[520,10]],edge:'torn',color:'#333D63',seed:612,depth:1.4,amp:15,freq:.05,fringeColor:'#B3AEC0',shadowA:.38});++ // light shaft from the gap down to the boat+ ctx.save();ctx.globalAlpha=.15;ctx.fillStyle='#F4DFA8';+ ctx.fill(path(rough([[205,120],[350,95],[560,560],[350,600]],{amp:3,step:8,seed:620,freq:.2})));+ ctx.globalAlpha=.07;+ ctx.fill(path(rough([[165,130],[410,86],[660,580],[300,640]],{amp:3,step:8,seed:621,freq:.2})));+ ctx.restore();++ // distant sea behind the wave+ drawPiece({base:seaStrip(452,9,2.6,.6,H+40),edge:'torn',color:'#1C4D58',seed:630,depth:.9,amp:6,freq:.1,fringe:false,sh:RIM,shDist:6,shadowA:.3});++ /* THE WAVE: giant torn layers diagonal from upper right, curling lip over the boat */+ // back sheet: tall wall+ drawPiece({base:[[610,470],[680,350],[760,280],[900,205],[1080,140],[1320,80],[1340,780],[590,780]],+ edge:'torn',color:'#20626B',seed:640,depth:1.7,amp:15,freq:.05,fringeColor:'#E8E1D0',shadowA:.42,sh:RIM,shDist:9});+ // mid sheet: diagonal face sweeping down-left to the water, lip at the top+ drawPiece({base:[[500,614],[560,520],[640,428],[662,368],[642,338],[702,316],[802,298],[932,260],[1100,214],[1320,180],[1340,780],[470,780]],+ edge:'torn',color:'#174751',seed:641,depth:2.1,amp:16,freq:.055,fringeColor:'#EDE7DA',shadowA:.45,sh:RIM,shDist:10});+ // spray: elongated ragged shreds flying off the lip, pointing down-left+ const shred=(cx,cy,len,wd,ang,sd)=>{+ const b=rot([[cx-len/2,cy],[cx+len/2,cy-wd*.4],[cx+len/2,cy+wd*.6],[cx-len/2+4,cy+wd*.3]],cx,cy,ang);+ drawPiece({base:b,edge:'torn',color:'#E9E2D2',seed:sd,depth:1.3,amp:wd*.5,freq:.2,fringe:false,shadowA:.24});+ };+ shred(600,320,58,16,-0.5,660);shred(536,380,44,13,-0.55,661);+ shred(668,268,50,14,-0.4,662);shred(790,238,40,12,-0.35,663);+ shred(492,452,34,11,-0.6,664);++ // the boat: small, bright, clean-cut, bow up toward the wave, in the beam+ drawBoat(414,562,66,-0.2,700,2.0);+ // foam sliver crossing its waterline+ drawPiece({base:[[350,574],[482,562],[476,578],[358,586]],edge:'cut',color:'#D8D2C0',seed:701,depth:.5,amp:1.6,shadowA:.16,shDist:2});++ // foreground torn water, low, not covering the boat+ drawPiece({base:seaStrip(636,12,1.8,2.4,H+40),edge:'torn',color:'#102A38',seed:642,depth:2.4,amp:12,freq:.06,fringeColor:'#9FB1B2',sh:RIM,shDist:10,shadowA:.4});+ drawPiece({base:seaStrip(692,10,1.4,4.4,H+40),edge:'torn',color:'#0B1F2B',seed:643,depth:2.8,amp:10,freq:.07,fringe:false,sh:RIM,shDist:10,shadowA:.4});+}++window.drawFrame=function(which){+ ctx.save();ctx.clearRect(0,0,W,H);+ if(which==='a')frameA();else frameB();+ ctx.restore();window.DONE=true;+};+window.READY=true;+</script></body></html>diff --git a/assets/previews-src/penciltest/boat.html b/assets/previews-src/penciltest/boat.htmlnew file mode 100644index 0000000..d95e755--- /dev/null+++ b/assets/previews-src/penciltest/boat.html@@ -0,0 +1,466 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>pencil test boat</title>+<style>html,body{margin:0;padding:0;background:#888}#c{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W=1280,H=720;+function mulberry32(seed){let a=seed>>>0;return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}+function noise1(seed){const r=mulberry32(seed);const v=[];for(let i=0;i<256;i++)v.push(r()*2-1);+ return t=>{const i=Math.floor(t),f=t-i,a=v[((i%256)+256)%256],b=v[(((i+1)%256)+256)%256],u=f*f*(3-2*f);return a+(b-a)*u;};}+const cv=document.getElementById('c'),ctx=cv.getContext('2d');+function mk(){const c=document.createElement('canvas');c.width=W;c.height=H;return c;}++// ---------- palette ----------+const PAPER='#EDE6D8';+const INK={red:'#C23A4F',blue:'#8FB0D0',gray:'#55575C',purple:'#6A4C9C'};+let L={}; // layers per pencil+let scratch=mk(),sx=scratch.getContext('2d');++// ---------- tooth tile ----------+const tooth=document.createElement('canvas');tooth.width=tooth.height=256;+{const g=tooth.getContext('2d'),img=g.createImageData(256,256),r=mulberry32(11);+ for(let y=0;y<256;y++)for(let x=0;x<256;x++){const i=(y*256+x)*4;+ // slight horizontal streak so graphite reads as drawn on tooth+ const v=0.42+0.58*r();img.data[i]=img.data[i+1]=img.data[i+2]=0;img.data[i+3]=Math.floor(255*v);}+ g.putImageData(img,0,0);}++// ---------- geometry ----------+function catmull(P,dens){+ if(P.length<3)return P.slice();+ const out=[];const get=i=>P[Math.max(0,Math.min(P.length-1,i))];+ for(let i=0;i<P.length-1;i++){const p0=get(i-1),p1=get(i),p2=get(i+1),p3=get(i+2);+ const seg=Math.max(2,Math.ceil(Math.hypot(p2[0]-p1[0],p2[1]-p1[1])/(dens||5)));+ for(let j=0;j<seg;j++){const t=j/seg,t2=t*t,t3=t2*t;+ out.push([0.5*((2*p1[0])+(-p0[0]+p2[0])*t+(2*p0[0]-5*p1[0]+4*p2[0]-p3[0])*t2+(-p0[0]+3*p1[0]-3*p2[0]+p3[0])*t3),+ 0.5*((2*p1[1])+(-p0[1]+p2[1])*t+(2*p0[1]-5*p1[1]+4*p2[1]-p3[1])*t2+(-p0[1]+3*p1[1]-3*p2[1]+p3[1])*t3)]);}}+ out.push(P[P.length-1].slice());return out;}+function resample(P,step){+ const out=[P[0].slice()];let acc=0;+ for(let i=1;i<P.length;i++){const a=P[i-1],b=P[i];const d=Math.hypot(b[0]-a[0],b[1]-a[1]);+ if(d===0)continue;let pos=step-acc;+ while(pos<=d){out.push([a[0]+(b[0]-a[0])*pos/d,a[1]+(b[1]-a[1])*pos/d]);pos+=step;}+ acc=d-(pos-step);}+ const last=P[P.length-1];out.push(last.slice());return out;}++// ---------- pencil stroke ----------+// opts: w, alpha, jit, seed, smooth, taper, over (overshoot px), dbl (double-line prob)+function stroke(layer,pts,o){+ o=o||{};const seed=o.seed||1;const w=o.w||1.6,alpha=o.alpha===undefined?0.9:o.alpha,jit=o.jit===undefined?0.9:o.jit;+ let P=pts.map(p=>p.slice());+ if(o.over){ // overshoot ends a little along the tangent+ const a=P[0],b=P[1],n=P.length,y=P[n-1],z=P[n-2];+ const d1=Math.hypot(a[0]-b[0],a[1]-b[1])||1,d2=Math.hypot(y[0]-z[0],y[1]-z[1])||1;+ P.unshift([a[0]+(a[0]-b[0])/d1*o.over,a[1]+(a[1]-b[1])/d1*o.over]);+ P.push([y[0]+(y[0]-z[0])/d2*o.over,y[1]+(y[1]-z[1])/d2*o.over]);}+ if(o.smooth)P=catmull(P,4);+ const R=resample(P,2.2);const n=R.length;if(n<2)return;+ const nj=noise1(seed*977+3),nw=noise1(seed*977+5);+ const taper=o.taper===undefined?0.18:o.taper;+ // bbox+ let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9;for(const p of R){x0=Math.min(x0,p[0]);y0=Math.min(y0,p[1]);x1=Math.max(x1,p[0]);y1=Math.max(y1,p[1]);}+ const pad=w*2+jit*3+4;x0=Math.max(0,Math.floor(x0-pad));y0=Math.max(0,Math.floor(y0-pad));x1=Math.min(W,Math.ceil(x1+pad));y1=Math.min(H,Math.ceil(y1+pad));+ if(x1<=x0||y1<=y0)return;+ sx.clearRect(x0,y0,x1-x0,y1-y0);+ sx.save();sx.strokeStyle='#000';sx.lineCap='round';sx.lineJoin='round';+ let totalLen=0;for(let i=1;i<n;i++)totalLen+=Math.hypot(R[i][0]-R[i-1][0],R[i][1]-R[i-1][1]);+ const Q=R.map((p,i)=>{const a=R[Math.max(0,i-1)],b=R[Math.min(n-1,i+1)];let dx=b[0]-a[0],dy=b[1]-a[1];const d=Math.hypot(dx,dy)||1;+ const off=nj(i*2.2/38)*jit;return[p[0]-dy/d*off,p[1]+dx/d*off];});+ for(let i=0;i<n-1;i++){const t=i/(n-1);+ let prof=Math.min(1,t/taper,(1-t)/taper);prof=Math.max(0.15,prof);+ sx.lineWidth=Math.max(0.4,w*Math.pow(prof,0.7)*(0.78+0.3*(0.5+0.5*nw(i*2.2/30))));+ sx.beginPath();sx.moveTo(Q[i][0],Q[i][1]);sx.lineTo(Q[i+1][0],Q[i+1][1]);sx.stroke();}+ sx.restore();+ const g=layer.getContext('2d');g.save();g.globalAlpha=alpha;+ g.drawImage(scratch,x0,y0,x1-x0,y1-y0,x0,y0,x1-x0,y1-y0);g.restore();+ if(o.dbl){const r=mulberry32(seed*13+7);if(r()<o.dbl){stroke(layer,pts,Object.assign({},o,{dbl:0,seed:seed+4001,alpha:alpha*0.45,w:w*0.7,jit:jit*1.8+0.8}));}}+}+// fast thin stroke straight on the layer (hatching, rain)+function fast(layer,pts,o){+ const g=layer.getContext('2d');g.save();g.globalAlpha=o.alpha;g.lineWidth=o.w;g.strokeStyle='#000';g.lineCap='round';+ const r=mulberry32(o.seed||1);g.beginPath();+ const R=o.smooth?catmull(pts,6):pts;+ g.moveTo(R[0][0]+(r()-0.5)*o.jit,R[0][1]+(r()-0.5)*o.jit);+ for(let i=1;i<R.length;i++)g.lineTo(R[i][0]+(r()-0.5)*o.jit,R[i][1]+(r()-0.5)*o.jit);+ g.stroke();g.restore();}++function ellipsePts(cx,cy,rx,ry,rot,a0,a1,n){const p=[];n=n||40;const c=Math.cos(rot||0),s=Math.sin(rot||0);+ for(let i=0;i<=n;i++){const a=a0+(a1-a0)*i/n;const x=Math.cos(a)*rx,y=Math.sin(a)*ry;p.push([cx+x*c-y*s,cy+x*s+y*c]);}return p;}+// hand-drawn loop: slightly more than a full turn, drifting+function loop(layer,cx,cy,rx,ry,o){const r=mulberry32(o.seed||3);const st=-1.9+r()*0.4;+ const p=[];for(let i=0;i<=46;i++){const t=i/46,a=st+t*(Math.PI*2+0.5);const k=1+0.06*Math.sin(t*5+r())+t*0.05;p.push([cx+Math.cos(a)*rx*k,cy+Math.sin(a)*ry*k]);}+ stroke(layer,p,Object.assign({smooth:true,taper:0.08},o));}++// ---------- single-stroke lettering ----------+const E=(cx,cy,rx,ry)=>ellipsePts(cx,cy,rx,ry,0,-Math.PI/2,Math.PI*1.5+0.15,22);+const G={+A:[[[0,1],[0.45,0],[0.9,1]],[[0.2,0.62],[0.72,0.62]]],+B:[[[0,1],[0,0],[0.6,0],[0.82,0.1],[0.84,0.32],[0.6,0.47],[0,0.47]],[[0.6,0.47],[0.88,0.6],[0.9,0.86],[0.66,1],[0,1]]],+C:[[[0.9,0.16],[0.68,0],[0.32,0],[0.06,0.22],[0.04,0.72],[0.3,1],[0.68,1],[0.92,0.84]]],+D:[[[0,0],[0,1],[0.5,1],[0.84,0.8],[0.9,0.5],[0.84,0.2],[0.5,0],[0,0]]],+E:[[[0.82,0],[0,0],[0,1],[0.84,1]],[[0,0.5],[0.66,0.5]]],+F:[[[0.82,0],[0,0],[0,1]],[[0,0.5],[0.64,0.5]]],+G:[[[0.9,0.16],[0.68,0],[0.32,0],[0.06,0.22],[0.04,0.72],[0.3,1],[0.68,1],[0.92,0.82],[0.92,0.56],[0.52,0.56]]],+H:[[[0,0],[0,1]],[[0.84,0],[0.84,1]],[[0,0.5],[0.84,0.5]]],+I:[[[0.12,0],[0.12,1]]],+J:[[[0.74,0],[0.74,0.76],[0.56,1],[0.24,1],[0.04,0.8]]],+K:[[[0,0],[0,1]],[[0.8,0],[0,0.62]],[[0.28,0.42],[0.84,1]]],+L:[[[0,0],[0,1],[0.78,1]]],+M:[[[0,1],[0,0],[0.5,0.62],[1,0],[1,1]]],+N:[[[0,1],[0,0],[0.84,1],[0.84,0]]],+O:[E(0.47,0.5,0.47,0.5)],+P:[[[0,1],[0,0],[0.62,0],[0.84,0.14],[0.84,0.38],[0.62,0.52],[0,0.52]]],+Q:[E(0.47,0.5,0.47,0.5),[[0.58,0.7],[0.98,1.06]]],+R:[[[0,1],[0,0],[0.62,0],[0.84,0.14],[0.84,0.38],[0.62,0.52],[0,0.52]],[[0.42,0.52],[0.86,1]]],+S:[[[0.84,0.14],[0.6,0],[0.28,0],[0.04,0.16],[0.08,0.38],[0.44,0.5],[0.8,0.62],[0.86,0.86],[0.6,1],[0.26,1],[0,0.86]]],+T:[[[0,0],[0.88,0]],[[0.44,0],[0.44,1]]],+U:[[[0,0],[0,0.72],[0.2,1],[0.64,1],[0.84,0.72],[0.84,0]]],+V:[[[0,0],[0.44,1],[0.88,0]]],+W:[[[0,0],[0.25,1],[0.5,0.36],[0.75,1],[1,0]]],+X:[[[0,0],[0.84,1]],[[0.84,0],[0,1]]],+Y:[[[0,0],[0.44,0.52],[0.88,0]],[[0.44,0.52],[0.44,1]]],+Z:[[[0,0],[0.84,0],[0,1],[0.86,1]]],+'0':[E(0.36,0.5,0.34,0.5)],+'1':[[[0.08,0.2],[0.36,0],[0.36,1]]],+'2':[[[0.04,0.2],[0.24,0],[0.56,0],[0.74,0.18],[0.7,0.42],[0,1],[0.8,1]]],+'3':[[[0.04,0.1],[0.28,0],[0.56,0],[0.74,0.14],[0.7,0.36],[0.38,0.48]],[[0.38,0.48],[0.74,0.6],[0.78,0.86],[0.56,1],[0.26,1],[0.02,0.88]]],+'4':[[[0.62,1],[0.62,0],[0,0.7],[0.84,0.7]]],+'5':[[[0.74,0],[0.14,0],[0.08,0.45],[0.4,0.38],[0.7,0.5],[0.78,0.76],[0.56,1],[0.24,1],[0.02,0.88]]],+'6':[[[0.7,0.06],[0.44,0],[0.16,0.16],[0.04,0.56],[0.1,0.9],[0.4,1],[0.7,0.9],[0.76,0.64],[0.6,0.46],[0.34,0.44],[0.08,0.62]]],+'7':[[[0,0],[0.8,0],[0.3,1]]],+'8':[[[0.4,0.47],[0.1,0.35],[0.1,0.12],[0.4,0],[0.7,0.12],[0.7,0.35],[0.4,0.47],[0.06,0.62],[0.06,0.88],[0.4,1],[0.74,0.88],[0.74,0.62],[0.4,0.47]]],+'9':[[[0.74,0.4],[0.52,0.54],[0.22,0.52],[0.06,0.3],[0.16,0.05],[0.44,0],[0.7,0.1],[0.78,0.44],[0.66,0.84],[0.36,1],[0.1,0.92]]],+'.':[[[0.04,0.9],[0.16,0.88],[0.18,1],[0.04,1],[0.05,0.9]]],+'-':[[[0.04,0.56],[0.5,0.56]]],+'+':[[[0.04,0.52],[0.64,0.52]],[[0.34,0.22],[0.34,0.82]]],+"'":[[[0.14,0],[0.08,0.26]]],+'(':[[[0.34,-0.06],[0.08,0.3],[0.06,0.7],[0.34,1.06]]],+')':[[[0,-0.06],[0.26,0.3],[0.28,0.7],[0,1.06]]],+'·':[[[0.08,0.46],[0.2,0.44],[0.22,0.56],[0.08,0.57],[0.09,0.46]]],+'>':[[[0,0.52],[1.1,0.52]],[[0.8,0.3],[1.1,0.52],[0.8,0.74]]],+'/':[[[0.6,0],[0,1]]],+};+function glyphW(ch){if(ch===' ')return 0.55;const g=G[ch];if(!g)return 0.6;let m=0;for(const s of g)for(const p of s)m=Math.max(m,p[0]);return m;}+function textWidth(str,size){let x=0;for(const ch of str)x+=(glyphW(ch)+0.36)*size*0.66;return x-0.36*size*0.66;}+// size = cap height. Returns width.+function write(layer,str,x,y,size,o){+ o=o||{};const r=mulberry32(o.seed||7);let cx=x;const sw=size*0.66;+ for(const ch of str){+ if(ch!==' '&&G[ch]){+ const bj=(r()-0.5)*size*0.07,sj=1+(r()-0.5)*0.08,rot=(r()-0.5)*0.05;+ for(const s of G[ch]){+ const pts=s.map(p=>{const px=p[0]*sw*sj,py=(p[1]-1)*size*sj;return[cx+px*Math.cos(rot)-py*Math.sin(rot),y+bj+px*Math.sin(rot)+py*Math.cos(rot)];});+ stroke(layer,pts,{w:o.w||1.6,alpha:o.alpha||0.9,jit:o.jit===undefined?0.35:o.jit,seed:Math.floor(r()*1e6),taper:0.12,smooth:s.length>4});+ }}+ cx+=(glyphW(ch)+0.36)*sw;}+ return cx-x;}++// ---------- paper ----------+function paper(seed){+ ctx.fillStyle=PAPER;ctx.fillRect(0,0,W,H);+ // light-table centre lift+ let g=ctx.createRadialGradient(W*0.5,H*0.52,40,W*0.5,H*0.52,W*0.62);+ g.addColorStop(0,'rgba(255,252,244,0.45)');g.addColorStop(1,'rgba(255,252,244,0)');ctx.fillStyle=g;ctx.fillRect(0,0,W,H);+ // aged blotches+ const r=mulberry32(seed);ctx.save();ctx.globalCompositeOperation='multiply';+ for(let i=0;i<22;i++){const x=r()*W,y=r()*H,rad=60+r()*220;const gg=ctx.createRadialGradient(x,y,0,x,y,rad);+ gg.addColorStop(0,'rgba(196,176,140,'+(0.05+r()*0.06)+')');gg.addColorStop(1,'rgba(196,176,140,0)');ctx.fillStyle=gg;ctx.fillRect(x-rad,y-rad,rad*2,rad*2);}+ // grain+ const gt=document.createElement('canvas');gt.width=gt.height=256;{const q=gt.getContext('2d'),im=q.createImageData(256,256),rr=mulberry32(seed+9);+ for(let i=0;i<im.data.length;i+=4){const v=226+rr()*29;im.data[i]=v;im.data[i+1]=v-2;im.data[i+2]=v-6;im.data[i+3]=255;}q.putImageData(im,0,0);+ q.strokeStyle='rgba(130,112,88,0.35)';q.lineWidth=0.6;for(let i=0;i<45;i++){const x=rr()*256,y=rr()*256,a=rr()*Math.PI,l=2+rr()*6;q.beginPath();q.moveTo(x,y);q.quadraticCurveTo(x+Math.cos(a)*l*0.5+rr()*2,y+Math.sin(a)*l*0.5,x+Math.cos(a)*l,y+Math.sin(a)*l);q.stroke();}}+ ctx.globalAlpha=0.55;ctx.fillStyle=ctx.createPattern(gt,'repeat');ctx.fillRect(0,0,W,H);ctx.globalAlpha=1;+ // warm vignette+ g=ctx.createRadialGradient(W*0.5,H*0.5,H*0.42,W*0.5,H*0.5,W*0.72);+ g.addColorStop(0,'rgba(170,130,85,0)');g.addColorStop(1,'rgba(150,108,62,0.42)');ctx.fillStyle=g;ctx.fillRect(0,0,W,H);+ ctx.restore();}++function composite(name,alpha,blotchy){+ const c=L[name],g=c.getContext('2d');+ g.save();g.globalCompositeOperation='destination-in';g.fillStyle=g.createPattern(tooth,'repeat');g.fillRect(0,0,W,H);g.restore();+ g.save();g.globalCompositeOperation='source-in';g.fillStyle=INK[name];g.fillRect(0,0,W,H);g.restore();+ ctx.save();ctx.globalCompositeOperation='multiply';ctx.globalAlpha=alpha||1;ctx.drawImage(c,0,0);ctx.restore();}++// ---------- the paper boat ----------+// local coords: hull top edge y=0 from -100..100, keel at y=40, sail peak at y=-80+function boatParts(){+ return {+ hull:[[-104,-2],[-64,40],[64,40],[104,-2]],+ rim:[[-104,-2],[104,-2]],+ brim:[[-90,11],[90,11]],+ sail:[[-66,-2],[-4,-96],[62,-2]],+ crease:[[-4,-96],[-2,-2]],+ fold:[[-66,-2],[-30,-20]],fold2:[[62,-2],[28,-18]],+ };}+function xf(pts,b){const c=Math.cos(b.ang),s=Math.sin(b.ang);const sqx=1+(b.sq||0),sqy=1/(1+(b.sq||0));+ return pts.map(p=>{const x=p[0]*b.s*sqx,y=p[1]*b.s*sqy;return[b.x+x*c-y*s,b.y+x*s+y*c];});}+function drawBoat(layer,b,o){+ const P=boatParts(),seed=o.seed||1;const w=o.w||2.4,al=o.alpha===undefined?0.95:o.alpha;+ const k={w:w,alpha:al,jit:o.jit||0.7,over:o.over===undefined?3:o.over,dbl:o.dbl===undefined?0.5:o.dbl,taper:0.1};+ let i=0;+ for(const key of ['hull','rim','sail','crease','brim','fold','fold2']){+ const kk=Object.assign({},k,{seed:seed*50+(i++)});+ if(key==='brim'||key==='fold'||key==='fold2'||key==='crease'){kk.w=w*0.7;kk.alpha=al*0.8;}+ stroke(layer,xf(P[key],b),kk);}+}+function boatConstruction(layer,b,o){+ const seed=o.seed||2,al=o.alpha||0.7,w=o.w||1.3;+ // bounding ellipse of hull+ const e=ellipsePts(0,14,118,38,0,0,Math.PI*2+0.3,40);stroke(layer,xf(e,b),{w:w,alpha:al,jit:1.4,seed:seed,smooth:true});+ // centre / tilt axis, overshooting+ stroke(layer,xf([[-150,6],[150,6]],b),{w:w,alpha:al*0.8,jit:1,seed:seed+1});+ stroke(layer,xf([[-3,-112],[-1,56]],b),{w:w,alpha:al*0.8,jit:1,seed:seed+2});+ // rough sail triangle, looser+ stroke(layer,xf([[-74,4],[-6,-106],[70,4]],b),{w:w,alpha:al*0.7,jit:2.2,seed:seed+3});+ // rough hull box+ stroke(layer,xf([[-112,-6],[-70,46],[70,46],[114,-8]],b),{w:w,alpha:al*0.6,jit:2.4,seed:seed+4});+}+function boatPeak(b){return xf([[-4,-96]],b)[0];}+function boatKeel(b){return xf([[0,40]],b)[0];}++// ---------- slate + counter ----------+function slate(title,seed){+ write(L.gray,'PROD. 2026-A SEQ. 3 SC. 12',70,86,17,{w:1.5,alpha:0.95,seed:seed,jit:0.2});+ const tw=write(L.red,title,70,132,29,{w:2.4,alpha:0.95,seed:seed+1,jit:0.35});+ stroke(L.red,[[66,145],[70+tw*0.5,143],[70+tw+10,146]],{w:2.2,alpha:0.9,jit:0.8,seed:seed+2,smooth:true,taper:0.25});+}+function counter(num,label,circled,seed){+ const size=34;const tw=textWidth(num,size);const x=1198-tw/2;+ write(L.gray,num,x,650,size,{w:2.4,alpha:0.95,seed:seed,jit:0.3});+ if(circled)loop(L.gray,1198,633,tw/2+22,26,{w:1.6,alpha:0.8,seed:seed+3,jit:0.8});+ const lw=textWidth(label,15);write(L.gray,label,1198-lw/2,690,15,{w:1.4,alpha:0.9,seed:seed+5,jit:0.2});+}+function circNum(layer,num,cx,cy,o){o=o||{};const size=o.size||17;const tw=textWidth(num,size);+ write(layer,num,cx-tw/2,cy+size/2,size,{w:1.5,alpha:o.alpha||0.9,seed:o.seed||5,jit:0.25});+ loop(layer,cx,cy,tw/2+13,size*0.95,{w:1.3,alpha:(o.alpha||0.9)*0.85,seed:(o.seed||5)+9,jit:0.6});}+// dashed arc with cross ticks+function dashedArc(layer,pts,o){+ const C=catmull(pts,4);const R=resample(C,3);let s=o.seed||9;const dash=o.dash||5,gap=o.gap||4;+ let i=0;while(i<R.length-1){const j=Math.min(R.length-1,i+dash);stroke(layer,R.slice(i,j+1),{w:o.w||1.4,alpha:o.alpha||0.8,jit:0.3,seed:s++,taper:0.3});i=j+gap;}+ if(o.ticks){for(let k=o.tickEvery;k<R.length-2;k+=o.tickEvery){const a=R[k-1],b=R[k+1];const dx=b[0]-a[0],dy=b[1]-a[1],d=Math.hypot(dx,dy)||1;+ const nx=-dy/d*6,ny=dx/d*6;stroke(layer,[[R[k][0]-nx,R[k][1]-ny],[R[k][0]+nx,R[k][1]+ny]],{w:1.2,alpha:(o.alpha||0.8)*0.9,jit:0.2,seed:s++,taper:0.3});}}+ return R;}+function arrow(layer,pts,o){const C=catmull(pts,4);stroke(layer,C,Object.assign({w:1.4,alpha:0.85,jit:0.5,taper:0.12},o));+ const n=C.length,a=C[n-4]||C[0],b=C[n-1];const ang=Math.atan2(b[1]-a[1],b[0]-a[0]);const hl=11;+ stroke(layer,[[b[0]-Math.cos(ang-0.45)*hl,b[1]-Math.sin(ang-0.45)*hl],b,[b[0]-Math.cos(ang+0.45)*hl,b[1]-Math.sin(ang+0.45)*hl]],Object.assign({w:1.4,alpha:0.85,jit:0.3,taper:0.2},o,{seed:(o.seed||1)+77}));}++// hatching inside polygon (fast strokes)+function hatch(layer,poly,ang,sp,o){+ const g=layer.getContext('2d');g.save();g.beginPath();g.moveTo(poly[0][0],poly[0][1]);for(const p of poly)g.lineTo(p[0],p[1]);g.closePath();g.clip();+ if(o.clipOut){g.beginPath();g.rect(0,0,W,H);for(const q of o.clipOut){g.moveTo(q[0][0],q[0][1]);for(const p of q)g.lineTo(p[0],p[1]);g.closePath();}g.clip('evenodd');}+ const r=mulberry32(o.seed||5);const xs=poly.map(p=>p[0]),ys=poly.map(p=>p[1]);+ const cx=(Math.min(...xs)+Math.max(...xs))/2,cy=(Math.min(...ys)+Math.max(...ys))/2;const R=Math.hypot(Math.max(...xs)-Math.min(...xs),Math.max(...ys)-Math.min(...ys))/2+20;+ const dx=Math.cos(ang),dy=Math.sin(ang);+ for(let d=-R;d<R;d+=sp*(0.7+r()*0.6)){const ox=cx-dy*d,oy=cy+dx*d;+ let a=o.dens?o.dens(ox,oy):1;for(const c of CLEAR){const dd=Math.hypot(ox-c[0],oy-c[1]);}if(r()>a)continue;+ const L0=R*(0.9+r()*0.2);+ // broken strokes: split into 1-3 pieces+ let t=-L0;while(t<L0){const len=40+r()*160;const t2=Math.min(L0,t+len);+ {const mx=ox+dx*(t+t2)/2,my=oy+dy*(t+t2)/2;let keep=1;for(const c of CLEAR){keep*=Math.max(0,Math.min(1,(Math.hypot(mx-c[0],my-c[1])-c[2])/c[3]));}if(r()>keep){t=t2+r()*o.gap;continue;}}+ fast(layer,[[ox+dx*t,oy+dy*t],[ox+dx*(t+t2)/2+(r()-0.5)*2,oy+dy*(t+t2)/2+(r()-0.5)*2],[ox+dx*t2,oy+dy*t2]],{w:o.w||1,alpha:(o.alpha||0.35)*(0.6+r()*0.5),jit:0.8,seed:Math.floor(r()*1e6)});+ t=t2+r()*o.gap;}}+ g.restore();}++let CLEAR=[];+function reset(){CLEAR=[];L={blue:mk(),gray:mk(),red:mk(),purple:mk()};ctx.globalCompositeOperation='source-over';ctx.globalAlpha=1;}+function finish(){composite('blue',0.95);composite('gray',0.92);composite('red',1);}++// ================= FRAME A: the run, dawn, on twos =================+function frameA(){+ reset();paper(21);+ const hz=420;+ // --- graphite background layout ---+ // horizon, broken+ const r=mulberry32(4);+ let x=-10;while(x<W+10){const l=90+r()*260;stroke(L.gray,[[x,hz+(r()-0.5)*1.5],[x+l*0.5,hz+(r()-0.5)*2],[x+l,hz+(r()-0.5)*1.5]],{w:1.3,alpha:0.7,jit:0.6,seed:Math.floor(r()*1e5),taper:0.15});x+=l+4+r()*14;}+ // sun: half disc on horizon, with rays+ const sc=[905,hz];stroke(L.gray,ellipsePts(sc[0],sc[1],64,64,0,Math.PI+0.05,Math.PI*2-0.02,40),{w:1.6,alpha:0.85,jit:0.6,seed:31,smooth:true,over:4});+ stroke(L.gray,ellipsePts(sc[0],sc[1],70,70,0,Math.PI+0.3,Math.PI*1.7,30),{w:1,alpha:0.4,jit:1.2,seed:32,smooth:true});+ for(let i=0;i<13;i++){const a=Math.PI+0.18+i*(Math.PI-0.36)/12;const r1=86+(i%2)*6,r2=r1+(i%2?26:42);+ stroke(L.gray,[[sc[0]+Math.cos(a)*r1,sc[1]+Math.sin(a)*r1],[sc[0]+Math.cos(a)*r2,sc[1]+Math.sin(a)*r2]],{w:1.3,alpha:0.7,jit:0.3,seed:40+i,taper:0.3});}+ // sun glitter path on water+ const rg=mulberry32(12);+ for(let i=0;i<34;i++){const y=hz+10+Math.pow(i/34,1.4)*250;const spread=18+(y-hz)*0.55;const cx=sc[0]+(rg()-0.5)*spread*1.6;const l=10+(y-hz)*0.12+rg()*16;+ stroke(L.gray,[[cx-l/2,y],[cx+l/2,y+(rg()-0.5)]],{w:1.1+(y-hz)/260,alpha:0.55,jit:0.3,seed:100+i,taper:0.35});}+ // water ripples: sparse near horizon, bigger closer+ for(let i=0;i<60;i++){const t=rg();const y=hz+12+t*t*270;const xx=rg()*W;if(Math.abs(xx-sc[0])<60)continue;const l=14+t*60+rg()*20;+ if(xx>150&&xx<560&&y>455&&y<560)continue; // keep boat zone clean+ stroke(L.gray,[[xx-l/2,y],[xx,y-1.5-t*3],[xx+l/2,y]],{w:0.9+t*0.8,alpha:0.45,jit:0.4,seed:300+i,smooth:true,taper:0.35});}+ // clouds: simple outlines, like layout props+ function cloud(cx,cy,s,seed){const rr=mulberry32(seed);const bumps=[[-62,14],[-30,26],[10,34],[48,22],[78,10]];+ for(let i=0;i<bumps.length;i++){const [bx,br]=bumps[i];const R=br*s*(0.95+rr()*0.15);const l=i===0?-84:(bumps[i-1][0]+bx)/2,rt=i===bumps.length-1?90:(bumps[i+1][0]+bx)/2;+ const p=[[cx+l*s,cy-(i===0?0:4*s)],[cx+(l+bx)/2*s,cy-R*0.8],[cx+bx*s,cy-R],[cx+(rt+bx)/2*s,cy-R*0.8],[cx+rt*s,cy-(i===bumps.length-1?0:4*s)]];+ stroke(L.gray,p,{w:1.3,alpha:0.62,jit:0.6,seed:seed+i*7,smooth:true,taper:0.15});}+ stroke(L.gray,[[cx-92*s,cy+2],[cx+96*s,cy+1]],{w:1,alpha:0.5,jit:0.6,seed:seed+1,taper:0.2});}+ cloud(640,215,1.1,501);cloud(1090,160,0.8,502);cloud(300,300,0.7,503);+ // gulls+ for(const [gx,gy,gs] of [[760,285,1],[800,262,0.75]]){stroke(L.gray,[[gx-14*gs,gy-2],[gx-6*gs,gy-7*gs],[gx,gy]],{w:1.3,alpha:0.75,seed:gx,smooth:true});stroke(L.gray,[[gx,gy],[gx+7*gs,gy-8*gs],[gx+15*gs,gy-3]],{w:1.3,alpha:0.75,seed:gx+1,smooth:true});}++ // --- the run: pose library keyed by frame (on twos) ---+ const poses={45:{x:175,y:520,s:0.98,ang:0.07,sq:0.06},51:{x:310,y:506,s:0.98,ang:-0.03,sq:-0.04},57:{x:450,y:510,s:1.06,ang:-0.1,sq:0}};+ // blue construction layout: bob path + waterline guides+ stroke(L.blue,[[60,548],[640,548]],{w:1.2,alpha:0.55,jit:1,seed:61});+ stroke(L.blue,[[80,470],[620,440]],{w:1,alpha:0.35,jit:1.4,seed:62});+ // onion skins (older = fainter)+ drawBoat(L.blue,poses[45],{w:2.3,alpha:0.3,seed:45,dbl:0.3});boatConstruction(L.blue,poses[45],{alpha:0.16,seed:450});+ drawBoat(L.blue,poses[51],{w:2.3,alpha:0.4,seed:51,dbl:0.3});boatConstruction(L.blue,poses[51],{alpha:0.2,seed:510});+ // path of the sail peak, dashed with ticks+ const pk=[45,51,57].map(f=>boatPeak(poses[f]));+ dashedArc(L.blue,[[pk[0][0]-60,pk[0][1]+14],pk[0],pk[1],pk[2],[pk[2][0]+70,pk[2][1]-10]],{alpha:0.8,w:1.4,seed:71,ticks:true,tickEvery:14});+ // current drawing: blue rough under red clean+ boatConstruction(L.blue,poses[57],{alpha:0.75,seed:570,w:1.4});+ drawBoat(L.blue,Object.assign({},poses[57],{x:poses[57].x-3,y:poses[57].y+2}),{w:1.6,alpha:0.5,seed:571,jit:1.8,dbl:0});+ drawBoat(L.red,poses[57],{w:3.3,alpha:1,seed:57,dbl:0.6});+ // red wake + waterline (part of the drawing)+ const b=poses[57];+ const wl=(lx,ly)=>xf([[lx,ly]],b)[0];+ // waterline hugging the hull, bow wave, and a V wake opening behind (to the left)+ stroke(L.red,[wl(-78,28),wl(-30,33),wl(30,31),wl(80,24)],{w:1.8,alpha:0.85,jit:0.5,seed:581,smooth:true});+ stroke(L.red,[wl(84,22),wl(104,14),wl(120,20)],{w:1.6,alpha:0.8,seed:585,smooth:true});+ stroke(L.red,[wl(-86,30),wl(-118,27),wl(-150,27)],{w:1.5,alpha:0.7,seed:582,smooth:true,taper:0.4});+ stroke(L.red,[wl(-80,38),wl(-116,44),wl(-156,47)],{w:1.5,alpha:0.6,seed:583,smooth:true,taper:0.4});+ // circled key numbers under the drawings (graphite)+ circNum(L.gray,'45',poses[45].x,612,{seed:901,alpha:0.7});circNum(L.gray,'51',poses[51].x,612,{seed:902,alpha:0.7});circNum(L.gray,'57',poses[57].x,612,{seed:903,alpha:0.85});+ for(const f of [45,51,57])stroke(L.gray,[[poses[f].x,560],[poses[f].x,590]],{w:1,alpha:0.5,seed:f+950});+ slate('SETTING OUT (DAWN)',1001);+ counter('57','ON TWOS',true,1101);+ finish();+}++// ================= FRAME B: storm peak, frozen and dissected =================+function frameB(){+ reset();paper(22);+ // wave comes from upper right and breaks LEFT over the boat. face = trough (lower left) up to under the lip.+ CLEAR=[[1198,655,40,60]];+ const face=[[40,652],[250,634],[430,596],[575,540],[690,470],[780,392],[840,312],[872,236],[884,176]];+ // lip outer contour, right edge -> crest -> thrown forward -> curling down+ const lipTop=[[1290,128],[1180,78],[1060,44],[960,38],[870,56],[800,96],[764,146],[772,186],[806,196],[828,172],[824,150]];+ const lipUnder=[[824,150],[850,150],[884,176]];+ const faceC=catmull(face,4);+ const body=faceC.concat(lipUnder.slice().reverse(),lipTop.slice().reverse(),[[1290,720],[40,720]]);+ // --- storm sky: light graphite hatching around a clearing where the light breaks through ---+ const gap=ellipsePts(600,58,74,40,-0.1,0,Math.PI*2,30);+ const beam=[[560,70],[652,62],[720,440],[600,470]];+ const skyMass=[[470,0],[1280,0],[1280,260],[980,240],[760,200],[620,150],[520,120],[480,70]];+ // light falloff: hatching thins toward the clearing and along the beam (no hard edges)+ const beamD=(x,y)=>{const t=Math.max(0,Math.min(1,(y-58)/400));const cx=606+t*54,hw=40+t*30;return Math.abs(x-cx)/hw;};+ const lightK=(x,y)=>{const g=Math.hypot((x-600)/90,(y-58)/55);const k=Math.min(g,y<470?beamD(x,y):9);return Math.max(0,Math.min(1,(k-0.6)/1.4));};+ const soft=(x,y)=>Math.max(0,Math.min(1,0.35+(x-470)/450-(y)/1000))*lightK(x,y);+ hatch(L.gray,skyMass,-0.35,6.5,{seed:5,alpha:0.36,w:1.1,gap:14,clipOut:[body],dens:soft});+ hatch(L.gray,skyMass,0.95,8,{seed:6,alpha:0.28,w:1,gap:20,clipOut:[body],dens:(x,y)=>soft(x,y)*0.85});+ const r=mulberry32(33);+ // scalloped underside of the storm cloud+ stroke(L.gray,[[480,40],[500,74],[536,92],[560,118]],{w:1.3,alpha:0.5,jit:1.4,seed:41,smooth:true});+ // clearing rim + beam edges aimed at the boat+ for(let i=0;i<6;i++){const a0=[572+i*12,70],a1=[586+i*22,300+i*26];stroke(L.gray,[a0,a1],{w:0.9,alpha:0.2+0.04*(i%2),jit:0.6,seed:43+i,taper:0.4});}+ // rain slanting in from the right, never inside the beam+ const inBeam=(x,y)=>{const t=Math.max(0,Math.min(1,(y-66)/390));return x>560+t*40-6&&x<652+t*68+6&&y<470;};+ for(let i=0;i<220;i++){const x=470+r()*810,y=r()*440;if(inBeam(x,y)||y>150+(x-470)*0.9)continue;const l=12+r()*16;fast(L.gray,[[x,y],[x-l*0.4,y+l]],{w:1,alpha:0.38,jit:0.3,seed:i});}+ // --- wave body: graphite hatching, darkest in the tube under the lip ---+ hatch(L.gray,body,-0.6,4,{seed:7,alpha:0.58,w:1.2,gap:8,dens:(x,y)=>Math.min(1,0.45+(x-300)/600+(560-y)/600)});+ hatch(L.gray,body,0.4,4.6,{seed:8,alpha:0.5,w:1.1,gap:12,dens:(x,y)=>Math.max(0,Math.min(1,(x-560)/380+(460-y)/380))});+ hatch(L.gray,body,1.2,6,{seed:10,alpha:0.3,w:1,gap:14,dens:(x,y)=>Math.max(0,Math.min(1,(x-760)/300+(300-y)/300))});+ // tube shadow: dense band just under the lip on the face+ const tube=[[884,176],[850,150],[824,150],[828,172],[806,196],[812,226],[852,236],[872,236],[884,176],[960,150],[1040,120],[1100,110],[1000,210],[930,300],[860,330],[872,236]];+ hatch(L.gray,body,-0.25,2.6,{seed:9,alpha:0.62,w:1.2,gap:4,dens:(x,y)=>{const d=Math.hypot(x-920,y-180);return Math.max(0,1.2-d/200);}});+ hatch(L.gray,body,1.1,3,{seed:19,alpha:0.55,w:1.1,gap:5,dens:(x,y)=>{const d=Math.hypot(x-940,y-160);return Math.max(0,1.2-d/170);}});+ // contours+ stroke(L.gray,face,{w:2.6,alpha:0.95,jit:0.9,seed:11,smooth:true,taper:0.06,over:4});+ stroke(L.gray,lipTop,{w:2.6,alpha:0.95,jit:0.8,seed:12,smooth:true,taper:0.06});+ stroke(L.gray,lipUnder,{w:1.8,alpha:0.85,jit:0.6,seed:13,smooth:true});+ // spray thrown off the lip: scribble loops + flecks+ // spray: short flicked strokes thrown forward (left) off the lip+ {const lp=catmull(lipTop,6);for(let i=0;i<46;i++){const q=lp[Math.floor(r()*(lp.length*0.7))];const d=6+r()*26;const x=q[0]-r()*14,y=q[1]-4-r()*18;+ stroke(L.gray,[[x,y],[x-d,y-d*0.25+r()*6]],{w:1.1,alpha:0.55,jit:0.3,seed:700+i,taper:0.4});}}+ for(let i=0;i<40;i++){const x=730+r()*140,y=110+r()*140;fast(L.gray,[[x,y],[x+1.5,y+1.5]],{w:1.8,alpha:0.6,jit:0,seed:i+500});}+ // flow lines on the face+ for(let k=0;k<5;k++){const off=36+k*44;stroke(L.gray,faceC.filter((p,i)=>i%3===0).map(p=>[p[0]+off*0.7,p[1]+off*0.5]).filter(p=>p[1]<712&&p[0]<1270&&p[1]>150),{w:1,alpha:0.38,jit:1.4,seed:20+k,taper:0.3,smooth:true});}+ // --- blue construction of the wave: rhythm curve + curl circle ---+ stroke(L.blue,[[40,712],[420,650],[720,470],[860,250],[900,120],[980,60]],{w:1.4,alpha:0.55,jit:1.6,seed:51,smooth:true,over:10});+ stroke(L.blue,ellipsePts(840,150,82,64,0,0,Math.PI*2+0.3,36),{w:1.2,alpha:0.45,jit:1.8,seed:52,smooth:true});++ // --- pose library: the climb, keyed by frame (sat on the face surface) ---+ function onFace(x,dAng,sq,s){let i=0;while(i<faceC.length-2&&faceC[i][0]<x)i++;const p=faceC[i],q=faceC[Math.min(faceC.length-1,i+2)],pp=faceC[Math.max(0,i-2)];+ const ang=Math.atan2(q[1]-pp[1],q[0]-pp[0])+dAng;const sink=33*s;return{x:p[0]+Math.sin(ang)*sink,y:p[1]-Math.cos(ang)*sink,s:s,ang:ang,sq:sq};}+ const S=0.64;+ const poses={108:onFace(190,0.2,0,S),115:onFace(318,-0.02,0.26,S),119:onFace(440,-0.08,-0.22,S),124:onFace(548,-0.02,-0.08,S),131:onFace(662,0,0,0.68)};+ const onion=[108,115,119,124];+ onion.forEach((f,i)=>{const b=poses[f];boatConstruction(L.blue,b,{alpha:0.2,seed:f*3,w:1.1});drawBoat(L.blue,b,{w:2.6,alpha:0.34+i*0.02,seed:f,dbl:0.3,over:2});});+ const pk=[108,115,119,124,131].map(f=>boatPeak(poses[f]));+ dashedArc(L.blue,[[pk[0][0]-50,pk[0][1]+4]].concat(pk,[[pk[4][0]+70,pk[4][1]-90],[pk[4][0]+110,pk[4][1]-180]]),{alpha:0.95,w:1.7,seed:81,ticks:true,tickEvery:12});+ boatConstruction(L.blue,poses[131],{alpha:0.7,seed:1310,w:1.3});+ drawBoat(L.red,poses[131],{w:2.9,alpha:1,seed:131,dbl:0.6,over:2});+ const b=poses[131];const wl=(lx,ly)=>xf([[lx,ly]],b)[0];+ stroke(L.red,[wl(-80,28),wl(0,32),wl(80,26)],{w:1.6,alpha:0.8,seed:1320,smooth:true});+ stroke(L.red,[wl(84,20),wl(110,6),wl(128,-6)],{w:1.5,alpha:0.75,seed:1321,smooth:true});+ stroke(L.red,[wl(-90,32),wl(-150,40),wl(-210,40)],{w:1.4,alpha:0.6,seed:1322,smooth:true,taper:0.4});+ // circled frame numbers below each key+ [108,115,119,124,131].forEach(f=>{const b=poses[f];const kp=boatKeel(b);const cx=b.x+18,cy=Math.min(700,kp[1]+58);+ stroke(L.gray,[[b.x+6,kp[1]+10],[cx,cy-18]],{w:1,alpha:0.5,seed:f+700});+ circNum(L.gray,String(f),cx,cy,{seed:f+800,alpha:0.85,size:15});});++ // --- spacing chart under the slate ---+ const sy=182;+ write(L.gray,'SPACING · ANTIC > CLIMB · ON ONES',70,sy,15,{w:1.4,alpha:0.9,seed:1201,jit:0.2});+ const rx0=72,rx1=470,ry=252;+ stroke(L.gray,[[rx0,ry],[rx1,ry]],{w:1.4,alpha:0.85,seed:1202,jit:0.4});+ const nT=22;for(let i=0;i<=nT;i++){const u=i/nT;const e=0.5-0.5*Math.cos(Math.PI*u);const x=rx0+e*(rx1-rx0);const tall=(i%5===0)?11:6;+ stroke(L.gray,[[x,ry-tall],[x,ry+tall]],{w:1.1,alpha:0.8,seed:1210+i,jit:0.2,taper:0.25});}+ [[108,0],[115,0.3],[119,0.5],[124,0.68],[131,1]].forEach(([f,u],i)=>{const e=0.5-0.5*Math.cos(Math.PI*u);const x=rx0+e*(rx1-rx0);circNum(L.gray,String(f),x,218,{seed:1300+i,size:12,alpha:0.85});});++ // --- principle labels with arrows ---+ function label(str,x,y,size,seed){return write(L.gray,str,x,y,size,{w:1.7,alpha:0.95,seed:seed,jit:0.25});}+ label('ANTICIPATION',48,468,19,1401);+ arrow(L.gray,[[118,478],[146,522],[166,560]],{seed:1402});+ label('SQUASH',236,400,19,1403);+ arrow(L.gray,[[284,408],[300,468],[306,528]],{seed:1404});+ label('STRETCH',356,322,19,1405);+ arrow(L.gray,[[404,330],[420,400],[430,466]],{seed:1406});+ label('ARC',566,268,22,1407);+ arrow(L.gray,[[620,258],[672,252],[716,288]],{seed:1408});++ slate('STORM PEAK (WAVE)',1001);+ counter('131','ONES',true,1111);+ finish();+ stamp(1030,520,-0.13);+}++// ---------- APPROVED rubber stamp ----------+function stamp(cx,cy,rot){+ const c=mk(),g=c.getContext('2d');+ const bw=textWidth('APPROVED',50)+84,bh=128;+ g.save();g.translate(cx,cy);g.rotate(rot);g.strokeStyle='#000';g.lineJoin='round';+ function rr(x,y,w,h,r){g.beginPath();g.moveTo(x+r,y);g.lineTo(x+w-r,y);g.quadraticCurveTo(x+w,y,x+w,y+r);g.lineTo(x+w,y+h-r);g.quadraticCurveTo(x+w,y+h,x+w-r,y+h);g.lineTo(x+r,y+h);g.quadraticCurveTo(x,y+h,x,y+h-r);g.lineTo(x,y+r);g.quadraticCurveTo(x,y,x+r,y);g.closePath();}+ g.lineWidth=6;rr(-bw/2,-bh/2,bw,bh,12);g.stroke();+ g.lineWidth=2.2;rr(-bw/2+10,-bh/2+10,bw-20,bh-20,7);g.stroke();+ g.restore();+ // letters via stroke font on a temp layer, transformed+ const tl=mk();+ const big='APPROVED',bs=50;const bwid=textWidth(big,bs);+ const tmpL={getContext:()=>tl.getContext('2d')};+ // draw letters in local space then rotate by drawing onto c with transform+ const lc=mk();write(lc,big,640-bwid/2,360+6,bs,{w:7.6,alpha:1,seed:77,jit:0.15});+ const small="PENCIL TEST · SC. 12 · SEP 29 '26",ss=12;const swid=textWidth(small,ss);+ write(lc,small,640-swid/2,360+36,ss,{w:1.9,alpha:1,seed:78,jit:0.1});+ stroke(lc,[[640-bwid/2,360+15],[640+bwid/2,360+15]],{w:1.6,alpha:1,seed:79,jit:0.2});+ g.save();g.translate(cx,cy);g.rotate(rot);g.drawImage(lc,-640,-360-10);g.restore();+ // ink texture: coarse dropout noise + fine tooth+ const n=mk(),q=n.getContext('2d');const r=mulberry32(99);+ q.fillStyle='#000';q.fillRect(0,0,W,H);q.globalCompositeOperation='destination-out';+ for(let i=0;i<900;i++){const x=cx-190+r()*380,y=cy-110+r()*220,rad=1+r()*r()*7;q.globalAlpha=0.35+r()*0.6;q.beginPath();q.arc(x,y,rad,0,7);q.fill();}+ // pressure falloff on one side+ q.globalCompositeOperation='destination-out';const gr=q.createLinearGradient(cx-180,cy,cx+180,cy);gr.addColorStop(0,'rgba(0,0,0,0.35)');gr.addColorStop(0.5,'rgba(0,0,0,0)');gr.addColorStop(1,'rgba(0,0,0,0.1)');q.globalAlpha=1;q.fillStyle=gr;q.fillRect(0,0,W,H);+ g.save();g.globalCompositeOperation='destination-in';g.drawImage(n,0,0);g.restore();+ L.purple=c;composite('purple',0.9);+}++window.drawFrame=function(which){if(which==='a')frameA();else frameB();window.DONE=true;};+window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/pixel/boat.html b/assets/previews-src/pixel/boat.htmlnew file mode 100644index 0000000..c7a254c--- /dev/null+++ b/assets/previews-src/pixel/boat.html@@ -0,0 +1,332 @@+<!doctype html>+<html><head><meta charset="utf-8">+<style>html,body{margin:0;background:#000}#c{display:block;image-rendering:pixelated}</style>+</head><body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+/* THE PAPER BOAT — pixel art film style preview.+ Logical canvas 320x180, 4x nearest-neighbor upscale. Everything whole pixels.+ Deterministic: seeded hash only. */+const LW=320,LH=180;+const cv=document.getElementById('c'),G=cv.getContext('2d');+const lo=document.createElement('canvas');lo.width=LW;lo.height=LH;+const c=lo.getContext('2d');+let cf='';const fs=k=>{if(k!==cf){c.fillStyle=k;cf=k}};+const P=(x,y,k)=>{x|=0;y|=0;if(x<0||y<0||x>=LW||y>=LH)return;fs(k);c.fillRect(x,y,1,1)};+const R=(x,y,w,h,k)=>{fs(k);c.fillRect(x|0,y|0,w,h)};+function hash(a,b){let h=Math.imul(a|0,374761393)^Math.imul((b|0)+1013,668265263);h=Math.imul(h^(h>>>13),1274126177);h^=h>>>16;return(h>>>0)/4294967296}+const B4M=[[0,8,2,10],[12,4,14,6],[3,11,1,9],[15,7,13,5]];+const bay4=(x,y)=>(B4M[y&3][x&3]+0.5)/16;+const bay8=(x,y)=>(4*B4M[y&3][x&3]+B4M[(y>>2)&3][(x>>2)&3]+0.5)/64;+const clamp=(v,a,b)=>v<a?a:v>b?b:v;+// ordered-dither pick from a ramp at float position f+function rampAt(ramp,f,x,y,bay){f=clamp(f,0,ramp.length-1);const i=Math.floor(f),fr=f-i;const j=Math.min(ramp.length-1,i+1);return fr>bay(x,y)?ramp[j]:ramp[i]}++/* ============ the paper boat sprite (generated pixel grid, drawn 1px rects) ============ */+// pal={o,l,w,s,d} o outline, l highlight, w lit face, s shade face, d dark fold+// opt: hw half-width of gunwale, ph peak height, hh hull height, tip tip rise,+// light: 1 = lit from right, -1 = lit from left, shear: px lean per row (x += (y-by)*shear)+function drawBoat(bx,by,pal,opt){+ const hw=opt.hw,ph=opt.ph,hh=opt.hh,tip=opt.tip,L=opt.light,sh=opt.shear||0;+ const OX=y=>Math.round((y-by)*sh);+ // peak (sail triangle), apex at by-ph+ for(let r=0;r<ph;r++){+ const y=by-ph+r,half=Math.max(0,Math.round(r*(hw*0.62)/(ph-1)));+ const o=OX(y);+ for(let x=bx-half;x<=bx+half;x++){+ let k;+ if(x===bx-half||x===bx+half||r===0)k=pal.o;+ else if(x===bx)k=pal.d; // center fold+ else k=(x>bx)===(L>0)?pal.w:pal.s;+ P(x+o,y,k);+ }+ // highlight rim on lit edge+ if(r>0&&r<ph-1)P(bx+(L>0?half-1:-half+1)+o,y,pal.l);+ }+ // tips (the two upturned paper ends)+ for(let s=-1;s<=1;s+=2){+ const tx=bx+s*hw;+ for(let k=1;k<=tip;k++){const y=by-k;P(tx+OX(y),y,pal.o);}+ P(bx+s*(hw-1)+OX(by-1),by-1,s===L?pal.l:pal.s);+ }+ // hull (trapezoid tapering down)+ for(let r=0;r<hh;r++){+ const y=by+r,half=hw-1-Math.round(r*(hw*0.42)/(hh-1));+ const o=OX(y);+ for(let x=bx-half;x<=bx+half;x++){+ let k;+ if(x===bx-half||x===bx+half||r===hh-1)k=pal.o;+ else if(r===0)k=pal.d; // shadow under gunwale fold+ else if(r===1)k=pal.l; // gunwale highlight+ else k=r<hh-2?pal.w:pal.s;+ P(x+o,y,k);+ }+ }+ // gunwale line itself+ for(let x=bx-hw;x<=bx+hw;x++)P(x+OX(by),by,pal.o);+ for(let x=bx-hw+2;x<=bx+hw-2;x++)P(x+OX(by),by,pal.l);+}++/* =================================== FRAME A =================================== */+function frameA(){+ const HOR=112,SUNX=234,SUNY=97,SUNR=9;+ // --- sky: dithered gradient bands, dawn ramp, calm 8x8 bayer+ const SKY=['#191540','#33205a','#5d2c66','#8f3f68','#c05e60','#e5825c','#f5ab64','#ffd489'];+ for(let y=0;y<HOR;y++){+ const f=Math.pow(y/(HOR-1),1.18)*(SKY.length-1);+ for(let x=0;x<LW;x++){+ let k=rampAt(SKY,f,x,y,bay8);+ // sun + dithered halo+ const dx=x-SUNX,dy=y-SUNY,d=Math.sqrt(dx*dx+dy*dy);+ if(d<SUNR)k='#fff6cf';+ else if(d<SUNR+2)k='#ffe6a4';+ else if(d<SUNR+11){const p=1-(d-SUNR-2)/9;if(bay4(x,y)<p*0.85)k='#ffca7e';}+ else if(d<SUNR+20){const p=1-(d-SUNR-11)/9;if(bay4(x,y)<p*0.3)k='#f5a86a';}+ P(x,y,k);+ }+ }+ // --- clouds: chunky strips, lit underside toward the sun+ cloudA(58,30,52,'#4a2a60','#6e3a6e','#e08a68');+ cloudA(210,22,40,'#3c2356','#5c3168','#c8735f');+ cloudA(128,52,66,'#5c3266','#84406b','#f5a86a');+ cloudA(268,64,34,'#6e3a68','#94486a','#ffb877');+ // --- sea: dithered depth ramp+ const SEA=['#c06158','#8a4660','#5c3a66','#403060','#2c2852','#1e1e44','#141534'];+ for(let y=HOR;y<LH;y++){+ const f=Math.pow((y-HOR)/(LH-1-HOR),0.8)*(SEA.length-1);+ for(let x=0;x<LW;x++)P(x,y,rampAt(SEA,f,x,y,bay4));+ }+ // horizon glint: dithered warm dashes ON the sea's top row+ for(let x=0;x<LW;x++){if(bay4(x,HOR)<0.6)P(x,HOR,'#ffcf8e');if(bay4(x,HOR+1)<0.25)P(x,HOR+1,'#e8a878');}+ // --- ripples: seeded dashes, wider spacing lower (perspective)+ for(let row=0;row<26;row++){+ const y=HOR+2+Math.round(Math.pow(row/25,1.5)*62);+ const n=10-Math.round(row*0.25);+ for(let i=0;i<n;i++){+ const x=Math.floor(hash(row,i)*LW),w=2+Math.floor(hash(row,i+50)*4);+ const dk=hash(row,i+90)<0.5;+ const k=dk?'#191a3a':(y<HOR+18?'#a85868':'#4a3a66');+ for(let j=0;j<w;j++)P(x+j,y,k);+ }+ }+ // --- sun glitter path+ for(let y=HOR+1;y<LH-8;y++){+ const spread=3+(y-HOR)*0.55;+ const n=y<HOR+20?3:y<HOR+42?2:1;+ for(let i=0;i<n;i++){+ if(hash(y,i+7)<0.62){+ const x=SUNX+Math.round((hash(y,i+31)*2-1)*spread);+ const w=1+Math.floor(hash(y,i+61)*3);+ const k=hash(y,i+81)<0.4?'#ffe9b0':'#ffca7e';+ for(let j=0;j<w;j++)P(x+j,y,k);+ }+ }+ }+ // --- the boat: lower-left third, heading right, frozen mid-bob (1px lean)+ const BP={o:'#38222e',l:'#fff7e2',w:'#f6e3bd',s:'#d8a678',d:'#a86e52'};+ const bx=92,by=142;+ // reflection: broken cream dashes straight under the hull+ for(let i=0;i<9;i++){+ const y=by+9+i;if(hash(i,3)<0.3)continue;+ const w=Math.max(3,Math.round(16-i*1.7));const x=bx-Math.floor(w/2)+Math.round((hash(i,9)*2-1)*2);+ for(let j=0;j<w;j++)if(bay4(x+j,y)<0.55)P(x+j,y,i<3?'#e8b482':'#8a5468');+ }+ drawBoat(bx,by,BP,{hw:19,ph:13,hh:8,tip:3,light:1,shear:-0.08});+ // waterline: hull sits IN the water, a lit ripple hugging the hull+ for(let x=bx-19;x<=bx+19;x++)if(bay4(x,by+7)<0.75)P(x,by+7,'#ffdca4');+ // wake: two trailing V-lines opening left, plus sparse foam dashes+ for(let i=0;i<20;i++){+ const x=bx-20-i;+ if(i%3!==2)P(x,by+7+Math.floor(i/4),'#e8b482');+ if(i%3!==2)P(x,by+8+Math.floor(i/3),'#a86478');+ }+ for(let i=0;i<6;i++){+ const x=bx-24-Math.floor(hash(i,1)*16),y=by+8+Math.floor(hash(i,2)*4);+ P(x,y,'#e8b482');P(x+1,y,'#e8b482');+ }+ // bow water: bright cut at the front+ P(bx+20,by+6,'#fff1d0');P(bx+21,by+7,'#ffd9a0');P(bx+22,by+7,'#e8b482');+ // gulls: two tiny far specks+ P(160,44,'#2a1c4a');P(161,43,'#2a1c4a');P(162,44,'#2a1c4a');+ P(178,52,'#2a1c4a');P(179,51,'#2a1c4a');P(180,52,'#2a1c4a');+}+function cloudA(cx,cy,len,top,body,lit){+ const h=5;+ for(let r=0;r<h;r++){+ const y=cy+r;+ const half=Math.round(len/2*(r===0?0.55:r===1?0.85:r===h-1?0.9:1));+ const k=r===0?top:r===h-1?lit:body;+ for(let x=cx-half;x<=cx+half;x++)if(!(r===0&&bay4(x,y)>0.7))P(x,y,k);+ }+ // ragged puffs on top+ for(let i=0;i<5;i++){+ const x=cx-len/2+Math.floor(hash(cx+i,cy)*len),w=3+Math.floor(hash(i,cy)*5);+ for(let j=0;j<w;j++)P(x+j,cy-1,top);+ }+}++/* =================================== FRAME B =================================== */+function frameB(){+ const HOR=100;+ // --- storm sky+ const SKY=['#05060e','#0a0e1c','#12192b','#1b2538'];+ for(let y=0;y<HOR;y++){+ const f=(y/(HOR-1))*(SKY.length-1);+ for(let x=0;x<LW;x++)P(x,y,rampAt(SKY,f,x,y,bay8));+ }+ // heavy cloud masses: overlapping dithered ellipse blobs+ for(let i=0;i<10;i++){+ const cx=Math.floor(hash(i,11)*LW),cy=4+Math.floor(hash(i,12)*40);+ const rx=16+Math.floor(hash(i,13)*26),ry=4+Math.floor(hash(i,14)*5);+ for(let y=cy-ry;y<=cy+ry;y++)for(let x=cx-rx;x<=cx+rx;x++){+ const dx=(x-cx)/rx,dy=(y-cy)/ry,d=dx*dx+dy*dy;+ if(d<1){+ if(d>0.7&&bay4(x,y)>0.5)continue;+ const lit=y>cy+ry*0.4&&x<cx; // undersides toward the break catch light+ P(x,y,lit&&bay4(x,y)<0.4?'#20303e':'#060a13');+ }+ }+ }+ // --- the break in the clouds, upper-left: a ragged bright slit, not a disc+ const BX=48,BY=22;+ const BRK=['#f2f3da','#c9d2ba','#8a988e','#46565a'];+ for(let y=BY-5;y<BY+6;y++)for(let x=BX-30;x<=BX+30;x++){+ const dx=(x-BX)/(30-Math.abs(y-BY)*2.2),dy=(y-BY)/5.5,d=Math.sqrt(dx*dx+dy*dy);+ const rag=1+((hash(x>>2,3)-0.5)*0.35);+ if(d<rag)P(x,y,rampAt(BRK,d*(BRK.length-0.4),x,y,bay4));+ }+ // dark cloud lips hugging the slit so it reads as a gap in the storm+ for(let x=BX-34;x<=BX+34;x++){+ const wob=Math.floor(hash(x>>1,5)*3);+ for(let k=0;k<3+wob;k++){P(x,BY-6-k,'#04060c');P(x,BY+6+Math.floor(wob/2)-0,'#04060c');}+ }+ // god-rays: thin solid diagonal beams from the slit toward the boat's water+ for(let s=0;s<3;s++){+ const sx0=BX-13+s*13,slope=0.24+s*0.05,len=96-((s*37)%23);+ for(let i=0;i<len;i++){+ const y=BY+5+i,x=Math.round(sx0+i*slope);+ const t=i/len;+ if(t>0.45&&bay4(x,y)>0.9*(1-t))continue; // dither out at the tail+ const k=s===1?'#3e4c46':'#303e3a';+ P(x,y,k);if(s===1&&t<0.4)P(x+1,y,'#343f3c');+ }+ }+ // the lit patch of sea where the shaft lands (under the boat)+ for(let y=118;y<136;y++)for(let x=52;x<112;x++){+ const dx=(x-81)/30,dy=(y-127)/9;+ if(dx*dx+dy*dy<1&&bay4(x,y)<0.3)P(x,y,'#4c6058');+ }+ // --- sea base (left of / in front of the wave)+ const SEAB=['#13202e','#0e1926','#0a121d'];+ for(let y=HOR;y<LH;y++){+ const f=((y-HOR)/(LH-HOR))*(SEAB.length-1);+ for(let x=0;x<LW;x++)P(x,y,rampAt(SEAB,f,x,y,bay4));+ }+ // wind-torn streaks on the sea+ for(let i=0;i<26;i++){+ const y=HOR+2+Math.floor(hash(i,21)*72),x=Math.floor(hash(i,22)*LW);+ const w=3+Math.floor(hash(i,23)*8);+ for(let j=0;j<w;j++)P(x+j,y,hash(i,24)<0.5?'#2c4450':'#42606a');+ }+ // --- THE WAVE: huge sprite-styled wall, diagonal from upper right+ const WAVE=['#a4d6a2','#63aa88','#3a8378','#265c66','#193f50','#102a3c','#0a1b2b'];+ const crestY=x=>Math.round(16+(320-x)*0.33+Math.sin(x*0.06)*2.5);+ const XL=80; // leftmost wave pixel (under the curl)+ const frontX=y=>84+Math.max(0,y-112)*1.2+Math.round(Math.sin(y*0.35)*3); // forward base, wobbly+ for(let x=XL;x<LW;x++){+ const cy2=crestY(x);+ for(let y=Math.max(0,cy2);y<LH;y++){+ if(x<frontX(y))continue;+ const d=y-cy2;+ let f=Math.min(WAVE.length-1,d/9);+ // diagonal streak shading running with the slope (sprite-style banding)+ const st=((x+d*3)%23+23)%23;+ if(st<3&&d>4)f=Math.min(WAVE.length-1,f+1);+ if(st>=12&&st<14&&d>6&&f>0.8)f-=0.8;+ P(x,y,rampAt(WAVE,f,x,y,bay4));+ }+ }+ // --- the curl: crest lip hooking over toward the boat+ const CX2=112,CY2=crestY(112)+10;+ for(let y=CY2-30;y<CY2+26;y++)for(let x=CX2-34;x<=CX2+6;x++){+ const dx=x-CX2,dy=y-CY2,r=Math.sqrt(dx*dx+dy*dy*1.15);+ const a=Math.atan2(dy,dx); // -PI..PI, 0 = right+ if(r>13&&r<27&&(a<-0.15||a>2.5)){+ const dd=27-r;+ let f=Math.min(WAVE.length-1,dd/4.5);+ P(x,y,rampAt(WAVE,f,x,y,bay4));+ }+ }+ // --- foam: crest edge + chunky clumps + spray+ for(let x=XL+8;x<LW;x++){+ const cy2=crestY(x);+ for(let d=0;d<3;d++)if(bay4(x,cy2+d)<(d===0?0.95:0.5))P(x,cy2+d,d===0?'#eef6e6':'#a9cfa8');+ }+ // clumps along crest+ for(let i=0;i<30;i++){+ const x=XL+8+Math.floor(hash(i,31)*(LW-XL-8)),cy2=crestY(x);+ const w=2+Math.floor(hash(i,32)*4),h=1+Math.floor(hash(i,33)*2);+ for(let j=0;j<w;j++)for(let k=0;k<h;k++)P(x+j,cy2-k+1,hash(i+j,34)<0.7?'#f4f9ee':'#c9e2c2');+ }+ // curl lip foam+ for(let y=CY2-30;y<CY2+26;y++)for(let x=CX2-34;x<=CX2+6;x++){+ const dx=x-CX2,dy=y-CY2,r=Math.sqrt(dx*dx+dy*dy*1.15);+ const a=Math.atan2(dy,dx);+ if(r>=24&&r<27&&(a<-0.15||a>2.5)&&bay4(x,y)<0.75)P(x,y,'#eef6e6');+ if(r>=13&&r<16&&(a<-0.15||a>2.5)&&bay4(x,y)<0.4)P(x,y,'#a9cfa8');+ }+ // spray blown off the lip, wind to the left+ for(let i=0;i<46;i++){+ const t=hash(i,41);+ const x=CX2-30-Math.floor(t*38),y=CY2-14-Math.floor(hash(i,42)*22)+Math.floor(t*10);+ if(hash(i,43)<0.8)P(x,y,hash(i,44)<0.55?'#dfeadb':'#8fb4a4');+ }+ // wave-base churn: a continuous boiling foam band hiding the base line+ for(let y=103;y<LH;y++){+ const fx=Math.round(frontX(y));+ const w=7+Math.floor(hash(y,52)*9);+ for(let x=fx-Math.floor(w*0.6);x<fx+w;x++){+ const e=Math.abs(x-fx)/w;+ const p=0.95-e*0.9;+ if(hash(x,y)<p)P(x,y,hash(x+7,y)<0.6?'#dcebd8':'#79988e');+ }+ // dark boil shadow just left of the foam+ for(let k=0;k<3;k++)if(hash(y,60+k)<0.6)P(fx-Math.floor(w*0.6)-1-k,y,'#1b3340');+ }+ // foam scraps drifting left off the base toward the boat+ for(let i=0;i<16;i++){+ const y=124+Math.floor(hash(i,56)*30),x=40+Math.floor(hash(i,57)*70);+ const w=2+Math.floor(hash(i,58)*3);+ for(let j=0;j<w;j++)P(x+j,y,'#5c7a76');+ }+ // --- the boat: small, lower-left, climbing, bow up, still pointing forward+ const BP={o:'#10141e',l:'#fff8e0',w:'#e4d6b4',s:'#8e8a92',d:'#5c5a66'};+ const bx=76,by=127;+ drawBoat(bx,by,BP,{hw:12,ph:8,hh:5,tip:2,light:-1,shear:0.25});+ // white water breaking around the hull+ for(let i=0;i<20;i++){+ const x=bx-16+Math.floor(hash(i,61)*32),y=by+3+Math.floor(hash(i,62)*5);+ const w=1+Math.floor(hash(i,64)*3);+ for(let j=0;j<w;j++)P(x+j,y,hash(i,63)<0.6?'#eef6e6':'#9fbfae');+ }+ // rain: sparse diagonal ticks+ for(let i=0;i<60;i++){+ const x=Math.floor(hash(i,71)*LW),y=Math.floor(hash(i,72)*140);+ P(x,y,'#33465a');P(x+1,y+1,'#26374a');+ }+}++/* =================================== driver =================================== */+window.drawFrame=function(which){+ cf='';+ c.clearRect(0,0,LW,LH);+ if(which==='a')frameA();else frameB();+ G.imageSmoothingEnabled=false;+ G.clearRect(0,0,1280,720);+ G.drawImage(lo,0,0,1280,720);+ window.DONE=true;+};+window.READY=true;+</script>+</body></html>diff --git a/assets/previews-src/riso/boat.html b/assets/previews-src/riso/boat.htmlnew file mode 100644index 0000000..792770e--- /dev/null+++ b/assets/previews-src/riso/boat.html@@ -0,0 +1,345 @@+<!doctype html>+<meta charset="utf-8">+<style>html,body{margin:0;padding:0;background:#000}canvas{display:block}</style>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+// RISO POP: the paper boat, printed in 3 inks on cream stock.+// Separations model: every shape is painted as COVERAGE (0..1) onto one plate per ink.+// Each plate is screened with its own AM dot screen at its own angle, gets dot gain,+// is offset a couple of px (misregistration), and all inks MULTIPLY onto the paper.+// Halftone recipe informed by anidoodle (Apache-2.0): 30deg screen spacing, midtone dot gain,+// highlight dropout, misregistration lip.+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');+const W = 1280, H = 720;++function mulberry32(seed){ let a = seed>>>0; return function(){ a|=0; a=(a+0x6D2B79F5)|0;+ let t=Math.imul(a^(a>>>15),1|a); t=(t+Math.imul(t^(t>>>7),61|t))^t; return ((t^(t>>>14))>>>0)/4294967296; }; }++// ---------- inks (ONLY these; overprints make every other colour) ----------+const PAPER = [0xE6,0xDE,0xCB];+const INKS = {+ y: { rgb:[0xF4,0xC5,0x1A], angle:75, pitch:9.5, off:[0,0] }, // yellow+ p: { rgb:[0xF0,0x50,0x8C], angle:15, pitch:9.5, off:[2,-1] }, // fluorescent pink+ b: { rgb:[0x21,0x60,0xA8], angle:45, pitch:9.5, off:[-1,2] }, // blue+};+const KEYS = ['y','p','b'];++// ---------- plates ----------+const plates = {};+KEYS.forEach(k => { const c = document.createElement('canvas'); c.width=W; c.height=H;+ plates[k] = { cv:c, ctx:c.getContext('2d') }; });+function clearPlates(){ KEYS.forEach(k => { const g = plates[k].ctx; g.setTransform(1,0,0,1,0,0);+ g.globalCompositeOperation='source-over'; g.fillStyle='#000'; g.fillRect(0,0,W,H); }); }+const gray = v => { const n = Math.round(Math.max(0,Math.min(1,v))*255); return `rgb(${n},${n},${n})`; };+// paint(fn, cov, overprint): fn(g) builds path and calls g.fill()/g.stroke().+// cov: {y,p,b} each a number or (g)=>CanvasGradient. Unlisted plates are KNOCKED OUT unless overprint.+function paint(fn, cov, overprint){+ KEYS.forEach(k => {+ let v = cov[k];+ if (v === undefined){ if (overprint) return; v = 0; }+ const g = plates[k].ctx; g.save();+ const style = (typeof v === 'function') ? v(g) : gray(v);+ g.fillStyle = style; g.strokeStyle = style;+ fn(g); g.restore();+ });+}+const rgrad = (x,y,r0,r1,stops) => g => { const gr = g.createRadialGradient(x,y,r0,x,y,r1); stops.forEach(s=>gr.addColorStop(s[0],gray(s[1]))); return gr; };+const lgrad = (x0,y0,x1,y1,stops) => g => { const gr = g.createLinearGradient(x0,y0,x1,y1); stops.forEach(s=>gr.addColorStop(s[0],gray(s[1]))); return gr; };++// ---------- value noise ----------+function makeNoise(seed, cell){+ const R = mulberry32(seed); const gw = Math.ceil(W/cell)+2, gh = Math.ceil(H/cell)+2;+ const grid = new Float32Array(gw*gh); for (let i=0;i<grid.length;i++) grid[i]=R();+ return (x,y) => { const fx=x/cell, fy=y/cell, ix=Math.floor(fx), iy=Math.floor(fy);+ let tx=fx-ix, ty=fy-iy; tx=tx*tx*(3-2*tx); ty=ty*ty*(3-2*ty);+ const a=grid[iy*gw+ix], b=grid[iy*gw+ix+1], c=grid[(iy+1)*gw+ix], d=grid[(iy+1)*gw+ix+1];+ return a+(b-a)*tx+(c-a)*ty+(a-b-c+d)*tx*ty; };+}++// ---------- the press: screen, gain, offset, multiply, paper ----------+function press(seed){+ const R = mulberry32(seed);+ const cov = {}; KEYS.forEach(k => { const d = plates[k].ctx.getImageData(0,0,W,H).data;+ const a = new Float32Array(W*H); for (let i=0;i<W*H;i++) a[i]=d[i*4]/255; cov[k]=a; });+ const nLow = makeNoise(seed+1, 90), nMid = makeNoise(seed+2, 14), nFib = makeNoise(seed+3, 3.2);+ const inkMottle = { y:makeNoise(seed+11,60), p:makeNoise(seed+12,60), b:makeNoise(seed+13,60) };+ const inkGrain = { y:makeNoise(seed+21,2.1), p:makeNoise(seed+22,2.1), b:makeNoise(seed+23,2.1) };+ const img = ctx.createImageData(W,H); const out = img.data;+ const TAU = Math.PI*2;+ const sc = {}; KEYS.forEach(k => { const t = INKS[k].angle*Math.PI/180;+ sc[k] = { c:Math.cos(t)/INKS[k].pitch, s:Math.sin(t)/INKS[k].pitch }; });+ for (let y=0;y<H;y++){+ for (let x=0;x<W;x++){+ const i = y*W+x;+ const fib = nFib(x,y);+ let r=PAPER[0], g=PAPER[1], b=PAPER[2];+ for (let q=0;q<3;q++){+ const k = KEYS[q], ink = INKS[k];+ const sx = Math.min(W-1, Math.max(0, x - ink.off[0])), sy = Math.min(H-1, Math.max(0, y - ink.off[1]));+ let c = cov[k][sy*W+sx];+ if (c < 0.04) continue; // highlights drop out to bare paper+ let a;+ if (c > 0.985){ a = 1; } // solid+ else {+ c = c + 0.5*c*(1-c); // dot gain, ~+25% at 50%+ const u = x*sc[k].c + y*sc[k].s, v = -x*sc[k].s + y*sc[k].c;+ let t = (Math.cos(TAU*u) + Math.cos(TAU*v))*0.25 + 0.5; // round dots -> checker -> holes+ t += (fib-0.5)*0.16; // ragged fibre edge+ a = (t - (1 - c))/0.09 + 0.5; a = a<0?0:a>1?1:a;+ }+ if (a <= 0) continue;+ // uneven riso ink laydown: soft mottle + fine speckle, starved specks+ const m = 0.86 + 0.14*inkMottle[k](x,y);+ const gr = inkGrain[k](x,y);+ a *= m * (gr < 0.12 ? 0.45 : 0.93 + 0.07*gr);+ r *= 1 - a*(1 - ink.rgb[0]/255);+ g *= 1 - a*(1 - ink.rgb[1]/255);+ b *= 1 - a*(1 - ink.rgb[2]/255);+ }+ // paper grain: blotchy tooth + fibre+ const pg = 0.965 + 0.035*nLow(x,y) + 0.03*(nMid(x,y)-0.5) + 0.045*(fib-0.5) + (R()-0.5)*0.03;+ out[i*4]=r*pg; out[i*4+1]=g*pg; out[i*4+2]=b*pg; out[i*4+3]=255;+ }+ }+ ctx.putImageData(img,0,0);+ // a few paper flecks and a faint crease (scanned proof)+ ctx.save();+ for (let k=0;k<70;k++){ ctx.globalAlpha = 0.18 + R()*0.3; ctx.fillStyle = R()<0.5 ? '#f4efe2' : '#8c8474';+ ctx.beginPath(); ctx.ellipse(R()*W, R()*H, 0.6+R()*2.2, 0.5+R()*1.2, R()*3, 0, 7); ctx.fill(); }+ ctx.restore();+}++// ---------- shared pieces ----------+const TYPE = "'Courier New', Courier, monospace";+const SLAB = "'Arial Black', 'Helvetica Neue', Arial, sans-serif";++function regMark(x,y){ // printed in all three inks: misregistration shows as colour fringes+ paint(g => { g.lineWidth = 1.6; g.beginPath(); g.arc(x,y,13,0,7); g.moveTo(x-22,y); g.lineTo(x+22,y);+ g.moveTo(x,y-22); g.lineTo(x,y+22); g.stroke(); }, {y:1,p:1,b:1}, true);+}+function margins(){ // bare paper trim: the art is a print on a sheet+ const M=24, MB=48;+ paint(g => { g.beginPath(); g.rect(0,0,W,H); g.rect(M,M,W-2*M,H-M-MB); g.fill('evenodd'); }, {});+ regMark(32, H-24); regMark(W-32, H-24);+ paint(g => { g.lineWidth=1.2; [[M,M],[W-M,M]].forEach(([x,y])=>{ g.beginPath(); g.moveTo(x,y-18); g.lineTo(x,y-6); g.moveTo(x-18,y); g.lineTo(x-6,y); g.moveTo(x+6,y); g.lineTo(x+18,y); g.stroke(); }); }, {y:1,p:1,b:1}, true);+ slug('PROOF \u00b7 PAPER BOAT \u00b7 3 COLOUR', 66, H-18);+ swatches(1090, H-35);+}+function slug(txt, x, y){+ paint(g => { g.font = `900 12px ${SLAB}`; try{ g.letterSpacing='3px'; }catch(e){} g.fillText(txt, x, y); }, {b:1});+}+function swatches(x, y){+ paint(g => g.fillRect(x, y, 30, 22), {y:1});+ paint(g => g.fillRect(x+38, y, 30, 22), {p:1});+ paint(g => g.fillRect(x+76, y, 30, 22), {b:1});+}+// typewriter caption card: line1 plain, line2 struck through in pink+function caption(x, y, w, line1, line2, typed){+ paint(g => { g.fillRect(x+5, y+5, w, 92); }, {p:1}); // pink offset shadow+ paint(g => { g.fillRect(x, y, w, 92); }, {}); // cream card (knockout)+ paint(g => { g.lineWidth = 2; g.strokeRect(x+1, y+1, w-2, 90); }, {b:1});+ paint(g => { g.font = `bold 24px ${TYPE}`; g.fillText(line1, x+20, y+38); }, {b:1});+ paint(g => { g.font = `bold 24px ${TYPE}`; g.fillText(line2, x+20, y+74); }, {b:1});+ const g0 = plates.b.ctx; g0.font = `bold 24px ${TYPE}`;+ const tw = g0.measureText(line2).width;+ paint(g => { g.lineWidth = 3.2; g.beginPath(); g.moveTo(x+14, y+68); g.lineTo(x+26+tw, y+66); g.stroke(); }, {p:1}, true);+ if (typed){ const tw1 = g0.measureText(line2).width; // blinking typewriter cursor after the struck line+ paint(g => g.fillRect(x+30+tw1, y+54, 3, 26), {b:1}); }+}++// folded paper boat. faces get separate coverage (the light model is per-plate tint)+function boat(x, y, s, rot, faces){+ const T = g => { g.translate(x,y); g.rotate(rot); };+ const hull = g => { T(g); g.beginPath(); g.moveTo(-0.56*s,0); g.lineTo(0.56*s,0); g.lineTo(0.32*s,0.30*s); g.lineTo(-0.32*s,0.30*s); g.closePath(); g.fill(); };+ const sailL = g => { T(g); g.beginPath(); g.moveTo(-0.34*s,0.005*s); g.lineTo(0.03*s,-0.66*s); g.lineTo(0.03*s,0.005*s); g.closePath(); g.fill(); };+ const sailR = g => { T(g); g.beginPath(); g.moveTo(0.03*s,-0.66*s); g.lineTo(0.34*s,0.005*s); g.lineTo(0.03*s,0.005*s); g.closePath(); g.fill(); };+ const flaps = g => { T(g); g.beginPath(); g.moveTo(-0.56*s,0.005*s); g.lineTo(-0.43*s,-0.17*s); g.lineTo(-0.30*s,0.005*s); g.closePath();+ g.moveTo(0.30*s,0.005*s); g.lineTo(0.43*s,-0.17*s); g.lineTo(0.56*s,0.005*s); g.closePath(); g.fill(); };+ paint(hull, faces.hull); paint(flaps, faces.flaps); paint(sailL, faces.sailL); paint(sailR, faces.sailR);+ // fold lines: thin solid blue+ paint(g => { T(g); g.lineWidth = Math.max(1.4, s*0.018); g.lineJoin='round';+ g.beginPath(); g.moveTo(-0.56*s,0.005*s); g.lineTo(0.56*s,0.005*s);+ g.moveTo(0.03*s,-0.64*s); g.lineTo(0.03*s,0); g.stroke(); }, {b:1}, true);+}++// =====================================================================+// FRAME A: riso dawn. calm sea, smiley sun rising, sunburst.+// =====================================================================+function frameA(){+ clearPlates();+ const R = mulberry32(4401);+ const HZ = 418;+ // sky: yellow screen rising from the horizon, pink screen from the top+ paint(g => g.fillRect(0,0,W,HZ), {+ y: lgrad(0,HZ,0,0,[[0,0.78],[0.55,0.22],[1,0.0]]),+ p: lgrad(0,0,0,HZ,[[0,0.62],[0.5,0.22],[1,0.05]]),+ b: lgrad(0,0,0,HZ,[[0,0.10],[0.35,0.0],[1,0]]) });+ // sunburst rays from the sun (mid-century wedges), yellow overprint+ const SX = 930, SY = 300;+ for (let k=0;k<24;k+=2){+ const a0 = (k/24)*Math.PI*2, a1 = ((k+1)/24)*Math.PI*2;+ paint(g => { g.beginPath(); g.moveTo(SX,SY); g.arc(SX,SY,1400,a0,a1); g.closePath(); g.fill(); },+ { y: rgrad(SX,SY,100,700,[[0,0.62],[1,0.30]]) }, true);+ }+ // re-clean the sea area from rays+ // sea+ paint(g => g.fillRect(0,HZ,W,H-HZ), {+ b: lgrad(0,HZ,0,H,[[0,0.42],[0.35,0.62],[1,0.92]]),+ p: lgrad(0,HZ,0,H,[[0,0.18],[1,0.0]]) });+ // calm swell bands: blue screen stepping darker toward the viewer, soft wavy edges+ for (let band=0; band<6; band++){+ const y0 = HZ + 34 + band*band*9 + band*22, th = 10 + band*5;+ paint(g => { g.beginPath(); for (let x=-5;x<=W+5;x+=6) g.lineTo(x, y0 + 3*Math.sin(x*0.012+band*1.7));+ for (let x=W+5;x>=-5;x-=6) g.lineTo(x, y0 + th + 3*Math.sin(x*0.012+band*1.7+0.8)); g.closePath(); g.fill(); },+ { b: Math.min(1, 0.72 + band*0.06) }, true);+ }+ // distant scallop swell row at the horizon (solid blue)+ paint(g => { g.beginPath(); for (let x=-10;x<W+30;x+=26){ g.moveTo(x,HZ+6); g.arc(x+13,HZ+6,13,Math.PI,0); } g.fill(); }, {b:0.82});+ // sun: yellow solid disc, pink cheek-shading, blue face (overprints green)+ const SR = 88;+ paint(g => { g.beginPath(); g.arc(SX,SY,SR,0,7); g.fill(); }, {y:1});+ paint(g => { g.beginPath(); g.arc(SX,SY,SR,0,7); g.fill(); },+ { p: rgrad(SX-40,SY-45,10,SR*2.0,[[0,0],[0.45,0.08],[0.8,0.6],[1,0.85]]) }, true);+ paint(g => { g.beginPath(); g.ellipse(SX-27,SY-18,8,13,0,0,7); g.ellipse(SX+27,SY-18,8,13,0,0,7); g.fill(); }, {b:1}, true);+ paint(g => { g.lineWidth=7; g.lineCap='round'; g.beginPath(); g.arc(SX+2,SY-10,50,0.22*Math.PI,0.80*Math.PI); g.stroke(); }, {b:1}, true);+ // sun half-sunk: redraw sea over the lower sun? sun sits above horizon; add reflection column+ for (let j=0;j<8;j++){+ const yy = HZ+20+j*24+j*j*1.2, ww = 120 - j*10 + R()*24, x0 = SX-ww/2+(R()-0.5)*26;+ paint(g => { g.lineWidth = 6 + j*0.4; g.lineCap='round'; g.beginPath(); g.moveTo(x0,yy);+ for (let t=0;t<=1.001;t+=0.1) g.lineTo(x0+ww*t, yy + 2.5*Math.sin(t*9+j)); g.stroke(); }, j%3===1 ? {y:1, p:0.5} : {y:1});+ }+ // ripple dashes: solid blue and paper knockouts+ for (let k=0;k<70;k++){+ const yy = HZ+30+Math.pow(R(),0.8)*(H-HZ-40), len = 18 + (yy-HZ)*0.18*R() + 10;+ const xx = R()*W; if (Math.abs(xx-SX)<80) continue;+ const knock = R()<0.45;+ paint(g => { g.lineWidth = 2 + (yy-HZ)*0.012; g.lineCap='round'; g.beginPath(); g.moveTo(xx,yy);+ g.quadraticCurveTo(xx+len/2,yy-4,xx+len,yy); g.stroke(); }, knock ? {} : {b:1}, !knock);+ }+ // the boat, lower-left third, heading right, a little bow-up+ const BX = 350, BY = 566, BS = 150;+ // wake: paper V-lines behind, shadow beneath+ paint(g => { g.beginPath(); g.ellipse(BX+6,BY+50,98,12,0,0,7); g.fill(); }, {b:1, p:0.55});+ for (let j=0;j<4;j++){+ paint(g => { g.lineWidth = 4-j*0.6; g.lineCap='round'; g.beginPath();+ g.moveTo(BX-80-j*38, BY+36+j*6); g.quadraticCurveTo(BX-100-j*40, BY+38+j*7, BX-120-j*44, BY+44+j*9); g.stroke(); }, {});+ }+ boat(BX, BY, BS, -0.06, {+ hull:{}, flaps:{b:0.32}, sailL:{b:0.30}, sailR:{y:0.14} });+ // print furniture+ caption(60, 56, 470, 'Day 1: setting out', 'what could go wrong', true);+ margins();+ press(20260929);+}++// =====================================================================+// FRAME B: storm peak. navy overprint sky, one yellow light, halftone wave.+// =====================================================================+function surfY(x){ return 650 - 0.44*x + 34*Math.sin(x*0.0045+1.1) + 12*Math.sin(x*0.013+3.0) + 5*Math.sin(x*0.033+0.7); }+function frameB(){+ clearPlates();+ const R = mulberry32(9917);+ const LX = 470, LY = 190;+ // sky: blue + pink overprint = navy/violet; both retreat toward the one light, yellow fills the hole+ paint(g => g.fillRect(0,0,W,H), {+ b: rgrad(LX,LY,80,400,[[0,0.0],[0.25,0.3],[0.6,0.85],[1,1]]),+ p: rgrad(LX,LY,40,560,[[0,0.0],[0.25,0.55],[0.6,0.6],[1,0.78]]),+ y: rgrad(LX,LY,0,260,[[0,1],[0.45,0.8],[1,0.0]]) });+ // the light itself: a solid yellow disc with a paper core, bursting+ paint(g => { g.beginPath(); g.arc(LX,LY,62,0,7); g.fill(); }, {y:1});+ for (let k=0;k<16;k++){+ const a = k/16*Math.PI*2 + 0.2, r0 = 78, r1 = 104 + (k%2)*26;+ paint(g => { g.lineWidth = 7; g.lineCap='round'; g.beginPath(); g.moveTo(LX+Math.cos(a)*r0, LY+Math.sin(a)*r0);+ g.lineTo(LX+Math.cos(a)*r1, LY+Math.sin(a)*r1); g.stroke(); }, {y:1});+ }+ // scalloped storm clouds (flat-bottom mid-century), solid blue + pink = navy+ const cloud = (cx,cy,rs) => g => { g.beginPath(); let x=cx; rs.forEach((r,i)=>{ g.moveTo(x+r, cy); g.arc(x, cy, r, 0, Math.PI, true); x += r*1.35; });+ g.fill(); };+ paint(cloud(40, 330, [30,44,36,26]), {b:1, p:1});+ paint(cloud(350, 292, [34,52,60,44,30]), {b:1, p:1});+ paint(cloud(1080, 60, [26,38,30]), {b:1, p:1});+ // rain: thin paper-knockout slashes+ for (let k=0;k<140;k++){+ const x = R()*W, y = R()*H*0.8, xi = Math.floor(Math.min(W-1,Math.max(0,x)));+ if (y > surfY(xi) + 14 || (x > 640 && y < 330)) continue;+ const dx = x-LX, dy = y-LY; if (dx*dx+dy*dy < 170*170) continue;+ paint(g => { g.lineWidth = 1.6; g.beginPath(); g.moveTo(x,y); g.lineTo(x-7,y+22); g.stroke(); }, {});+ }+ KEYS.forEach(k => plates[k].ctx.setTransform(1,0,0,1,0,34)); // drop the wave+boat so the crest clears the trim+ // THE WAVE: face rises from lower-left, goes steep, and the lip curls back over toward the boat+ const S = surfY, XC = 700;+ const TOP = [930, 58], TIP = [690, 150];+ const outline = g => { g.beginPath(); g.moveTo(-5, H+5);+ for (let x=-5;x<=XC;x+=4) g.lineTo(x, S(x));+ g.bezierCurveTo(780, S(XC)-30, 850, 220, 870, 130); // steepening face+ g.bezierCurveTo(880, 90, 900, 60, TOP[0], TOP[1]); // up into the crest+ g.bezierCurveTo(1030, 50, 1120, 110, 1180, 170); // back of the wave+ g.lineTo(W+5, 200); g.lineTo(W+5, H+5); g.closePath(); };+ // the lip: a crescent from the crest hanging left, tip curling down+ const lip = g => { g.beginPath(); g.moveTo(TOP[0]+30, TOP[1]+4);+ g.bezierCurveTo(880, 20, 760, 30, 705, 90); // outer edge over the top+ g.bezierCurveTo(680, 115, 678, 140, TIP[0], TIP[1]); // tip+ g.bezierCurveTo(712, 120, 760, 96, 810, 100); // underside of the lip+ g.bezierCurveTo(850, 104, 868, 120, 872, 140); g.lineTo(890, 90); g.closePath(); };+ paint(g => { outline(g); g.fill(); }, {b:1});+ paint(g => { lip(g); g.fill(); }, {b:1});+ // the barrel under the lip: pink over blue = deep navy+ const barrel = g => { g.beginPath(); g.moveTo(TIP[0]+4, TIP[1]-2);+ g.bezierCurveTo(712, 124, 760, 100, 810, 104); g.bezierCurveTo(850, 108, 868, 124, 870, 146);+ g.bezierCurveTo(850, 220, 780, 260, XC+2, S(XC)+2);+ g.bezierCurveTo(690, 250, 684, 190, TIP[0]+4, TIP[1]-2); g.closePath(); };+ paint(g => { barrel(g); g.fill(); }, {b:1, p:1});+ // streaks of light inside the barrel+ for (let k=0;k<4;k++) paint(g => { barrel(g); g.clip(); g.lineWidth = 9 - k*1.5; g.beginPath();+ g.arc(820, 250, 90 + k*24, -2.3, -0.6); g.stroke(); }, {p:0.45, b:1});+ // halftone bands flowing along the face: pink screen stepping up with depth+ const clipFace = g => { outline(g); g.clip(); };+ for (let band=0; band<10; band++){+ const d0 = 26 + band*58, th = 28 + band*3.5;+ const cov = Math.min(0.9, 0.18 + band*0.085);+ paint(g => { clipFace(g); g.beginPath();+ for (let x=-5;x<=W+5;x+=4) g.lineTo(x, S(Math.min(x,XC)) + d0 + 10*Math.sin(x*0.018+band) - Math.max(0,x-XC)*0.4);+ for (let x=W+5;x>=-5;x-=4) g.lineTo(x, S(Math.min(x,XC)) + d0 + th + 10*Math.sin(x*0.018+band+0.6) - Math.max(0,x-XC)*0.4);+ g.closePath(); g.fill(); }, { p: cov }, true);+ }+ // lit edge: yellow along the face, blue/pink knocked so it reads clean+ paint(g => { g.lineWidth = 6; g.lineJoin='round'; g.lineCap='round'; g.beginPath(); for (let x=-5;x<=XC;x+=4) g.lineTo(x, S(x)+3);+ g.stroke(); }, {y:1});+ // foam band riding the lip: solid paper, then claws (paper dots) shrinking to the tip+ paint(g => { g.lineWidth = 16; g.lineCap='round'; g.beginPath(); g.moveTo(TOP[0]+60, TOP[1]+12);+ g.bezierCurveTo(880, 26, 770, 36, 712, 92); g.stroke(); }, {});+ paint(g => { g.lineWidth = 5; g.lineCap='round'; g.beginPath(); g.moveTo(TOP[0]+40, TOP[1]+24);+ g.bezierCurveTo(880, 40, 780, 50, 722, 100); g.stroke(); }, {y:1});+ const clawPts = [[706,108,11],[694,126,9],[690,146,7.5],[700,160,6],[676,150,6],[680,170,5],[694,178,4],[668,172,4],[672,190,3]];+ clawPts.forEach(c => paint(g => { g.beginPath(); g.arc(c[0],c[1],c[2],0,7); g.fill(); }, {}));+ for (let i=0;i<14;i++){ const t=i/13; const x = 720 + t*260, y = 34 - Math.sin(t*Math.PI)*16 + 40*(1-t)*0.4;+ paint(g => { g.beginPath(); g.arc(x, y - 10, 5 + 5*Math.sin(t*Math.PI), 0, 7); g.fill(); }, {}); }+ // spray flung off the crest and falling off the tip (dot matrix)+ for (let k=0;k<160;k++){+ const t = R(); let x, y, r;+ if (k < 110){ x = 700 + t*480 + (R()-0.5)*40; y = 18 + R()*50 + Math.abs(t-0.45)*40; r = 1.4 + R()*4.5; }+ else { x = 640 + R()*70; y = 170 + R()*110; r = 1.2 + R()*3; if (y > S(Math.floor(x)) - 8) continue; }+ if (y < 26) continue;+ paint(g => { g.beginPath(); g.arc(x, y, r, 0, 7); g.fill(); }, R()<0.2 ? {y:1} : {});+ }+ // foam lace riding the face+ for (let x=0;x<XC;x+=20){+ if (R()<0.35) continue; const y = S(x) + 18 + R()*6;+ paint(g => { g.beginPath(); g.arc(x, y, 3.5 + R()*4, 0, 7); g.fill(); }, {});+ }+ // the boat: small, climbing the slope, bow up, still pointing forward (toward the curl)+ const bx = 330, by = S(bx) + 10;+ const slope = (S(bx+26)-S(bx-26))/52; const rot = Math.atan(slope) - 0.10;+ paint(g => { g.translate(bx,by); g.rotate(rot); g.beginPath(); g.ellipse(-4,26,60,8,0,0,7); g.fill(); }, {b:1, p:1});+ boat(bx, by, 100, rot, { hull:{}, flaps:{b:0.35}, sailL:{y:0.5}, sailR:{b:0.30} });+ KEYS.forEach(k => plates[k].ctx.setTransform(1,0,0,1,0,0));+ caption(60, 56, 520, "You're absolutely right.", "it's just a little wave", false);+ margins();+ press(777);+}++window.drawFrame = function(which){ if (which === 'a') frameA(); else frameB(); window.DONE = true; };+window.READY = true;+</script>diff --git a/assets/previews-src/short/boat.html b/assets/previews-src/short/boat.htmlnew file mode 100644index 0000000..2066f54--- /dev/null+++ b/assets/previews-src/short/boat.html@@ -0,0 +1,437 @@+<!doctype html>+<meta charset="utf-8">+<style>html,body{margin:0;background:#000}canvas{display:block}</style>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const FH = Math.round(W / 2.39); // 536 film height (2.39:1)+const FY = Math.round((H - FH) / 2); // 92 top bar+const FB = FY + FH; // 628 film bottom+const ctx = document.getElementById('c').getContext('2d');++function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+let R = mulberry32(1);+const rr = (a,b)=>a+R()*(b-a);++function lin(x0,y0,x1,y1,stops){const g=ctx.createLinearGradient(x0,y0,x1,y1);for(const [o,c] of stops)g.addColorStop(o,c);return g}+function rad(x,y,r,stops){const g=ctx.createRadialGradient(x,y,0,x,y,r);for(const [o,c] of stops)g.addColorStop(o,c);return g}++// soft glowing dot (bloom in code)+function glow(x,y,r,col,a){+ ctx.fillStyle = rad(x,y,r,[[0,col.replace('A',a)],[0.4,col.replace('A',a*0.45)],[1,col.replace('A',0)]]);+ ctx.beginPath(); ctx.arc(x,y,r,0,7); ctx.fill();+}+// soft-shaded puff (stylized-3D cloud lobe): vertical gradient top->bottom+function puff(x,y,rx,ry,top,bot,a=1,rot=0){+ ctx.save(); ctx.globalAlpha=a; ctx.translate(x,y); ctx.rotate(rot); ctx.scale(rx,ry);+ const g=ctx.createLinearGradient(0,-1,0,1); g.addColorStop(0,top); g.addColorStop(1,bot);+ ctx.fillStyle=g; ctx.beginPath(); ctx.arc(0,0,1,0,7); ctx.fill(); ctx.restore();+}+// soft-edged elliptical blob: radial fade to transparent, optional rotation (no hard rims)+function softblob(x,y,rx,ry,col,a,rot=0){+ ctx.save(); ctx.translate(x,y); ctx.rotate(rot); ctx.scale(rx,ry);+ const g=ctx.createRadialGradient(0,0,0,0,0,1);+ g.addColorStop(0,col.replace('A',a)); g.addColorStop(0.55,col.replace('A',a*0.55)); g.addColorStop(1,col.replace('A',0));+ ctx.fillStyle=g; ctx.beginPath(); ctx.arc(0,0,1,0,7); ctx.fill(); ctx.restore();+}+// union of ellipse lobes as ONE path -> one fill, no internal edges+function lobeUnion(L){+ ctx.beginPath();+ for(const [x,y,rx,ry] of L){ ctx.moveTo(x+rx,y); ctx.ellipse(x,y,rx,ry,0,0,Math.PI*2); }+}++/* ---------- the paper boat (soft-3D shaded, no face, no limbs) ----------+ local units: hull half-width 62, hull depth 30, sail apex -54.+ pal = {litHull, shadeHull, litSail, shadeSail, rim, crease, rimW} ; light from the right when litOnRight */+function drawBoat(pal){+ // hull+ const hull = ()=>{ctx.beginPath();ctx.moveTo(-62,0);ctx.lineTo(62,0);+ ctx.quadraticCurveTo(52,24,34,30);ctx.lineTo(-34,30);ctx.quadraticCurveTo(-52,24,-62,0);ctx.closePath();};+ hull();+ ctx.fillStyle = lin(-62,0,62,0,[[0,pal.shadeHull],[0.55,pal.midHull],[1,pal.litHull]]);+ ctx.fill();+ // hull bottom occlusion (sits in water)+ hull(); ctx.save(); ctx.clip();+ ctx.fillStyle = lin(0,14,0,32,[[0,'rgba(0,0,0,0)'],[1,pal.occl]]);+ ctx.fillRect(-70,10,140,24); ctx.restore();+ // paper rim strip along the gunwale (the fold's top edge catches light)+ ctx.beginPath(); ctx.moveTo(-62,0); ctx.lineTo(62,0); ctx.lineTo(55,5.5); ctx.lineTo(-55,5.5); ctx.closePath();+ ctx.fillStyle = pal.rimStrip; ctx.fill();+ // sail: two folded faces+ ctx.beginPath(); ctx.moveTo(0,-54); ctx.lineTo(-28,0); ctx.lineTo(0,0); ctx.closePath();+ ctx.fillStyle = pal.shadeSail; ctx.fill();+ ctx.beginPath(); ctx.moveTo(0,-54); ctx.lineTo(28,0); ctx.lineTo(0,0); ctx.closePath();+ ctx.fillStyle = lin(0,-54,28,0,[[0,pal.litSail],[1,pal.litSail2]]);+ ctx.fill();+ // center crease+ ctx.strokeStyle = pal.crease; ctx.lineWidth = 1.2;+ ctx.beginPath(); ctx.moveTo(0,-52); ctx.lineTo(0,-2); ctx.stroke();+ // warm rim light on the lit edges (wide soft pass + thin bright pass)+ for (const [w,a] of [[4.5,0.28],[1.8,0.9]]){+ ctx.strokeStyle = pal.rim.replace('A',a); ctx.lineWidth=w; ctx.lineCap='round';+ ctx.beginPath(); ctx.moveTo(0,-54); ctx.lineTo(28,0); ctx.lineTo(62,0); ctx.stroke();+ }+ // faint cool edge on shadow side keeps the silhouette readable+ ctx.strokeStyle = pal.coolEdge; ctx.lineWidth=1.4;+ ctx.beginPath(); ctx.moveTo(0,-54); ctx.lineTo(-28,0); ctx.lineTo(-62,0); ctx.stroke();+}++function letterboxAndVignette(strength){+ // gentle in-code vignette inside the film area+ ctx.save(); ctx.beginPath(); ctx.rect(0,FY,W,FH); ctx.clip();+ ctx.fillStyle = rad(W/2, FY+FH*0.52, W*0.72, [[0,'rgba(0,0,0,0)'],[0.72,'rgba(0,0,0,0)'],[1,'rgba(4,6,14,'+strength+')']]);+ ctx.fillRect(0,FY,W,FH); ctx.restore();+ // cinema bars+ ctx.fillStyle='#000'; ctx.fillRect(0,0,W,FY); ctx.fillRect(0,FB,W,H-FB);+}++/* =========================== FRAME A : setting out =========================== */+function frameA(){+ R = mulberry32(101);+ ctx.clearRect(0,0,W,H);+ ctx.save(); ctx.beginPath(); ctx.rect(0,FY,W,FH); ctx.clip();++ const yh = FY + Math.round(FH*0.56); // horizon 392+ const sunX = 880, sunY = yh - 22;++ // dawn sky: night violet still up high, pink dawn low+ ctx.fillStyle = lin(0,FY,0,yh,[+ [0,'#252a52'],[0.35,'#4a4470'],[0.62,'#8f6584'],[0.82,'#d18b88'],[1,'#f8b98d']]);+ ctx.fillRect(0,FY,W,yh-FY);++ // fading stars in the high night part+ for(let i=0;i<70;i++){+ const x=rr(0,W), y=FY+rr(4,170), a=(1-(y-FY)/175)*rr(0.25,0.9);+ ctx.fillStyle='rgba(255,244,230,'+a.toFixed(3)+')';+ const s=rr(0.6,1.5); ctx.beginPath(); ctx.arc(x,y,s,0,7); ctx.fill();+ if(R()<0.12) glow(x,y,rr(4,7),'rgba(255,240,220,A)',0.35);+ }++ // sun bloom, then the risen sun+ glow(sunX,sunY,300,'rgba(255,190,120,A)',0.5);+ glow(sunX,sunY,140,'rgba(255,214,150,A)',0.7);+ ctx.fillStyle = rad(sunX,sunY,30,[[0,'#fff4d8'],[0.7,'#ffd9a0'],[1,'rgba(255,205,140,0)']]);+ ctx.beginPath(); ctx.arc(sunX,sunY,30,0,7); ctx.fill();++ // far horizon cloud streaks (flat dawn bands)+ for(let i=0;i<7;i++){+ const y=yh-rr(14,70), w=rr(120,330), x=rr(-40,W-100), h=rr(4,9);+ puff(x+w/2,y,w/2,h,'rgba(214,140,150,0.55)','rgba(255,190,150,0.65)');+ }+ // mid stylized clouds: one silhouette, one gradient, warm underlight clipped inside+ const cloud=(cx,cy,s)=>{+ const L=[[-1.5,0.15,0.9],[-0.9,-0.2,1.12],[-0.2,-0.38,1.28],[0.5,-0.3,1.18],[1.1,-0.05,1.0],[1.8,0.2,0.72]]+ .map(([dx,dy,r])=>[cx+dx*46*s, cy+dy*40*s, 52*r*s, 34*r*s]);+ lobeUnion(L);+ ctx.fillStyle=lin(0,cy-58*s,0,cy+42*s,[[0,'#877aa8'],[0.55,'#bd8f9d'],[1,'#efad98']]);+ ctx.fill();+ ctx.save(); lobeUnion(L); ctx.clip();+ ctx.fillStyle=rad(cx+34*s,cy+42*s,130*s,[[0,'rgba(255,206,160,0.7)'],[1,'rgba(255,206,160,0)']]);+ ctx.fillRect(cx-170*s,cy-95*s,340*s,160*s);+ ctx.restore();+ };+ cloud(230, FY+118, 1.15);+ cloud(560, FY+70, 0.7);+ cloud(1080, FY+150, 0.95);++ // sea+ ctx.fillStyle = lin(0,yh,0,FB,[+ [0,'#e9a487'],[0.12,'#a97d92'],[0.35,'#5f5c8c'],[0.7,'#3b4270'],[1,'#2b3157']]);+ ctx.fillRect(0,yh,W,FB-yh);+ // horizon line softly lit+ ctx.fillStyle='rgba(255,220,180,0.5)'; ctx.fillRect(0,yh-1,W,2);++ // tiny far lighthouse on the right horizon (a home to come back to)+ (function(){+ const x=1168, base=yh+1;+ ctx.fillStyle='#3a3350';+ ctx.beginPath(); ctx.moveTo(x-6,base); ctx.lineTo(x-3.5,base-26); ctx.lineTo(x+3.5,base-26); ctx.lineTo(x+6,base); ctx.closePath(); ctx.fill();+ ctx.fillRect(x-4.5,base-31,9,5);+ glow(x,base-29,16,'rgba(255,220,150,A)',0.9);+ ctx.fillStyle='#ffeebe'; ctx.beginPath(); ctx.arc(x,base-29,2.4,0,7); ctx.fill();+ })();++ // sun glitter path on the water (perspective widening dashes)+ for(let i=0;i<64;i++){+ const t=R(); const y=yh+4+t*t*(FB-yh-30);+ const spread=26+(y-yh)*0.85, len=rr(6,16)+(y-yh)*0.12;+ const x=sunX+rr(-1,1)*spread*rr(0.3,1);+ ctx.fillStyle='rgba(255,'+Math.round(rr(200,230))+','+Math.round(rr(150,185))+','+rr(0.25,0.7).toFixed(2)+')';+ ctx.fillRect(x-len/2,y,len,rr(1.2,2.6));+ }+ // gentle ripple bands+ for(let i=0;i<46;i++){+ const t=R(); const y=yh+8+t*t*(FB-yh-12);+ const x=rr(-40,W), len=rr(40,150)+(y-yh)*0.5;+ ctx.strokeStyle='rgba(20,22,52,'+rr(0.05,0.14).toFixed(2)+')';+ ctx.lineWidth=rr(1,2.4); ctx.beginPath();+ ctx.moveTo(x,y); ctx.quadraticCurveTo(x+len/2, y+rr(-3,3), x+len, y); ctx.stroke();+ }++ // ---- the boat, lower-left third, heading right into the light ----+ const bx=386, by=506, sc=1.42, rot=-0.05;+ // reflection (broken slices)+ ctx.save(); ctx.translate(bx,by+16); ctx.scale(sc,-sc*0.42); ctx.globalAlpha=0.20;+ for(let s=0;s<6;s++){+ ctx.save(); ctx.beginPath(); ctx.rect(-80,-60+s*16,160,11); ctx.clip();+ ctx.translate(rr(-4,4),0);+ drawBoat({litHull:'#ffd9ae',midHull:'#e7b9a8',shadeHull:'#8f7f9d',occl:'rgba(30,25,60,0.4)',+ rimStrip:'#ffe9c8',litSail:'#fff1d4',litSail2:'#ffd7a8',shadeSail:'#a493b2',+ crease:'rgba(120,100,140,0.5)',rim:'rgba(255,225,170,A)',coolEdge:'rgba(90,80,130,0.5)'});+ ctx.restore();+ }+ ctx.restore();+ // contact shadow+ ctx.fillStyle=rad(bx,by+40,110,[[0,'rgba(18,16,48,0.5)'],[1,'rgba(18,16,48,0)']]);+ ctx.save(); ctx.translate(bx,by+40); ctx.scale(1,0.22); ctx.beginPath(); ctx.arc(0,0,110,0,7); ctx.fill(); ctx.restore();+ // wake: a soft widening band fading behind (to the left)+ ctx.save();+ ctx.fillStyle = lin(bx-40,0,bx-250,0,[[0,'rgba(255,238,216,0.30)'],[0.5,'rgba(255,238,216,0.12)'],[1,'rgba(255,238,216,0)']]);+ ctx.beginPath(); ctx.moveTo(bx-46,by+30);+ ctx.quadraticCurveTo(bx-140,by+22, bx-250,by+18);+ ctx.lineTo(bx-250,by+52); ctx.quadraticCurveTo(bx-140,by+48, bx-46,by+40);+ ctx.closePath(); ctx.fill();+ ctx.restore();+ for(let i=0;i<30;i++){ // foam speckles in the wake+ const t=R(), x=bx-52-t*190, y=by+34+rr(-7,9)*(0.5+t);+ ctx.fillStyle='rgba(255,240,220,'+(0.5*(1-t)).toFixed(2)+')';+ ctx.beginPath(); ctx.arc(x,y,rr(0.7,2.2),0,7); ctx.fill();+ }+ // a couple of faint flat ripples just ahead of the bow+ ctx.strokeStyle='rgba(255,236,214,0.22)'; ctx.lineWidth=1.6; ctx.lineCap='round';+ for(const [dx,w] of [[105,42],[140,30]]){+ ctx.beginPath(); ctx.moveTo(bx+dx,by+42);+ ctx.quadraticCurveTo(bx+dx+w/2,by+38, bx+dx+w,by+42); ctx.stroke();+ }+ // the boat itself+ ctx.save(); ctx.translate(bx,by); ctx.rotate(rot); ctx.scale(sc,sc);+ drawBoat({litHull:'#ffe3ba',midHull:'#f2cdb4',shadeHull:'#9c8bab',occl:'rgba(40,32,70,0.45)',+ rimStrip:'#fff3d9',litSail:'#fff8e6',litSail2:'#ffdfae',shadeSail:'#b3a3c2',+ crease:'rgba(130,110,150,0.55)',rim:'rgba(255,214,150,A)',coolEdge:'rgba(105,95,145,0.6)'});+ ctx.restore();++ // soft warm grade drifting from the sun corner+ ctx.fillStyle = rad(sunX,sunY,700,[[0,'rgba(255,180,110,0.10)'],[1,'rgba(255,180,110,0)']]);+ ctx.fillRect(0,FY,W,FH);+ ctx.restore();+ letterboxAndVignette(0.5);+}++/* =========================== FRAME B : the storm peak =========================== */+function frameB(){+ R = mulberry32(202);+ ctx.clearRect(0,0,W,H);+ ctx.save(); ctx.beginPath(); ctx.rect(0,FY,W,FH); ctx.clip();++ // storm sky, grey-green, very dark+ ctx.fillStyle = lin(0,FY,0,FB,[[0,'#0d1416'],[0.45,'#1e2e2d'],[1,'#0c1413']]);+ ctx.fillRect(0,FY,W,FH);++ // heavy cloud ceiling: a few big masses, each ONE union path + one gradient+ const mass=(cx,cy,s,n,lo)=>{+ const L=[]; for(let i=0;i<n;i++)+ L.push([cx+rr(-1.8,1.8)*60*s, cy+rr(-0.5,0.45)*44*s, rr(0.7,1.3)*62*s, rr(0.5,0.85)*44*s]);+ lobeUnion(L);+ ctx.fillStyle=lin(0,cy-62*s,0,cy+56*s,[[0,'#101a1c'],[1,lo||'#3a4e47']]);+ ctx.fill(); return L;+ };+ const mL = mass(140, FY+50, 1.35, 8);+ const mN = mass(450, FY+30, 1.25, 8);+ mass(780, FY+45, 1.55, 9);+ mass(1140, FY+70, 1.45, 9);+ mass(950, FY+15, 1.3, 7);+ mass(620, FY+128, 0.85, 6, '#2c3d38');+ mass(60, FY+150, 0.7, 5, '#2c3d38');+ // seal the very top so masses merge into one ceiling+ ctx.fillStyle=lin(0,FY,0,FY+95,[[0,'#0c1517'],[0.5,'rgba(12,21,23,0.7)'],[1,'rgba(12,21,23,0)']]);+ ctx.fillRect(0,FY,W,95);++ // the break in the clouds, upper-left: one light fighting through+ const LX=320, LY=FY+62;+ ctx.save(); ctx.globalCompositeOperation='lighter';+ glow(LX,LY,220,'rgba(238,222,176,A)',0.45);+ glow(LX,LY,95,'rgba(250,240,205,A)',0.8);+ ctx.restore();+ // cloud edges catching the light, clipped inside the masses+ for(const L of [mL,mN]){+ ctx.save(); lobeUnion(L); ctx.clip();+ ctx.fillStyle=rad(LX,LY+20,190,[[0,'rgba(238,224,180,0.5)'],[1,'rgba(238,224,180,0)']]);+ ctx.fillRect(LX-220,LY-120,440,260); ctx.restore();+ }++ // dark open sea+ ctx.fillStyle = lin(0,FY+290,0,FB,[[0,'#1a2928'],[1,'#0a1211']]);+ ctx.fillRect(0,FY+290,W,FB-(FY+290));++ // volumetric shaft: layered wedges, each fading out before it lands+ ctx.save(); ctx.globalCompositeOperation='lighter';+ const shaft=(hw0,xb0,xb1,a)=>{+ ctx.fillStyle = lin(0,LY,0,585,[[0,'rgba(238,222,170,'+a+')'],[0.55,'rgba(238,222,170,'+(a*0.55)+')'],[1,'rgba(238,222,170,0)']]);+ ctx.beginPath(); ctx.moveTo(LX-hw0,LY-14); ctx.lineTo(LX+hw0,LY-14);+ ctx.lineTo(xb1,585); ctx.lineTo(xb0,585); ctx.closePath(); ctx.fill();+ };+ shaft(56, 120, 600, 0.07);+ shaft(34, 180, 520, 0.09);+ shaft(14, 250, 440, 0.12);+ ctx.restore();++ // ---- the big diagonal wave: a wall from upper right ----+ const CP = t => [1280-890*t, 138+242*Math.pow(t,1.3)]; // crest param, (1280,138)->(390,380)+ const crestPath=()=>{ctx.moveTo(1310,134);+ for(let t=0;t<=1.001;t+=0.05){const [x,y]=CP(Math.min(t,1)); ctx.lineTo(x,y);}};+ const waveBody=()=>{ctx.beginPath(); crestPath(); ctx.lineTo(298,FB+10); ctx.lineTo(1310,FB+10); ctx.closePath();};+ waveBody();+ ctx.fillStyle = lin(950,170,380,FB,[[0,'#3f6a5c'],[0.3,'#2b4a42'],[0.62,'#16261f'.replace('f','f')],[1,'#0b1312']]);+ ctx.fill();++ // perpendicular to the crest, pointing down the visible face+ const perp = t=>{const e=0.01,[x0,y0]=CP(t),[x1,y1]=CP(Math.min(t+e,1));+ const dx=x1-x0,dy=y1-y0,l=Math.hypot(dx,dy)||1; return [dy/l,-dx/l];};++ ctx.save(); waveBody(); ctx.clip();+ // backlit translucency where the light grazes the thin crest water+ ctx.globalCompositeOperation='lighter';+ ctx.fillStyle = rad(700,276,300,[[0,'rgba(105,185,150,0.34)'],[1,'rgba(105,185,150,0)']]);+ ctx.fillRect(300,140,900,430);+ ctx.globalCompositeOperation='source-over';+ // deep-water weight, soft-edged (no rims)+ softblob(980,500,430,180,'rgba(3,9,8,A)',0.55,-0.35);+ softblob(600,540,360,150,'rgba(3,9,8,A)',0.5,-0.4);+ // foam lace sliding down the face, elongated along the slope+ for(let i=0;i<48;i++){+ const t=rr(0.05,0.96); const [x0,y0]=CP(t); const [px,py]=perp(t);+ const d=rr(18,130);+ softblob(x0+px*d+rr(-8,8), y0+py*d, rr(26,80), rr(2.5,6),+ 'rgba(165,205,184,A)', rr(0.1,0.26), Math.atan2(py,px));+ }+ // scattered foam flecks on the face+ for(let i=0;i<40;i++){+ const t=rr(0.1,0.95); const [x0,y0]=CP(t); const [px,py]=perp(t);+ const d=rr(20,150);+ softblob(x0+px*d, y0+py*d, rr(2,6), rr(1.5,4), 'rgba(180,215,195,A)', rr(0.12,0.3));+ }+ ctx.restore();++ // soft shadow tucked under the crest (kept off the boat's corner)+ for(let i=0;i<30;i++){+ const t=rr(0,0.84); const [x0,y0]=CP(t); const [px,py]=perp(t);+ softblob(x0+px*rr(10,26), y0+py*rr(10,26), rr(16,34), rr(6,12), 'rgba(10,22,18,A)', 0.4);+ }+ // turbulent foam crest: thin in the distance, heavy where it breaks near the boat+ for(let k=0;k<27;k++){+ const t=Math.min(Math.max(k/26+rr(-0.015,0.015),0),1);+ const [x0,y0]=CP(t);+ const m=0.5+1.35*t*t;+ const L=[]; const n=4+Math.round(3*t);+ for(let i=0;i<n;i++){+ const s=rr(5,12)*m;+ L.push([x0+rr(-30,20)*(0.55+0.6*t), y0+rr(-13,8)*(0.55+0.7*t), s*rr(1.2,2.0), s]);+ }+ lobeUnion(L);+ const lit=0.45+0.55*t; // brighter toward the beam side (left, near the boat)+ ctx.fillStyle=lin(0,y0-24,0,y0+18,[+ [0,'rgba(243,249,244,'+(0.72+0.26*lit).toFixed(2)+')'],+ [1,'rgba('+Math.round(120+30*lit)+','+Math.round(150+28*lit)+','+Math.round(138+26*lit)+',0.85)']]);+ ctx.fill();+ }+ // the lip curling over and pouring down toward the boat+ for(let i=0;i<26;i++){ // overhang beyond the crest end+ const [xe,ye]=CP(1);+ const reach=rr(0,85), sag=reach*rr(0.15,0.45);+ const w=rr(8,20)*(1-reach/170);+ puff(xe-reach, ye+sag-rr(0,10), w*rr(1.2,1.9), w,+ 'rgba(240,247,242,'+rr(0.55,0.9).toFixed(2)+')','rgba(150,178,164,'+rr(0.4,0.7).toFixed(2)+')');+ }+ for(let i=0;i<46;i++){ // cascade falling to the base of the wall (soft mist column)+ const t=rr(0.82,1.0); const [x0,y0]=CP(t);+ const drop=rr(6,200)*Math.pow((t-0.8)/0.2,1.2);+ const w=rr(8,22)*(1-drop/340);+ if(drop<40)+ puff(x0-rr(0,30)-drop*0.22, y0+drop, w*rr(1.2,1.8), w,+ 'rgba(236,245,239,'+rr(0.5,0.85).toFixed(2)+')','rgba(140,168,155,'+rr(0.35,0.6).toFixed(2)+')');+ else+ softblob(x0-rr(0,30)-drop*0.22, y0+drop, w*1.8, w*1.1,+ 'rgba(226,240,232,A)', rr(0.3,0.6));+ }+ for(let i=0;i<22;i++){ // falling streaks inside the cascade+ const t=rr(0.88,1.0); const [x0,y0]=CP(t);+ ctx.strokeStyle='rgba(220,236,228,'+rr(0.15,0.4).toFixed(2)+')'; ctx.lineWidth=rr(1,2.2); ctx.lineCap='round';+ const sx=x0-rr(0,40), l=rr(30,110);+ ctx.beginPath(); ctx.moveTo(sx,y0+rr(0,60));+ ctx.quadraticCurveTo(sx-8,y0+60+l*0.5, sx-l*0.25,y0+60+l); ctx.stroke();+ }+ // spray blown off the crest, streaming up-left with the wind+ for(let i=0;i<60;i++){+ const t=R(); const [x0,y0]=CP(t);+ const dx=rr(18,110), dy=rr(-42,-4);+ ctx.strokeStyle='rgba(232,242,236,'+rr(0.08,0.3).toFixed(2)+')'; ctx.lineWidth=rr(0.7,1.5);+ ctx.beginPath(); ctx.moveTo(x0+rr(-8,8),y0-rr(2,12));+ ctx.quadraticCurveTo(x0-dx*0.5,y0+dy*0.7-8, x0-dx,y0+dy); ctx.stroke();+ }+ // spray mist drifting off the crest+ for(let i=0;i<46;i++){+ const t=R(); const [x0,y0]=CP(t);+ softblob(x0-rr(10,90), y0-rr(6,44), rr(3,10), rr(2,6), 'rgba(230,242,236,A)', rr(0.08,0.28));+ }+ // whitewater churning where the wall meets the sea, just behind the boat+ for(let i=0;i<44;i++)+ softblob(rr(300,455), rr(488,592), rr(12,36), rr(7,18), 'rgba(208,228,218,A)', rr(0.25,0.6));+ for(let i=0;i<16;i++)+ puff(rr(310,430), rr(498,572), rr(5,13), rr(4,9),'rgba(232,245,238,0.9)','rgba(130,158,146,0.7)');++ // chop + whitecaps on the near sea (lower left)+ for(let i=0;i<44;i++){+ const y=rr(495,FB-4), x=rr(-20,420);+ ctx.strokeStyle='rgba(180,208,196,'+rr(0.06,0.22).toFixed(2)+')'; ctx.lineWidth=rr(1,2.6);+ ctx.beginPath(); ctx.moveTo(x,y); ctx.quadraticCurveTo(x+rr(18,46),y-rr(2,8),x+rr(56,100),y); ctx.stroke();+ }++ // pool of beam light on the water around the boat+ const bx=286, by=512, sc=0.9, rot=-0.2;+ ctx.save(); ctx.globalCompositeOperation='lighter';+ ctx.fillStyle=rad(bx+8,by+16,150,[[0,'rgba(242,224,168,0.3)'],[0.5,'rgba(242,224,168,0.12)'],[1,'rgba(242,224,168,0)']]);+ ctx.save(); ctx.translate(bx+8,by+16); ctx.scale(1,0.4); ctx.beginPath(); ctx.arc(0,0,150,0,7); ctx.fill(); ctx.restore();+ ctx.restore();++ // ---- the boat: small, climbing, bow still pointing forward ----+ ctx.fillStyle=rad(bx,by+22,64,[[0,'rgba(0,0,0,0.55)'],[1,'rgba(0,0,0,0)']]);+ ctx.save(); ctx.translate(bx,by+22); ctx.scale(1,0.24); ctx.beginPath(); ctx.arc(0,0,64,0,7); ctx.fill(); ctx.restore();+ // splash burst at the bow+ for(let i=0;i<30;i++){+ const a=rr(-2.7,-0.5), r=rr(6,36);+ const x=bx+44*Math.cos(rot)+Math.cos(a)*r, y=by+14+Math.sin(a)*r*0.8;+ ctx.fillStyle='rgba(228,242,234,'+rr(0.25,0.65).toFixed(2)+')';+ ctx.beginPath(); ctx.arc(x,y,rr(0.8,2.6),0,7); ctx.fill();+ }+ ctx.save(); ctx.translate(bx,by); ctx.rotate(rot); ctx.scale(sc,sc);+ drawBoat({litHull:'#fdf5da',midHull:'#d9d9c3',shadeHull:'#5a6a68',occl:'rgba(6,12,12,0.5)',+ rimStrip:'#fff8de',litSail:'#fffae6',litSail2:'#e8e4c8',shadeSail:'#6b7b76',+ crease:'rgba(55,70,68,0.6)',rim:'rgba(255,238,180,A)',coolEdge:'rgba(160,185,175,0.55)'});+ ctx.restore();+ // the beam kissing the sail+ ctx.save(); ctx.globalCompositeOperation='lighter';+ glow(bx+4,by-28,48,'rgba(250,232,175,A)',0.34);+ ctx.restore();++ // driving rain, angled with the wind (from the right)+ ctx.strokeStyle='rgba(196,212,206,1)';+ for(let i=0;i<140;i++){+ const x=rr(-40,W+40), y=rr(FY,FB), l=rr(24,62);+ ctx.globalAlpha=rr(0.04,0.11); ctx.lineWidth=rr(0.7,1.3);+ ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x-l*0.34,y+l); ctx.stroke();+ }+ ctx.globalAlpha=1;++ // cold grade, corners pushed down so the lit boat owns the eye+ ctx.fillStyle = lin(0,FY,0,FB,[[0,'rgba(8,16,18,0.28)'],[0.5,'rgba(0,0,0,0)'],[1,'rgba(4,9,9,0.34)']]);+ ctx.fillRect(0,FY,W,FH);+ ctx.fillStyle = lin(W,0,W*0.45,0,[[0,'rgba(5,10,10,0.28)'],[1,'rgba(5,10,10,0)']]);+ ctx.fillRect(0,FY,W,FH);+ ctx.restore();+ letterboxAndVignette(0.7);+}++window.drawFrame = w => { (w==='a'?frameA:frameB)(); window.DONE = true; };+window.READY = true;+</script>diff --git a/assets/previews-src/sketch/boat.html b/assets/previews-src/sketch/boat.htmlnew file mode 100644index 0000000..c505914--- /dev/null+++ b/assets/previews-src/sketch/boat.html@@ -0,0 +1,393 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>sketchbook boat</title>+<style>html,body{margin:0;padding:0;background:#888}#c{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+// ---------- deterministic rng ----------+function mulberry32(seed){let a=seed>>>0;return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}+function noise1(seed){const r=mulberry32(seed);const v=[];for(let i=0;i<128;i++)v.push(r()*2-1);+ return t=>{const i=Math.floor(t),f=t-i,a=v[((i%128)+128)%128],b=v[(((i+1)%128)+128)%128],u=f*f*(3-2*f);return a+(b-a)*u;};}++const cv=document.getElementById('c'),ctx=cv.getContext('2d');++// ---------- paper grain tile ----------+const grain=document.createElement('canvas');grain.width=grain.height=256;+{const g=grain.getContext('2d'),img=g.createImageData(256,256),r=mulberry32(77);+ for(let i=0;i<img.data.length;i+=4){const n=225+r()*30;img.data[i]=img.data[i+1]=img.data[i+2]=n;img.data[i+3]=255;}+ g.putImageData(img,0,0);+ // sparse fibers+ g.strokeStyle='rgba(120,110,95,0.35)';const fr=mulberry32(78);+ for(let i=0;i<60;i++){g.beginPath();const x=fr()*256,y=fr()*256,a=fr()*Math.PI;g.moveTo(x,y);g.lineTo(x+Math.cos(a)*(2+fr()*4),y+Math.sin(a)*(2+fr()*4));g.lineWidth=0.5;g.stroke();}}++// ---------- stroke engine: centreline + width profile + jitter seed ----------+function resample(pts,step){+ // catmull-rom through pts, then arc-length resample+ const out=[];const P=pts;+ if(P.length<2)return P.slice();+ const cr=[];const get=i=>P[Math.max(0,Math.min(P.length-1,i))];+ for(let i=0;i<P.length-1;i++){+ const p0=get(i-1),p1=get(i),p2=get(i+1),p3=get(i+2);+ const seg=Math.max(2,Math.ceil(Math.hypot(p2[0]-p1[0],p2[1]-p1[1])/6));+ for(let j=0;j<seg;j++){const t=j/seg,t2=t*t,t3=t2*t;+ cr.push([0.5*((2*p1[0])+(-p0[0]+p2[0])*t+(2*p0[0]-5*p1[0]+4*p2[0]-p3[0])*t2+(-p0[0]+3*p1[0]-3*p2[0]+p3[0])*t3),+ 0.5*((2*p1[1])+(-p0[1]+p2[1])*t+(2*p0[1]-5*p1[1]+4*p2[1]-p3[1])*t2+(-p0[1]+3*p1[1]-3*p2[1]+p3[1])*t3)]);}}+ cr.push(P[P.length-1].slice());+ let acc=0;out.push(cr[0]);+ for(let i=1;i<cr.length;i++){acc+=Math.hypot(cr[i][0]-cr[i-1][0],cr[i][1]-cr[i-1][1]);+ if(acc>=step){out.push(cr[i]);acc=0;}}+ if(out.length<2)out.push(cr[cr.length-1]);+ return out;}++// tools+const TOOLS={+ pen: {ink:'#232830',alpha:0.88,w:1.7,jit:1.1,pvar:0.25},+ penSoft:{ink:'#2a3038',alpha:0.55,w:1.5,jit:1.3,pvar:0.35},+ pencil: {ink:'#3a3e45',alpha:0.34,w:2.2,jit:1.8,pvar:0.5},+ charcoal:{ink:'#26241f',alpha:0.16,w:26,jit:4,pvar:0.6}};++function stroke(pts,opt){+ const tool=TOOLS[opt.tool||'pen'];+ const seed=opt.seed||1;+ const cut=opt.cut===undefined?1:opt.cut; // fraction of centreline drawn (still arriving)+ const w=(opt.w!==undefined?opt.w:tool.w);+ const alpha=(opt.alpha!==undefined?opt.alpha:tool.alpha);+ const jit=(opt.jit!==undefined?opt.jit:tool.jit);+ const taper=opt.taper===undefined?0.12:opt.taper;+ const nx=noise1(seed*7919+1),ny=noise1(seed*7919+2),nw=noise1(seed*7919+3),na=noise1(seed*7919+4);+ let rp=resample(pts,3);+ const nTot=rp.length;+ const nDraw=Math.max(2,Math.floor(nTot*cut));+ ctx.save();+ ctx.lineCap='round';ctx.lineJoin='round';+ ctx.strokeStyle=(opt.ink||tool.ink);+ ctx.globalCompositeOperation=opt.comp||'source-over';+ for(let i=0;i<nDraw-1;i++){+ const t=i/(nTot-1);+ const f=t/cut; // progress along the drawn part+ // width profile: taper both ends; if stroke is cut, sharp taper at the moving tip+ let prof=Math.min(1,t/taper||1,cut<1?Math.max(0.05,(cut-t)/0.06):(1-t)/taper);+ prof=Math.max(0.05,Math.min(1,prof));+ const jx=nx(t*14)*jit,jy=ny(t*14)*jit;+ const jx2=nx((t+1/(nTot-1))*14)*jit,jy2=ny((t+1/(nTot-1))*14)*jit;+ ctx.beginPath();+ ctx.moveTo(rp[i][0]+jx,rp[i][1]+jy);+ ctx.lineTo(rp[i+1][0]+jx2,rp[i+1][1]+jy2);+ ctx.lineWidth=Math.max(0.3,w*Math.pow(prof,0.6)*(1-tool.pvar/2+tool.pvar*(0.5+0.5*nw(t*9))));+ ctx.globalAlpha=alpha*(0.72+0.28*(0.5+0.5*na(t*11)))*(opt.fade?1-t*opt.fade:1);+ ctx.stroke();}+ ctx.restore();}++// dashed / lifted line: several sub-strokes with gaps+function brokenLine(pts,opt){+ const r=mulberry32((opt.seed||1)*31+5);+ const rp=resample(pts,3);const n=rp.length;+ let i=0,s=opt.seed||1;+ while(i<n-2){+ const len=Math.floor(n*(0.12+r()*0.3));+ const j=Math.min(n-1,i+len);+ stroke(rp.slice(i,j+1),Object.assign({},opt,{seed:s++}));+ i=j+Math.floor(n*(0.015+r()*0.05));}}++// ---------- hatching ----------+function polyPath(poly){ctx.beginPath();ctx.moveTo(poly[0][0],poly[0][1]);for(let i=1;i<poly.length;i++)ctx.lineTo(poly[i][0],poly[i][1]);ctx.closePath();}+function hatch(poly,angle,spacing,opt){+ opt=opt||{};+ const r=mulberry32((opt.seed||1)*101+9);+ ctx.save();+ polyPath(poly);ctx.clip();+ if(opt.exclude){ctx.beginPath();ctx.rect(-10,-10,1300,740);exPath(opt.exclude);ctx.clip('evenodd');}+ const xs=poly.map(p=>p[0]),ys=poly.map(p=>p[1]);+ const cx=(Math.min(...xs)+Math.max(...xs))/2,cy=(Math.min(...ys)+Math.max(...ys))/2;+ const diag=Math.hypot(Math.max(...xs)-Math.min(...xs),Math.max(...ys)-Math.min(...ys))/2+30;+ let d=-diag,k=0;+ while(d<diag){+ const a=angle+(r()-0.5)*0.06;+ const dx=Math.cos(a),dy=Math.sin(a),nxv=-dy,nyv=dx;+ const ox=cx+nxv*d,oy=cy+nyv*d;+ const L=diag*(0.85+r()*0.3);+ stroke([[ox-dx*L,oy-dy*L],[ox+dx*L,oy+dy*L]],+ {tool:opt.tool||'pen',w:opt.w,alpha:opt.alpha,jit:opt.jit===undefined?1.6:opt.jit,seed:(opt.seed||1)*503+k,taper:0.03});+ d+=spacing*(0.75+r()*0.5);k++;}+ ctx.restore();}++// evenodd exclusion blob path appender+function exPath(blob){ctx.moveTo(blob[0][0],blob[0][1]);for(let i=1;i<blob.length;i++)ctx.lineTo(blob[i][0],blob[i][1]);ctx.closePath();}+function blobPts(cx,cy,rx,ry,seed){const n=noise1(seed);const out=[];for(let i=0;i<26;i++){const a=i/26*Math.PI*2;const k=1+0.22*n(i*0.9);out.push([cx+Math.cos(a)*rx*k,cy+Math.sin(a)*ry*k]);}return out;}++// ---------- wash (single accent) ----------+function wash(cx,cy,rx,ry,color,alpha,seed){+ const b=blobPts(cx,cy,rx,ry,seed);+ ctx.save();ctx.globalCompositeOperation='multiply';+ polyPath(b);ctx.globalAlpha=alpha;ctx.fillStyle=color;ctx.fill();+ // pooled rim+ ctx.globalAlpha=alpha*0.45;ctx.lineWidth=1.2;ctx.strokeStyle=color;polyPath(b);ctx.stroke();+ // second uneven lobe+ const b2=blobPts(cx+rx*0.15,cy+ry*0.1,rx*0.6,ry*0.6,seed+3);+ polyPath(b2);ctx.globalAlpha=alpha*0.5;ctx.fill();+ ctx.restore();}++// ---------- handwritten single-stroke letters ----------+const O=(cx,cy,r,open)=>{const p=[];const a0=-2.2,a1=a0+(open?5.7:6.28);for(let i=0;i<=10;i++){const a=a0+(a1-a0)*i/10;p.push([cx+Math.cos(a)*r,cy+Math.sin(a)*r]);}return p;};+const GLYPH={+ a:{w:0.55,s:[O(0.25,0.77,0.2,1),[[0.45,0.57],[0.46,1.0]]]},+ d:{w:0.55,s:[O(0.25,0.77,0.2,1),[[0.45,0.05],[0.46,1.0]]]},+ e:{w:0.5,s:[[[0.08,0.76],[0.4,0.72],[0.37,0.56],[0.18,0.53],[0.07,0.68],[0.1,0.9],[0.3,1.0],[0.44,0.92]]]},+ f:{w:0.5,s:[[[0.42,0.1],[0.28,0.04],[0.2,0.2],[0.2,1.0]],[[0.05,0.5],[0.4,0.5]]]},+ g:{w:0.55,s:[O(0.25,0.75,0.2,1),[[0.45,0.55],[0.45,1.12],[0.32,1.28],[0.1,1.2]]]},+ h:{w:0.52,s:[[[0.1,0.05],[0.1,1.0]],[[0.1,0.68],[0.22,0.53],[0.38,0.56],[0.42,1.0]]]},+ i:{w:0.32,s:[[[0.18,0.55],[0.2,1.0]],[[0.17,0.36],[0.2,0.39]]]},+ l:{w:0.34,s:[[[0.18,0.05],[0.2,0.88],[0.3,1.0]]]},+ m:{w:0.62,s:[[[0.06,0.55],[0.06,1.0]],[[0.06,0.66],[0.15,0.53],[0.24,0.58],[0.25,1.0]],[[0.25,0.66],[0.34,0.53],[0.44,0.58],[0.46,1.0]]]},+ n:{w:0.52,s:[[[0.1,0.55],[0.1,1.0]],[[0.1,0.66],[0.22,0.53],[0.38,0.57],[0.4,1.0]]]},+ o:{w:0.52,s:[O(0.25,0.77,0.21,1)]},+ r:{w:0.45,s:[[[0.12,0.55],[0.12,1.0]],[[0.12,0.7],[0.22,0.55],[0.38,0.53]]]},+ s:{w:0.48,s:[[[0.4,0.6],[0.22,0.53],[0.1,0.62],[0.22,0.74],[0.36,0.82],[0.34,0.96],[0.09,0.95]]]},+ t:{w:0.46,s:[[[0.22,0.2],[0.22,0.85],[0.3,1.0],[0.42,0.93]],[[0.06,0.5],[0.4,0.5]]]},+ '.':{w:0.28,s:[[[0.13,0.97],[0.16,1.0]]]},+ ' ':{w:0.42,s:[]}};+function writeText(text,x,y,size,opt){+ opt=opt||{};let cx=x;let k=0;+ const slant=opt.slant||0.06;const r=mulberry32((opt.seed||1)*17+3);+ for(const ch of text){+ const g=GLYPH[ch];if(!g){cx+=size*0.4;continue;}+ const jx=(r()-0.5)*size*0.06,jy=(r()-0.5)*size*0.08;+ for(const st of g.s){+ const pts=st.map(p=>[cx+jx+(p[0]-slant*(p[1]-1))*size,y+jy+(p[1]-1)*size]);+ stroke(pts,{tool:opt.tool||'pen',w:opt.w||1.4,alpha:opt.alpha,jit:0.7,seed:(opt.seed||1)*97+k,taper:0.15});k++;}+ cx+=g.w*size*(0.96+r()*0.1);}+ return cx;}++// ---------- paper ----------+function paper(){+ ctx.save();ctx.setTransform(1,0,0,1,0,0);ctx.globalCompositeOperation='source-over';ctx.globalAlpha=1;+ ctx.fillStyle='#f5f1e6';ctx.fillRect(0,0,1280,720);+ ctx.restore();}+function grainOver(){+ ctx.save();ctx.setTransform(1,0,0,1,0,0);+ ctx.globalCompositeOperation='multiply';ctx.globalAlpha=0.5;+ const pat=ctx.createPattern(grain,'repeat');ctx.fillStyle=pat;ctx.fillRect(0,0,1280,720);+ ctx.restore();}++// ---------- boat geometry (paper boat: hull + sail peak, no face/limbs) ----------+function boatPts(cx,cy,s,tilt){+ // returns named polylines in world coords; s = half width+ const c=Math.cos(tilt),sn=Math.sin(tilt);+ const T=p=>[cx+p[0]*c*s-p[1]*sn*s,cy+p[0]*sn*s+p[1]*c*s];+ return {+ gunwale:[[-1,0],[1,0]].map(T), // top edge of hull+ hullL:[[-1,0],[-0.55,0.42]].map(T),+ hullR:[[1,0],[0.55,0.42]].map(T),+ hullB:[[-0.55,0.42],[0.55,0.42]].map(T),+ peakL:[[-0.02,-0.78],[-0.5,0]].map(T),+ peakR:[[-0.02,-0.78],[0.52,0]].map(T),+ fold:[[-0.02,-0.78],[0.1,0]].map(T),+ bowTick:[[0.78,-0.1],[1,0],[0.9,0.14]].map(T)};}++// ============================================================+window.drawFrame=function(which){+ ctx.setTransform(1,0,0,1,0,0);ctx.globalAlpha=1;ctx.globalCompositeOperation='source-over';+ ctx.clearRect(0,0,1280,720);+ if(which==='a')frameA();else frameB();+ // flatten: fill paper behind any semi-transparent (erased) pixels+ ctx.save();ctx.setTransform(1,0,0,1,0,0);ctx.globalAlpha=1;+ ctx.globalCompositeOperation='destination-over';ctx.fillStyle='#f5f1e6';ctx.fillRect(0,0,1280,720);+ ctx.restore();+ window.DONE=true;};++// ---------------- FRAME A : setting out ----------------+function frameA(){+ paper();+ const HZ=418; // horizon+ // --- pencil construction, faint, left visible ---+ stroke([[40,HZ+1],[1240,HZ-3]],{tool:'pencil',alpha:0.16,seed:11}); // horizon guide+ stroke([[955,190],[955,330]],{tool:'pencil',alpha:0.13,seed:12}); // sun drop line+ // boat construction box + centreline+ stroke([[300,468],[520,462]],{tool:'pencil',alpha:0.2,seed:13});+ stroke([[300,468],[300,590]],{tool:'pencil',alpha:0.16,seed:14});+ stroke([[520,462],[520,585]],{tool:'pencil',alpha:0.16,seed:15});+ stroke([[406,585],[402,452]],{tool:'pencil',alpha:0.18,seed:16});++ // --- the single accent wash: pale morning ochre ---+ wash(950,268,145,85,'#e3c37c',0.17,24); // sun halo+ wash(660,436,720,24,'#e8cd8f',0.11,22); // light band on horizon+ wash(930,520,55,85,'#e3c37c',0.10,23); // reflection streak++ // --- sun: paper left bright inside a pen circle, few rays ---+ brokenLine(O(950,268,40,1).map(p=>p),{tool:'pen',w:1.5,alpha:0.7,seed:31});+ for(let i=0;i<7;i++){const a=-0.5+i*0.32;const r1=50,r2=60+(i%2)*8;+ stroke([[950+Math.cos(a)*r1,268+Math.sin(a)*r1],[950+Math.cos(a)*r2,268+Math.sin(a)*r2]],{tool:'pen',w:1.3,alpha:0.55,seed:32+i});}++ // --- horizon: pen, with lifts ---+ brokenLine([[60,HZ],[500,HZ-2],[900,HZ+1],[1230,HZ-2]],{tool:'pen',w:1.6,alpha:0.8,seed:41});++ // --- minimal sky hatching: two thin cloud bands ---+ hatch([[120,330],[430,318],[470,342],[150,352]],-0.03,7,{tool:'penSoft',w:1.2,alpha:0.4,seed:51});+ hatch([[620,300],[860,292],[880,312],[640,316]],-0.02,8,{tool:'penSoft',w:1.1,alpha:0.32,seed:52});++ // --- water: sparse horizontal ticks, denser near horizon and under sun ---+ const wr=mulberry32(61);+ for(let i=0;i<64;i++){+ const y=HZ+8+Math.pow(wr(),1.6)*270;+ let x=80+wr()*1050;const len=24+wr()*90;+ const nearRef=Math.abs(x+len/2-935)<90&&y<560?0.5:0;+ stroke([[x,y],[x+len,y+(wr()-0.5)*3]],{tool:'pen',w:1.2,alpha:0.3+nearRef+0.25*(1-(y-HZ)/300),seed:600+i,taper:0.2});}++ // --- the boat, HALF-DRAWN: some strokes still arriving ---+ const B=boatPts(408,528,105,-0.05);+ stroke(B.gunwale,{tool:'pen',w:2.1,alpha:0.9,seed:71});+ stroke(B.hullL,{tool:'pen',w:2.0,alpha:0.9,seed:72});+ stroke(B.hullR,{tool:'pen',w:2.0,alpha:0.88,seed:73});+ stroke(B.hullB,{tool:'pen',w:2.0,alpha:0.88,seed:74,cut:0.72}); // bottom edge still arriving+ stroke(B.peakL,{tool:'pen',w:2.0,alpha:0.9,seed:75});+ stroke(B.peakR,{tool:'pen',w:2.0,alpha:0.9,seed:76,cut:0.55}); // sail edge mid-stroke+ stroke(B.fold,{tool:'pencil',alpha:0.3,seed:77,cut:0.8}); // fold line, pencil+ // hull shadow: a few light hatch ticks on the left face only+ hatch([[B.gunwale[0][0]+4,B.gunwale[0][1]+6],[B.hullL[1][0]+6,B.hullL[1][1]-2],[B.hullL[1][0]+52,B.hullL[1][1]-2],[B.gunwale[0][0]+46,B.gunwale[0][1]+6]],1.0,7,{tool:'penSoft',w:1.1,alpha:0.3,seed:78});+ // waterline + wake, partial+ stroke([[300,578],[420,584],[528,578]],{tool:'pen',w:1.5,alpha:0.55,seed:79});+ stroke([[298,592],[248,598],[203,596]],{tool:'pen',w:1.3,alpha:0.45,seed:80,cut:0.65}); // wake arriving+ // reflection hatch under boat+ hatch([[340,596],[495,594],[485,634],[352,638]],0.02,10,{tool:'penSoft',w:1.0,alpha:0.26,seed:81});++ // --- margin notes ---+ writeText('first light',78,92,30,{seed:91,w:1.5,alpha:0.75});+ stroke([[78,104],[212,102]],{tool:'pen',w:1.2,alpha:0.5,seed:92}); // underline+ writeText('finish the sail',878,652,24,{seed:93,w:1.4,alpha:0.7});+ // small arrow from note toward the unfinished sail edge, kept clear of the hull+ stroke([[870,646],[660,632],[478,432]],{tool:'pen',w:1.2,alpha:0.5,seed:94,taper:0.05});+ stroke([[478,432],[472,452]],{tool:'pen',w:1.2,alpha:0.5,seed:95});+ stroke([[478,432],[456,436]],{tool:'pen',w:1.2,alpha:0.5,seed:96});++ grainOver();}++// ---------------- FRAME B : the storm peak ----------------+function frameB(){+ paper();+ // boat placement + protected bare patch of untouched paper+ const bx=375,by=488;+ const halo=blobPts(bx,by-10,120,95,201);++ // crest curve of the big diagonal wave (from upper right down toward the boat)+ const crest=[[1300,95],[1060,140],[860,215],[690,315],[585,405],[545,455]];+ // regions+ const sky=[[0,0],[1280,0],[1300,95],[1060,140],[860,215],[690,315],[585,405],[545,455],[300,455],[0,420]];+ const waveFace=[[1300,95],[1060,140],[860,215],[690,315],[585,405],[545,455],[560,540],[780,650],[1280,690],[1300,300]];+ const foreSea=[[0,420],[300,455],[545,455],[560,540],[780,650],[1280,690],[1280,720],[0,720]];++ // --- pencil construction arcs, buried but present ---+ stroke([[1240,130],[820,250],[600,420]],{tool:'pencil',alpha:0.25,seed:210});+ stroke([[40,428],[520,458]],{tool:'pencil',alpha:0.2,seed:211});++ // --- charcoal masses (side of the stick), boat patch excluded ---+ const ch=(poly,passes,seedBase,alpha,w)=>{+ ctx.save();polyPath(poly);ctx.clip();+ ctx.beginPath();ctx.rect(-10,-10,1300,740);exPath(halo);ctx.clip('evenodd');+ for(let i=0;i<passes.length;i++)stroke(passes[i],{tool:'charcoal',alpha:alpha,w:w||36,seed:seedBase+i});+ ctx.restore();};+ // sky clouds: broken heavy drags, heavier at the top+ {const drags=[];const r=mulberry32(220);+ for(let i=0;i<11;i++){const y=16+i*30+r()*20;const x0=-40+r()*300;+ drags.push([[x0,y+r()*22],[x0+300+r()*220,y-14+r()*30],[x0+700+r()*250,y+r()*24],[x0+1100,y-8+r()*20]]);}+ ch(sky,drags,230,0.1,44);+ const drags2=[];for(let i=0;i<6;i++){const y=6+i*18+r()*10;drags2.push([[-40,y+r()*8],[600+r()*300,y+r()*16],[1320,y-4]]);}+ ch([[0,0],[1280,0],[1280,150],[0,130]],drags2,247,0.14,40);}+ // wave face: drags following the flow (this is the darkest mass)+ {const drags=[];const r=mulberry32(240);+ for(let i=0;i<9;i++){const o=14+i*34;+ drags.push(crest.map(p=>[p[0]+o*0.35+r()*10,p[1]+o+r()*10]));}+ ch(waveFace,drags,260,0.13,46);}++ // --- cross-hatching: sky, kept a step lighter than the wave ---+ hatch(sky,-0.3,10,{tool:'pen',w:1.4,alpha:0.42,seed:261,exclude:halo});+ hatch(sky,1.08,13,{tool:'pen',w:1.2,alpha:0.32,seed:262,exclude:halo});+ hatch([[0,0],[1280,0],[1280,110],[0,95]],0.32,6,{tool:'pen',w:1.4,alpha:0.5,seed:263,exclude:halo}); // top of frame darkest++ // --- wave face: dense furious hatching along the flow + two cross passes ---+ {ctx.save();polyPath(waveFace);ctx.clip();+ ctx.beginPath();ctx.rect(-10,-10,1300,740);exPath(halo);ctx.clip('evenodd');+ const r=mulberry32(270);+ // short flow strokes scattered on the face, following the local slope (no concentric shell)+ for(let i=0;i<150;i++){+ const t=r()*0.92;const idx=t*(crest.length-1);const i0=Math.floor(idx);const f=idx-i0;+ const p0=crest[i0],p1=crest[Math.min(i0+1,crest.length-1)];+ const x=p0[0]+(p1[0]-p0[0])*f+r()*60,y=p0[1]+(p1[1]-p0[1])*f+10+r()*230;+ const tx=p1[0]-p0[0],ty=p1[1]-p0[1];const L=Math.hypot(tx,ty)||1;+ const dl=40+r()*110;+ stroke([[x,y],[x+tx/L*dl*0.5+r()*14,y+ty/L*dl*0.5+dl*0.28],[x+tx/L*dl,y+ty/L*dl+dl*0.5]],+ {tool:'pen',w:1.8,alpha:0.55,seed:2700+i,taper:0.06});}+ ctx.restore();}+ hatch(waveFace,-1.0,7.5,{tool:'pen',w:1.5,alpha:0.55,seed:281,exclude:halo});+ hatch(waveFace,0.15,9,{tool:'pen',w:1.3,alpha:0.4,seed:283,exclude:halo});+ hatch([[690,315],[585,405],[545,455],[560,540],[780,650],[950,540],[840,390]],0.5,4.5,{tool:'pen',w:1.7,alpha:0.6,seed:282,exclude:halo}); // extra darkness by the boat++ // --- crest contour: one confident dark line ---+ stroke(crest,{tool:'pen',w:3.2,alpha:0.85,seed:285});++ // --- foreground sea: lighter chop, so the page has a floor ---+ hatch(foreSea,0.12,12,{tool:'pen',w:1.4,alpha:0.4,seed:291,exclude:halo});+ hatch(foreSea,-0.5,17,{tool:'pen',w:1.2,alpha:0.3,seed:292,exclude:halo});++ // --- foam on the crest: scribble loops, paper showing through (never on the boat patch) ---+ {ctx.save();ctx.beginPath();ctx.rect(0,0,1280,720);exPath(halo);ctx.clip('evenodd');+ const r=mulberry32(300);+ for(let i=0;i<24;i++){const t=i/24;const idx=t*(crest.length-1);const i0=Math.floor(idx);const f=idx-i0;+ const p0=crest[Math.min(i0,crest.length-1)],p1=crest[Math.min(i0+1,crest.length-1)];+ const x=p0[0]+(p1[0]-p0[0])*f+(r()-0.5)*18,y=p0[1]+(p1[1]-p0[1])*f-6-r()*14;+ const pts=[];let a=r()*6.28;+ for(let j=0;j<9;j++){a+=0.9+r()*0.7;const rad=5+r()*9;pts.push([x+Math.cos(a)*rad+j*3,y+Math.sin(a)*rad*0.7]);}+ stroke(pts,{tool:'pen',w:1.3,alpha:0.6,seed:3000+i});}+ // heavy foam boiling at the breaking tip, right above the boat+ for(let i=0;i<20;i++){const x=545+r()*130,y=385+r()*80;+ const pts=[];let a=r()*6.28;+ for(let j=0;j<11;j++){a+=0.85+r()*0.7;const rad=6+r()*11;pts.push([x+Math.cos(a)*rad+j*2.5,y+Math.sin(a)*rad*0.75]);}+ stroke(pts,{tool:'pen',w:1.4,alpha:0.65,seed:3300+i});}+ // spray flying off the lip, blown toward the boat+ for(let i=0;i<22;i++){const x=560+r()*460,y=160+r()*220;+ stroke([[x,y],[x-18-r()*30,y+6+r()*14]],{tool:'pen',w:1.1,alpha:0.45,seed:3100+i,taper:0.3});}+ ctx.restore();}++ // --- the light fighting through: kneaded-eraser lift (streaky, grey residue stays) ---+ {const r=mulberry32(320);+ for(let i=0;i<12;i++){const o=(i-6)*16+(r()-0.5)*10;+ const p=[[150+o,-20],[235+o*0.85,160],[315+o*0.7,330]];+ stroke(p,{comp:'destination-out',w:6+r()*6,alpha:0.16+r()*0.12,jit:1.2,seed:3200+i,taper:0.25,ink:'#000',tool:'pen'});}+ // cloud edge re-cut where the shaft breaks through+ stroke([[85,55],[160,28],[248,44]],{tool:'pen',w:1.6,alpha:0.5,seed:330});}++ // --- the boat: small, dark, confident, climbing, pointing forward ---+ const B=boatPts(bx,by,54,-0.18);+ for(const[k,seed,wd]of[['gunwale',341,2.6],['hullL',342,2.4],['hullR',343,2.4],['hullB',344,2.4],['peakL',345,2.4],['peakR',346,2.4]])+ stroke(B[k],{tool:'pen',w:wd,alpha:1,seed:seed});+ stroke(B.fold,{tool:'pen',w:1.3,alpha:0.5,seed:347});+ hatch([[B.gunwale[0][0]+3,B.gunwale[0][1]+4],[B.hullL[1][0]+4,B.hullL[1][1]-2],[B.hullL[1][0]+30,B.hullL[1][1]-2],[B.gunwale[0][0]+26,B.gunwale[0][1]+4]],1.0,4.5,{tool:'pen',w:1.1,alpha:0.5,seed:348});+ // water grabbing at the hull inside the bare patch+ stroke([[bx-72,by+30],[bx-20,by+40],[bx+45,by+28],[bx+74,by+36]],{tool:'pen',w:1.7,alpha:0.75,seed:349});+ stroke([[bx-58,by+46],[bx-6,by+52],[bx+42,by+44]],{tool:'pen',w:1.3,alpha:0.5,seed:350,cut:0.8});+ stroke([[bx-95,by+18],[bx-60,by+24]],{tool:'pen',w:1.2,alpha:0.4,seed:351});+ stroke([[bx+55,by+52],[bx+95,by+46]],{tool:'pen',w:1.2,alpha:0.4,seed:352});+ // rough the halo edge so the bare patch reads as protected paper, not a sticker+ {const r=mulberry32(355);+ for(let i=0;i<30;i++){const a=r()*6.28;const rx=120*1.12,ry=95*1.12;+ const x=bx+Math.cos(a)*rx*(0.92+r()*0.2),y=by-10+Math.sin(a)*ry*(0.92+r()*0.2);+ const dl=8+r()*16,da=a+1.57+(r()-0.5)*0.8;+ stroke([[x,y],[x+Math.cos(da)*dl,y+Math.sin(da)*dl]],{tool:'pen',w:1.2,alpha:0.35,seed:3550+i,taper:0.3});}}++ // --- margin note: urgent scrawl on a scrap of calmer paper ---+ {ctx.save();ctx.globalCompositeOperation='destination-out';ctx.globalAlpha=0.75;+ polyPath(blobPts(160,668,120,34,371));ctx.fillStyle='#000';ctx.fill();ctx.restore();}+ writeText('hold on.',72,668,34,{seed:361,w:1.9,alpha:0.9,slant:0.12});+ stroke([[70,682],[248,678]],{tool:'pen',w:1.6,alpha:0.7,seed:362});+ stroke([[74,690],[240,687]],{tool:'pen',w:1.4,alpha:0.6,seed:363});++ grainOver();}++window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/snap.mjs b/assets/previews-src/snap.mjsnew file mode 100644index 0000000..50840b7--- /dev/null+++ b/assets/previews-src/snap.mjs@@ -0,0 +1,17 @@+// Renders frames a+b from a boat.html (see BOAT-BRIEF.md). Usage:+// NODE_PATH=<dir containing node_modules with playwright-core>/node_modules node ../snap.mjs boat.html+import { chromium } from 'playwright-core';+import path from 'node:path';+const file = process.argv[2] || 'boat.html';+const b = await chromium.launch({ channel: 'chrome', headless: true, args: ['--allow-file-access-from-files'] });+const p = await b.newPage({ viewport: { width: 1280, height: 720 } });+p.on('pageerror', e => console.log('PAGEERR', e.message));+p.on('console', m => { if (m.type() === 'error') console.log('CONSOLE', m.text()); });+await p.goto('file://' + path.resolve(file));+await p.waitForFunction(() => window.READY, null, { timeout: 20000 });+for (const which of ['a', 'b']) {+ await p.evaluate(async (w) => { window.DONE = false; const r = window.drawFrame(w); if (r && r.then) await r; }, which);+ await p.waitForFunction(() => window.DONE !== false, null, { timeout: 60000 }).catch(() => {});+ await p.locator('#c').screenshot({ path: `${which}.png` });+}+await b.close(); console.log('wrote a.png b.png');diff --git a/assets/previews-src/teach/boat.html b/assets/previews-src/teach/boat.htmlnew file mode 100644index 0000000..fbdf6db--- /dev/null+++ b/assets/previews-src/teach/boat.html@@ -0,0 +1,509 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<style>html,body{margin:0;padding:0;background:#000;overflow:hidden}#c{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script type="module">+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';++// ---------- deterministic PRNG ----------+function mulberry32(seed){return function(){let t=seed+=0x6D2B79F5;t=Math.imul(t^t>>>15,t|1);t^=t+Math.imul(t^t>>>7,t|61);return((t^t>>>14)>>>0)/4294967296;}}++const W=1280,H=720;+const cv=document.getElementById('c');+const ctx=cv.getContext('2d');++// offscreen WebGL canvas+const glc=document.createElement('canvas');glc.width=W;glc.height=H;+const renderer=new THREE.WebGLRenderer({canvas:glc,antialias:true,alpha:true,preserveDrawingBuffer:true});+renderer.setPixelRatio(1);renderer.setSize(W,H,false);+renderer.outputColorSpace=THREE.SRGBColorSpace;+renderer.toneMapping=THREE.ACESFilmicToneMapping;+renderer.toneMappingExposure=1.1;++const ORANGE='#ff8a1e', ORANGE_DIM='rgba(255,138,30,', GREEN='#8aff3c';++// ---------- sea height fields ----------+function seaHA(x,z){+ return 0.10*Math.sin(x*0.32+z*0.44)+0.07*Math.sin(x*0.83-z*0.31+1.7)+0.05*Math.sin(x*0.13+z*0.9+4.0);+}+// storm: choppy base + one huge diagonal ridge (wall of water from upper right)+function ridgeB(x,z){+ // ridge crest crosses the view: through (16,-16), direction (-1,-0.55) — a wall ahead,+ // taller toward the right (upper-right on screen), sloping down to the left+ const px=x-15, pz=z+14;+ const L=Math.hypot(1,0.55);+ const dx=-1/L, dz=-0.55/L;+ const nx=-dz, nz=dx;+ const d=px*nx+pz*nz; // signed distance to ridge line+ const along=px*dx+pz*dz; // negative toward the right+ const ramp=Math.min(1,Math.max(0,(along+30)/50));+ const hmax=14.5*(1-0.55*ramp);+ const h=hmax*Math.exp(-(d*d)/(2*6.3*6.3));+ return {h:h, hmax:hmax, d:d, ramp:ramp};+}+function seaHB(x,z){+ const chop=0.45*Math.sin(x*0.5+z*0.6)+0.35*Math.sin(x*0.9-z*0.4+2.2)+0.3*Math.sin(x*0.23+z*1.1+0.7);+ return chop+ridgeB(x,z).h;+}++// ---------- paper boat geometry ----------+function paperBoat(){+ const g=new THREE.Group();+ const rim=0.55, bow=1.35, stern=-1.35, side=0.48, keelF=0.62, keelB=-0.62;+ const A=[keelB,0,0], B=[keelF,0,0];+ const P1=[bow,rim,0], P2=[stern,rim,0], S1=[0,rim,side], S2=[0,rim,-side];+ const tris=[+ [A,B,S1],[B,A,S2],+ [B,P1,S1],[P1,B,S2],+ [A,S1,P2],[P2,S2,A],+ ];+ const pos=[];+ for(const t of tris){for(const v of t){pos.push(v[0],v[1],v[2]);}}+ const hull=new THREE.BufferGeometry();+ hull.setAttribute('position',new THREE.Float32BufferAttribute(pos,3));+ hull.computeVertexNormals();+ const paper=new THREE.MeshStandardMaterial({color:0xf4f1ea,roughness:0.62,metalness:0.0,side:THREE.DoubleSide,flatShading:true});+ g.add(new THREE.Mesh(hull,paper));+ // central sail peak (folded triangle)+ const sail=new THREE.BufferGeometry();+ const sp=[ 0.62,rim,0.02, -0.62,rim,0.02, 0,1.55,0.02,+ -0.62,rim,-0.02, 0.62,rim,-0.02, 0,1.55,-0.02];+ sail.setAttribute('position',new THREE.Float32BufferAttribute(sp,3));+ sail.computeVertexNormals();+ const paper2=new THREE.MeshStandardMaterial({color:0xfbf8f2,roughness:0.6,metalness:0.0,side:THREE.DoubleSide,flatShading:true});+ g.add(new THREE.Mesh(sail,paper2));+ // slight inner shadow rim line+ return g;+}++// ---------- route curve ----------+function routeCurve(which){+ if(which==='a'){+ return new THREE.CatmullRomCurve3([+ new THREE.Vector3(-5.8,0.55,4.8),+ new THREE.Vector3(-1.0,0.5,-4.0),+ new THREE.Vector3(6.0,0.5,-18.0),+ new THREE.Vector3(11.5,0.5,-40.0),+ new THREE.Vector3(14.0,0.5,-70.0),+ ]);+ }+ // storm: route bends toward and up the face of the wave, hovering above the sea+ const raw=[[-6.6,5.2],[-3.0,1.0],[1.5,-4.0],[5.5,-8.5],[9.0,-12.0]];+ const pts=raw.map(([x,z])=>new THREE.Vector3(x,seaHB(x,z)+1.05,z));+ return new THREE.CatmullRomCurve3(pts);+}++// ---------- scene builder ----------+function buildScene(which){+ const scene=new THREE.Scene();+ const rnd=mulberry32(which==='a'?1234:7777);+ const fogCol=which==='a'?new THREE.Color('#b58d64'):new THREE.Color('#171c22');+ scene.fog=new THREE.Fog(fogCol, which==='a'?40:26, which==='a'?95:70);++ const camera=new THREE.PerspectiveCamera(42,W/H,0.1,300);+ if(which==='a'){+ camera.position.set(0,3.4,21);+ camera.lookAt(3.5,1.2,-32);+ }else{+ camera.position.set(-1,2.2,21);+ camera.lookAt(4.0,6.5,-20);+ }++ // lights+ if(which==='a'){+ renderer.toneMappingExposure=1.1;+ scene.add(new THREE.HemisphereLight(0xb9c2cf,0x22262b,0.85));+ const sun=new THREE.DirectionalLight(0xffc27d,2.6);+ sun.position.set(26,7,-46); // low morning sun ahead-right+ scene.add(sun);+ const fill=new THREE.DirectionalLight(0xe8e4da,0.85); // lift the camera-facing side of the boat+ fill.position.set(-12,9,34); scene.add(fill);+ const kiss=new THREE.PointLight(0xffc9a0,9,10,1.9); // dawn warmth on the paper+ kiss.position.set(-3.2,1.6,3.6); scene.add(kiss);+ }else{+ renderer.toneMappingExposure=1.35;+ scene.add(new THREE.HemisphereLight(0x6c7f94,0x11141a,0.9));+ const gap=new THREE.DirectionalLight(0xffb072,3.0); // one light fighting through, upper left+ gap.position.set(-22,26,4);+ gap.target.position.set(-6,1,5); scene.add(gap); scene.add(gap.target);+ const cool=new THREE.DirectionalLight(0x4a6a8c,1.2);+ cool.position.set(24,10,10); scene.add(cool);+ const rim=new THREE.DirectionalLight(0xffc9a0,1.5); // rim on the crest, from behind the wave+ rim.position.set(18,16,-42); scene.add(rim);+ }++ // ---------- instanced voxel sea ----------+ const NX=110, NZ=100, SP=1.06;+ const X0=-58, Z0=12;+ const count=NX*NZ;+ const geo=new THREE.BoxGeometry(0.97,1,0.97);+ const mat=new THREE.MeshStandardMaterial({color:0xffffff,roughness:which==='a'?0.42:0.5,metalness:0.18,flatShading:true});+ const sea=new THREE.InstancedMesh(geo,mat,count);+ const m=new THREE.Matrix4();+ const col=new THREE.Color();+ const seaH=which==='a'?seaHA:seaHB;+ const curve=routeCurve(which);+ const routePts=curve.getPoints(220);+ let i=0;+ for(let iz=0;iz<NZ;iz++){+ for(let ix=0;ix<NX;ix++){+ const x=X0+ix*SP, z=Z0-iz*SP;+ const h=seaH(x,z);+ const depth=2.2; // block body below the surface+ const top=h;+ const hgt=depth+h+ (which==='b'?0.001:0);+ m.makeScale(1,Math.max(0.25,hgt),1);+ m.setPosition(x, top-hgt/2, z);+ sea.setMatrixAt(i,m);+ // graphite base with variation+ let r=0.145+rnd()*0.03, g2=0.16+rnd()*0.03, b2=0.185+rnd()*0.035;+ if(which==='b'){+ // dark slate-blue water+ r=0.085+rnd()*0.025; g2=0.11+rnd()*0.03; b2=0.15+rnd()*0.035;+ const rg=ridgeB(x,z);+ const rel=rg.h/rg.hmax;+ // foam near the crest (relative to local ridge height)+ if(rel>0.7&&rg.h>3){const f=Math.min(1,(rel-0.7)/0.18); r+=f*0.75; g2+=f*0.77; b2+=f*0.78;}+ else if(rel>0.4&&rg.h>1.5){const f=(rel-0.4)/0.3; r+=f*0.07; g2+=f*0.1; b2+=f*0.15;}+ }+ // orange route glow bleeding into nearby cells+ let dmin=1e9;+ for(let k=0;k<routePts.length;k+=6){+ const rp=routePts[k];+ const dd=(rp.x-x)*(rp.x-x)+(rp.z-z)*(rp.z-z);+ if(dd<dmin)dmin=dd;+ }+ if(dmin<8){const f=Math.exp(-dmin/3.2)*0.85; r+=f*0.85; g2+=f*0.3; b2+=f*0.02;}+ col.setRGB(Math.min(1,r),Math.min(1,g2),Math.min(1,b2));+ sea.setColorAt(i,col);+ i++;+ }+ }+ sea.instanceMatrix.needsUpdate=true;+ if(sea.instanceColor)sea.instanceColor.needsUpdate=true;+ scene.add(sea);++ // ---------- glowing route line ----------+ const tube=new THREE.Mesh(+ new THREE.TubeGeometry(curve,120,0.09,8,false),+ new THREE.MeshBasicMaterial({color:0xff8a1e})+ );+ scene.add(tube);+ const tubeGlow=new THREE.Mesh(+ new THREE.TubeGeometry(curve,120,0.26,8,false),+ new THREE.MeshBasicMaterial({color:0xff7a10,transparent:true,opacity:0.22,blending:THREE.AdditiveBlending,depthWrite:false})+ );+ scene.add(tubeGlow);+ // route waypoint dots+ const wpGeo=new THREE.SphereGeometry(0.17,10,10);+ const wpMat=new THREE.MeshBasicMaterial({color:0xffb45e});+ const wpN=which==='a'?5:4;+ for(let k=1;k<=wpN;k++){+ const p=curve.getPoint(k/(wpN+0.4));+ const s=new THREE.Mesh(wpGeo,wpMat);s.position.copy(p);s.position.y+=0.05;scene.add(s);+ }++ // ---------- the boat ----------+ const boat=paperBoat();+ let boatPos, crestPos=null;+ if(which==='a'){+ boatPos=new THREE.Vector3(-5.8,0.62,4.8);+ boat.position.copy(boatPos);+ boat.scale.setScalar(1.5);+ boat.rotation.y=-0.3; // heading right, slightly away+ boat.rotation.z=0.06; boat.rotation.x=0.03; // gentle heel+ }else{+ boatPos=new THREE.Vector3(-6.6,seaHB(-6.6,5.2)+0.55,5.2);+ boat.position.copy(boatPos);+ boat.scale.setScalar(1.15);+ boat.rotation.y=-0.4;+ boat.rotation.z=-0.16; boat.rotation.x=-0.30; // pitched up into the wave, heeled+ // a hand of warm light on the boat itself+ const pl=new THREE.PointLight(0xffd2a0,40,14,1.8);+ pl.position.set(boatPos.x-1.5,boatPos.y+3.5,boatPos.z+3);+ scene.add(pl);+ crestPos=new THREE.Vector3(17,9.4,-12.9);+ }+ scene.add(boat);++ // wake: two diverging light strokes behind the boat+ const wakeMat=new THREE.MeshBasicMaterial({color:0xdfe6ea,transparent:true,opacity:which==='a'?0.25:0.3,depthWrite:false});+ for(const s of[-1,1]){+ const wk=new THREE.Mesh(new THREE.PlaneGeometry(1.6,0.12),wakeMat);+ wk.rotation.x=-Math.PI/2;+ wk.rotation.z=s*0.18+(which==='a'?-0.3:-0.4);+ const back=which==='a'?new THREE.Vector3(-7.1,0.62,5.4):new THREE.Vector3(-7.9,boatPos.y-0.35,5.7);+ wk.position.copy(back); wk.position.z+=s*0.3;+ scene.add(wk);+ }++ return {scene,camera,boatPos,crestPos,curve};+}++// ---------- 2D: sky ----------+function drawSkyA(){+ const g=ctx.createLinearGradient(0,0,0,H*0.62);+ g.addColorStop(0,'#20242c');+ g.addColorStop(0.45,'#4d4b4e');+ g.addColorStop(0.78,'#8a715c');+ g.addColorStop(1,'#c99b6b');+ ctx.fillStyle=g;ctx.fillRect(0,0,W,H*0.62);+ ctx.fillStyle='#c99b6b';ctx.fillRect(0,H*0.60,W,H*0.4);+ // sun glow + disc (ahead-right, where the boat is heading)+ const sx=905,sy=300;+ let rg=ctx.createRadialGradient(sx,sy,0,sx,sy,240);+ rg.addColorStop(0,'rgba(255,214,150,0.55)');+ rg.addColorStop(0.4,'rgba(255,190,120,0.18)');+ rg.addColorStop(1,'rgba(255,190,120,0)');+ ctx.fillStyle=rg;ctx.fillRect(sx-260,sy-260,520,520);+ rg=ctx.createRadialGradient(sx,sy,0,sx,sy,30);+ rg.addColorStop(0,'#ffe9c4');rg.addColorStop(0.8,'#ffd394');rg.addColorStop(1,'rgba(255,211,148,0)');+ ctx.fillStyle=rg;ctx.beginPath();ctx.arc(sx,sy,30,0,7);ctx.fill();+ // thin graphite cloud strokes+ const rnd=mulberry32(42);+ ctx.save();+ for(let k=0;k<9;k++){+ const y=40+rnd()*200, x=rnd()*W, w=140+rnd()*320, h=5+rnd()*9;+ ctx.fillStyle=`rgba(30,33,40,${0.12+rnd()*0.16})`;+ ctx.beginPath();ctx.ellipse(x,y,w,h,0,0,7);ctx.fill();+ }+ ctx.restore();+}+function drawSkyB(){+ const g=ctx.createLinearGradient(0,0,0,H);+ g.addColorStop(0,'#0a0d12');+ g.addColorStop(0.5,'#141a21');+ g.addColorStop(1,'#1c232b');+ ctx.fillStyle=g;ctx.fillRect(0,0,W,H);+ // heavy stormcloud masses+ const rnd=mulberry32(99);+ for(let k=0;k<26;k++){+ const x=rnd()*W, y=rnd()*260-20, r=60+rnd()*150;+ const cg=ctx.createRadialGradient(x,y,0,x,y,r);+ const dk=0.16+rnd()*0.22;+ cg.addColorStop(0,`rgba(6,8,11,${dk})`);+ cg.addColorStop(1,'rgba(6,8,11,0)');+ ctx.fillStyle=cg;ctx.fillRect(x-r,y-r,r*2,r*2);+ }+ // one break of warm light, upper-left+ const lx=250,ly=95;+ let rg=ctx.createRadialGradient(lx,ly,0,lx,ly,260);+ rg.addColorStop(0,'rgba(255,190,130,0.5)');+ rg.addColorStop(0.35,'rgba(255,170,110,0.16)');+ rg.addColorStop(1,'rgba(255,170,110,0)');+ ctx.fillStyle=rg;ctx.fillRect(lx-280,ly-280,560,560);+}+function drawShaftB(bx,by){+ // beam from the cloud-gap down toward the boat+ const lx=250,ly=90;+ ctx.save();+ const g=ctx.createLinearGradient(lx,ly,bx,by);+ g.addColorStop(0,'rgba(255,196,140,0.20)');+ g.addColorStop(1,'rgba(255,196,140,0.02)');+ ctx.fillStyle=g;+ ctx.beginPath();+ ctx.moveTo(lx-70,ly);ctx.lineTo(lx+90,ly);+ ctx.lineTo(bx+150,by+40);ctx.lineTo(bx-150,by+40);+ ctx.closePath();ctx.fill();+ ctx.restore();+}+function drawRainB(){+ const rnd=mulberry32(313);+ ctx.save();+ ctx.strokeStyle='rgba(200,215,230,0.10)';+ ctx.lineWidth=1;+ for(let k=0;k<70;k++){+ const x=rnd()*W,y=rnd()*H,l=18+rnd()*40;+ ctx.globalAlpha=0.04+rnd()*0.10;+ ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x-l*0.42,y+l);ctx.stroke();+ }+ ctx.restore();+}++// ---------- 2D: karaoke caption ----------+function drawKaraoke(which){+ const lines={+ a:{words:['Two','knots','at','dawn','on','a','glass-flat','sea'],hot:3},+ b:{words:['The','twelve-meter','wave','takes','the','bow'],hot:2},+ };+ const {words,hot}=lines[which];+ const x0=58,y0=84;+ ctx.save();+ ctx.textBaseline='alphabetic';+ ctx.font='700 40px "Helvetica Neue", Helvetica, Arial, sans-serif';+ let x=x0;+ for(let i2=0;i2<words.length;i2++){+ const w=words[i2];+ if(i2===hot){+ ctx.shadowColor='rgba(255,138,30,0.9)';ctx.shadowBlur=18;+ ctx.fillStyle=ORANGE;+ ctx.fillText(w,x,y0);+ ctx.shadowBlur=0;+ // underline tick under the sung word+ const ww=ctx.measureText(w).width;+ ctx.fillStyle=ORANGE_DIM+'0.9)';+ ctx.fillRect(x,y0+9,ww,4);+ }else if(i2<hot){+ ctx.fillStyle='rgba(255,255,255,0.95)';+ ctx.fillText(w,x,y0);+ }else{+ ctx.fillStyle='rgba(255,255,255,0.32)';+ ctx.fillText(w,x,y0);+ }+ x+=ctx.measureText(w).width+15;+ }+ // song tag line, mono+ ctx.font='500 15px "SF Mono", Menlo, monospace';+ ctx.fillStyle='rgba(255,255,255,0.5)';+ ctx.fillText(which==='a'?'♪ THE PAPER BOAT · verse 1 · 0:12':'♪ THE PAPER BOAT · chorus · 1:48',x0,y0+40);+ ctx.restore();+}++// ---------- 2D: pinned callout labels ----------+function drawCallout(px,py,lx,ly,text,align){+ ctx.save();+ ctx.strokeStyle='rgba(255,255,255,0.65)';+ ctx.lineWidth=1;+ ctx.beginPath();ctx.moveTo(px,py);ctx.lineTo(lx,ly);ctx.stroke();+ ctx.fillStyle='rgba(255,255,255,0.9)';+ ctx.beginPath();ctx.arc(px,py,2.6,0,7);ctx.fill();+ ctx.font='500 14px "SF Mono", Menlo, monospace';+ const w=ctx.measureText(text).width;+ const tx=align==='right'?lx-w-8:lx+8;+ ctx.fillStyle='rgba(10,12,16,0.66)';+ ctx.fillRect(tx-6,ly-15,w+12,22);+ ctx.fillStyle='rgba(255,255,255,0.92)';+ ctx.fillText(text,tx,ly+1);+ ctx.restore();+}++// ---------- 2D: recurring route chart ----------+function drawChart(which){+ const w=316,h=158,x0=W-w-42,y0=H-h-40;+ ctx.save();+ // panel+ ctx.fillStyle='rgba(8,10,14,0.78)';+ ctx.strokeStyle='rgba(255,255,255,0.18)';+ ctx.lineWidth=1;+ roundRect(x0,y0,w,h,10);ctx.fill();ctx.stroke();+ // title+ ctx.font='600 12px "SF Mono", Menlo, monospace';+ ctx.fillStyle='rgba(255,255,255,0.8)';+ ctx.fillText('THE ROUTE — wave height (m)',x0+14,y0+22);+ // plot area+ const px=x0+38,py=y0+34,pw=w-58,ph=h-64;+ ctx.strokeStyle='rgba(255,255,255,0.14)';+ for(let gy=0;gy<=2;gy++){+ const yy=py+ph-gy*ph/2;+ ctx.beginPath();ctx.moveTo(px,yy);ctx.lineTo(px+pw,yy);ctx.stroke();+ ctx.fillStyle='rgba(255,255,255,0.45)';+ ctx.font='500 10px "SF Mono", Menlo, monospace';+ ctx.fillText(String(gy*6),x0+16,yy+3);+ }+ // wave-height curve along the route: calm, then the storm spike at 65%+ const spikeX=0.65;+ function hAt(t){+ const calm=0.8+0.35*Math.sin(t*21)+0.2*Math.sin(t*47+2);+ const spike=12*Math.exp(-Math.pow((t-spikeX)/0.055,2));+ return calm+(which==='b'?spike:0);+ }+ function fspike(t){return 0.9+12*Math.exp(-Math.pow((t-spikeX)/0.055,2));}+ const Y=v=>py+ph-(v/12)*ph;+ // forecast spike (frame A: dashed green outline = the storm ahead)+ if(which==='a'){+ ctx.setLineDash([4,4]);+ ctx.strokeStyle='rgba(138,255,60,0.55)';+ ctx.lineWidth=1.5;+ ctx.beginPath();+ for(let k=0;k<=120;k++){const t=k/120;const yy=Y(Math.min(12,fspike(t)));if(k===0)ctx.moveTo(px+t*pw,yy);else ctx.lineTo(px+t*pw,yy);}+ ctx.stroke();ctx.setLineDash([]);+ ctx.fillStyle='rgba(138,255,60,0.7)';+ ctx.font='500 10px "SF Mono", Menlo, monospace';+ ctx.fillText('forecast',px+spikeX*pw-22,Y(12)+12);+ }+ // actual curve+ ctx.strokeStyle=which==='b'?'rgba(138,255,60,0.95)':'rgba(255,255,255,0.75)';+ ctx.lineWidth=2;+ if(which==='b'){ctx.shadowColor='rgba(138,255,60,0.8)';ctx.shadowBlur=8;}+ ctx.beginPath();+ const tEnd=which==='a'?1:1;+ for(let k=0;k<=140;k++){+ const t=k/140*tEnd;+ const yy=Y(Math.min(12,hAt(t)));+ if(k===0)ctx.moveTo(px+t*pw,yy);else ctx.lineTo(px+t*pw,yy);+ }+ ctx.stroke();ctx.shadowBlur=0;+ // spike value label in B+ if(which==='b'){+ ctx.fillStyle='rgba(138,255,60,0.95)';+ ctx.font='700 12px "SF Mono", Menlo, monospace';+ ctx.fillText('12 m',px+spikeX*pw+14,Y(11.4));+ }+ // "you" = orange glowing ball on the curve+ const bt=which==='a'?0.07:0.62;+ const bx=px+bt*pw, by=Y(Math.min(12,hAt(bt)));+ ctx.shadowColor='rgba(255,138,30,1)';ctx.shadowBlur=12;+ ctx.fillStyle=ORANGE;+ ctx.beginPath();ctx.arc(bx,by,5,0,7);ctx.fill();+ ctx.shadowBlur=0;+ ctx.fillStyle='rgba(255,180,110,0.95)';+ ctx.font='500 10px "SF Mono", Menlo, monospace';+ if(which==='a')ctx.fillText('you',bx-8,by-10);+ else ctx.fillText('you',bx-30,by+3);+ // x progress+ ctx.fillStyle='rgba(255,255,255,0.5)';+ ctx.font='500 10px "SF Mono", Menlo, monospace';+ ctx.fillText(which==='a'?'nm 3 / 40':'nm 26 / 40',px+pw-58,py+ph+16);+ ctx.restore();+}+function roundRect(x,y,w,h,r){+ ctx.beginPath();+ ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);+ ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();+}+function vignette(strength){+ const g=ctx.createRadialGradient(W/2,H/2,H*0.42,W/2,H/2,H*0.85);+ g.addColorStop(0,'rgba(0,0,0,0)');+ g.addColorStop(1,`rgba(0,0,0,${strength})`);+ ctx.fillStyle=g;ctx.fillRect(0,0,W,H);+}+function project(v,camera){+ const p=v.clone().project(camera);+ return {x:(p.x*0.5+0.5)*W, y:(1-(p.y*0.5+0.5))*H};+}++// ---------- main ----------+window.drawFrame=function(which){+ const {scene,camera,boatPos,crestPos}=buildScene(which);+ renderer.render(scene,camera);+ ctx.clearRect(0,0,W,H);+ if(which==='a')drawSkyA();else drawSkyB();+ ctx.drawImage(glc,0,0);+ const bp=project(boatPos.clone().add(new THREE.Vector3(0,0.8,0)),camera);+ if(which==='b'){+ drawShaftB(bp.x,bp.y);+ drawRainB();+ }+ // callouts+ if(which==='a'){+ drawCallout(bp.x+14,bp.y-4, bp.x+96,bp.y-72,'paper boat · 2 kn','left');+ }else{+ drawCallout(bp.x+12,bp.y+2, bp.x+110,bp.y+64,'hull · holding','left');+ if(crestPos){+ const cp=project(crestPos,camera);+ drawCallout(cp.x-10,cp.y+4, cp.x-170,cp.y-40,'wave · 12 m','left');+ }+ }+ drawKaraoke(which);+ drawChart(which);+ vignette(which==='a'?0.16:0.34);+ window.DONE=true;+};+window.READY=true;+</script>+</body>+</html>diff --git a/assets/previews-src/title/boat.html b/assets/previews-src/title/boat.htmlnew file mode 100644index 0000000..7c2df6a--- /dev/null+++ b/assets/previews-src/title/boat.html@@ -0,0 +1,605 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<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=Archivo+Black&family=Playfair+Display:ital,wght@1,700&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">+<style>html,body{margin:0;padding:0;background:#000}#c{display:block}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const W = 1280, H = 720;+const cv = document.getElementById('c');+const ctx = cv.getContext('2d');++// ---------- seeded rng ----------+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}++// ---------- palettes ----------+const A = { // warm paper cream + orange, ink type+ paper:'#f2e8d5', paperHi:'#f8f1e2', ink:'#211b12', orange:'#e8621a', orangeDeep:'#c94e0e',+ sea:'#eddfc4', seaLine:'#b9743c'+};+const B = { // black + electric blue, white type+ bg:'#05070c', bg2:'#0a1220', blue:'#3f9bff', blueDeep:'#123a6e', blueDark:'#0b2038',+ white:'#f2f6fc', foam:'#dcecff'+};++// ---------- helpers ----------+function fitSize(family, text, targetW, ls){+ ctx.font = '100px ' + family;+ ctx.letterSpacing = (ls||0)+'px';+ const w = ctx.measureText(text).width;+ ctx.letterSpacing = '0px';+ return 100 * targetW / w;+}+function brackets(col, alpha){+ ctx.save(); ctx.strokeStyle = col; ctx.globalAlpha = alpha; ctx.lineWidth = 2;+ const m = 22, L = 26;+ [[m,m,1,1],[W-m,m,-1,1],[m,H-m,1,-1],[W-m,H-m,-1,-1]].forEach(([x,y,sx,sy])=>{+ ctx.beginPath(); ctx.moveTo(x+L*sx, y); ctx.lineTo(x, y); ctx.lineTo(x, y+L*sy); ctx.stroke();+ });+ ctx.restore();+}+function mono(txt, x, y, col, size, align, alpha, bold){+ ctx.save(); ctx.fillStyle = col; ctx.globalAlpha = alpha==null?1:alpha;+ ctx.font = (bold?'700 ':'400 ') + (size||15) + 'px "JetBrains Mono", monospace';+ ctx.textAlign = align||'left'; ctx.textBaseline = 'alphabetic';+ ctx.letterSpacing = '1px';+ ctx.fillText(txt, x, y); ctx.letterSpacing='0px'; ctx.restore();+}+function beatSquares(x, y, col, pattern){ // pattern like [1,0,1,1] filled/empty+ ctx.save(); ctx.strokeStyle = col; ctx.fillStyle = col; ctx.lineWidth = 1.5;+ pattern.forEach((p,i)=>{+ const bx = x + i*16;+ if(p) ctx.fillRect(bx, y-9, 10, 10); else ctx.strokeRect(bx+0.5, y-8.5, 9, 9);+ });+ ctx.restore();+}+function grain(rng, n, alpha, light){+ ctx.save();+ for(let i=0;i<n;i++){+ const x = rng()*W, y = rng()*H, v = rng();+ ctx.globalAlpha = alpha * rng();+ ctx.fillStyle = (light ? (v>0.5?'#ffffff':'#000000') : (v>0.35?'#000000':'#ffffff'));+ ctx.fillRect(x, y, 1.1, 1.1);+ }+ ctx.restore();+}+function vignette(strength){+ const g = ctx.createRadialGradient(W/2, H/2, H*0.35, W/2, H/2, H*0.85);+ g.addColorStop(0,'rgba(0,0,0,0)'); g.addColorStop(1,'rgba(0,0,0,'+strength+')');+ ctx.fillStyle = g; ctx.fillRect(0,0,W,H);+}++// ---------- the paper boat (hull + triangular peak, no face/limbs) ----------+function boat(x, y, s, tilt, opts){+ // s = hull half-width. opts: {fill, line, shade, lw}+ ctx.save(); ctx.translate(x,y); ctx.rotate(tilt);+ const o = opts;+ // hull: trapezoid, wide gunwale, pointed-ish ends+ const gy = -0.34*s; // gunwale y+ const by = 0.16*s; // bottom y+ ctx.beginPath();+ ctx.moveTo(-1.0*s, gy);+ ctx.lineTo( 1.0*s, gy);+ ctx.lineTo( 0.52*s, by);+ ctx.quadraticCurveTo(0, by+0.06*s, -0.52*s, by);+ ctx.closePath();+ ctx.fillStyle = o.fill; ctx.fill();+ ctx.lineWidth = o.lw; ctx.strokeStyle = o.line; ctx.lineJoin='round'; ctx.stroke();+ // hull shade (right/under side)+ ctx.beginPath();+ ctx.moveTo(-1.0*s, gy); ctx.lineTo(1.0*s, gy);+ ctx.lineTo(0.52*s, by); ctx.quadraticCurveTo(0, by+0.06*s, -0.52*s, by); ctx.closePath();+ ctx.save(); ctx.clip();+ ctx.fillStyle = o.shade; ctx.globalAlpha = 0.5;+ ctx.fillRect(-1.05*s, gy + 0.28*s, 2.2*s, s);+ ctx.restore();+ // sail peak: triangle leaning slightly forward+ ctx.beginPath();+ ctx.moveTo(-0.52*s, gy);+ ctx.lineTo( 0.10*s, gy - 0.88*s);+ ctx.lineTo( 0.56*s, gy);+ ctx.closePath();+ ctx.fillStyle = o.fill; ctx.fill(); ctx.stroke();+ // fold line on peak+ ctx.beginPath();+ ctx.moveTo(0.10*s, gy - 0.88*s); ctx.lineTo(0.02*s, gy);+ ctx.globalAlpha = 0.55; ctx.lineWidth = o.lw*0.7; ctx.stroke(); ctx.globalAlpha = 1;+ // shade on rear face of peak+ ctx.beginPath();+ ctx.moveTo(-0.52*s, gy); ctx.lineTo(0.10*s, gy-0.88*s); ctx.lineTo(0.02*s, gy); ctx.closePath();+ ctx.fillStyle = o.shade; ctx.globalAlpha = 0.35; ctx.fill(); ctx.globalAlpha = 1;+ ctx.restore();+}++// ---------- split-flap strip ----------+function splitFlap(cx, y, text, tile, colors, flipIndex){+ // colors: {tile, char, seam, hi}+ const tw = tile, th = tile*1.34, gap = 5;+ const total = text.length*(tw+gap)-gap;+ let x = cx - total/2;+ ctx.save();+ ctx.textAlign='center'; ctx.textBaseline='middle';+ for(let i=0;i<text.length;i++){+ const ch = text[i];+ const tx = x + tw/2;+ // tile+ ctx.fillStyle = colors.tile;+ r(x, y, tw, th, 4); ctx.fill();+ if(ch !== ' '){+ ctx.fillStyle = colors.char;+ ctx.font = '700 ' + (th*0.62) + 'px "Archivo Black", "Arial Black", sans-serif';+ if(i === flipIndex){+ // frozen mid-flip: full top half + foreshortened flap falling below the seam+ ctx.save(); ctx.beginPath(); ctx.rect(x, y, tw, th/2); ctx.clip();+ ctx.fillText(ch, tx, y+th/2+th*0.03);+ ctx.restore();+ const flapH = th*0.30;+ ctx.save(); ctx.beginPath(); ctx.rect(x+1, y+th/2, tw-2, flapH); ctx.clip();+ ctx.fillStyle = colors.hi; ctx.globalAlpha = 0.22;+ ctx.fillRect(x+1, y+th/2, tw-2, flapH);+ ctx.globalAlpha = 1; ctx.fillStyle = colors.char;+ ctx.translate(tx, y+th/2); ctx.scale(1, 0.58); ctx.translate(-tx, -(y+th/2));+ ctx.fillText(ch, tx, y+th/2+th*0.03);+ ctx.restore();+ ctx.strokeStyle = colors.hi; ctx.globalAlpha = 0.9; ctx.lineWidth = 1.5;+ ctx.beginPath(); ctx.moveTo(x+2, y+th/2+flapH); ctx.lineTo(x+tw-2, y+th/2+flapH); ctx.stroke();+ ctx.globalAlpha = 1;+ } else {+ ctx.fillText(ch, tx, y+th/2+th*0.03);+ }+ }+ // seam+ ctx.strokeStyle = colors.seam; ctx.lineWidth = 2;+ ctx.beginPath(); ctx.moveTo(x+1, y+th/2); ctx.lineTo(x+tw-1, y+th/2); ctx.stroke();+ x += tw+gap;+ }+ ctx.restore();+ return {w: total, h: th};+}+function r(x,y,w,h,rad){+ ctx.beginPath();+ ctx.moveTo(x+rad,y); ctx.arcTo(x+w,y,x+w,y+h,rad); ctx.arcTo(x+w,y+h,x,y+h,rad);+ ctx.arcTo(x,y+h,x,y,rad); ctx.arcTo(x,y,x+w,y,rad); ctx.closePath();+}++// ---------- HUD ----------+function hud(col, meta){ // meta:{tl,tr,bl,brLeft,pattern,barTxt,caption:[txt,x,y,align]}+ brackets(col, 0.85);+ mono(meta.tl, 52, 52, col, 14, 'left', 0.9, true);+ mono(meta.tr, W-52, 52, col, 14, 'right', 0.9, true);+ mono(meta.bl, 52, H-42, col, 13, 'left', 0.75);+ // bottom-right: BPM + squares + bar+ ctx.save();+ ctx.font = '400 13px "JetBrains Mono", monospace';+ const barW = ctx.measureText(meta.barTxt).width;+ ctx.restore();+ const sqW = 4*16-6;+ const bx = W-52 - barW;+ mono(meta.brLeft, bx - sqW - 14, H-42, col, 13, 'right', 0.75);+ beatSquares(bx - sqW - 6, H-45, col, meta.pattern);+ mono(meta.barTxt, W-52, H-42, col, 13, 'right', 0.75);+}++// =====================================================================+// FRAME A — chapter 01, warm paper cream + orange+// =====================================================================+function frameA(){+ const rng = mulberry32(20260928);+ // paper base+ const g = ctx.createLinearGradient(0,0,0,H);+ g.addColorStop(0, A.paperHi); g.addColorStop(0.62, A.paper); g.addColorStop(1, '#ead9ba');+ ctx.fillStyle = g; ctx.fillRect(0,0,W,H);+ // paper fibers+ ctx.save();+ for(let i=0;i<900;i++){+ const x = rng()*W, y = rng()*H, len = 3+rng()*9, a = rng()*Math.PI;+ ctx.strokeStyle = rng()>0.5 ? A.ink : '#8a6f4d';+ ctx.globalAlpha = 0.028*rng();+ ctx.lineWidth = 0.8;+ ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x+Math.cos(a)*len, y+Math.sin(a)*len); ctx.stroke();+ }+ ctx.restore();++ const HOR = 468;++ // morning sun, low right, behind everything+ ctx.save();+ const sg = ctx.createRadialGradient(1035, HOR-45, 10, 1035, HOR-45, 190);+ sg.addColorStop(0,'rgba(232,98,26,0.30)'); sg.addColorStop(1,'rgba(232,98,26,0)');+ ctx.fillStyle = sg; ctx.fillRect(800, HOR-260, 480, 300);+ ctx.fillStyle = A.orange; ctx.globalAlpha = 0.92;+ ctx.beginPath(); ctx.arc(1035, HOR-45, 62, 0, Math.PI*2); ctx.fill();+ ctx.restore();++ // sea band+ ctx.fillStyle = A.sea; ctx.fillRect(0, HOR, W, H-HOR);+ // horizon rule+ ctx.strokeStyle = A.ink; ctx.globalAlpha = 0.65; ctx.lineWidth = 2;+ ctx.beginPath(); ctx.moveTo(0,HOR); ctx.lineTo(W,HOR); ctx.stroke(); ctx.globalAlpha = 1;+ // sea line-work, perspective spacing+ ctx.save();+ let y = HOR+12, step = 7, k = 0;+ while(y < H-8){+ const amp = 1.2 + k*0.35;+ ctx.strokeStyle = (k%4===1) ? A.orangeDeep : A.seaLine;+ ctx.globalAlpha = (k%4===1) ? 0.5 : 0.4;+ ctx.lineWidth = 1 + k*0.06;+ ctx.beginPath();+ const ph = rng()*Math.PI*2;+ for(let x=-10;x<=W+10;x+=14){+ const yy = y + Math.sin(x*0.014+ph)*amp;+ x===-10 ? ctx.moveTo(x,yy) : ctx.lineTo(x,yy);+ }+ ctx.stroke();+ k++; y += step; step *= 1.16;+ }+ // sun track on water+ const tg = ctx.createLinearGradient(0,HOR,0,H);+ tg.addColorStop(0,'rgba(232,98,26,0.34)'); tg.addColorStop(1,'rgba(232,98,26,0.04)');+ ctx.fillStyle = tg;+ ctx.beginPath();+ ctx.moveTo(1000, HOR); ctx.lineTo(1070, HOR); ctx.lineTo(1180, H); ctx.lineTo(890, H);+ ctx.closePath(); ctx.fill();+ ctx.restore();++ // ---- typography block (the hero) ----+ // marquee: stroke-only title scrolling behind, two rows+ ctx.save();+ ctx.textBaseline='alphabetic'; ctx.textAlign='left';+ ctx.strokeStyle = A.orange; ctx.lineWidth = 1.6;+ ctx.font = '92px "Archivo Black", "Arial Black", sans-serif';+ ctx.globalAlpha = 0.4;+ const mtxt = 'THE CROSSING · THE CROSSING · THE CROSSING';+ ctx.strokeText(mtxt, -318, 258);+ ctx.globalAlpha = 0.24;+ ctx.strokeText(mtxt, -820, 448);+ ctx.restore();++ // split-flap chapter strip+ splitFlap(W/2, 92, 'CHAPTER 01', 34,+ {tile:A.ink, char:A.paper, seam:'#4a3d28', hi:A.paperHi}, 5);+ mono('SPLIT-FLAP × 10 · 20 FLIPS/S · LOCK ON THE 1/16', W/2, 168, A.ink, 12, 'center', 0.55);++ // "THE" letterspaced+ ctx.save();+ ctx.fillStyle = A.ink; ctx.textAlign='center'; ctx.textBaseline='alphabetic';+ ctx.font = '44px "Archivo Black", "Arial Black", sans-serif';+ ctx.letterSpacing = '30px';+ ctx.fillText('THE', W/2+15, 252);+ ctx.letterSpacing = '0px';+ ctx.restore();++ // CROSSING — giant, filling width+ ctx.save();+ const fam = '"Archivo Black", "Arial Black", sans-serif';+ const size = fitSize(fam, 'CROSSING', 1170);+ ctx.font = size + 'px ' + fam;+ ctx.textAlign='center'; ctx.textBaseline='alphabetic';+ // soft drop+ ctx.fillStyle = A.orangeDeep; ctx.globalAlpha = 0.28;+ ctx.fillText('CROSSING', W/2+6, 434);+ ctx.globalAlpha = 1;+ ctx.fillStyle = A.ink;+ ctx.fillText('CROSSING', W/2, 428);+ ctx.restore();++ // italic serif accent+ ctx.save();+ ctx.translate(1000, 464); ctx.rotate(-0.045);+ ctx.font = 'italic 700 64px "Playfair Display", Georgia, serif';+ ctx.textAlign='center'; ctx.textBaseline='alphabetic';+ ctx.fillStyle = A.paper;+ ctx.strokeStyle = A.paper; ctx.lineWidth=7; ctx.globalAlpha=0.85;+ ctx.strokeText('first light', 0, 0); ctx.globalAlpha=1;+ ctx.fillStyle = A.orange;+ ctx.fillText('first light', 0, 0);+ ctx.restore();++ // ---- the boat, lower-left third, heading right ----+ const bx = 330, by = 582, bs = 78, tilt = -0.05;+ // wake trailing left+ ctx.save();+ ctx.strokeStyle = A.ink; ctx.globalAlpha = 0.4; ctx.lineWidth = 2;+ for(let i=0;i<3;i++){+ ctx.beginPath();+ const wy = by + 16 + i*9, wl = 120 - i*28;+ ctx.moveTo(bx - 60 - wl, wy + Math.sin(i)*2);+ ctx.quadraticCurveTo(bx - 40, wy - 4, bx - 8, wy - 1);+ ctx.stroke();+ }+ ctx.restore();+ // water shadow under boat+ ctx.save();+ ctx.fillStyle = A.orangeDeep; ctx.globalAlpha = 0.16;+ ctx.beginPath(); ctx.ellipse(bx+4, by+20, bs*1.05, 10, 0, 0, Math.PI*2); ctx.fill();+ ctx.restore();+ boat(bx, by, bs, tilt, {fill:'#fdf8ec', line:A.ink, shade:'#d8b98a', lw:3.4});+ // bow ripple+ ctx.save();+ ctx.strokeStyle = A.ink; ctx.globalAlpha=0.45; ctx.lineWidth=2;+ ctx.beginPath(); ctx.moveTo(bx+bs*0.9, by+14); ctx.quadraticCurveTo(bx+bs*1.35, by+10, bx+bs*1.6, by+16); ctx.stroke();+ ctx.restore();+ // caption under the boat (matches chapter 02 device)+ mono('01 · THE BOAT · SETTING OUT', bx+8, by+62, A.ink, 12, 'center', 0.65, true);++ // HUD+ hud(A.ink, {+ tl:'THE CROSSING — SEASON 2026',+ tr:'01 — FIRST LIGHT',+ bl:'TC 00:00:04:12 · 60 FPS',+ brLeft:'148 BPM', pattern:[0,1,0,0], barTxt:' BAR 02/16'+ });++ grain(rng, 16000, 0.06, true);+}++// =====================================================================+// FRAME B — chapter 02, black + electric blue storm+// =====================================================================+function frameB(){+ const rng = mulberry32(99120426);+ // deep bg+ const g = ctx.createLinearGradient(0,0,0,H);+ g.addColorStop(0, B.bg); g.addColorStop(0.55, B.bg2); g.addColorStop(1, '#040609');+ ctx.fillStyle = g; ctx.fillRect(0,0,W,H);++ // storm streak clouds+ ctx.save();+ for(let i=0;i<26;i++){+ const y = rng()*260, len = 140+rng()*420, x = rng()*W - 100;+ ctx.strokeStyle = i%3===0 ? B.blueDeep : '#0e1a2e';+ ctx.globalAlpha = 0.35*rng()+0.1;+ ctx.lineWidth = 2+rng()*7;+ ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x+len, y - len*0.06); ctx.stroke();+ }+ ctx.restore();++ // one light source fighting through: gap upper-left, shaft toward the boat+ ctx.save();+ const lg = ctx.createRadialGradient(250, 60, 5, 250, 60, 330);+ lg.addColorStop(0,'rgba(220,236,255,0.55)'); lg.addColorStop(0.35,'rgba(120,170,255,0.16)');+ lg.addColorStop(1,'rgba(0,0,0,0)');+ ctx.fillStyle = lg; ctx.fillRect(0,0,700,430);+ const shaft = ctx.createLinearGradient(250,60, 300,560);+ shaft.addColorStop(0,'rgba(220,236,255,0.22)'); shaft.addColorStop(1,'rgba(220,236,255,0.02)');+ ctx.fillStyle = shaft;+ ctx.beginPath(); ctx.moveTo(205,42); ctx.lineTo(305,42); ctx.lineTo(430,590); ctx.lineTo(160,590);+ ctx.closePath(); ctx.fill();+ ctx.restore();++ // marquee stroke rows behind title+ ctx.save();+ ctx.textBaseline='alphabetic'; ctx.textAlign='left';+ ctx.strokeStyle = B.blue; ctx.lineWidth = 1.5;+ ctx.font = '96px "Archivo Black", "Arial Black", sans-serif';+ const mt = 'THE STORM · THE STORM · THE STORM ·';+ ctx.globalAlpha = 0.30; ctx.strokeText(mt, -240, 168);+ ctx.globalAlpha = 0.16; ctx.strokeText(mt, -640, 452);+ ctx.restore();++ // ---- THE WAVE: big diagonal from upper right down to lower left ----+ function waveEdge(baseY, drop, jag, seed){+ const rr = mulberry32(seed);+ const pts = [];+ for(let x=W+40; x>=-40; x-=26){+ const t = (W+40-x)/(W+80); // 0 at right, 1 at left+ const yy = baseY + t*drop + (rr()-0.5)*jag + Math.sin(x*0.02+seed)*jag*0.4;+ pts.push([x,yy]);+ }+ return pts;+ }+ function fillWave(pts, fill){+ ctx.beginPath();+ ctx.moveTo(W+40, H+40);+ pts.forEach(p=>ctx.lineTo(p[0],p[1]));+ ctx.lineTo(-40, H+40); ctx.closePath();+ ctx.fillStyle = fill; ctx.fill();+ }+ // back swell+ fillWave(waveEdge(258, 260, 16, 7), '#081426');+ // main wave body+ const mainPts = waveEdge(200, 330, 22, 13);+ fillWave(mainPts, B.blueDark);+ // lighter face band along the edge (the wave catching light)+ ctx.save();+ ctx.beginPath();+ ctx.moveTo(W+40, H+40);+ mainPts.forEach(p=>ctx.lineTo(p[0],p[1]));+ ctx.lineTo(-40, H+40); ctx.closePath();+ ctx.clip();+ ctx.strokeStyle = '#1e5896'; ctx.lineWidth = 60; ctx.globalAlpha = 0.55;+ ctx.beginPath();+ mainPts.forEach((p,i)=> i===0?ctx.moveTo(p[0],p[1]+24):ctx.lineTo(p[0],p[1]+24));+ ctx.stroke();+ ctx.strokeStyle = '#2f74bd'; ctx.lineWidth = 22; ctx.globalAlpha = 0.6;+ ctx.beginPath();+ mainPts.forEach((p,i)=> i===0?ctx.moveTo(p[0],p[1]+8):ctx.lineTo(p[0],p[1]+8));+ ctx.stroke();+ // face streaks running down-slope, clipped inside the wave+ const sr = mulberry32(88);+ ctx.lineWidth = 1.8;+ for(let i=0;i<52;i++){+ const t = sr();+ const x = 60 + t*1200, y0 = 210 + (1-t)*60 + t*330 + sr()*120;+ const len = 40+sr()*130;+ ctx.strokeStyle = sr()>0.6 ? B.foam : B.blue;+ ctx.globalAlpha = 0.06+0.14*sr();+ ctx.beginPath(); ctx.moveTo(x, y0); ctx.lineTo(x - len*0.9, y0 + len*0.42); ctx.stroke();+ }+ ctx.restore();+ // breaking lip curling over at upper right+ ctx.save();+ ctx.fillStyle = '#2f74bd';+ ctx.beginPath();+ ctx.moveTo(W-470, 250);+ ctx.quadraticCurveTo(W-190, 118, W-40, 152);+ ctx.quadraticCurveTo(W+16, 168, W-8, 216);+ ctx.quadraticCurveTo(W-150, 190, W-290, 266);+ ctx.closePath(); ctx.fill();+ ctx.fillStyle = B.foam; ctx.globalAlpha = 0.9;+ ctx.beginPath();+ ctx.moveTo(W-470, 252);+ ctx.quadraticCurveTo(W-200, 128, W-60, 158);+ ctx.quadraticCurveTo(W-210, 158, W-360, 236);+ ctx.closePath(); ctx.fill();+ ctx.restore();+ // foam mass on the crest edge+ ctx.save();+ const fr = mulberry32(41);+ ctx.strokeStyle = B.foam; ctx.lineWidth = 5; ctx.globalAlpha = 0.95; ctx.lineJoin='round';+ ctx.beginPath();+ mainPts.forEach((p,i)=> i===0?ctx.moveTo(p[0],p[1]):ctx.lineTo(p[0],p[1]));+ ctx.stroke();+ for(let i=0;i<mainPts.length;i++){+ const [x,y] = mainPts[i];+ for(let j=0;j<6;j++){+ ctx.globalAlpha = 0.3+0.6*fr();+ ctx.fillStyle = B.foam;+ ctx.beginPath(); ctx.arc(x+(fr()-0.5)*36, y-3-fr()*20, 1.0+fr()*3.2, 0, Math.PI*2); ctx.fill();+ }+ }+ // spray blowing off the lip, top-right+ for(let i=0;i<160;i++){+ ctx.globalAlpha = 0.2+0.6*fr();+ ctx.fillStyle = B.foam;+ const x = W-520+fr()*500, y = 100+fr()*150;+ ctx.beginPath(); ctx.arc(x, y, 0.8+fr()*2.2, 0, Math.PI*2); ctx.fill();+ }+ // stray foam patches on the dark water lower right+ for(let i=0;i<14;i++){+ const x = 620+fr()*620, y = 520+fr()*170;+ ctx.strokeStyle = B.foam; ctx.globalAlpha = 0.10+0.16*fr(); ctx.lineWidth = 2;+ ctx.beginPath(); ctx.moveTo(x, y); ctx.quadraticCurveTo(x+30+fr()*40, y-5, x+70+fr()*60, y+2); ctx.stroke();+ }+ ctx.restore();++ // ---- title: THE STORM with glitch slices ----+ const oc = document.createElement('canvas'); oc.width = W; oc.height = 300;+ const o = oc.getContext('2d');+ const fam = '"Archivo Black", "Arial Black", sans-serif';+ o.font = ctx.font = '100px '+fam;+ const size = (function(){ o.font='100px '+fam; return 100*1150/o.measureText('THE STORM').width; })();+ o.font = size + 'px ' + fam;+ o.textAlign = 'center'; o.textBaseline = 'alphabetic';+ // color-shift ghosts+ o.fillStyle = B.blue; o.globalAlpha = 0.7; o.fillText('THE STORM', W/2-7, 218);+ o.fillStyle = '#ff3d5e'; o.globalAlpha = 0.35; o.fillText('THE STORM', W/2+7, 218);+ o.globalAlpha = 1; o.fillStyle = B.white; o.fillText('THE STORM', W/2, 218);+ // blit with glitch slices+ const TY = 128; // dest top+ const gr = mulberry32(777);+ let sy = 0;+ const slices = [];+ while(sy < 300){+ const h = 10 + Math.floor(gr()*34);+ const dx = (gr() < 0.42) ? Math.round((gr()-0.5)*44) : 0;+ slices.push([sy, Math.min(h, 300-sy), dx]);+ sy += h;+ }+ slices.forEach(([y0, h, dx])=>{+ ctx.drawImage(oc, 0, y0, W, h, dx, TY+y0, W, h);+ });+ // caption under the effect+ mono('GLITCH SLICE × '+slices.filter(s=>s[2]!==0).length+' · CUT ON THE 1', 64, TY+270, B.blue, 12, 'left', 0.9);++ // chapter strip (split-flap, dark tiles, blue chars)+ splitFlap(W/2, 46, 'CHAPTER 02', 30,+ {tile:'#101b2c', char:B.blue, seam:'#223a55', hi:B.foam}, 3);++ // italic serif accent+ ctx.save();+ ctx.translate(1052, 372); ctx.rotate(-0.05);+ ctx.font = 'italic 700 54px "Playfair Display", Georgia, serif';+ ctx.textAlign='center';+ ctx.strokeStyle = B.bg; ctx.lineWidth = 8; ctx.globalAlpha=0.8;+ ctx.strokeText('no way back', 0, 0); ctx.globalAlpha=1;+ ctx.fillStyle = B.blue;+ ctx.fillText('no way back', 0, 0);+ ctx.restore();++ // ---- the boat: small, on the rising water lower-left, bow up, lit by the shaft ----+ const bx = 302, by = 548, bs = 42, tilt = -0.30;+ // glow where light hits+ ctx.save();+ const bg2 = ctx.createRadialGradient(bx, by-10, 4, bx, by-10, 120);+ bg2.addColorStop(0,'rgba(220,236,255,0.35)'); bg2.addColorStop(1,'rgba(220,236,255,0)');+ ctx.fillStyle = bg2; ctx.fillRect(bx-130, by-140, 260, 260);+ ctx.restore();+ // churned water at hull+ ctx.save();+ const wr = mulberry32(5150);+ ctx.fillStyle = B.foam;+ for(let i=0;i<46;i++){+ ctx.globalAlpha = 0.25+0.6*wr();+ const a = wr()*Math.PI*2, d = wr()*bs*1.7;+ ctx.beginPath();+ ctx.arc(bx+Math.cos(a)*d, by+14+Math.sin(a)*d*0.35, 0.8+wr()*2.2, 0, Math.PI*2);+ ctx.fill();+ }+ ctx.strokeStyle = B.foam; ctx.globalAlpha = 0.7; ctx.lineWidth = 2.4;+ ctx.beginPath(); ctx.moveTo(bx-bs*1.4, by+20); ctx.quadraticCurveTo(bx, by+30, bx+bs*1.5, by+8); ctx.stroke();+ ctx.restore();+ boat(bx, by, bs, tilt, {fill:'#eef4fd', line:'#0a1524', shade:B.blueDeep, lw:2.6});+ // rim light on windward edge+ ctx.save(); ctx.translate(bx,by); ctx.rotate(tilt);+ ctx.strokeStyle = B.foam; ctx.lineWidth = 2; ctx.globalAlpha = 0.9;+ ctx.beginPath(); ctx.moveTo(-0.52*bs, -0.34*bs); ctx.lineTo(0.10*bs, -1.22*bs); ctx.stroke();+ ctx.beginPath(); ctx.moveTo(-1.0*bs, -0.34*bs); ctx.lineTo(1.0*bs, -0.34*bs); ctx.stroke();+ ctx.restore();+ // locator brackets around the boat (HUD garnish helping phone read)+ ctx.save();+ ctx.strokeStyle = B.blue; ctx.globalAlpha = 0.85; ctx.lineWidth = 1.6;+ const m = 64, L2 = 12;+ [[bx-m,by-m,1,1],[bx+m,by-m,-1,1],[bx-m,by+m-6,1,-1],[bx+m,by+m-6,-1,-1]].forEach(([x,y,sx,sy2])=>{+ ctx.beginPath(); ctx.moveTo(x+L2*sx,y); ctx.lineTo(x,y); ctx.lineTo(x,y+L2*sy2); ctx.stroke();+ });+ ctx.restore();+ mono('01 · THE BOAT · HOLDING COURSE', bx, by+96, B.blue, 12, 'center', 0.85, true);++ // rain streaks+ ctx.save();+ const rr2 = mulberry32(3210);+ ctx.strokeStyle = B.foam; ctx.lineWidth = 1;+ for(let i=0;i<130;i++){+ const x = rr2()*W, y = rr2()*H, len = 10+rr2()*22;+ ctx.globalAlpha = 0.05+0.13*rr2();+ ctx.beginPath(); ctx.moveTo(x,y); ctx.lineTo(x-len*0.35, y+len); ctx.stroke();+ }+ ctx.restore();++ hud(B.white, {+ tl:'THE CROSSING — SEASON 2026',+ tr:'02 — THE STORM',+ bl:'TC 00:00:11:03 · 60 FPS',+ brLeft:'148 BPM', pattern:[1,0,1,1], barTxt:' BAR 09/16'+ });++ grain(rng, 22000, 0.09, false);+ vignette(0.55);+}++// ---------- harness ----------+window.drawFrame = function(which){+ ctx.save();+ ctx.clearRect(0,0,W,H);+ if(which === 'a') frameA(); else frameB();+ ctx.restore();+ window.DONE = true;+};+const need = [+ document.fonts.load('100px "Archivo Black"'),+ document.fonts.load('italic 700 54px "Playfair Display"'),+ document.fonts.load('400 15px "JetBrains Mono"'),+ document.fonts.load('700 15px "JetBrains Mono"')+];+Promise.all(need).then(()=>document.fonts.ready).then(()=>{ window.READY = true; })+ .catch(()=>{ window.READY = true; });+</script>+</body>+</html>diff --git a/assets/previews-src/watercolor/boat.html b/assets/previews-src/watercolor/boat.htmlnew file mode 100644index 0000000..7ffa157--- /dev/null+++ b/assets/previews-src/watercolor/boat.html@@ -0,0 +1,521 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>Paper Boat — watercolor</title>+<style>html,body{margin:0;padding:0;background:#efe9da}#c{display:block;width:100vw;height:100vh}</style>+</head>+<body>+<canvas id="c" width="1280" height="720"></canvas>+<script>+'use strict';+const cv = document.getElementById('c');+let ctx = cv.getContext('2d');+const W = 1280, H = 720;++// ---------- seeded RNG ----------+let _s = 1;+function seed(n){ _s = n >>> 0; }+function rnd(){ // mulberry32+ _s |= 0; _s = (_s + 0x6D2B79F5) | 0;+ let t = Math.imul(_s ^ (_s >>> 15), 1 | _s);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+}+function rr(a, b){ return a + (b - a) * rnd(); }+function gauss(){ let s = 0; for (let i = 0; i < 6; i++) s += rnd(); return (s - 3) / 3; } // ~N(0, .33)++// ---------- watercolor machinery ----------+// Add vertices so long straight edges can feather like a real wash rim.+function resample(pts, maxLen){+ const out = [];+ for (let i = 0; i < pts.length; i++){+ const a = pts[i], b = pts[(i + 1) % pts.length];+ const d = Math.hypot(b.x - a.x, b.y - a.y);+ const n = Math.max(1, Math.ceil(d / maxLen));+ for (let s = 0; s < n; s++){+ const t = s / n;+ out.push({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });+ }+ }+ return out;+}+// Tyler-Hobbs-style recursive polygon deformation.+function deform(pts, depth, mag){+ let p = pts;+ for (let d = 0; d < depth; d++){+ const out = [];+ for (let i = 0; i < p.length; i++){+ const a = p[i], b = p[(i + 1) % p.length];+ const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;+ let nx = -(b.y - a.y), ny = (b.x - a.x);+ const len = Math.hypot(nx, ny) || 1;+ nx /= len; ny /= len;+ const disp = gauss() * mag * len * 0.5;+ const tng = gauss() * mag * len * 0.2;+ out.push(a, { x: mx + nx * disp + (b.x - a.x) / len * tng,+ y: my + ny * disp + (b.y - a.y) / len * tng });+ }+ p = out;+ }+ return p;+}+function pathOf(c, p){+ c.beginPath(); c.moveTo(p[0].x, p[0].y);+ for (let i = 1; i < p.length; i++) c.lineTo(p[i].x, p[i].y);+ c.closePath();+}+// One watercolor wash: base polygon layered as many deformed translucent fills.+function wash(basePts, color, opts){+ const o = Object.assign({ layers: 16, alpha: 0.032, mag: 0.34, depth: 4, edge: 0.10, gran: 0, res: 70 }, opts || {});+ // pre-roughen the base once so all layers share one wet footprint+ const rootMag = o.rootMag !== undefined ? o.rootMag : o.mag * 0.8;+ const base = resample(basePts, o.res);+ const root = deform(base, 2, rootMag);+ ctx.fillStyle = color;+ for (let i = 0; i < o.layers; i++){+ let p, a;+ if (i % 3 === 2){ // feather layer: wanders far from the footprint -> soft gradient rim+ p = deform(base, o.depth + 1, o.mag * rr(1.3, 1.9));+ a = o.alpha * rr(0.4, 0.8);+ } else { // body layer: hugs the footprint+ p = deform(root, o.depth, o.mag * rr(0.5, 1.15));+ a = o.alpha * rr(0.6, 1.3);+ }+ ctx.globalAlpha = a;+ pathOf(ctx, p); ctx.fill();+ }+ // edge darkening: pigment pools at the rim+ if (o.edge > 0){+ const p = deform(root, o.depth, o.mag * 0.7);+ pathOf(ctx, p);+ ctx.globalAlpha = o.edge; ctx.strokeStyle = color; ctx.lineWidth = rr(1.4, 2.6);+ ctx.stroke();+ }+ // granulation: dark specks trapped in the wash+ if (o.gran > 0){+ const p = deform(root, 3, o.mag * 0.6);+ let minx = 1e9, miny = 1e9, maxx = -1e9, maxy = -1e9;+ for (const q of p){ minx = Math.min(minx, q.x); maxx = Math.max(maxx, q.x); miny = Math.min(miny, q.y); maxy = Math.max(maxy, q.y); }+ ctx.save(); pathOf(ctx, p); ctx.clip();+ ctx.fillStyle = color;+ for (let i = 0; i < o.gran; i++){+ ctx.globalAlpha = rr(0.03, 0.10);+ const x = rr(minx, maxx), y = rr(miny, maxy);+ ctx.beginPath(); ctx.arc(x, y, rr(0.4, 1.6), 0, 7); ctx.fill();+ }+ ctx.restore();+ }+ ctx.globalAlpha = 1;+}+function blobPts(cx, cy, rx, ry, n, rough){+ n = n || 10; rough = rough === undefined ? 0.18 : rough;+ const pts = [];+ const a0 = rnd() * Math.PI * 2;+ for (let i = 0; i < n; i++){+ const a = a0 + (i / n) * Math.PI * 2;+ const k = 1 + gauss() * rough;+ pts.push({ x: cx + Math.cos(a) * rx * k, y: cy + Math.sin(a) * ry * k });+ }+ return pts;+}+// A soft blob wash shortcut+function blot(cx, cy, rx, ry, color, opts){+ const o = opts || {};+ wash(blobPts(cx, cy, rx, ry, o.n || 10, o.rough !== undefined ? o.rough : 0.16), color, opts);+}+// An elongated rotated blob: one loaded brush stroke+function strokeBlob(cx, cy, len, wid, ang, color, opts){+ ctx.save(); ctx.translate(cx, cy); ctx.rotate(ang);+ blot(0, 0, len / 2, wid / 2, color, opts);+ ctx.restore();+}+// Wobbly ink line ("boil" frozen at one frame)+function ink(pts, width, color, alpha, wob){+ wob = wob === undefined ? 1.4 : wob;+ ctx.strokeStyle = color;+ ctx.lineCap = 'round'; ctx.lineJoin = 'round';+ for (let pass = 0; pass < 2; pass++){+ ctx.globalAlpha = (alpha || 0.85) * (pass ? 0.45 : 1);+ ctx.beginPath();+ let prev = null;+ for (let i = 0; i < pts.length; i++){+ const a = pts[i], b = pts[Math.min(i + 1, pts.length - 1)];+ const segs = Math.max(2, Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / 9));+ for (let s = 0; s <= segs; s++){+ const t = s / segs;+ const x = a.x + (b.x - a.x) * t + gauss() * wob + (pass ? gauss() * wob : 0);+ const y = a.y + (b.y - a.y) * t + gauss() * wob + (pass ? gauss() * wob : 0);+ if (!prev) ctx.moveTo(x, y); else ctx.lineTo(x, y);+ prev = { x, y };+ }+ }+ ctx.lineWidth = width * (pass ? rr(0.5, 0.7) : rr(0.9, 1.1));+ ctx.stroke();+ }+ ctx.globalAlpha = 1;+}+function spatter(cx, cy, r, color, n, aMin, aMax, rMax){+ ctx.fillStyle = color;+ for (let i = 0; i < n; i++){+ const a = rnd() * Math.PI * 2, d = Math.sqrt(rnd()) * r;+ ctx.globalAlpha = rr(aMin, aMax);+ ctx.beginPath();+ ctx.arc(cx + Math.cos(a) * d, cy + Math.sin(a) * d * 0.7, rr(0.5, rMax), 0, 7);+ ctx.fill();+ }+ ctx.globalAlpha = 1;+}++// ---------- paper ----------+function paper(){+ ctx.globalAlpha = 1;+ ctx.fillStyle = '#f7f2e4';+ ctx.fillRect(0, 0, W, H);+ // fibre noise+ const img = ctx.getImageData(0, 0, W, H);+ const d = img.data;+ for (let i = 0; i < d.length; i += 4){+ const n = (rnd() - 0.5) * 11;+ d[i] += n; d[i + 1] += n; d[i + 2] += n * 0.9;+ }+ ctx.putImageData(img, 0, 0);+ // a few long faint fibres+ ctx.strokeStyle = '#d8cfae';+ for (let i = 0; i < 130; i++){+ ctx.globalAlpha = rr(0.05, 0.14);+ const x = rr(0, W), y = rr(0, H), a = rr(0, Math.PI), l = rr(3, 14);+ ctx.lineWidth = rr(0.4, 0.9);+ ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l); ctx.stroke();+ }+ ctx.globalAlpha = 1;+}+function paperGrainOver(){+ // multiply a faint grain back over the paint so pigment sits IN the paper+ ctx.globalCompositeOperation = 'multiply';+ ctx.globalAlpha = 0.16;+ for (let i = 0; i < 900; i++){+ ctx.fillStyle = rnd() < 0.5 ? '#cfc3a4' : '#e6dcc2';+ const x = rr(0, W), y = rr(0, H);+ ctx.fillRect(x, y, rr(1, 3), rr(1, 2));+ }+ ctx.globalCompositeOperation = 'source-over';+ ctx.globalAlpha = 1;+ // gentle vignette of clean paper at the very edges (deckled border feel)+ ctx.globalAlpha = 0.5;+ ctx.strokeStyle = '#f7f2e4';+ for (let i = 0; i < 3; i++){+ ctx.lineWidth = 10 - i * 3;+ ctx.globalAlpha = 0.22 - i * 0.05;+ ctx.strokeRect(ctx.lineWidth / 2, ctx.lineWidth / 2, W - ctx.lineWidth, H - ctx.lineWidth);+ }+ ctx.globalAlpha = 1;+}++// ---------- the paper boat ----------+// Drawn in a local frame: boat length = 1 unit (from stern tip to bow tip).+function boat(cx, cy, len, tilt, opts){+ const o = Object.assign({ inkW: 2.2, shadow: true, dark: false }, opts || {});+ ctx.save();+ ctx.translate(cx, cy);+ ctx.rotate(tilt);+ const s = len;+ // silhouette (classic folded paper boat, side view, bow to the RIGHT)+ const hull = [+ { x: -0.50 * s, y: -0.16 * s }, // stern tip (raised point)+ { x: -0.30 * s, y: -0.045 * s },+ { x: 0.30 * s, y: -0.045 * s },+ { x: 0.50 * s, y: -0.16 * s }, // bow tip (raised point)+ { x: 0.34 * s, y: 0.16 * s }, // waterline right+ { x: -0.34 * s, y: 0.16 * s } // waterline left+ ];+ const sail = [+ { x: -0.155 * s, y: -0.05 * s },+ { x: 0.155 * s, y: -0.05 * s },+ { x: 0.015 * s, y: -0.46 * s }+ ];+ // paper body: reserved white, so paint it opaque-ish white first+ ctx.fillStyle = o.dark ? '#f3ecdb' : '#fbf7ec';+ ctx.globalAlpha = 0.94;+ pathOf(ctx, deform(hull, 3, 0.05)); ctx.fill();+ pathOf(ctx, deform(sail, 3, 0.05)); ctx.fill();+ ctx.globalAlpha = 1;+ // soft warm shadow wash on the hull's lower half + right of sail+ wash([{ x: -0.34 * s, y: 0.03 * s }, { x: 0.34 * s, y: 0.03 * s }, { x: 0.33 * s, y: 0.16 * s }, { x: -0.33 * s, y: 0.16 * s }],+ o.dark ? '#5d6b80' : '#c9b48c', { layers: 5, alpha: 0.07, mag: 0.2, depth: 3, edge: 0.06 });+ wash([{ x: 0.015 * s, y: -0.44 * s }, { x: 0.14 * s, y: -0.06 * s }, { x: 0.02 * s, y: -0.06 * s }],+ o.dark ? '#5d6b80' : '#cbb691', { layers: 4, alpha: 0.06, mag: 0.22, depth: 3, edge: 0.05 });+ // a blush of reflected light color on the sail (ties boat into scene)+ if (o.glow){+ wash([{ x: -0.13 * s, y: -0.08 * s }, { x: 0.01 * s, y: -0.4 * s }, { x: 0.0 * s, y: -0.08 * s }],+ o.glow, { layers: 4, alpha: 0.06, mag: 0.25, depth: 3, edge: 0 });+ }+ // ink outline (wobbly, hand-drawn)+ const inkC = o.dark ? '#20242e' : '#3a3b33';+ ink(deform(hull, 1, 0.03).concat([deform(hull, 1, 0.02)[0]]), o.inkW, inkC, 0.9, 1.1);+ ink(deform(sail, 1, 0.03).concat([deform(sail, 1, 0.02)[0]]), o.inkW * 0.9, inkC, 0.9, 1.0);+ // fold line: gunwale crease + sail center crease+ ink([{ x: -0.30 * s, y: -0.045 * s }, { x: 0.30 * s, y: -0.045 * s }], o.inkW * 0.6, inkC, 0.55, 0.9);+ ink([{ x: 0.015 * s, y: -0.44 * s }, { x: 0.02 * s, y: -0.05 * s }], o.inkW * 0.5, inkC, 0.4, 0.9);+ ctx.restore();+}++// ---------- FRAME A: setting out ----------+function frameA(){+ seed(20260928);+ paper();++ // SKY — wet-on-wet morning: pale cerulean above, rose, then lemon at the horizon+ const HOR = 462;+ wash([{ x: -60, y: -60 }, { x: W + 60, y: -60 }, { x: W + 60, y: 290 }, { x: 640, y: 250 }, { x: -60, y: 280 }],+ '#8fb8d6', { mag: 0.4, edge: 0.05, gran: 260 });+ wash([{ x: -60, y: 180 }, { x: 700, y: 150 }, { x: W + 60, y: 175 }, { x: W + 60, y: 380 }, { x: 500, y: 360 }, { x: -60, y: 390 }],+ '#e8b8a4', { layers: 13, alpha: 0.03, mag: 0.42, edge: 0.04 });+ wash([{ x: -60, y: 320 }, { x: 620, y: 300 }, { x: W + 60, y: 318 }, { x: W + 60, y: HOR + 6 }, { x: -60, y: HOR + 6 }],+ '#f0d68a', { layers: 15, alpha: 0.035, mag: 0.4, edge: 0.05 });+ // blend blobs straddling the band seams (wet-on-wet, no hard boundary)+ blot(340, 265, 420, 46, '#dcb9a8', { layers: 6, alpha: 0.028, mag: 0.5, edge: 0 });+ blot(1000, 250, 380, 42, '#e2bfa2', { layers: 6, alpha: 0.026, mag: 0.5, edge: 0 });+ blot(500, 350, 480, 44, '#eecf95', { layers: 6, alpha: 0.03, mag: 0.5, edge: 0 });+ blot(240, 170, 380, 40, '#a9c3d6', { layers: 5, alpha: 0.028, mag: 0.5, edge: 0 });+ // sun: reserved pale disc with a warm bloom, upper right of center+ const sx = 905, sy = 300;+ for (let i = 0; i < 9; i++){ // scattered bloom, no concentric rings+ const a = rnd() * Math.PI * 2, d = rr(20, 95);+ blot(sx + Math.cos(a) * d, sy + Math.sin(a) * d * 0.8, rr(60, 120), rr(45, 90), '#f0c67c',+ { layers: 4, alpha: 0.022, mag: 0.5, edge: 0 });+ }+ blot(sx, sy, 58, 50, '#f6e3ae', { layers: 7, alpha: 0.08, mag: 0.28, edge: 0, n: 18, rough: 0.07 });+ blot(sx, sy, 44, 41, '#fbf4e0', { layers: 7, alpha: 0.16, mag: 0.16, edge: 0, n: 18, rough: 0.05 });+ // two lazy morning clouds+ blot(300, 190, 150, 34, '#f3ede0', { layers: 9, alpha: 0.06, mag: 0.4, edge: 0.03 });+ blot(390, 214, 100, 22, '#e7ddcb', { layers: 6, alpha: 0.05, mag: 0.4, edge: 0.03 });+ blot(1090, 165, 110, 24, '#f1ebdd', { layers: 7, alpha: 0.055, mag: 0.4, edge: 0.03 });++ // SEA — calm bands, greener close, sun path glitter+ wash([{ x: -60, y: HOR }, { x: W + 60, y: HOR }, { x: W + 60, y: H + 60 }, { x: -60, y: H + 60 }],+ '#7fb3c9', { mag: 0.22, edge: 0.06, gran: 320 });+ wash([{ x: -60, y: HOR + 85 }, { x: 660, y: HOR + 65 }, { x: W + 60, y: HOR + 80 }, { x: W + 60, y: H + 60 }, { x: -60, y: H + 60 }],+ '#6ea3a4', { layers: 13, alpha: 0.032, mag: 0.3, edge: 0.05 });+ wash([{ x: -60, y: HOR + 190 }, { x: 700, y: HOR + 172 }, { x: W + 60, y: HOR + 185 }, { x: W + 60, y: H + 60 }, { x: -60, y: H + 60 }],+ '#4f7f92', { layers: 11, alpha: 0.032, mag: 0.32, edge: 0.05, gran: 200 });+ // blend blobs over the sea band seams+ blot(400, HOR + 88, 460, 34, '#6aa5ac', { layers: 5, alpha: 0.028, mag: 0.5, edge: 0 });+ blot(980, HOR + 80, 380, 30, '#74a8b0', { layers: 5, alpha: 0.026, mag: 0.5, edge: 0 });+ blot(600, HOR + 190, 520, 36, '#578798', { layers: 5, alpha: 0.028, mag: 0.5, edge: 0 });+ // sun path on the water+ wash([{ x: sx - 80, y: HOR + 4 }, { x: sx + 80, y: HOR + 4 }, { x: sx + 140, y: 640 }, { x: sx - 160, y: 640 }],+ '#f2d489', { layers: 10, alpha: 0.032, mag: 0.5, edge: 0 });+ // calm ripple strokes (drybrush)+ for (let i = 0; i < 26; i++){+ const y = HOR + 14 + Math.pow(rnd(), 1.4) * 235;+ const x = rr(30, W - 130), l = rr(35, 150) * (0.4 + (y - HOR) / 260);+ const c = rnd() < 0.35 ? '#e9dfc2' : '#3f6f84';+ ink([{ x, y }, { x: x + l, y: y + rr(-2, 2) }], rr(1, 2.4), c, rr(0.14, 0.34), 0.7);+ }+ // horizon: one confident broken ink line+ ink([{ x: 20, y: HOR }, { x: 240, y: HOR - 3 }, { x: 470, y: HOR - 1 }], 1.6, '#3d5a66', 0.38, 1.6);+ ink([{ x: 610, y: HOR - 1 }, { x: 930, y: HOR + 2 }, { x: 1255, y: HOR - 2 }], 1.6, '#3d5a66', 0.33, 1.6);++ // BOAT — lower-left third, heading right, bow a touch up: eager+ const bx = 356, by = 560, blen = 210, tilt = -0.06;+ // its reflection first: draw offscreen, composite squashed + faint + wobbled+ const off = document.createElement('canvas'); off.width = 512; off.height = 512;+ const main = ctx; ctx = off.getContext('2d');+ boat(256, 256, blen * 0.96, -tilt, { inkW: 1.4, shadow: false });+ ctx = main;+ ctx.save(); ctx.translate(bx, by + 58); ctx.scale(1, -0.34);+ for (let i = 0; i < 3; i++){+ ctx.globalAlpha = 0.11;+ ctx.drawImage(off, -256 + rr(-3, 3), -229 + rr(-5, 5));+ }+ ctx.restore(); ctx.globalAlpha = 1;+ // wash the reflection wobbly with sea color so it sits under water+ wash([{ x: bx - 120, y: by + 40 }, { x: bx + 120, y: by + 40 }, { x: bx + 130, y: by + 120 }, { x: bx - 130, y: by + 120 }],+ '#6ea3a4', { layers: 4, alpha: 0.06, mag: 0.3, depth: 4, edge: 0 });+ // wake: small V opening behind (left of) the boat+ ink([{ x: bx - 88, y: by + 44 }, { x: bx - 158, y: by + 58 }], 2, '#e9e4cf', 0.5, 1.4);+ ink([{ x: bx - 86, y: by + 50 }, { x: bx - 172, y: by + 70 }], 2.2, '#3f6f84', 0.26, 1.4);+ ink([{ x: bx + 92, y: by + 42 }, { x: bx + 150, y: by + 50 }], 1.8, '#e9e4cf', 0.4, 1);+ boat(bx, by, blen, tilt, { glow: '#f0d68a' });+ // waterline touch: a little green lapping at the hull+ wash([{ x: bx - 78, y: by + 30 }, { x: bx + 82, y: by + 28 }, { x: bx + 92, y: by + 52 }, { x: bx - 92, y: by + 54 }],+ '#5d94a0', { layers: 4, alpha: 0.07, mag: 0.3, depth: 4, edge: 0.05 });++ // two distant birds+ ink([{ x: 620, y: 205 }, { x: 634, y: 198 }, { x: 648, y: 205 }], 1.7, '#4a4d44', 0.55, 0.8);+ ink([{ x: 676, y: 228 }, { x: 687, y: 222 }, { x: 698, y: 228 }], 1.5, '#4a4d44', 0.45, 0.8);++ paperGrainOver();+}++// ---------- FRAME B: the storm peak ----------+// The crest of the one big wave, as a curve from upper right down to the boat.+function crestPt(t){ // t in [0,1], 0 = off-canvas upper right, 1 = near the boat+ const x = 1330 - 810 * t;+ const y = 130 + 330 * t + 90 * Math.sin(t * Math.PI) * (1 - t * 0.4);+ return { x, y };+}+function frameB(){+ seed(70424511);+ paper();++ // SKY — one full bruised wash first (covers down past the horizon: NO bare paper)+ wash([{ x: -60, y: -60 }, { x: W + 60, y: -60 }, { x: W + 60, y: 500 }, { x: -60, y: 480 }],+ '#41546e', { layers: 15, alpha: 0.038, mag: 0.34, edge: 0.05, gran: 380 });+ // second, darker wash across the top half of the sky+ wash([{ x: -60, y: -60 }, { x: W + 60, y: -60 }, { x: W + 60, y: 300 }, { x: -60, y: 240 }],+ '#37485f', { layers: 11, alpha: 0.032, mag: 0.4, edge: 0 });+ // storm mass as big soft blobs, heavier to the upper right (no polygon seams)+ const cloudSpots = [+ [1120, 90, 320, 120, '#2c3a50', 0.04], [860, 180, 280, 105, '#2c3a50', 0.035],+ [1180, 270, 250, 115, '#243247', 0.036], [640, 80, 250, 90, '#33425a', 0.032],+ [980, 40, 280, 85, '#243247', 0.038], [520, 210, 230, 80, '#36455c', 0.026]+ ];+ for (const [cx2, cy2, rx2, ry2, col, al] of cloudSpots){+ // each cloud is a cluster of overlapping soft blobs, not one cut shape+ for (let k = 0; k < 3; k++){+ blot(cx2 + rr(-rx2, rx2) * 0.35, cy2 + rr(-ry2, ry2) * 0.4,+ rx2 * rr(0.6, 0.95), ry2 * rr(0.6, 0.95), col,+ { layers: 6, alpha: al * 0.7, mag: 0.6, edge: 0 });+ }+ }++ // weigh down the lower sky so the storm presses on the sea+ wash([{ x: -60, y: 250 }, { x: W + 60, y: 210 }, { x: W + 60, y: 470 }, { x: -60, y: 480 }],+ '#4c5e75', { layers: 8, alpha: 0.026, mag: 0.42, edge: 0 });++ // ONE LIGHT: a gap upper-left, a pale shaft falling toward the boat+ blot(280, 145, 130, 82, '#f3e3b2', { layers: 10, alpha: 0.05, mag: 0.5, edge: 0, n: 14, rough: 0.1 });+ blot(280, 145, 70, 48, '#f7ecc9', { layers: 8, alpha: 0.075, mag: 0.4, edge: 0, n: 14, rough: 0.09 });+ wash([{ x: 215, y: 165 }, { x: 360, y: 160 }, { x: 500, y: 555 }, { x: 190, y: 585 }],+ '#efdda6', { layers: 9, alpha: 0.028, mag: 0.5, edge: 0 });++ // SEA — dark heaving water, overlapping well up into the sky wash+ wash([{ x: -60, y: 420 }, { x: 500, y: 440 }, { x: 900, y: 380 }, { x: W + 60, y: 360 }, { x: W + 60, y: H + 60 }, { x: -60, y: H + 60 }],+ '#2f4a5c', { layers: 14, alpha: 0.04, mag: 0.3, edge: 0.06, gran: 380 });+ wash([{ x: -60, y: 545 }, { x: 600, y: 570 }, { x: W + 60, y: 505 }, { x: W + 60, y: H + 60 }, { x: -60, y: H + 60 }],+ '#22394a', { layers: 11, alpha: 0.04, mag: 0.3, edge: 0.06 });+ // blend the sea/sky meeting on the left into a rough weather line+ blot(210, 445, 320, 40, '#33506a', { layers: 6, alpha: 0.035, mag: 0.5, edge: 0 });+ strokeBlob(180, 425, 420, 28, -0.03, '#42607a', { layers: 4, alpha: 0.03, mag: 0.55, edge: 0 });+ strokeBlob(360, 438, 320, 24, -0.05, '#3a5871', { layers: 4, alpha: 0.028, mag: 0.55, edge: 0 });+ // heavy water in the near corner+ blot(150, 660, 340, 90, '#1a3242', { layers: 8, alpha: 0.04, mag: 0.5, edge: 0 });+ blot(60, 540, 220, 60, '#22394a', { layers: 6, alpha: 0.035, mag: 0.5, edge: 0 });+ // open-sea brushwork: long horizontal strokes, slightly lifted by the storm+ for (let i = 0; i < 10; i++){+ const y = rr(460, 700), x = rr(-40, 400);+ strokeBlob(x, y, rr(140, 300), rr(16, 34), rr(-0.12, -0.02),+ rnd() < 0.5 ? '#1d3a4c' : '#33566b',+ { layers: 4, alpha: 0.035, mag: 0.5, edge: 0 });+ }+ // swell strokes on the open sea, following the storm's diagonal+ for (let i = 0; i < 12; i++){+ const y = rr(470, 690), x = rr(-20, 420), l = rr(60, 170);+ ink([{ x, y }, { x: x + l, y: y - l * 0.16 }], rr(1.4, 3), '#16303f', rr(0.14, 0.3), 1.4);+ }++ // THE WAVE — one huge diagonal built off the crest curve+ const N = 14;+ const crestLine = []; for (let i = 0; i <= N; i++) crestLine.push(crestPt(i / N));+ const waveBody = crestLine.concat([{ x: 430, y: 700 }, { x: 760, y: H + 60 }, { x: W + 60, y: H + 60 }, { x: W + 60, y: 130 }]);+ wash(waveBody, '#27435a', { layers: 15, alpha: 0.045, mag: 0.24, res: 52, edge: 0.09, gran: 420 });+ // the face of the wave: brush strokes running parallel to the crest, darker deeper+ const faceBands = [+ [42, '#1d374c', 0.038, 42], [110, '#16293c', 0.036, 58],+ [195, '#132b3d', 0.032, 72], [285, '#122636', 0.028, 84]+ ];+ for (const [off, col, al, wid] of faceBands){+ for (let i = 0; i < 5; i++){+ const t = (i + rr(0.3, 0.7)) / 5;+ if (t > 1) continue;+ const p1 = crestPt(Math.max(0, t - 0.08)), p2 = crestPt(Math.min(1, t + 0.08));+ const ang = Math.atan2(p2.y - p1.y, p2.x - p1.x);+ const p = crestPt(t);+ strokeBlob(p.x + 45 + rr(-8, 8), p.y + off + rr(-8, 8),+ rr(280, 430), wid * rr(0.9, 1.2), ang, col,+ { layers: 4, alpha: al, mag: 0.42, edge: 0 });+ }+ }+ // green glassy face where the light shaft hits the wave, just above the boat+ strokeBlob(575, 505, 230, 70, -0.6, '#4e7d78', { layers: 7, alpha: 0.04, mag: 0.45, edge: 0 });+ strokeBlob(640, 470, 170, 46, -0.55, '#5d8a80', { layers: 5, alpha: 0.04, mag: 0.45, edge: 0 });++ // crest foam: one connected churn hugging the curve — smaller far away, bigger near+ for (let i = 0; i <= 34; i++){+ const t = i / 34;+ const p = crestPt(t);+ const persp = 0.5 + 0.7 * t; // grows toward the viewer/boat+ blot(p.x + rr(-9, 9), p.y + rr(-12, 12), rr(18, 48) * persp, rr(9, 22) * persp, '#f6f1e2',+ { layers: 5, alpha: 0.12, mag: 0.6, edge: 0 });+ }+ // bright lip dabs right on the edge+ for (let i = 0; i <= 16; i++){+ const t = i / 16;+ const p = crestPt(t);+ const persp = 0.55 + 0.65 * t;+ blot(p.x + rr(-8, 8), p.y - rr(2, 12), rr(9, 20) * persp, rr(5, 11) * persp, '#fbf8ee',+ { layers: 4, alpha: 0.26, mag: 0.6, edge: 0 });+ }+ // the breaking lip overhanging near the boat: a heavier churning mass+ blot(555, 452, 64, 34, '#f6f1e2', { layers: 6, alpha: 0.16, mag: 0.55, edge: 0 });+ blot(510, 478, 52, 30, '#fbf8ee', { layers: 5, alpha: 0.2, mag: 0.55, edge: 0 });+ spatter(520, 460, 70, '#f6f1e2', 60, 0.25, 0.6, 2.2);+ // foam sliding down the face: soft narrow streak-blots, not ink staples+ for (let i = 0; i < 9; i++){+ const t = rr(0.2, 0.97);+ const p = crestPt(t);+ const len = rr(40, 100) * (0.5 + 0.6 * t);+ const steps = 4;+ for (let s2 = 0; s2 < steps; s2++){+ const q = s2 / (steps - 1);+ blot(p.x - q * len * 0.5 + rr(-4, 4), p.y + 12 + q * len * 0.85,+ rr(7, 14) * (1 - q * 0.5), rr(5, 9), '#e8e3d1',+ { layers: 3, alpha: 0.1 * (1 - q * 0.55), mag: 0.5, edge: 0 });+ }+ }+ // dark water bites just under the foam edge (short, broken)+ for (let i = 0; i < 7; i++){+ const t = rr(0.15, 0.92);+ const a = crestPt(t), b = crestPt(Math.min(1, t + 0.05));+ ink([{ x: a.x - 2, y: a.y + 20 }, { x: b.x - 2, y: b.y + 20 }], rr(1.8, 2.8), '#152633', rr(0.22, 0.38), 2);+ }+ // spray blown off the crest, upwind+ spatter(900, 260, 170, '#f2ecdc', 120, 0.18, 0.55, 2.3);+ spatter(640, 400, 110, '#f2ecdc', 70, 0.15, 0.5, 2);+ spatter(1120, 180, 120, '#dfe4dd', 55, 0.12, 0.4, 2.1);++ // rain: slanted drybrush strokes over the right sky+ for (let i = 0; i < 30; i++){+ const x = rr(500, W), y = rr(0, 300), l = rr(25, 60);+ ink([{ x, y }, { x: x - l * 0.45, y: y + l }], rr(0.8, 1.5), '#8ea0b4', rr(0.08, 0.2), 0.5);+ }++ // BOAT — small, climbing the lit slope, bow up, still pointing right/into it+ const bx = 440, by = 566, blen = 122, tilt = -0.30;+ // halo of the light shaft catching the boat FIRST (paint light, then subject)+ blot(bx + 8, by - 30, 95, 75, '#f2e4b4', { layers: 6, alpha: 0.045, mag: 0.4, edge: 0 });+ // trough shadow beneath it+ wash([{ x: bx - 70, y: by + 28 }, { x: bx + 62, y: by + 8 }, { x: bx + 78, y: by + 48 }, { x: bx - 80, y: by + 64 }],+ '#122736', { layers: 6, alpha: 0.045, mag: 0.42, edge: 0 });+ boat(bx, by, blen, tilt, { dark: true, inkW: 1.8, glow: '#f0dda6' });+ // foam smacking the hull+ spatter(bx - 42, by + 28, 46, '#f4efe1', 46, 0.3, 0.7, 2);+ ink([{ x: bx - 62, y: by + 28 }, { x: bx - 112, y: by + 50 }], 2.2, '#e9e4d2', 0.55, 1.6);+ ink([{ x: bx + 42, y: by + 10 }, { x: bx + 86, y: by + 4 }], 1.8, '#e9e4d2', 0.4, 1.4);++ paperGrainOver();+}++// ---------- harness ----------+window.drawFrame = function(which){+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, W, H);+ if (which === 'b') frameB(); else frameA();+ window.DONE = true;+};+window.READY = true;+</script>+</body>+</html>diff --git a/assets/previews/ascii-a.jpg b/assets/previews/ascii-a.jpgnew file mode 100644index 0000000..90230b0Binary files /dev/null and b/assets/previews/ascii-a.jpg differdiff --git a/assets/previews/ascii-b.jpg b/assets/previews/ascii-b.jpgnew file mode 100644index 0000000..9dc0be9Binary files /dev/null and b/assets/previews/ascii-b.jpg differdiff --git a/assets/previews/chrome-a.jpg b/assets/previews/chrome-a.jpgnew file mode 100644index 0000000..06dee55Binary files /dev/null and b/assets/previews/chrome-a.jpg differdiff --git a/assets/previews/chrome-b.jpg b/assets/previews/chrome-b.jpgnew file mode 100644index 0000000..77fca9fBinary files /dev/null and b/assets/previews/chrome-b.jpg differdiff --git a/assets/previews/crayon-a.jpg b/assets/previews/crayon-a.jpgnew file mode 100644index 0000000..abc9f53Binary files /dev/null and b/assets/previews/crayon-a.jpg differdiff --git a/assets/previews/crayon-b.jpg b/assets/previews/crayon-b.jpgnew file mode 100644index 0000000..74a586dBinary files /dev/null and b/assets/previews/crayon-b.jpg differdiff --git a/assets/previews/dark-a.jpg b/assets/previews/dark-a.jpgnew file mode 100644index 0000000..fb98c9aBinary files /dev/null and b/assets/previews/dark-a.jpg differdiff --git a/assets/previews/dark-b.jpg b/assets/previews/dark-b.jpgnew file mode 100644index 0000000..33016d3Binary files /dev/null and b/assets/previews/dark-b.jpg differdiff --git a/assets/previews/explainer-a.jpg b/assets/previews/explainer-a.jpgnew file mode 100644index 0000000..46bc069Binary files /dev/null and b/assets/previews/explainer-a.jpg differdiff --git a/assets/previews/explainer-b.jpg b/assets/previews/explainer-b.jpgnew file mode 100644index 0000000..95c6b15Binary files /dev/null and b/assets/previews/explainer-b.jpg differdiff --git a/assets/previews/game-a.jpg b/assets/previews/game-a.jpgnew file mode 100644index 0000000..d42c7e6Binary files /dev/null and b/assets/previews/game-a.jpg differdiff --git a/assets/previews/game-b.jpg b/assets/previews/game-b.jpgnew file mode 100644index 0000000..6a418fdBinary files /dev/null and b/assets/previews/game-b.jpg differdiff --git a/assets/previews/glow-a.jpg b/assets/previews/glow-a.jpgnew file mode 100644index 0000000..49c83fcBinary files /dev/null and b/assets/previews/glow-a.jpg differdiff --git a/assets/previews/glow-b.jpg b/assets/previews/glow-b.jpgnew file mode 100644index 0000000..f9ca973Binary files /dev/null and b/assets/previews/glow-b.jpg differdiff --git a/assets/previews/hud-a.jpg b/assets/previews/hud-a.jpgnew file mode 100644index 0000000..ec47a22Binary files /dev/null and b/assets/previews/hud-a.jpg differdiff --git a/assets/previews/hud-b.jpg b/assets/previews/hud-b.jpgnew file mode 100644index 0000000..a6ca599Binary files /dev/null and b/assets/previews/hud-b.jpg differdiff --git a/assets/previews/ink-a.jpg b/assets/previews/ink-a.jpgnew file mode 100644index 0000000..1dd02f5Binary files /dev/null and b/assets/previews/ink-a.jpg differdiff --git a/assets/previews/ink-b.jpg b/assets/previews/ink-b.jpgnew file mode 100644index 0000000..bfa75a7Binary files /dev/null and b/assets/previews/ink-b.jpg differdiff --git a/assets/previews/lyric-a.jpg b/assets/previews/lyric-a.jpgnew file mode 100644index 0000000..a6a6d20Binary files /dev/null and b/assets/previews/lyric-a.jpg differdiff --git a/assets/previews/lyric-b.jpg b/assets/previews/lyric-b.jpgnew file mode 100644index 0000000..46d7697Binary files /dev/null and b/assets/previews/lyric-b.jpg differdiff --git a/assets/previews/manifesto-a.jpg b/assets/previews/manifesto-a.jpgnew file mode 100644index 0000000..16f58acBinary files /dev/null and b/assets/previews/manifesto-a.jpg differdiff --git a/assets/previews/manifesto-b.jpg b/assets/previews/manifesto-b.jpgnew file mode 100644index 0000000..a23b7f1Binary files /dev/null and b/assets/previews/manifesto-b.jpg differdiff --git a/assets/previews/mono-a.jpg b/assets/previews/mono-a.jpgnew file mode 100644index 0000000..37c2aaeBinary files /dev/null and b/assets/previews/mono-a.jpg differdiff --git a/assets/previews/mono-b.jpg b/assets/previews/mono-b.jpgnew file mode 100644index 0000000..d8e1827Binary files /dev/null and b/assets/previews/mono-b.jpg differdiff --git a/assets/previews/papercut-a.jpg b/assets/previews/papercut-a.jpgnew file mode 100644index 0000000..505e0edBinary files /dev/null and b/assets/previews/papercut-a.jpg differdiff --git a/assets/previews/papercut-b.jpg b/assets/previews/papercut-b.jpgnew file mode 100644index 0000000..07a31bcBinary files /dev/null and b/assets/previews/papercut-b.jpg differdiff --git a/assets/previews/penciltest-a.jpg b/assets/previews/penciltest-a.jpgnew file mode 100644index 0000000..1667cacBinary files /dev/null and b/assets/previews/penciltest-a.jpg differdiff --git a/assets/previews/penciltest-b.jpg b/assets/previews/penciltest-b.jpgnew file mode 100644index 0000000..2a4ece7Binary files /dev/null and b/assets/previews/penciltest-b.jpg differdiff --git a/assets/previews/pixel-a.jpg b/assets/previews/pixel-a.jpgnew file mode 100644index 0000000..236052aBinary files /dev/null and b/assets/previews/pixel-a.jpg differdiff --git a/assets/previews/pixel-b.jpg b/assets/previews/pixel-b.jpgnew file mode 100644index 0000000..88fcbfeBinary files /dev/null and b/assets/previews/pixel-b.jpg differdiff --git a/assets/previews/riso-a.jpg b/assets/previews/riso-a.jpgnew file mode 100644index 0000000..62b9f36Binary files /dev/null and b/assets/previews/riso-a.jpg differdiff --git a/assets/previews/riso-b.jpg b/assets/previews/riso-b.jpgnew file mode 100644index 0000000..6679e8aBinary files /dev/null and b/assets/previews/riso-b.jpg differdiff --git a/assets/previews/short-a.jpg b/assets/previews/short-a.jpgnew file mode 100644index 0000000..3dfb087Binary files /dev/null and b/assets/previews/short-a.jpg differdiff --git a/assets/previews/short-b.jpg b/assets/previews/short-b.jpgnew file mode 100644index 0000000..d38287cBinary files /dev/null and b/assets/previews/short-b.jpg differdiff --git a/assets/previews/sketch-a.jpg b/assets/previews/sketch-a.jpgnew file mode 100644index 0000000..9f38b7cBinary files /dev/null and b/assets/previews/sketch-a.jpg differdiff --git a/assets/previews/sketch-b.jpg b/assets/previews/sketch-b.jpgnew file mode 100644index 0000000..a106a2eBinary files /dev/null and b/assets/previews/sketch-b.jpg differdiff --git a/assets/previews/teach-a.jpg b/assets/previews/teach-a.jpgnew file mode 100644index 0000000..82374f5Binary files /dev/null and b/assets/previews/teach-a.jpg differdiff --git a/assets/previews/teach-b.jpg b/assets/previews/teach-b.jpgnew file mode 100644index 0000000..8f67eb0Binary files /dev/null and b/assets/previews/teach-b.jpg differdiff --git a/assets/previews/title-a.jpg b/assets/previews/title-a.jpgnew file mode 100644index 0000000..2ccaa2bBinary files /dev/null and b/assets/previews/title-a.jpg differdiff --git a/assets/previews/title-b.jpg b/assets/previews/title-b.jpgnew file mode 100644index 0000000..7c4c458Binary files /dev/null and b/assets/previews/title-b.jpg differdiff --git a/assets/previews/watercolor-a.jpg b/assets/previews/watercolor-a.jpgnew file mode 100644index 0000000..8796825Binary files /dev/null and b/assets/previews/watercolor-a.jpg differdiff --git a/assets/previews/watercolor-b.jpg b/assets/previews/watercolor-b.jpgnew file mode 100644index 0000000..4c88664Binary files /dev/null and b/assets/previews/watercolor-b.jpg differdiff --git a/examples/INDEX.md b/examples/INDEX.mdnew file mode 100644index 0000000..8c81ddc--- /dev/null+++ b/examples/INDEX.md@@ -0,0 +1,53 @@+# Work we studied++Films and posts by other people that taught this skill something. Each one belongs to its maker, linked here. Nothing of theirs is in this repo: no frames, no prompts, no code. Every style is taught by its own written recipe in `references/styles/` and proven with our own two preview frames.++If you made one of these and want the entry changed or removed, open an issue.++| Work | Maker | What it taught |+|---|---|---|+| "You're Absolutely Right!" | [@MilitantAI](https://x.com/MilitantAI/status/2104809953282465952) | Three-ink overprint, a mascot lead, one gag per sung line (riso pop) |+| Launch-video notes | [notes.apoorv.xyz/launch-videos](https://notes.apoorv.xyz/launch-videos) | How launch films are structured, shot by shot |+| Pencil test | @Ror_Fly | Perform a motion, freeze it, take it apart (animator's pencil test) |+| Motion-design pipeline | [howseen-ai/claude-motion-design](https://github.com/howseen-ai/claude-motion-design) (MIT), Raphael Aubry | Closed-form springs and motion moves that read as designed |+| "The history of dinosaurs in under one minute" | [@kevin_t_ngo](https://x.com/kevin_t_ngo/status/2104638743634391408) | Wobbly line and crayon fill make characters that can move a lot (crayon storybook) |+| motionmaxxing | [Tejashmakwana/motionmaxxing](https://github.com/Tejashmakwana/motionmaxxing) (Apache-2.0), Tejas Makwana | Asking of every shot whether it is a page or a picture, and measuring a film's text with a script instead of by eye (ideas only: our check and our script are our own) |+| anidoodle | [alexgreensh/anidoodle](https://github.com/alexgreensh/anidoodle) (Apache-2.0), Alex Greenshpun | Music and sound made in code, loudness gates, a render gate (code adapted, see `THIRD_PARTY.md`) |+| "Frontier Traders" | [@goatfishxyz](https://x.com/goatfishxyz/status/2104163769224204376) | Pure black and white with section inversions and one gold moment (monochrome launch film) |+| "ESCAPE VELOCITY" production notes | @anabology | Running a long music video in chapters; lip-sync checked by measurement |+| "Chasing the Roofline" | [@elliotarledge](https://x.com/elliotarledge/status/2104096029847277687) | A song that teaches, shown in a 3D world of its subject |+| "Open Alignment" | [@Thom_Wolf](https://x.com/Thom_Wolf/status/2103545533474206118) | The manifesto shape: fact, story, turn, numbered vision, callback |+| Music video | [@eudaemonea](https://x.com/eudaemonea/status/2102610626321490404) | Brushstroke skies and a glowing figure (painterly glow) |+| "Goodnight, Keeper" | posted by [@mattshumer_](https://x.com/mattshumer_/status/2103928105320763818) | A wordless short carried by story (cinematic animated short) |+| P(doom) lyric video | [@_mexicat](https://x.com/_mexicat/status/2103108369569726802) | Words as the picture (kinetic lyric video) |+| "THE FRONTIER" | [@vikktorrrre](https://x.com/vikktorrrre/status/2103829638799618407) | Beat-locked type for line-ups and openers (broadcast title sequence) |+| Fashion film | [@anabology](https://x.com/anabology/status/2103534482930491441) | Model footage under a code-drawn overlay (editorial HUD) |+| P(doom) remake | [@donaldjewkes](https://x.com/donaldjewkes/status/2102801274173587569) | A risograph take on the same song |+| "I'm Upping My P(doom)" | [JohnHeibel/PDoomVideo](https://github.com/JohnHeibel/PDoomVideo) | A character-led watercolor music video built in chapters |+| Product explainer | [@achxvi](https://x.com/achxvi/status/2103918792845963545) | A product in 15 to 30 seconds (clean kinetic explainer) |+| "Opus 5.5 Motion Lab: Make Claude Animate Like a Studio" | [Florence, @flxrnc](https://x.com/flxrnc/status/2105311836190978392) | Naming the default look and banning each part by name; a number in place of every adjective; motion numbers that hold up (ideas only, see `THIRD_PARTY.md`) |+| A cinema built in 3D | [@flxrnc](https://x.com/flxrnc/status/2109629188525420930) | Real light, a beam and focus blur change how a code-made film is read |+| Mixed-media paper film | [@chetaslua](https://x.com/chetaslua/status/2109375245320847702) | A different technique in almost every shot, held together by one paper, one palette and small labels |+| Remake of a product film by the motion designer rajzmotion | [@blueemi99](https://x.com/blueemi99/status/2109633997638938935) | A light ground, very small type, real photos, one idea per shot |+| "8'20''" | [@mr_salio](https://x.com/mr_salio/status/2109414908014018906) | One strict system of small type across very different shots |+| What Ships | [whatships.com](https://whatships.com/) | A public directory of launch videos, each linked to its maker's post: where the films in the rows below were found |+| "Every session teaches Devin how you like to work." | [@cognition](https://x.com/cognition/status/2107165034463867001) | A process shown as one real object that changes at each step, one word naming the step |+| Zingage showreel | [@stevelauda_](https://x.com/stevelauda_/status/2101855047412031533) (Blissful) | One real control shot very close, like a product on a table |+| "Introducing Code Review" | [@claudeai](https://x.com/claudeai/status/2031088171262554195) | The box the user types in as the whole frame; a team of agents never drawn |+| Launch reel | [@benjitaylor](https://x.com/benjitaylor/status/2082515001949221152) | Pure white or black, very small type, one real control at a time |+| "Introducing Graphical" | [@joshpuckett](https://x.com/joshpuckett/status/2107175379903594714) | The product's real parts as the picture, one of them changed live |+| Marmar launch film | [@tomiwebstr](https://x.com/tomiwebstr/status/2092175528396493189) | Footage, 3D, type and interface cut together in one colour |+| "GPT-6 and Intelligent UI" | [@OpenAI](https://x.com/OpenAI/status/2107894997538525580) | Real people and paper, the product as a small card over the footage |+| "A new home for designers" | [@getondesign](https://x.com/getondesign/status/2107333887026491811) | A launch film with no graphics at all |+| "Roma is the to-do list that does itself." | [@jans](https://x.com/jans/status/2107476474399985729) | A founder on camera, plain squares beside him |+| "A new Creative Studio at Vercel" | [@evilrabbit_](https://x.com/evilrabbit_/status/2105062376575992090) | Black, white and one red; a new technique in every shot |+| Cosmos launch film | [@Varcyyyy](https://x.com/Varcyyyy/status/2090184114083447165) (Pixel Frame) | A product shown through its own real content |+| Concept film for Linear | [@BhaskarVisuals](https://x.com/BhaskarVisuals/status/2092251902385807543) | A list of steps where each step gets its own picture and the words stay small |+| Pencil, swarm mode | [@tomkrcha](https://x.com/tomkrcha/status/2026329359838318906) | Many agents shown as the product working, with no diagram of them |+| Paper Mono, and how it was made | [@vladmoroz](https://x.com/vladmoroz/status/2107865714812162228), [@agusegui](https://x.com/agusegui/status/2108251509830140401) | A film made in code whose world is the product's own windows and a printed book |++For a far larger list of Opus 5.5 videos with the prompts their makers shared, see [yihui-dev/awesome-opus5-5-videos](https://github.com/yihui-dev/awesome-opus5-5-videos).++## Adding to this list++When someone shares a reference worth learning from: study it (`scripts/contact-sheet.sh`), write what it teaches in your own words, add a row here with a link to the maker, and if it is a new look, write a style file and render its two preview frames. Never copy the work itself.diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..67a14aa--- /dev/null+++ b/package.json@@ -0,0 +1,13 @@+{+ "name": "take-one",+ "version": "0.1.0",+ "private": true,+ "description": "Claude Code skill: a short film from one line, built like a studio team and rendered from code (headless Chrome + ffmpeg).",+ "license": "MIT",+ "engines": { "node": ">=18" },+ "scripts": {+ "gate:self-test": "node scripts/gate.mjs --self-test",+ "check": "for f in scripts/*.mjs scripts/music/*.mjs scripts/review-room/*.mjs assets/previews-src/snap.mjs; do node --check \"$f\" || exit 1; done && for f in scripts/*.sh; do bash -n \"$f\" || exit 1; done && echo all scripts parse"+ },+ "dependencies": { "playwright-core": "^1.63.0" }+}diff --git a/references/adapt-a-style.md b/references/adapt-a-style.mdnew file mode 100644index 0000000..6eeaffe--- /dev/null+++ b/references/adapt-a-style.md@@ -0,0 +1,46 @@+<!-- Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun -->++# Learn a style from a reference++The user shares a link or a video: "I love this look, can we do this?" The rule: **borrow the hand, never the picture.** A hand is a way of making marks: what touches the paper, what the edge does, the order things go down, the ground, the palette, how it moves. The reference's subject, composition, characters and text are not material; none of that crosses over.++Numbers help you look; they never decide. Every statistic of an image mixes subject, layout, lighting and medium: a mostly empty frame reads "light key, few edges" whatever hand drew it, and lettering reads as "line". Anidoodle proved this the hard way: in both of their documented adapt-a-style runs, the statistical nearest style was wrong. The verdict is a written recipe and the two PAPER BOAT frames rendered in the new hand.++## The workflow++1. **Get the pixels.** Download the video (or save the image). Contact-sheet it:+ ```bash+ scripts/contact-sheet.sh <video> [outdir]+ ```+ which writes a 6x4 sheet across the whole length plus 3 full frames (`frame-0.15.png`, `frame-0.5.png`, `frame-0.8.png`). Reference material stays in a study folder outside the skill, never in the skill (the gallery shows only our own renders).++2. **Analyze 2-3 frames** (visually different ones: a wide, a busy, a dark):+ ```bash+ node scripts/analyze-style.mjs <frame.png> --json <outdir>/profile.json+ # or straight off the video: node scripts/analyze-style.mjs <video> --frame 240+ ```+ It prints the palette (OKLab k-means, ground and darkest ink, area shares), value key and contrast, line presence and width, stroke direction and coherence (structure tensor on the grain), stroke length, speckle, edge hardness and pooled rims, spectrum slope, and a periodic-lattice (halftone) detector, then a prose summary. Exclude what is not the hand, UI and captions above all: `--exclude x,y,w,h;x,y,w,h`, or `--crop x,y,w,h` to a clean region.++3. **LOOK before you trust a number.** Open a frame at full size AND a 3x crop of a busy region, and write down what you see: what touched the surface, how wet or dry, what one unit mark is, what the edges do, what order things went down in. Only then read the profile, for what the eye misses: an exact ground hex, a stroke direction, a halftone pitch, whether edges pool. Where your eyes and the numbers disagree, the eyes win and you say so.++4. **Write the recipe as a style file**, `references/styles/<id>.md`, in our house format (exemplar: `references/styles/crayon-storybook.md`: reference credit line up top, "why this style exists", Design system, story grammar if the reference teaches one, Engine notes, "Best for"). The design system must fill these slots, in words a builder can execute:+ - **Medium, physically:** what touches the surface, how wet, what the ground does back.+ - **Marks:** the unit mark, its size, what varies along it.+ - **Edge:** hard, soft, lost, pooled, torn; where the edge darkens or disappears.+ - **Order:** what goes down first and what last. The order is half the hand.+ - **Palette:** the colours **with hex values**, the ground, and the value range they live in.+ - **Light:** one named source and what it does to the marks.+ - **Motion grammar:** how this hand moves: boil rate, what animates vs what holds, camera behaviour, transition devices, pacing/beat length.+ - **Not its neighbour:** name the nearest style already in our gallery (`SKILL.md` step 2 table) and the one or two things that make this one differ. If nothing real differs, it is not a new style; fold the lesson into the existing file instead.++5. **Provenance, in the style file's header block:** the source link, who brought it, the date, and the line "no reference pixel is copied; only tools read the image". The reference's subject, composition, characters, signature motifs and text are never reproduced; a living artist's signature motifs never cross over. Render code never opens the reference file.++6. **PROVE it: render the two PAPER BOAT frames** per `assets/previews-src/BOAT-BRIEF.md` (frame A "setting out", frame B "the storm peak", all code, deterministic) before the gallery card ships. This is the side-by-side test on a DIFFERENT subject: same hand, new picture. Self-review per the brief (full size and 360 px wide, honest 1-10 per frame); running `analyze-style.mjs` on your own frames next to the reference's profile is a good diagnostic, but iterate on the recipe, not on the numbers. Two or three rounds is normal.++7. **Ship it:** add the gallery card (`assets/gallery.html` + the two jpgs in `assets/previews/`), add the style row to the SKILL.md step 2 table, and **add the `examples/INDEX.md` row** for the reference (link, stats, style, how it was made, lesson), per the INDEX header.++## The no-copy rule++- Never trace, re-lay-out or re-stage the reference. New subject, new composition, always; the boat brief enforces this by construction.+- No reference pixel is copied; only tools read the image (`contact-sheet.sh`, `analyze-style.mjs`, your eyes on the frames).+- A small statistical distance cannot certify "a convincing adaptation", and no distance can certify "not a copy". The recipe in words plus the boat frames are the only verdicts.diff --git a/references/audio.md b/references/audio.mdnew file mode 100644index 0000000..db8c4c7--- /dev/null+++ b/references/audio.md@@ -0,0 +1,157 @@+# Audio++## Measure, don't guess (run before every delivery)++Run the meter on the final mix (or the exported MP4 itself) before showing the user anything:++```bash+node scripts/audio-check.mjs final.mp4 # film mix (default target)+node scripts/audio-check.mjs master.wav --target dense # music master, dense style+node scripts/audio-check.mjs master.wav --target gentle # music master, gentle style+node scripts/audio-check.mjs mix.wav --stems vocals.wav other.wav # vocal-masking check+```++It decodes through ffmpeg (so you meter what a player hears) and reports integrated LUFS (BS.1770-4), LRA (EBU 3342), 4x-oversampled true peak, and spectral centroid, each cross-checked against ffmpeg's own `ebur128`. If the two LUFS numbers disagree by more than 0.5 LU the tool exits 2: that is a metering bug, not a mix note.++The numbers must be:+- **Film final audio:** integrated near **-14 LUFS** (within 1 LU), true peak **<= -1 dBTP**.+- **Music master:** **-14 LUFS** for dense styles, **-16 LUFS** for gentle styles, true peak **<= -1 dBTP** either way.+- **Vocals/dialogue over music:** with `--stems`, the vocal stem must beat everything else by **>= 3 dB in 500 Hz-4 kHz in >= 80 %** of its active seconds. Below that, the words are likely masked; raise the vocal or dip the music in that band. (Integrated LUFS of the whole mix can look right while one part is buried: loudness says how loud the whole is, never which part is wrong.)+- Centroid is reported, never gated: it tells you brightness (a music-box piece should sit well above 1 kHz; ~400 Hz means a pad or rumble took over).++If loudness misses target, the tool prints the gain to apply; after any gain change re-run it, because the peak moves too. Fix a hot peak by lowering gain or limiting, never by shipping it: encoders clip inter-sample peaks above -1 dBTP.++## Instrumental beds, stings and loops in code (`scripts/music.mjs`)++When the film needs no vocals, compose the music as a score in code: it's deterministic, fitted exactly to the film's length, and needs no credits and no user round-trip. See `references/music-engine.md` for the notation, the instruments, and the two demo pieces. Use Suno (below) when the film needs a voice or a sung hook.++## Music from Suno (user generates, you cut)++Give the user a Custom-mode prompt with Instrumental on. Structure tags go in the Lyrics box. Don't name real artists or franchises (Suno blocks them); describe the sound.++Example (fighting game):+```+Style: 90s arcade fighting game techno, aggressive industrial techno, 140 BPM, pounding kick drum, distorted synth stabs, dark gothic choir hits, martial arts gongs, taiko drums, epic battle energy, instrumental+Lyrics:+[Intro] [ominous gong, dark choir]+[Build] [fast rising synth arpeggio]+[Drop] [full techno beat, heavy and relentless]+[Break] [everything drops out, heartbeat drum only]+[Outro] [huge choir hit and gong]+```+Ask for the full-length track (Suno clips can be ~20 s; use Extend for a break + outro).++## Cutting music to the story++1. Map the track's structure from its loudness envelope:+ ```bash+ python3 - <<'EOF'+ import subprocess,struct,math+ raw=subprocess.run(['ffmpeg','-v','error','-i','track.wav','-ac','1','-ar','8000','-f','s16le','-'],capture_output=True).stdout+ s=struct.unpack('<%dh'%(len(raw)//2),raw);w=2000+ for i in range(0,len(s),w):+ c=s[i:i+w];r=math.sqrt(sum(x*x for x in c)/len(c))/32768;db=20*math.log10(r+1e-9)+ print(f"{i/8000:5.2f}s {db:6.1f} "+'#'*int(max(0,db+40)))+ EOF+ ```+2. Plan placements: the drop on the big reveal ("FIGHT!"), a muffled low-passed rumble under slow motion, the full hit back on the impact, **silence (fade out) right before the final punchline**. Loop sections in whole bars (bar = 4 × 60/BPM s) to avoid audible seams.+3. **Find the drop by measurement, never from the auto beat grid.** Compute low-band (kick/bass, under ~150 Hz) energy per bar on the beat grid; the drop is the bar where it jumps (typically 6-10 dB over the bar before). Then refine inside that bar in **20 ms windows** of the same low band to the first window of the jump: that is `drop_in_song`. Auto grids and "section" detectors land a beat or a bar off on drops, and a drop that misses the reveal by 100 ms feels broken. Start the song at `drop_in_song - drop_in_film` (the film's reveal time), so the measured drop lands on the reveal's frame.+4. **Place recorded foley by its measured peak, not its file start.** A recorded whoosh, slam or click has lead-in silence and a build; its sync point is its loudest instant. Find it (`argmax` of the absolute sample value, or of 5 ms RMS for a smoother read) and delay the file by `hit_time - peak_offset`. File-start placement lands every recorded hit 20-200 ms late. (`sfx.mjs` cues already carry their sync point; this is for recorded and downloaded sounds.)+5. Build it with `scripts/mux-audio.sh` (edit the segment list) or an ffmpeg `filter_complex` of `atrim` + `adelay` + `afade` + `amix=normalize=0:duration=longest`, then `apad=whole_dur=<len>` and `loudnorm=I=-14:TP=-1.0`. Do not use a bare `apad` before `atrim` (it never ends).++### Three things a listener heard that the meters did not (the Take One launch film)++The maker cannot hear. These came from the owner's ears on a cut that passed every meter.++- **A repeat spliced into a quiet intro is heard at once** ("there was a weird cut in the music here, no?"). Looping "in whole bars" is not enough where nothing covers the join. Never repeat or remove bars in an exposed, quiet part. If the film needs the track longer or shorter, change the film's timing first; if the music must be cut, cut it at the end of a phrase going INTO a quiet part, or inside a full drop. Map the phrases before cutting: compare each bar's spectrum with every other bar (a simple correlation of log band energies); bars that match (0.9 and over) show the phrase shape (ours was A B C D A B), and the phrase end is where a cut can hide.+- **The best fit used one cut in 58 seconds.** Start the track at its own first beat and let its shape carry the film's turns: quiet intro under the thinking, its build under the last quiet beat, its drop on the first big picture, its break on the verdict, its second drop on the result, its last hit on the logo. Move the film's beats to the music's, not the other way round. A music-free second or two before the track enters (a hard cut to silence, keys being typed) makes its entry a moment.+- **Under a voice, fewer sounds.** "A sound for every visual event" is for a film without a narrator. Under one, the owner heard a bell on "A composer writes the music" as "an alarm" and a run of interface ticks under "A sound designer adds every sound" as plain bad. Keep the sounds of things that are pressed, typed, moved or cut (a thud, keys, a swish, paper), and one pop as each new thing takes its turn. Drop bells, chimes, sparkles and any run of ticks. When a line names music or sound, let the music itself answer it.+- **When a shot is about sound, let its sounds be heard, on the music's grid.** After asking for fewer sounds, the same owner asked for these: a lane where a sound designer drops marks labelled hit, whoosh, click, air wanted each mark heard, "even if it's subtle". Three things made that work on paper: each sound matches its label (four different kinds, never a run of one tick); the footage is re-timed so the marks land on the music's half beats (a mark every 0.2 s over a 120 bpm track is off the grid and reads as noise; every 0.25 s is an eighth note); and those sounds are mixed as their own layer over the music, about 6 dB under the voice, not ducked with the bed (`sfx.mjs mix` with a silent bed gives the layer alone). Say in the delivery note that it needs the owner's ear.++## A finished film inside the film++When the film shows another finished film whole (the ad the product made, a customer's spot), that film keeps its own finished sound, untouched. Do not rebuild it from its parts in the new mix: the balance of its voice, music and effects is what was approved, and a rebuild is a different mix. First done for the short Take One launch film (11 Oct 2026), after the owner said of a rebuilt seven-second version "it says just random words".++- **Take it from the lossless final mix** of the film it was approved in: the WAV the MP4 was muxed from, not the MP4's own audio. Prove it is the same sound as the approved file: cross-correlate the two over the stretch; 0.99 or more at zero lag is the same mix.+- **Lay it in after the new film's master**, so the new limiter never touches it: master the new film with silence where the inner film plays, then add the inner film's sound with a 4 ms fade in and a fade out over its last 90 ms.+- **Set its level by the voice, not by a meter.** Take a recorded line that is in both final mixes, find it in each (cross-correlate the clip against the mix) and read the least-squares gain at the best match; move the inserted sound by the difference. Ours was 0.3 dB. If no line is shared, match the narrator's level in the new film to the inner film's own voice the same way.+- **Nothing of the new film plays over it:** no narrator, none of the new film's effects. A transition whoosh that used to rise under the inner film's last second moves to after its last word; print the new film's own level under the insert and expect silence.+- **The new film's music must not run into it.** End the music at a phrase end on the inner film's first frame; bring music back later from silence, at a phrase start. Do not look for a clever join: the inner film has its own music, and a reset is what makes it read as its own thing.+- **Effects that sat on music are exposed when the music is taken out from under them.** After the insert there may be a stretch with no music; lower the effects there by about 3 dB and tell the person that stretch needs their ear.+- Then run the loudness check on the whole film and transcribe the whole mix again. **A transcription of a long mix can skip a line that is there** (ours dropped a whole sentence that followed a loud hit): before treating a line as missing, transcribe ten seconds round it on their own.++## A song whose tempo drifts++Before cutting a song to a grid, check that its tempo is steady: measure where its pulse falls (the phase of its eighth note, taken as a weighted circular mean of onset strength) in ten-second windows at the tempo you measured. A steady song keeps it within about 10 ms from start to end (two of ours: 5 and 8 ms). One generated track wandered by 250 ms and its two tempo readings disagreed (129.1 and 127.9): it was speeding up by about 1.5 % over its length. One stretch factor would have put its beats a third of a beat off the picture's cuts by the end of a 32 s stretch.++Fix it by following the pulse instead of assuming a tempo: unwrap that phase through the track, turn it into a map from song time to grid time, stretch the song in four-second pieces each by its own factor (ffmpeg `atempo`), and join the pieces with 60 ms crossfades. Then measure the pulse of the result again; ours held within 4 ms. Only after that read off the drop, the breaks and the last hit.++Two more things that measuring taught: a mono downmix made by ffmpeg reads about 3 dB hotter than the two channels, so compare songs channel by channel, and bring candidates to the same level before the owner compares them (the louder one tends to win for the wrong reason). And a song may have no last hit at all: if its groove simply stops on a held chord, let it swell in and stop on the film's hit, and let the hit's own sound do the rest.++## When the film has two pieces of music++A film that shows another film whole has two candidates for its own music: the inner film's song, or a second song.++- **The inner film's song is the benchmark.** If it is the better song, the owner will prefer to hear it everywhere. Ours said it in one line: "the ad music is so good that even if you hear it in all the video it's a better experience ... we need to elevate the song of the video". A second song only earns its place if it is as good to the owner's ear.+- **Give the second song a different job, not a smaller copy of the first.** The owner's brief for ours: "upbeat and uplifting ... but not to take away from the video ad sound". So: a brighter mood, a lighter low end (the inner film's hits then land harder), a different groove family, and the relative key (C major against the ad's A minor), so the change at the inner film's first frame is a turn of mood and not a clash.+- **You cannot hear it. The owner picks.** Make two styles, two takes each, give four links in one message, download only the pick (downloads are metered on most plans; read credits and downloads on the account page before and after, and say both). Until the pick, keep the cut that already works.+- A word or a call in the music (the product's name, "action") fights a narrator who speaks through most of the film. If the owner wants it, give it to the narrator as one short line where she is silent anyway.++## Sound effects: code-synthesized by default (`scripts/sfx.mjs`)++Hits, whooshes, UI ticks, pops, presses, swishes, risers, impacts, chimes, paper and ink are now **synthesized in code** (adapted from anidoodle, Apache-2.0): free, deterministic per seed, no ElevenLabs needed. Frames are deterministic, so hit times are known exactly; address every cue by integer film frame.++```+node scripts/sfx.mjs list # 10 kinds x variants, target levels, uses+node scripts/sfx.mjs one impact boom 3 out.wav # audition one (KEY=C BPM=90 env for tuned kinds)+node scripts/sfx.mjs mix plan.json music-bed.wav mixed.wav # place a cue plan over the music+```++`plan.json`: `{ fps, bpm?, key?, seed, cues: [{ kind, frame, variant?, snap? }] }`. The frame is the sound's **sync point**: the hit, the PASS-BY of a whoosh, the END of a riser (its build is rendered before the frame; too early throws). Fractional frames throw. Each cue gets its own seed from (kind, frame, occurrence), so inserting a cue never changes the others. The bed ducks under cues (40 ms attack, 280 ms release, 1.2 s after an impact, capped 9 dB), the mix goes through a look-ahead -1 dBTP ceiling, and any cue more than 6 dB under the ducked bed throws "buried cue" (a cue nobody hears is a bug, not a choice). Taste rules print as warnings: one riser + one impact per film; at most 2 cues in any 100 ms; effects only on real direction changes; transitions get only `whoosh:soft` / `swish` — never a sharp swoosh; typing is one `tick` per character.++**ElevenLabs (or Higgsfield `generate_audio`) stays for voice, announcers, and organic one-offs** the kit can't make (animals, crowds, real-world foley). Credits cost money: quote first.++## Timing a music video to the vocals (proven on a family song video)++1. Isolate vocals: `python -m demucs --two-stems=vocals -o sep song.mp3` (demucs installed in a Python environment).+2. Word timestamps: `whisper-cli -m <path to ggml-large-v3-turbo.bin> -f song16k.wav -l <lang> -ml 1 -sow` (whisper.cpp with the large-v3-turbo model) (the words are rough for sung lyrics; the times are good). Use the user's real lyrics for the text.+3. Onsets: read the vocals stem's loudness in 50 ms windows and mark rises above ~-30 dB; these are the exact hits ("Hai!", names, claps).+4. Tempo from onset autocorrelation; set the engine's bpm and offset so the beat grid sits on the vocal onsets.+5. Put **every word that triggers an action** in the brief's timeline (not only the big hits). Anything left out gets estimated by the animator and usually lands early or late.++## Stressed syllables, not word starts (Hebrew lesson)++Word timestamps mark where a word **starts**. The loud, on-beat moment is the **stressed syllable**, which in Hebrew (often final-stressed: שמחה, מצליח, הכול) comes 0.3-0.45 s later. Land impacts on the stressed syllable, measured from the vocal stem's loudness, or every hit lands 7-11 frames early. Record both times in the song map (start for mouth/anticipation, stress for the hit).++## A song written for the film (app-builder music video lesson)++The strongest thing in the app-builder music video was a Suno song whose lyrics were the film's own lines. The user loved hearing the story sung ("i love the lyrics with the voice") and the whole video was built on it.++**Write it for the storyboard.**+- Offer two tracks with the same arc so one edit fits both: an instrumental and a sung version.+- Lyrics = the on-screen lines: the problem ("Twenty-three requests, zero booked"), the turn ("Someone should" / "I will"), the payoff ("Booking confirmed, seat one of eight"), and the brand line.+- Put `[Break] [one beat of total silence]` before each chorus. Suno honored it, and those silences became the two best moments in the film (an a cappella "I will", a whispered brand name).+- Spell the brand the way it should be sung (a name with digits is written out, "Brand Forty-Four", not "Brand44").+- Give the prompt field by field, in Suno's Custom-mode order: Lyrics box, Styles box, Exclude styles, vocal gender, Weirdness (about 30%), Style Influence (about 75%), title. The user asked for exactly this format.++**Map it before cutting.**+- Measure the tempo; never trust the prompt. Asked for 120 BPM, Suno delivered 121.42 (instrumental) and 120.03 (vocal).+- Detect it on the demucs instrumental stem (`no_vocals.wav`), not the mix: onset autocorrelation for the period, then the phase that maximizes low-band (kick) onsets.+- Write every cut and action as a beat index, `B(k) = phase + k * beat`, and every sung action as a word time from the song map. Re-cutting to another take becomes a data change.+- Whisper drops and mishears sung words ("Booking" came out "Looking", a line vanished). Use the user's lyrics text with whisper's times, and snap word starts to phrase onsets found in the vocal stem's loudness.+- To cut a short pilot from a long song, splice at bar lines (4 beats) and jump to the song's real ending for the final hit.++**Let the song drive the picture.**+- Hook words slam in on the sung word; the drop lands on the story's reveal; the silences carry the turns.+- An audio-reactive HUD costs minutes: compute per-frame log-spectrum bands (about 44) from the song into a JSON file and let the HUD waveform read it, so the graphics breathe with the music.++## Mapping a user's sung track fast (whiteboard-product film lesson)++- `whisper-cli -ml 1` word times drift badly on singing (words start early, phrases merge). What worked: phrase segments from whisper, plus **windowed probes**, running whisper with `-ot <ms>` from successive offsets and reading which word comes first after each offset; plus a 0.1 s vocal-energy map of the demucs vocal stem printed as text. Together they pin each line within about 0.2 s.+- Measure tempo and phase on the instrumental stem, then check structure from the mix's loudness per second: intro, beat entry, chorus, the silent break, the drop.+- **Loop or CTA.** Ending on the song's own silence gives a seamless loop; spending the song's drop on the brand's CTA gives a stronger finish for a brand piece. The user chose the CTA ("it would have been better to finish with a cta"). Offer both at the pitch.+- Trim a quiet lead-in (start the film where the song starts to matter) and shift every timeline value by one constant (`SONG_IN`).++## Mapping a track you cannot hear++`python3 <skill>/scripts/songmap.py track.wav [bpm guess]` prints the tempo, where the first beat falls, loudness for every half second (all, bass, top), the silences and the last strong hit (needs numpy and scipy). Use it to put the track's drop on the film's turn, its silence on the quiet line and its last hit on the end card. To fit a track to the film's beat grid, stretch it by a few percent at most (`ffmpeg -af atempo=`); more than that is heard.diff --git a/references/before-the-first-cut.md b/references/before-the-first-cut.mdnew file mode 100644index 0000000..831a6b3--- /dev/null+++ b/references/before-the-first-cut.md@@ -0,0 +1,43 @@+# Before the first cut: what a checklist catches for free++Walk this on the stills (step 4, the stills gate), before any full export. Every item here was found by a fresh reviewer on a real film, round after round, after the export. Each one is visible in a still, so finding it there costs seconds.++**Why it exists.** On a 40 second product ad, three fresh reviewers in a row returned the cut for things on this page: labels too small for a phone, the surprise arriving at second three, nine seconds of screen with no person, a status that said "ordered" two shots after another said "delivered". Three rounds and two hours moved the score by half a point. None of it needed a reviewer.++## 1. Read it at phone width+Run `node <skill>/scripts/text-audit.mjs` from the film folder first: it measures every word the film draws and fails the ones too small for a phone (and the ones in section 5 that are not up long enough to read). Then make the 360 px sheet of every frame that carries words (`review-pack.sh --text`, or scale the stills) and read it without zooming, because the script cannot see words inside pictures.+- The captions usually pass. The misses are the small things: status chips, tags, counters, menu items, button labels, names under icons.+- A screen or a list is shown as a close crop, not whole: crop in until its text passes at 360 px. A whole screen at once is a screenshot nobody can read.+- A label never runs into the icon or picture beside it. Leave the gap, or make the card wider.++## 2. The first second+- The whole hook is on screen inside the first second, the surprising half included. If the turn is "and two agents", it is up by 0.8 s, not at 3 s.+- Frame 0 is not a bare picture waiting for its words.+- The picture may run ahead of the voice. Do not hold the words back to match a spoken line.++## 3. People stay in the film+- No stretch longer than about six seconds of interface or type with no person and no real result. Break it with a picture, or keep the picture alive behind the interface.+- If the film opens on people, they come back before the end.++## 4. What is on screen agrees with itself+- Every state agrees with every other frame: a status, a counter, who owns what, a name, a price, a day. Read the stills in order for this alone.+- Nothing has happened before the film shows it happen. If a step adds something, it is not already there a shot earlier.+- The voice and the line on screen use the same words. A brand line shown in full is spoken in full.+- Two different things look different. Two agents, two plans or two people that share one plain shape read as one.++## 5. Payoffs get time+- The beat the story turns on holds at least 1.2 s after it lands, on screen and before the cut. A payoff that lands 0.4 s before a cut was not seen.+- The one thing to do (the button, the link) holds three seconds or more. It is never the shortest hold in the film.++## 6. Nothing sits on what matters+- Not on a face, not on the hand doing the action, not on the thing the person is looking at (a phone, a page).+- Nothing important is cut by the frame's edge, and nothing waits half off-screen.+- In stacked lines of type, a descender does not run into the line below.++## 7. Things that travel+- An element that crosses the frame arrives without overshooting. A bouncy spring over a long distance throws it across its neighbours; keep the bounce for things that pop in place.+- Its sound lands on the arrival, not on the take-off.+- A thing that leaves a picture and reappears in an interface is hidden in between, or it reads as stray clutter.++## 8. Only what the product does+- Every screen shows something the product really does, or is plainly an illustration the person agreed to (`SKILL.md`, step 1c). List the illustrated screens now; the list goes in the delivery note.diff --git a/references/brand-brief.md b/references/brand-brief.mdnew file mode 100644index 0000000..0208886--- /dev/null+++ b/references/brand-brief.md@@ -0,0 +1,34 @@+# Brand brief + brand guidelines (required whenever a product or brand is in the video)++The user's rule after the app-builder music video: every product or brand video starts with a brief and brand guidelines, like the research pack another AI tool made for that brand. That pack is why the film looked 1:1 like the brand's own marketing video: design, colors, even the font. No build starts without it.++## Two ways to get it (in stages, ask the user which; on a run, audit the site yourself and say so)++1. **The user's own research agent (for example ChatGPT).** Give the user the prompt below to paste, with the brand, the product URL and the reference video attached. It returns a pack (brief, audit, storyboard, moodboard). Read all of it before pitching.+2. **Claude does it.** Drive the live site in Chrome: computed styles, `@font-face` rules, the logo's DOM SVG, the product UI, the brand's official YouTube or campaign pages. Write the same sections into `BRAND-BRIEF.md` in the project folder.++Either way, then close the gaps with real assets (`references/brand.md`): font files, exact logo paths, a faithful UI rebuild.++## What the pack must contain++1. **Brand audit, observed vs. chosen.** A table of what was measured on the live site (each color with its hex and where it was read, e.g. logo fill, primary button, ink, backgrounds, CTA; each font with its job and weight) kept separate from creative choices. Two close values stay two values.+2. **Voice and lines.** The brand's real taglines, CTA wording and product phrases, quoted exactly.+3. **Motifs.** Recurring visual devices (headline casing, punctuation, grids, labels, framing of product shots, photography style).+4. **Official campaigns.** What the brand's own videos do (people, type, product proof), from its channel; what to keep, what to avoid.+5. **Asset register.** Logo master, font files, product screens, photos: each with source, status (have / need / stand-in) and who supplies it.+6. **The idea.** One takeaway, audience, hero, problem, payoff, and how the reference's craft translates to this brand (the reference gives the look and energy; the brand gives the facts).+7. **Claims check.** No invented metrics, testimonials or features; product proof only from real behavior.++## Research prompt (the user pastes it)++```+Prepare a brand brief and brand guidelines pack for a short video about <BRAND / PRODUCT> (<URL>).+1. Brand audit from the live site: measure every brand color (hex + where you read it: logo fill, primary action, ink, backgrounds, CTA, accents), every font with its job and weight, and save any font files you can. Keep observed facts separate from your creative suggestions.+2. The brand's exact taglines, CTA wording and product phrases.+3. Recurring visual motifs (headline style, punctuation, grids, labels, photography, how the product is framed).+4. Review the brand's official videos/campaigns: what they do, what to keep, what to avoid.+5. Asset register: logo master, fonts, product screens, photos, with source and status.+6. Attached is my style reference video: break down its craft (framing, type roles, overlays, transitions, pacing) and translate it to this brand without copying its subject.+7. One idea: takeaway, audience, hero, problem, payoff, a timed storyboard, and a claims check (no invented metrics or features).+Deliver it as markdown files plus a PDF.+```diff --git a/references/brand-pass.md b/references/brand-pass.mdnew file mode 100644index 0000000..3712d4a--- /dev/null+++ b/references/brand-pass.md@@ -0,0 +1,22 @@+# Brand pass (any film for a real brand or product)++Run it before the pitch's design section and again before showing the first render. A brand marketer's first questions are "is that our font, our colors, our logo, our CTA?" Answer them with the brand's own files, not a look-alike.++## Pull the brand from its live site (5 minutes)++```bash+curl -sL -A "" https://brand.com/ -o site.html # an empty User-Agent gets the public page even when logged in elsewhere+```+- **Typeface:** grep `@font-face` for `font-family` + `src` URLs (one whiteboard-product site: a commercial sans in Regular/Medium/SemiBold plus a mono, served from a site-builder CDN with CORS `*`). Link them from the page at render time; don't copy the files into the project. Keep the product's in-app font (that app used Noto Sans) for recreated UI.+- **Colors:** count `#rrggbb` in the HTML; the top few are ink, grey, accent, button (whiteboard product: ink #1C1C1E, grey #555A6A, yellow #FFDD33, button blue #3859FF).+- **Logo files:** inline `<svg>` in the HTML (wordmark and app icon, with their real fills). Never redraw a logo.+- **Headline and CTA:** the hero `<h1>` and the button next to it, verbatim, including micro-copy (for example "Human collaboration at the speed of AI" · "Get started" · "No credit card needed.").++## Rules+- Use the brand's headline exactly: case, punctuation (that brand's headline had no period).+- No decoration the brand doesn't use. A whiteboard product's tagline first shipped with an italic serif "AI." and a yellow highlighter stroke borrowed from the explainer style; the user asked "is that their design?" It wasn't. Style files set structure and motion; the brand sets type and color.+- End on the brand's real CTA, animated as an action (the cursor clicks the button on a downbeat), not just shown.+- Say what's off-brand you couldn't fix (licensed music, a made-up use case) instead of hiding it.++## Before showing+Walk `quality-checklist.md` in full, every render, and answer "would their brand marketer approve this?" with the specific changes they'd ask for.diff --git a/references/brand.md b/references/brand.mdnew file mode 100644index 0000000..2a51a6e--- /dev/null+++ b/references/brand.md@@ -0,0 +1,36 @@+# On brand, 100% (the app-builder film method)++The user's favorite thing about an app-builder music video: it looked 1:1 like that brand's own marketing video, in design, brand colors, even the font. Two things made that happen:+- **A brand audit before the build (a research pack from another AI tool).** It read the live site and wrote down the palette (logo orange #FF6A00, action orange #FF773C, ink, warm white, cobalt, charcoal CTA), the fonts and their jobs (a custom display face at weight 600 for headings, Geist for UI), the site's lines (its tagline and its "Start building" CTA) and its motifs (sentence-case headlines, dot grid, bracketed labels, white prompt field). Ask the user for such an audit, or do one yourself, as step 0. Use a brief's brand facts; take the look and energy from the user's reference.+- **Real assets for everything the audit could only name.** The steps below closed its gaps (the font files it couldn't download, the logo, the product UI).++For any video about a brand or product:++1. **Fonts: the real files.** Read the site's `@font-face` rules in the browser (`document.styleSheets`, `document.fonts`) and download the actual woff2 files (the brand's display face came from the app domain's static folder; the marketing domain returned empty files, so try the app domain too). Also note the UI font of the product itself (that product's prompt field used Wix Madefor Text, not the heading font).+2. **Colors: computed, not eyeballed.** Read computed styles from the live page: logo fill, primary action button, ink, backgrounds, secondary accents, idle/active states (app-builder brand: logo #FF6A00, action #FF773C, idle send #FFE8DB, ink #0F0E0E). Keep distinct values distinct; don't merge two oranges into one.+3. **Logo: exact vector paths.** Take the SVG paths from the site's header logo in the DOM and draw them in code. Never let an image model draw a logo. If the full wordmark can't be extracted, set it in the brand font as a clearly labeled stand-in and ask the user for the official file.+4. **The brand's own devices.** Look for small signatures and reuse them: that brand's headings end in an orange full stop ("Hi there."), so every slam in the film ended with one. Use their real product lines ("What will you build next?" and its tagline).+5. **Product UI rebuilt faithfully.** Screenshot the real product surface and rebuild it in code at a legible scale (same layout, controls, fonts, colors, states). Label it a rebuild, not a capture, and never let an image model invent the interface.+6. **Keep a tokens file** (colors, fonts, lines, logo paths, source URL and date) as the single source every shot reads from.+7. **Honesty:** for a spec piece, say "spec piece, not affiliated" in the post, and swap stand-ins (wordmark, fonts license) for official masters before wide release.++## When the owner doubts the typeface: a font test, not an argument++On the Take One launch film the owner said the type "gives the AI look away" and asked to "do some tests and select the best font". What worked:++1. Put the type behind one switch in the page (a table of candidates: family, weight, size factor, letter-spacing factor) chosen by a URL parameter, so every candidate renders the real frames, not a specimen. Keep the logo and the wordmark out of the switch: they are the brand, not the film's text.+2. Pick six to nine candidates in clearly different directions (the current face, a serif, a typewriter, a poster face, a pixel face that matches the icons, wider and narrower cuts of the current family), not six near neighbours.+3. Size every candidate so the film's longest headline is the same width in each. Otherwise wide faces look weak and narrow ones look loud.+4. Render the same three frames in each (the first frame, a busy middle frame, the end card), label the rows with one big letter and a two-word description, and send ONE image. Ask for a letter.+5. Expect the first choice to survive: on ours the owner called the original "still the best by far" after the first sheet of six, asked for a second sheet that went further, and then asked which face an admired film uses. A test that ends on the first choice is not wasted: the doubt is gone.+6. Free faces with real weights come from Google Fonts (`css2?family=...` with a browser user-agent returns woff2 links); keep the licence file with the film.++### Naming the typeface in a reference film++When the person asks "what font is this?", do not answer from memory: three confident guesses on ours (two paid faces and a popular free one) were all wrong, and the right answer came only from looking.++1. Find the frames where the type is largest (a tile of the first forty frames usually shows a zoom) and crop them at full resolution. Small captions hide the details that decide it.+2. Write down what the letters do: one-storey or two-storey a and g, the tail of y and j (straight, curved, turned with a flat end), the foot and the top of t, round or square dots, how c, e and s are cut, the notch where u and d meet their stems.+3. Render candidates with the same words beside the crops (a page of `@font-face` rows, screenshotted) and compare letter by letter. Free families come from Google Fonts and Fontshare; for a paid family, the designer's own site often has a free weight or trial, or specimen pictures that settle it.+4. Read the licence before proposing it. A weight that is free to use in a film may still not be redistributed, so its file stays in the film's folder and never goes into a shared repository or skill.+5. Then show the person their own frames in that face next to the current one. What made the reference feel hand-made is often how the type is used (small, sparse, tight, moving with the camera), not the face.diff --git a/references/captions.md b/references/captions.mdnew file mode 100644index 0000000..c4039ca--- /dev/null+++ b/references/captions.md@@ -0,0 +1,27 @@+# Captions that win (from 87 Opus 5.5 posts on X, Sep 2026)++- **The model name in the first three words**, then the result: "Opus 5.5 one-shotted a Mortal Kombat-style game starring me."+- **Under 15 words for the hook**, then at most 1-2 proof lines. The video does the rest.+- **A constraint beats an adjective:** "One prompt. One HTML file." / "No video model. No images." / "every frame drawn in JavaScript". Hype words ("insane", "crazy", "wild") are common but mid-tier; many users don't want them at all. Ask or leave them out.+- **A famous reference** people recognize in one frame (Minecraft, Mario Kart, Mortal Kombat) spreads best. Say "-style" when it isn't the real thing.+- **Hard numbers stick:** "$1874.40 of tokens", "12 hours", "1,605 lines".+- **Something to take away:** the prompt, a playable link, or the source repo in the first reply drives bookmarks.+- **A curated list is bookmark bait.** "10 launch videos that ..." / "every trick in this video, listed" in the post or first reply: one list post drew more bookmarks than likes. When the video teaches, give the list.+- **Make it theirs:** if the user is in the video, say so ("starring me"); strangers won't know otherwise.+- **Honest:** "one-shotted" only for an untouched one-shot file. Otherwise "built with Opus 5.5 in one prompt, then a few tweaks".++First reply template: "One prompt. One HTML file. [Where the art/audio came from]. [Link or 'prompt below']."++LinkedIn: same idea, fuller sentence, first person, one plain reaction line, no hashtags wall. Hebrew posts for Hebrew audiences if the user writes in Hebrew.++**Brand spec pieces:** say it in the post ("spec piece, not affiliated with <brand>"). Fonts, colors and logo paths pulled from the brand's live site are stand-ins until the brand supplies masters; never let an image model draw a logo.++## The brand's own launch posts++When the film launches someone's product, they also need the posts that carry it. These are in the brand's voice and about the product, not about how the film was made (that is the maker's post, above; offer it separately).++- One post per place it will run, each written for that place: X short and first, LinkedIn a fuller first-person sentence or two, Instagram a line and at most a couple of the brand's own tags.+- Open with the film's line or a question the viewer can answer in a word. A line any brand could post ("order yours today") loses to one only this product could say.+- One action, with the link they gave. No invented link, price, date or number.+- No wall of hashtags, no hype words the brand does not use itself.+- Give two or three options for the first line when the person is choosing, and mark them as yours.diff --git a/references/concept-check.md b/references/concept-check.mdnew file mode 100644index 0000000..2eb01d6--- /dev/null+++ b/references/concept-check.md@@ -0,0 +1,82 @@+# Concept check: before anything is built++A storyboard costs minutes. A film costs hours. This check sits between them, and it is the cheapest place to catch a film nobody wants to watch.++**Why it exists.** Two launch films for one tool were built unattended from a delegated brief on the same day, by two separate runs. Both passed the render gate, the text check and the audio meter. The owner watched each once. Of the first: "it doesn't say anything". Of the second: "almost nothing". Of both: "the storyboard or the concept isn't that good and feels like slop". One had taken two hours. Nothing in the process had asked, before building, whether the idea was worth a film.++Run it on the leading idea before the pitch, and again whenever the storyboard changes materially. It applies in full to launch, product, feature and brand films. For a story film or a music video, use steps 1, 3, 5 and 6.++## 1. Retell it++Write the film as a viewer would describe it to a friend, in three sentences at most: it opens on, then, it ends with. No shot numbers, no technique. If you cannot, there is no film yet, only a treatment.++## 2. The three answers++After one viewing, muted, could a stranger say:++- **what it is**,+- **what it does for them**,+- **what to do next**?++Write the answer the film gives to each, and the shot that gives it. An answer that only the caption or the end card gives does not count for the second one: what it does must be seen happening.++For the third, use the real next step. If no link, handle or date exists yet, do not invent one: design the place where it goes, say on delivery that it is missing, and still end on a plain instruction the viewer can act on.++Steps 3 to 5 are the slop test. Slop is work the viewer has already seen, that could be about any product, and that nobody chose.++## 3. Words off++Describe each shot with its words removed. If what is left is a plain ground, the idea in that shot is a caption, not a picture. More than about a third of the runtime as words on a plain ground is a slideshow. Rework the storyboard so the product, a person or an event carries the meaning and the words confirm it.++## 4. Defaults that have already failed++Each of these was built as a product launch, finished cleanly and rejected. Some are real story shapes with their own uses (`formats.md`); what failed was using them to introduce a product to people who might want it. An unattended run drifts toward them because they are safe and easy to make truthful. For an introduction, treat a storyboard that rests on one as a failed concept and choose again, unless the user asked for it by name.++| Default | What it looks like | Why it fails |+|---|---|---|+| The film about itself | its own prompt, storyboard or timeline on screen; "you're watching it"; the making-of as the payoff | Two independent runs landed on this same payoff. It is a wink at the maker. The viewer learns nothing they can use. |+| Samples doing the work | existing sample or portfolio footage as most of the product proof | The viewer sees a showreel assembled, not the product working. Hand-directed samples are not a first-run result, however they are labelled. |+| The process tour | the pipeline's steps as beats: storyboard, animation, music, review | It describes how the maker works. Viewers want the result. |+| The genre joke | mocking other launch films instead of showing this product | It spends the runtime on other people's work and still has to end on a name and a line. |+| The typed prompt on black | the opening is a request being typed on an empty ground | Every tool of this kind opens this way. It is also type on a plain ground (step 3). |++## Result or process: decide it, do not leave it to the user++For a product film, decide how much of how the product works belongs on screen, and say so in the storyboard. The default: the result first and on screen throughout. What makes this product different from the others in its field is then shown as features, one per beat, each seen happening to the hero result itself (a shot sent back and returned better), never as cards, lists or captions. A tool with a real difference in how it works (a director's judgement, a review step, a team of roles) needs those beats, or its position is only a slogan. The moment the result leaves the screen to explain the process, it has become a tour, which has already failed (`launch-film.md`, Rules).++## 5. The one image++Name the single frame a viewer would describe to someone else. If it is a line of text, a logo or a grid of thumbnails, keep looking. This frame usually belongs in the first seconds, not at the end.++## 6. A cold read++This read protects the build, the expensive step. It must not delay the user's first look: when someone is waiting, show them the ways and the storyboard first and run this while they read or straight after they pick. One test run made a user wait half an hour for a first storyboard because two outside reads were placed in front of them.++Makers grade their own storyboards about two points above outside readers. So before building, give the storyboard to a fresh reader who has seen none of the discussion: the retelling and the shot table only, with no rationale and no grade of yours.++Use two fresh readers each round. Give each one line on who will watch it and where. Ask, in this order:+1. What is this for, and what does it do?+2. Would you watch to the end? Where would you stop?+3. What here have you seen before?+4. A score from 1 to 10 on each of the goal's thoughts (from the first reply), and overall. Give them the scale: 10, I would send this to someone; 7, good, I would watch it; 5, fine and forgettable.+5. The one change that would raise your score most.+6. What should not change.++**The bar on paper is 8 overall from both readers.** It was first set at 9, because an owner asked for a nine and a maker's own nine is not evidence. Then the same kind of reader was given three of the best-regarded launch films ever made, written up the same way with the names removed: the highest overall score was 8, and about 7 where the reader said they would not have known the film. So a 9 is not reachable on paper, and 8 is a high bar; the owner settled on it. The nine is judged later, on the picture: the decisive test shot, then the export. Readers hold points back for what the page does not prove, and their overall score follows "do I want the thing" more than "is this a great film". If a reader cannot answer the first question, or calls the idea generic, change the idea, not the wording. Keep what they say is strong. Revise and read again with two new readers, four rounds at most. If two rounds in a row end on the same overall grades, stop revising this idea: it has reached its ceiling. Widen the search instead (`launch-film.md`, "Search wide before you polish"). And when the readers' doubt is whether the picture is as good as the words, no round of text will settle it: build the one decisive shot and judge that. Then show the person the best version with its real grades, round by round. Never report a grade the readers did not give. If it is still under the bar, say what is holding it down and do not build it unattended.++When no fresh reader is available, do the read yourself after a break from the idea, say that it was a self-read, and be harder on it.++## 7. Who says yes++- **A person is there.** First, within a few minutes: the goal as you understand it and the scored ways with the first choice. End with their turn: go, pick another, or say what to change. Wait for it. Then, for the way they chose: the retelling and the storyboard, and the cold reader's answers as soon as they are in. This is the default, because a person who can see the ideas judges them faster and better than any check here.+- **They say it is close.** Fold their note in and run. Do not come back with a new round of options.+- **They delegated and left** ("I trust you", "finish it while I'm away"). The cold read stands in for the yes. Record its answers in `DIRECTION.md` and continue.++Delegation moves who says yes. It never removes this check.++## Where a stronger idea usually is++- **The viewer's moment.** When does this person need the product? Open inside that moment, not on the tool.+- **The strongest real result, first.** Make the best thing the product can make for this film, and build the film around showing it. For a tool with no screen of its own, see "When the product has no screen" in `launch-film.md`.+- **Range.** Several very different results, each made for this film and each on screen long enough to read as a real one.+- **One change, seen.** A single visible before and after, in one continuous shot, beats three explained features.diff --git a/references/directed-look.md b/references/directed-look.mdnew file mode 100644index 0000000..7d4d630--- /dev/null+++ b/references/directed-look.md@@ -0,0 +1,140 @@+# A directed look: when the frame must not look like every other AI explainer++Read this before designing the part of a film that explains a product, and any time someone says a cut "looks like AI" or "like all the others". It came from a launch film whose ad was praised and whose explaining part was not: viewers said it reminded them of every AI video, the same pattern, the same structure. The storyboard was fine. The design was the default.++## Why "avoid the AI look" does not work+Asking yourself for "something that doesn't look like AI" swaps one default for another. On that film the first fix replaced cards and pills with a flat drawing of a desk covered in paper, stamps and labels. It was a second default, with no real light, and the owner found it worse than the original.++What works has two halves: **name the defaults and ban each one by name**, and **replace every adjective with a number**.++That fixes the styling. It does not fix what is being shown, and on our film that turned out to be the larger half. Read the next three sections before anything about style.++## Ways to explain a product, and when each fits+The default look is what comes out when the design is made from memory. These are the ways real launch films explain a product, taken from the films in the next section. Pick the one that fits what this film is for, on your own, and say which and why in the art director's line. It is a way of showing, not a template: the brand, the idea and the film's own material decide what it looks like. Do not show the person other people's films or ask them to choose one.++| Way | What is on screen | Fits when |+|---|---|---|+| The real interface, very close | one control, one row or one typed line fills the frame, on white or black, with a few small words | software with a screen; one feature |+| One object that changes | a list, a board or a page gains and loses parts step by step, one word naming each step | a process, a pipeline, "how it works" |+| The product working | the real canvas filling up, the real output arriving, nothing drawn around it | agents or automation doing work you can see |+| The product's own output as the film | the things made with it, full frame, cut fast | creative tools, libraries, anything whose result is a picture |+| A person, plain shapes beside them | a founder at a desk, squares and lines on black next to them | a new idea that needs trust |+| Life, with the product small | people, hands and places; the interface as a small card or a phone in a hand | consumer products; a feeling more than a feature |+| Mixed media in one colour | footage, type cards, a close look at the interface, cut together in one accent | a strong brand colour and real footage to work with |+| Type alone, with the craft visible | one phrase at a time, thin guide lines and numbers around it | nothing to show yet; a manifesto |+| A few steps, each with its own picture | five lines, five different small scenes, the words kept small | a method of three to five steps |++Two ways can share a film (the product working, then its output full frame). One frame repeated for every item of a list is not on this table.++## What the films that look agency-made have in common+From 25 films read frame by frame in October 2026 (pictures only; nobody listened to them).++1. **They show the real thing, very close.** One real control, one real row, one real line of text fills the frame: a button shot at an angle with the far edge out of focus, a file list in plain mono type, the box the user types in. The interface is rebuilt cleanly, then treated like a product on a table. Nothing is explained with invented icons, numbered pills or diagram panels.+2. **Real people, real footage, real printed things.** A founder at a desk, hands on paper, a walk at golden hour, a clip of old home video, a printed specimen book. One real shot in a graphic film changes how the whole film is read.+3. **A strict palette.** Black, white or one paper tone, and one accent colour that shows up a few times in the whole film.+4. **Small type and a lot of empty space.** One typeface, sometimes one italic word as the accent. The words sit small in the middle or the lower third, often typed with a caret. No bold headline in a corner over a panel.+5. **A different technique in every shot, inside that one system.** Footage, then a type card, then a close look at the interface, then a collage, all in the same two colours and one face.+6. **Nobody lists.** No film showed N items in N matching frames. A process is shown as one real object that changes at each step, with one word naming the step (a file list that loses rows, gains folders, grows connecting lines). A team of agents is never drawn; the product is shown working, and three to five moments carry it.+7. **Short.** Most run 20 to 45 seconds in all.++## The skeleton is the tell, not the skin+Our explainer was rebuilt twice, as a paper desk and as a lit 3D stage, and both kept the same skeleton: a title with a number, a container, a row of invented things, once for each of twelve jobs. The owner preferred neither to the original ("I don't think we cracked it"). A new skin on the same skeleton is the same film.++So before any restyling, change what is shown:+- For each step ask: **what real thing did this step make?** A line of the brief, the sketch, the shot, the track, the note, the score. Put that on screen at full size. The film's own real material is its best picture; ours had a praised ad and kept it in a box.+- A step that made nothing you can see shares a shot with its neighbour.+- **A list becomes one picture that changes**, not one frame per item. Twelve jobs can be twelve changes to a single full-frame shot.+- Keep the storyline and the sound. This is a change of pictures, not of script.+- A made-up brand needs a name nobody else's film is using. Two unrelated films made with agent skills carried the same invented brand name, because a model reaches for the same few names; search a name before you commit to it.++The sections below are for when the film's world really is invented (a story, a song, a product with nothing to show yet). When there is a real thing, it comes first.++## 1. The ban list+Write it at the top of the page's code and keep it alive. After the first stills, name what the render used anyway and add it.++The look people now call the AI look, as our own explainer wore it:+- an off-white or near-black ground with soft colour clouds+- a card with round corners and a soft shadow, a dark panel on a light ground+- a pill with a number and a name; a row or grid of icon tiles+- a big bold sans headline in a corner, one accent colour on everything+- every element popping or sliding up with an overshoot; everything arriving at once+- karaoke boxes on the words; text that moves while it is being read+- **the same frame for every item of a list.** Twelve jobs in twelve identical panels is the pattern viewers named.+- also: purple or blue gradients, glow orbs, drifting particles, a spinning product on a turntable, everything centred++## 2. One committed world+Pick one physical or graphic world that belongs to what the product is, with objects that can carry every fact. A film-making skill became a dark sound stage: a row of twelve director's chairs with the job stencilled on each, a piece of real work beside each one, a lamp over each. Then every fact is an event in that world: storyboard cards drop onto a ledge, a board of slats turns a pencil sketch into the shot, a counter's number wheels roll to the score, paper slips swing down with the notes.++Rules for the world:+- **A list is one camera move past stations**, each built from different objects. It is not one layout shown N times.+- **The name of a thing lives in the world** (on the chair's back), and once more in the corner label.+- **The real result stays real.** The film's own shots are the pictures on the boards and the monitor, moving.+- **Flat pictures need something behind them.** A card floating in front of a far wall reads as an interface. Stand it on a ledge against a board so it casts a shadow.++## 3. Numbers, not adjectives+"Premium", "cinematic" and "modern" are where the default lives. Write the decision instead.++| Instead of | Write |+|---|---|+| premium materials | pale wood roughness 0.6; satin metal roughness 0.4, metalness 0.85; paper roughness 0.92 |+| nice lighting | one softbox key per subject, front left and high, about 4 m away, warm; a low cool fill from the whole sky; a cool rim from behind; which lamps are seen in frame |+| cinematic camera | field of view 16 to 24 degrees; 11 degrees down; never parked: a 2 to 5 % creep in every hold; one travel between subjects of 0.7 s |+| smooth motion | the easing by name, springs as a damping ratio, the frame each move lands on |++**Motion numbers that hold up:**+- Enter with ease-out (`0.16, 1, 0.3, 1` for reveals), move with ease-in-out (`0.76, 0, 0.24, 1`), exit with ease-in (`0.7, 0, 0.84, 0`) and make exits about half as long. Linear only for rotation and counters.+- Springs by damping ratio: 1.0 never bounces, 0.7 to 0.85 is calm, 0.4 to 0.6 is lively, under 0.3 is a cartoon. Position and size may bounce; opacity and colour never.+- A spring as a pure function of time (no simulation, so any frame renders alone): `1 - e^(-z w t) (cos(wd t) + (z w / wd) sin(wd t))`, with `w = 2 pi f`, `wd = w sqrt(1 - z^2)`.+- One hero move per shot. Secondary moves go 50 to 70 % as far and start 100 to 200 ms later. Start the next element when the last is a third to half done.+- Text holds 0.3 s per word plus 0.5 s before anything moves it.+- Frames per beat = fps x 60 / BPM. Compute every beat from time and round each one; adding a rounded count drifts.++## 4. Real light, in code+When the world is physical, flat fills and drop shadows give it away. Build it in a 3D engine on the graphics chip and light it like a set.++**Setup.** `npm i [email protected]` in the film's folder, load it with an import map from the local server (`serve.mjs`), render into a canvas that is not in the page, then draw that into the film's 2D canvas so the words can go on top. `renderFrame(t)` stays a pure function of `t`. The exporter already starts Chrome with the graphics chip on.++**The method: every frame is the average of N renders** (40 is enough for most shots). Each render:+- stands each shadow-casting lamp somewhere else inside its softbox (a 0.8 m square gives a soft edge that hardens at the contact)+- takes one direction of sky for the fill, drawn with more weight near straight up, with its own shadow map: this is what darkens corners and the ground under things+- shifts the camera inside its lens opening and skews the projection so the focus plane stays put: move the camera by `(ox, oy)` along its own right and up, then `m[8] = -m[0] * ox / focus`, `m[9] = -m[5] * oy / focus` on the projection matrix+- nudges the picture by a part of a pixel (add `-2 * jx / width`, `-2 * jy / height` to the same two entries)+- steps the time inside half a frame, which is the motion blur of a film shutter++Add the renders into a float buffer with weight 1/N, then one last pass: exposure, a curve that is straight to about 0.72 and rolls off above it, a small glow from what is brighter than white, darker corners, grain seeded by the frame number. Use the same sample set every frame, so what is left of the sampling stands still instead of flickering.++**What went wrong on the way, so check for it:**+- **A bright set looked like a basic 3D render.** With no bounced light, a white studio goes flat and grey. A dark stage is honest for this method: light falls into black, the pools of light do the composing, and simple shapes read as a set, not as a toy.+- **Fill with no shadow washes everything out.** Environment light, a hemisphere light and lamps that cast no shadow flattened the first stills. Keep them very low; let the key and the sky do the work.+- **A pixel with an endless value turns into black blocks** once the glow blurs it. Clamp what you read before adding it up, and drop any value that is not a number.+- **Small lights far out of focus show the sample pattern** as a cluster of dots. Make them larger than the spacing between samples, or raise N for that shot (128 while a slate filled the frame).+- **Rounded boxes and plain boxes will not merge** until both are made index-free.+- **A mirror in the floor** (the engine's reflector, added on top at about 0.2, stronger at a flat angle, blurred a little) did more for the "shot on a camera" feel than any material.+- **Every word on a prop is a texture**: load the fonts before building the scene.+- **A frame at a cut mixed two shots.** The renders of one frame are spread over the shutter, so the frame on a cut took half its renders from the next shot. Keep every render of a frame inside the shot the frame belongs to.+- **Milky pictures.** A small lift added to the blacks "like a print", plus glow, put the darkest pixel at 25 of 255 and made the film's own photos look washed next to the same photos in the old cut. No lift, less glow, a mild S-curve at the end, and measure the darkest pixel of a still.+- **Framing.** Decide how wide the frame is at the subject (4.6 m here) and place things from that. Nothing the viewer should read may be cut by the frame's edge when the camera settles.++## 5. Shots: no job gets the same frame as the last+The first cut of the new world scored 5.5 with a fresh reviewer, for reasons that had nothing to do with the light. Each one is now a rule.++- **Each job gets its own shot size.** A close look at the work (two cards landing on the ledge, the counter's wheels rolling), then the station. "Chair left, panel middle, prop right" three times in a row is the old card template in 3D.+- **The real result fills the frame for a beat.** The ad's own shot is the best picture in the film: after the board has turned to it, cut in until the board is nearly the whole frame.+- **A prop needs its parts.** A grey block with two discs is clip art next to a real photo. Give the hero prop what makes it that thing: reels with holes that turn while it runs, bright rings on the lens, a hood, a name plate, a red lamp.+- **What the words say must happen.** "It goes back" is the camera racing back down the row to the camera station, the shot being made again, and the camera returning to a new score. A change of text on a screen is not "going back".+- **Nothing waits empty.** A wire with no notes on it yet, a stand with no lamp on it: both read as mistakes. Build the thing that holds the notes as a board that looks finished before they land.+- **Vary a repeat.** Six cards falling exactly alike read as one animation copied. Change the fall time, the tilt and the settle a little for each, and speed the rhythm up.+- **A thing held in front of the lens is held by someone.** A slate floating in mid-frame looks wrong. Bring it so close that its lower edge leaves the frame, and keep its bottom row empty so no word is cut.+- **A very fast sideways move** leaves the renders of one frame as a row of copies. Smear each across the gap to the next one (a sideways blur as wide as the camera slides between two renders).+- **Grain** from a cheap hash shows a fine mesh that reads as compression. Use an integer hash on the pixel position.++## 6. Words: the film's own typeface, large enough for a phone+The first try borrowed a label system seen in a reference (a small figure number, a timecode, an italic serif line). The reviewer named where it came from, and none of it could be read on a phone. Use the film's own headline face at about 58 px for the job's number and name, one mono line under it, in the one corner that is empty in every station frame. No words over a close look. The take number sits small in the opposite corner and turns from "TAKE 1" to "TAKE 2" when the cut is sent back.++The second cut scored 6: better, still under the bar. Simple props beside real photos read as toys, and words on top of the picture were still the old film's title. Shown the cut after two rounds, the owner did not prefer it to the original. The lesson was not a third round of props: it was the three sections at the top of this page. An invented world, however well lit, competes with the real material the film already has.++## 7. Test before rebuilding+Rebuild three moments, not the film: the one that names the product, the strongest pair of steps, and the turn. Put them on the film's own sound and show them next to the old cut. Say what the test does not prove yet: the sound effects were timed to the old picture, the other stations are placeholders, no fresh review has seen it.++## Sound, when the picture changes this much+Every hit lands one frame after its picture, never before. Hits sit 3 to 6 dB over the bed in the band a phone can play (about 200 Hz to 6 kHz); a mix can read -14 LUFS and still be quiet there. Check by measuring the decoded file, not by trusting the plan.diff --git a/references/formats.md b/references/formats.mdnew file mode 100644index 0000000..f6f8a20--- /dev/null+++ b/references/formats.md@@ -0,0 +1,21 @@+# Formats and devices (orthogonal to style)++Recurring creative devices from the top-performing code-rendered videos (mined from a 1,401-video corpus, Sep 2026). A style says how frames look; these say what the piece IS. Offer the fitting one at the pitch.++## Formats++- **The interactive artifact IS the video.** Build a real playable toy/lab/game, then film it being used (cursor in frame, things reacting). Evidence: a draggable black-hole lens lab and a playable Splatoon clone both spread far. Works because viewers know they could touch it too; end the caption with the link. Our angle: we already build deterministic film.html pages; making one interactive first and filming it second is a small step.+- **Production receipts.** State in the caption: brief length, hours, model, tokens, cost, and post the exact brief as the first reply. Turns a nice video into a reproducible flex and drives bookmarks (the top showreels all did this). Pairs with our honesty rule: the numbers must be measured, not vibes. Capture them during the build, not after.+- **Model-vs-model duel.** The same brief run on two models, split-screen with labels. A format people reflexively share to argue in the replies (a case that spread widely). Cheap for us: our briefs are files; running one twice is free.+- **The film draws itself.** The making-of is the payoff: strokes arrive in a hand's order, the press does its make-ready, the scene assembles. Strongest with sketch/ink/crayon/paper styles. Mechanic: marks as data, replayed over a cached composite (see the style files).+- **Genre parody.** A famous launch grammar applied verbatim, deadpan, to an absurd subject: the reveal music, the slow orbit, the "Introducing", the spec callouts, the price slam, for a virus or a baguette. Evidence: a launch parody for a virus and one for a baguette both spread. Works because everyone knows the grammar and the gap between it and the subject is the joke; never wink at the camera. Mimic the grammar, not the brand: no real logos or marks of the company being parodied.+- **Throughline object.** One tiny element survives every cut (a dot, a cursor, a coin, a paper plane) and carries the eye from scene to scene, then ends exactly where it began so the video loops seamlessly. It is the shared-element handoff (`motion-kit.md`) made into the whole structure.+- **Remake mode.** A frame-locked 1:1 remake of a reference launch video for your own brand: same shots, same timings, same music hits, your product. Post it split-screen (original left, remake right). Credit the original by name in frame or caption, and no fake co-marks (their logo beside yours implies a partnership that doesn't exist). Lock timings from the reference's contact sheet (`scripts/contact-sheet.sh`) and cut list before building.+- **One continuous zoom, no cuts.** Macro-to-micro or micro-to-cosmos in a single shot (glass → atoms; a country → the observable universe). We proved it in-house with an infinite-zoom film for a whiteboard product. The discipline: plan the scale ladder first, each decade of zoom needs its own authored content.++## Levers++- **Sincere first-person AI stories out-earn spec demos** in the story cluster (top cases were "Claude reflects on its life" and "collecting human warmth"). A subject-matter lever to OFFER, never to impose (no unasked themes).+- **Scene-synthesized sound:** the scene's physics is the score — every collision plays a note, materials have voices. Beyond cutting to a track; needs the code SFX/music engine.+- **Data guard:** any on-screen number must come from a data slot that refuses invented values (one popular case made the guard itself the story). Extends our "claims literally true" rule to figures.+- **Length exception:** the 30-45 s feed rule stands, but reviewed educational explainers had a ~102 s median and still performed. A teaching piece may run long; a launch piece may not.diff --git a/references/launch-film.md b/references/launch-film.mdnew file mode 100644index 0000000..ecec8e6--- /dev/null+++ b/references/launch-film.md@@ -0,0 +1,72 @@+# Launch and product films: the shape that works++For a film that launches a product, an app, a brand or a feature. It comes from studying launch films with hundreds of thousands to millions of views, and from building one of our own through twenty-one cuts with its owner. A style file says how frames look; this says what goes where.++## The order+1. **Hook**, 3 to 5 s, under a tenth of the film: the viewer's own situation, shown, in a few big words. One clear story with one set of people, not a run of handsome pictures.+2. **Name the product**, right after the hook, with the full frame for about a second.+3. **Show it working on one example.**+4. **Features, each shown on that same example**, one per shot.+5. **The example at scale or out in the world**: the result where real people would meet it.+6. **End card**, about 4 to 5 s: the mark, the name, one line, and where to get it from the first second.++Total 30 to 60 s for a feed. The product and its result fill at least half.++## What the strong ones share+- **One hero example for the whole film.** The same product, the same people, in every shot.+- **The real-looking part is the result**, and it sits inside a calm designed frame. It is never the whole film.+- **The product is shown as small pieces, one per shot**: one control, one prompt box, one number, with a large cursor. A whole screen at once is a screenshot. For a product the person can log into, capture the real thing (`references/real-product.md`).+- **Few words, always big.** Two to five on screen at a time.+- **A plain ground**, light or near black, taken from the brand. The colour comes from the results.+- **Things on top of the pictures**: type that passes behind a person, a word that is the window onto the shot, a line that holds while pictures change behind it. Pictures with captions under them read as a template.++## What went wrong on ours, so check for it+- **The explaining part wore the default look.** The ad was praised; the stretch that explains the product was called "like every AI video, the same pattern, the same structure": one panel layout repeated for each of twelve jobs. Two restyles of the same layout (a paper desk, a lit 3D stage) did not win the owner over either: the repeat was the problem, not the styling. Design that stretch with `references/directed-look.md` before building it, starting from real launch films and the film's own real material.+- **One layout for too long.** If a stretch of more than ten seconds keeps the same frame (a bar on top, a panel, a line bottom left), break it with the result at full frame.+- **A sag in the middle.** Several same-shaped sentences in a row. Merge neighbours into one build and give the time to the strongest beat.+- **The same effect twice.** Each repeat of a pattern (four colours, three reasons) gets its own treatment.+- **The people never come back.** If it opens on people, let them be seen again near the end.+- **A long tail.** After the payoff, everything is short.+- **A film inside the film** needs a clear door: a line or a visible player, or viewers lose where they are.+- **Trust.** Nothing on screen the product does not really do. A number that looks invented costs more than it gains.++## A shorter cut of a film that exists++When the full film feels long, or the brief is a teaser. Learned by cutting our own 85 s launch film down through seven takes, five fresh reviewers (6.5, 7, 7, 7, 7) and the owner's notes between them. None of the short silent cuts passed. What follows is what each round taught.++**The order that held**+1. **The result first, from frame one**, inside a calm frame, 3 s, under one line that makes the viewer ask how. Open on a face if the piece has one: a product close-up read as "a render", a person read as a shoot.+2. **What the person does.** One prompt, typed, the only typed text in the film. The prompt names what the result shows: "make a launch film" followed by a headphone ad lost the viewer, the brand's name in the prompt did not.+3. **The name, early.** A cut that kept the name for the last three seconds was told: "leave before second 25 and you never learn what made it."+4. **The work, shown, each job with its turn.** A list of twelve names was "the one templated moment: twelve equal labels, nothing working". Half a second a job was "too fast", "rushed". One to three seconds each, with the job's real work in the frame, is the film.+5. **The gate.** The reviewer scores the cut, finds it short and sends it back. It is the beat that makes the promise believable, so it gets four seconds, not one and a half.+6. **The result again, at the whole frame, on the music's drop.** The payoff in the same box as the opener read as no payoff.+7. **The step back**, when the outer film was made the same way as the inner one: the picture shrinks back into its frame, then that whole screen shrinks into the same frame under the same headline. It needs both screens to share one layout, or the second frame is only a border.+8. **End card**, the name on the hit.++**What else it cost us to learn**+- **Shorter is not better.** The 28 s cut scored the same 7 as the 20 s one and the owner's note was one line: too fast. Ask how long the story needs before asking how short it can be.+- **Do not drop the voice to save time.** The long film had a narrator the owner had chosen. The short cuts left her out, nobody was asked, and the owner had to ask twice why. If the film has a voice, the short cut is built on her lines: each picture lasts as long as its line takes to say.+- **Proof that arrives after half the film is late**, however good the rest (proof at 53 %: 7).+- **A real stretch of the finished piece beats a re-cut of flashes.** Let it play on its own beat grid, with its own voice.+- **One headline line for the whole film**: one place, one size, its words roll while the pictures change under it. It replaced four layouts and the note "mechanical flips".+- **Cut the music as little as you can.** One stretch of the track whose own shape (quiet, build, drop, break, drop, last hit) carries the film's turns beat the same track cut into six. Repeat a few bars of its intro if the film needs a longer run-up.+- **A hit must be seen.** A full-frame flash on the clap hid the clap; two inverted frames with the object still on screen keep the flash and show the hit.+- **Footage of your own screens, shown small, needs its own crop for each moment.** One crop for all twelve left the work floating "small in empty black".+- **Nothing inside a frame may be cut by the frame.** A card, a panel, a label or a row of thumbnails that touches the player's edge reads as a mistake, however good the crop felt ("the right part of the black screen is cut", three notes in one round). Do not crop by eye: `scripts/content-box.py <video> <start> <seconds> --rest` measures the content box of a moment and prints the crop that keeps a clear margin round it; let the strip be shorter than the player rather than cut. A long timeline may run off the edge in a close-up that is moving; a box with a border may not.+- **Two films side by side read as a comparison, not as "this is inside that".** Our two-player frame for "it made that video, and the one you're watching" was called "very confusing". What read: one thing at a time. First the inner film alone in the player, over the line that made it. Then one step back: that whole screen becomes the picture in the same player, over its own line, and rewinds through everything the viewer has seen. Name each film by the line that made it; a file name under a player explained nothing.+- **A film shown inside the film is shown whole, with its own sound.** Four seconds of the ad, four portraits with one word each, "does not feel like an ad". Seven seconds that opened on the product with its name said aloud, then the people, with the narrator coming back over the rest, was no better: "it says just random words". What the owner had liked in the long film was the whole 15 s spot, with its full voice and its own music, and nobody talking over it. So give it its length, stop the narrator and the outer film's music for it, and use its own finished sound untouched (`audio.md`, "A finished film inside the film"). Say what it does to the length before building: ours went from 63 s to 71.5 s. After it ends, the outer film may play it again small (in a post, in a player) from its first full picture.+- **The first frame carries the first words, and the first shot really moves.** Our opening scored 7 four takes running: stills with a push, then one still made into a depth shot. The notes were the same from the owner and from the reviewer: it does not move, and frame 0 has no words. What changed it: real footage of the finished product (clean: the "workshop" picture with dust and scuffs read to the owner as rust), the first words on frame 0, the big word landing on the music's downbeat.+- **A pictogram of people needs heads apart from shoulders, and an overlap.** Three equal columns with a dot on each read as a bar chart ("no crew" was called that). Two figures behind and one in front in the accent colour read as a group.+- **Inside a player, a row that stands still gets the same margin left and right; a strip that slides fades out before the edge.** A face cut in half by the player's edge and a label chopped as it slid out were both called out in one review.+- **The opening gets its own shot, not one borrowed from the film inside the film.** We opened two takes on the ad's own product shot because it was the cleanest moving shot we had. A reviewer then counted the same close-up four times (opening, inside the ad, in the post, at the end of the rewind) and said the rewind "lands on a near twin of the ad's own shot". The fix was the same product in the maker's world (workbench, sketches, tools), one free picture and one short render: the opening now says "you built this", and the return to the first frame cannot be taken for the ad. With that shot and a giant word on every spoken beat, the hook went from 7 (four reviewed takes running) to 8 and the take was the first to pass.+- **Do not open on the finished result if the film's turn is the reveal of that result.** Showing the ad in the first seconds and again at the reveal read as "showing this and then the final video again". Open on what the viewer has (the thing they built), keep the result for its moment.++## Before pitching: the competitor study (the strategist's job)+For any product in a category the viewer already knows, and always when the person asks for it:+1. Find the two or three closest competitors and, for each, its main product or launch video (its site, its own channel, its ads).+2. Look, do not guess: a contact sheet and a few full frames of each (`scripts/contact-sheet.sh <video>`), its length, how fast it cuts, what the first three seconds show, who is on screen, how the product is shown, how it ends.+3. Write `COMPETITORS.md` in the project: one short block per film, then two lines: what this category always does, and where this film will do the same or differ and why.+4. Say those two lines in the pitch.++"In a similar style to the competitors" means the category's structure, pace and kind of shots. The look (colours, type, logo, lines) stays the brand's own, from the brand pack in step 1b, not from the style gallery. Never use a competitor's pictures or lines. The strongest competitor film is the reference for the bar check in step 5; with no reference at all, skip the side-by-side and say so.diff --git a/references/motion-kit.md b/references/motion-kit.mdnew file mode 100644index 0000000..52f5cec--- /dev/null+++ b/references/motion-kit.md@@ -0,0 +1,45 @@+# Motion kit: moves that read as designed++Small, proven mechanics from the launch-video studies (Raphael Aubry's pipeline, uxmiles, apoorveth; Sep 2026). All are pure functions of t, so they keep the render contract. Pair with the spring presets in `timing.md`.++## Zooms in log space++Scale is multiplicative: a linear tween from 1x to 8x spends almost all its time in the last doubling and feels like it lurches. Interpolate the log and exponentiate:+```js+const zoom = (t, z0, z1, p) => Math.exp(Math.log(z0) + (Math.log(z1) - Math.log(z0)) * Spring.unit(t, p));+```+Each doubling then takes the same time. **No back-to-back in/out:** a zoom in straight into a zoom out reads as a camera wobble; put a hold, a cut or a lateral move between them, or keep zooming the same way (the one-continuous-zoom format).++## Beat punches++A punch is a tiny scale kick on the beat that decays, so the frame breathes with the music without anyone noticing a zoom:+```js+// beats: times in seconds (from the song map); after the drop, bars punch harder+const punch = (t) => beats.reduce((s, b, i) => t < b ? s : s + (b >= DROP && i % 4 === 0 ? 0.03 : 0.012) * Math.exp(-(t - b) / 0.12), 0);+g.scale(1 + punch(t), 1 + punch(t)); // around the frame centre+```++0.012 per beat, +0.03 per bar after the drop, exponential decay (~0.12 s). Bigger reads as a shake. Nothing punches in the quiet sections.++## Shared elements across handoffs++At a scene change, one element carries across: the button that was clicked becomes the next scene's card, the counter's number flies into the headline, the dot becomes the logo's i. It is interpolated (spring, log-space size) from its rect in scene A to its rect in scene B while everything else crossfades or wipes around it. The eye follows the thing it was already looking at, so the cut never makes the viewer search. Rule: every handoff names its carrier, or it is a declared hard cut (the gate's pop check lists the rest).++## Flood circle transitions++A colour flood grows from the click point (or the carried element) to fill the frame:+- The radius must reach the **farthest corner**: `R = Math.hypot(max(x, W - x), max(y, H - y)) * 1.05`. Sized to the width only, a corner stays uncovered for a frame and flickers.+- **0.3-0.35 s**, eased out (`snappy` spring or a cubic ease-out). Faster reads as a flash (and trips the gate's pop check); slower drags.+- Render the next scene inside the circle as a clip, not after it, so the flood reveals rather than covers.++## A fast rewind or scrub through the film++When the film replays itself fast (a rewind inside a player, a scrub along a timeline), each frame jumps a second or more of film, so a dark shot, a light shot and a dark shot land on three frames in a row: a strobe. A fresh reviewer counted four flashes in a second on ours, brightness inside the player going from 4 % to 60 % and back.++- Draw each frame of the rewind as the **average of about ten moments** of the film, spread over the stretch that **five frames** cover, not only its own. Neighbouring frames then share four fifths of what they show and brightness can only drift. Averaging over the frame's own stretch alone does nothing for the flash: each frame still sits inside one shot.+- To average, point the drawing context at a spare canvas, draw the scene at one moment, and add it to an accumulation canvas with alpha `1/(k+1)` for the k-th moment. This needs the page's context variable to be `let`, and scenes that do not reset the transform themselves.+- Measure it: mean brightness inside the player for every frame of the rewind; no change of more than about 0.1 from one frame to the next, and no two opposite changes above 0.1 in a row. Ours went from 0.57 to 0.11.+- Ease in and out, so the first and last moments are sharp and readable; let the thing that explains the rewind (a line of text, a label) stand still for a second before it starts.++## Seek-compatible libraries only++Any animation library in film.html must be driven by t, not by its own clock (toolbox.md): Anime.js with `autoplay: false` then `anim.seek(t * 1000)`, Theatre.js with `sequence.position = t` for hand-tuned camera paths. Never a library that only plays in real time.diff --git a/references/music-engine.md b/references/music-engine.mdnew file mode 100644index 0000000..c723495--- /dev/null+++ b/references/music-engine.md@@ -0,0 +1,102 @@+# Code music engine (v1)++Instrumental music written as a score and synthesized in pure JavaScript. No samples, no API, no credits. The same score and seed always produce the same WAV, byte for byte. It's fitted to the film's exact length by solving the tempo, so the last note lands where the picture ends.++Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun. Every file under `scripts/music/` carries that header.++## When to use it, and when to use Suno++| Use the code engine | Use Suno |+|---|---|+| A bed under narration or captions | Anything with a voice or sung lyrics |+| A sting or button at a cut (a few bars, `hit: true`) | A full "song" that carries the film |+| A seamless loop for a web page or a looping post | A genre texture code can't fake (distorted guitars, real drums, choirs) |+| The film's length will change again (re-fit is free) | The user wants to direct the music himself in Suno's UI |+| Sync matters: notes land on exact frames | |++Code piano, strings, harp and soft lo-fi electronic sound good. Code does not do a convincing rock band, orchestral brass, or a human voice. Don't promise those.++## CLI++```bash+node scripts/music.mjs render <piece.mjs> --seconds 45 --out bed.wav # fit to 45 s, 48 kHz 32-bit float WAV+node scripts/music.mjs render <piece.mjs> --out loop.wav # a plan.loop piece renders as a seamless loop+node scripts/music.mjs check <piece.mjs> [--seconds N] # must print PASS before anyone listens+node scripts/music.mjs meter <file.wav|mp4> # meter any file+```++`<piece.mjs>` default-exports a Piece or a function returning one. `file.mjs#name` picks another export. Every render happens twice and the two are compared sample by sample (it prints `deterministic: yes`).++`check` runs: bar math (a bad bar throws while the score loads), the key/mode histogram against each section's declared key and mode, tempo against the style's range, no close thirds below C3 in piano parts, a determinism check, the master target (LUFS and true peak), onsets per beat, and a cross-check against ffmpeg `ebur128` (it must agree within 1 dB).++Mux the WAV with `scripts/mux-audio.sh`. A loop ships as WAV (MP3 encoder padding clicks at the seam).++**When the film needs an exact tempo.** `render` prints the tempo it solved ("tempo 99.9 bpm"). The fit lands the piece's end on `--seconds`, so a score written at 100 can come out a few beats a minute off. If the cut is on a beat grid, read that line, nudge `--seconds` until it prints the tempo you need, and trim or fade the tail in the mix. One film asked for 40.8 s and got 102.7 bpm; 41.87 s gave 99.9.++## The notation (`line`)++```js+import { line } from "./scripts/music/plan.mjs";+line(startBeat, "Eb4:1 | C5:2 Bb4:.5 Ab4:.5 | [Ab2 Eb3]:1 r:2", { role: "melody", v: 0.7, bpb: 3 });+```++| Token | Meaning |+|---|---|+| `C5:2` | note C5, 2 beats long |+| `F#4:.5` `Bb3:1/3` | sharps/flats; durations as decimals or fractions (triplets `1/3`) |+| `[C4 E4 G4]:1` | a chord; its notes roll by `roll` seconds each (default 12 ms) |+| `r:1.5` | rest |+| `G5:[email protected]` | per-note velocity multiplier (times the line's `v`) |+| `\|` | barline. **Every bar must sum to `bpb`**, the last one too |++Options: `role` (melody, inner, bass, accomp, color, drum), `v` (0.7 = mezzo), `bpb` (beats per bar: 3/4 = 3, 4/4 = 4, 6/8 = 2, 12/8 = 4), `pickup` (the first bar may be this many beats), `roll`, `kind` (drum variant: `o` = open hat), `hit: true` (a single sting bar shorter than the meter).++A wrong bar throws and names the fix: `bar 1 sums to 2.5 beats, meter wants 4: "G4:2 A4:.5" (a line that ends mid-bar writes its rest: "G4:2 A4:.5 r:1.5")`. A gap is always written, never silent.++## A Piece++```js+{+ title, seed, tail /* seconds of ring after the last onset */,+ harmony: [{ t: beat, name: "Am9" }], // drives the piano pedal (lifts at each change)+ plan: {+ style: "nocturne", // tables.mjs STYLES: sets tempo range, room, master+ tempo: 64, meter: "3/4", phraseBars: 4, swing: 0.57 /* 0.5 = straight */, loop: false,+ pickupBeats, rubato, ritard, // optional: rubato 1 = +-2.5 % phrase arch; ritard end-tempo ratio+ sections: [{ id, bars, mood, key: "G", mode: "major", melody: ["hook"], dyn: [0.4, 0.6],+ optional, repeatable, pickup, variations: ["octaveDouble", "octaveUp", "thin"], ending }],+ },+ parts: [{ id, inst, role, notes, gainDb, pan, send /* room send */, opts }],+ shortForm: () => Piece, // used automatically when the film is too short+ fx: { duck: { by: "kick", parts: ["pad"], depth, release }, tape: { wowCents, wowHz, flutterCents, flutterHz, drive }, clean },+ stemTargets: { kick: -14, lead: -17 }, // stem RMS dBFS targets (+-3 dB)+}+```++**Instruments (v1):** `piano` (modal: inharmonic partials, 2-3 detuned strings with two-stage decay, hammer spectrum and strike comb, knock, 40-mode soundboard, dampers, sustain pedal, sympathetic strings), `strings` (5 detuned PolyBLEP saws, bow attack, delayed vibrato; opts `attack release bright width`), `harp` / `guitar` (extended Karplus-Strong), `musicBox`, `ePiano` (FM), `warmPad` (7 chorused saws; `cut attack release spread`), `softPluck` (`decay bright pan delay feedback delayMix`), `sub`, `bass` (saturated, audible on phones), `kick`, `snare` (`rim: true` for ghosts), `hat` (`pan`, `crush`), `vinyl`.++**Performance** (automatic): velocity from the section's `dyn` curve times a phrase arch (peak near 62 % of the phrase), metric accents, AR(1) timing (about 7 ms) and velocity noise, a piano melody lead of 12-28 ms, legato overlap, swing, a closing ritard, and a breath before a sudden hush. Mechanical parts set `opts: { grid: true }`.++**Master:** gentle styles use one static gain to -16 LUFS, capped at -1 dBTP, never a compressor. If the cap stops it short, the loudness goes down (fix it in the notes: stagger the bass an eighth after the downbeat, roll the climax chord, don't double the climax note). Dense styles (lofi, drive) run -14 LUFS through a 1.5 ms look-ahead limiter.++**Fitting:** `fitToDuration` tries every drop of the `optional` sections and every repeat of the `repeatable` group (with variations), solves the tempo that lands the last onset at `seconds - tail`, and keeps the tempo within the style's range +-10 % and +-18 % of the written tempo. Nothing in a score hard-codes the film's length.++## The two demos (`scripts/music/pieces/`)++**`first-light.mjs`: a gentle bed in G, piano and strings, 3/4.** A hook that rises a third and settles by step, a theme with a half cadence and then a full cadence, a four-bar build that climbs to B5 over Am with an eighth-note left hand, a hush, a coda through a borrowed Cm (the Eb), and home. Strings enter at bar 5 as a sustained choir. It has a short form (intro plus theme) for films of 25-33 s.++- 45 s: fitted to 69.4 bpm, full form. -17.9 LUFS, LRA 8.7 LU, -1.05 dBTP (ffmpeg: -17.9 / -1.10), 1.00 onsets/s, centroid 681 Hz. The short-term loudness arcs from -23.8 up to -14.1 at the climax and back down to -26.2. The gentle master is peak-capped: piano treble attacks give a crest of about 17 dB, so it lands 1.9 dB under -16 rather than adding a compressor.+- It fits 30 s (short form, 57 bpm), 45 s, 60 s (theme doubled), 90 s and 120 s (theme and build restated with variations).++**`night-drive.mjs`: a 120 bpm half-time lo-fi loop, 8 bars = exactly 16.000 s.** Am, Fmaj9, Cmaj9, Em7 twice. A kick-ducked warm pad, FM e-piano offbeat stabs, a soft pluck hook through a dotted-eighth ping-pong delay, a sine sub, a snare on 3, swung (0.57) eighth hats, and vinyl and tape wow snapped to whole cycles per loop. The tail is folded back onto bar 1, so it loops without a seam.++- -14.0 LUFS, LRA 1.9 LU, -3.36 dBTP (ffmpeg: -14.0 / -3.40), 4.19 onsets/s (2.1 per beat), centroid 1262 Hz. All stems are within 3 dB of their targets.++Copy a demo as the starting shape for a new score. Write your own melody and changes: a reused tune isn't a new score.++## Limits (v1)++- No mood-table picker yet: you choose style, key, mode and tempo yourself (use `tables.mjs` MOODS as the guide).+- The windowed ghost, reverb and masking guards and the novelty check aren't ported yet. `check` reports onsets per beat for the whole piece only. Run the masking check by hand for melody-led beds (render the melody alone vs the rest, 500 Hz-4 kHz).+- Under about 22 s, First Light plays too fast and truncates (it needs a phrase-length form). Between 33 and 40 s it rings the tail longer.+- Meters are not ears. A PASS says the math is right, not that the music moves anyone. Listen to 8 seconds around the most important mood change before shipping.diff --git a/references/music-video.md b/references/music-video.mdnew file mode 100644index 0000000..b464302--- /dev/null+++ b/references/music-video.md@@ -0,0 +1,70 @@+# Use case: your song → a music video++The user brings a song (often a Suno track) and wants a clip "with lyrics and everything". This is the flow that worked on a family song.++1. **Get the song and the real lyrics** (ask the user to paste them; Suno shows them). Note structure tags ([Verse], [Chorus], [Bridge]).+2. **Map the song** (see audio.md): isolate vocals with demucs, word timestamps with whisper, onsets from the vocal stem, tempo from autocorrelation. Re-transcribe any section whisper garbles from the vocal stem alone. Produce a section map: start/end of every section and line.+3. **Style menu:** 3D teaching song (if the song explains something), watercolor character (story, people), kinetic lyric (words are the visuals), painterly glow (emotional, symbolic), cinematic short (story, stylized 3D), broadcast titles (anthem energy). Pitch the route as in SKILL.md step 3: for an illustrated clip code only is usually the best look, so say why when you pitch it, and say what pictures or moving shots would add.+4. **Concept for the whole song:** one arc across the sections (e.g. a day from dawn to stars; the bridge as the emotional turn; the ending rhymes with the opening). Choruses return to the same place/motif, escalating each time.+5. **Storyboard by section**, one row per section with what happens on screen and which words trigger actions. Approve with the user. For a full song, offer a 30 s test of the opening first.+6. **Build in chapters:** one chapter per section group, parallel animators, shared characters/palette/guide, shared files read-only. Every action word's timestamp goes in the brief.+7. **Lyrics on screen:** decide with the user: soft karaoke subtitles, painted words in the scene, or none. Hebrew and other RTL languages need `direction = 'rtl'` and a font that supports them.+8. **Render with the song** at 1080p; for a 3-4 minute song expect ~30-60 min of rendering on a GPU.+9. **Deliver** plus a 15-30 s cut of the best section (the chorus) for social.++## The studio process for long films (trust the process)++The user should be able to approve a concept and trust the result without checking every step. That trust comes from quality gates, not from luck:++1. **Director agent** (one): owns the plan. Produces (a) an exact song map at word level from the vocal stem, (b) a full shot-by-shot storyboard per chapter with each chapter's first/last frame defined so neighbours match, motifs with setup and payoff, and the escalation plan for returning choruses, (c) a chapter guide for animators (file ownership, shared read-only files, transitions, subtitles, render/review commands, quality bar), and (d) the chapter architecture in code with stubs, verifying the approved test section still renders identically.+2. **Critic agent** (independent, different from the director): reviews the storyboard against timing.md and quality-checklist.md before any animation: dead shots, two reads at once, choruses that don't escalate, weak bridge, missing payoffs, unreadable moments, handoff mismatches. The director (or you) revises. Fixing a storyboard costs minutes; fixing a rendered chapter costs an hour.+3. **Animator agents** (one per chapter, in parallel): build only their chapter file, follow the guide, review their own contact sheets and strips at every action word.+4. **Integrator** (one, last): renders the whole film, checks every chapter boundary frame by frame, fixes seams, renders with the song, and writes the delivery notes.++Use the approved short test (e.g. the first 30 s) as the style bible every agent looks at first.++## Hooks as slams, verses as karaoke (app-builder music video lesson)++- Sung hook lines ("Someone should", "I will", "I built it") slam in big, each word on its sung syllable. Verse lines run as a karaoke strip with the current word in the accent color. Never both for the same line.+- Lines already shown another way (a flap board spelling "23 BOOKING REQUESTS", chat bubbles arriving on a phone) skip the karaoke strip.+- A story clock that runs through the whole song (00 booked → 01 → 08 of 08) gives a 1-2 minute clip a spine, like the reference's countdown.++## Storytelling with the lyrics (make the clip enhance the song)++1. Every line gets an image that carries its meaning at the moment it's sung; the action lands on the line's key word. Write the key word of each line in the storyboard.+2. Repeated choruses are progress markers: the same words over images that show growth (first a hope, then an attempt, finally true). Design a recurring shot or gesture per chorus line that evolves.+3. Verses intimate (close, still, the inner voice); choruses open up (wider, movement, light); the bridge strips everything down.+4. Counterpoint beats literal sometimes: brave words over the small, shaky real step is more moving than a triumphant image.+5. Visual rhymes and payoffs: first frame ↔ last frame; a small motif (a line of light, a closed window, a creature's size) that grows or turns across the song.+6. Quiet, specific, true human details over spectacle (a hand hesitating on a latch; boxes unpacked little by little as a hidden progress bar).+7. Cut and move on the music: cuts on bars, emotional turns on lyric turns, holds when the voice holds. The story reads muted and lands harder with sound.++## Model-footage music video at scale (a public production record, Sep 2026)++One creator released the full production record of a model-footage music video (5:06, 141 shots, 19 h, ~50 director messages). The methods that transfer:++1. **Character identity lives in prompt text, not reference images.** Write the lead as a canon (exact hair, one accent detail, each wardrobe item) and paste it into EVERY image prompt, plus an explicit ethnicity/appearance descriptor (without it the model drifts the face shot to shot). Face-sheet image references over-condition (a close-up-sized head on a distant figure); identity edit passes drift the look. Batch 1 is a **casting call**: 2-3 directions, each as a turnaround + one scene shot + a face sheet; pick the silhouette that reads at thumbnail size.+2. **One family of style words ends every image prompt:** a palette+light line (with hex), the grain, the finish, and always "no text, no letters, no logos". Plus a declared empty area for type ("the top half empty night sky"). That family is what keeps 100+ plates in one world.+3. **Keep generation inputs in color; apply the look in post.** Monochrome plates fed to a video model come back grey and the grade can't recover the "image-model magic". Their fix was exemplar-based recolor using each shot's own source image; ours is simpler: never send a graded/desaturated frame as a generation input.+4. **Storyboard schema:** every shot carries its lyric, a **type mode** (subtitle / coverline / masthead / strobe), its plate prompt, its camera, and clip-or-2.5D. Boards compete: independent director agents board the song from different angles (fashion, meme density, narrative), judges score, a head director merges. Per chapter in the build: an animator writes, an **art-director agent reviews rendered frames** (not code), the animator fixes.+5. **No two clips start from the same frame.** Continue from the previous clip's last frame or pick another start; two clips from one frame is jarring.+6. **Sync most lips, not all** (the Grimes rule). A music video has inserts and cutaways; only the shots that present as singing need sync.+7. **Suno craft:** deadpan spoken verses carry dense references without stretching over melody; the sung euphoric chorus carries the emotional turn; spell out acronyms in the lyrics field (A G I) so Suno pronounces them; use the exclude-styles field.+8. **Director economics:** the director spends ~50 short messages, all taste calls at checkpoints, with a standing rule "wait 5 minutes after sending; silence = approval". Their closing move was ours too: "log all our learnings so future videos are rapid" — the skill IS the product of the work.++The Seedance lip-sync mechanics (audio conditioning, drift detection, cut-and-continue) are in toolbox.md.++## Running the parallel build (lessons from a Hebrew comedy clip, Sep 2026)++A 98 s Hebrew comedy clip, 8 chapters, built by 10 agents in one afternoon. What made the fan-out work, and what broke:++1. **One owner per film.** Before building, check whether another session is already directing the same project (search `~/.claude/projects/*/*.jsonl` for the project's guide file name). Two sessions writing the same `cast.js` overwrite each other. Pick one and tell the user to keep the other closed.+2. **Rig owner in parallel with the style-bible chapter.** Freeze the new rig option names in both briefs up front (`accessory:'shades'`, `lasers:0..1`, `beard:0..1`...) so the chapter animator codes against them before they exist (unknown options are ignored). The rig owner may only ADD options and must prove the approved cast renders pixel-identical with defaults.+3. **Pre-register every chapter's `<script>` tag before the fan-out.** Parallel agents editing the shared `studio.html` race. After registration, agents own only their `chN_*.js`.+4. **Shared render rules:** each agent renders its chapter with `--clip --range` to its own `out/chN.mp4`, never `--frames` (the frames folder is shared), check images under `out/check/chN_*`, and it keeps review renders small because 7 agents share the CPU.+5. **An as-built notes file** (`BUILD_NOTES.md`): the rig, set and prop APIs as actually delivered (not as planned), plus every direction the user gives mid-build. Users send fast fragments while agents work ("graphs up down", "nasdaq", "btc", "etc."); append them to the notes right away instead of asking, and every agent reads the file first.+6. **Say "if your file already exists, continue from it" in chapter briefs.** An interrupted workflow restarts unfinished agents from zero; without that line they may rebuild from scratch.+7. **HUD overlays go in screen space.** A ticker tape drawn inside the camera transform got cropped when the shot zoomed. Draw tapes, tickers and captions after `camEnd()`.+8. **Give the user an ETA for the final render.** p5.brush at 1080p24 ran at about 1.5 s per frame with 11 workers on a 12-core Mac, so a 98 s film took about an hour. Also export a share copy (`-crf 24`, about 90 MB instead of 250 MB) for WhatsApp, alongside the full-quality file and the chorus cut.++Adjusting the user's own character: when they ask to look "a bit younger, a bit slimmer", change the rig parameters (build, jaw, hair and beard colour, drop the tired-eye lines), show a before/after strip, and keep a backup of the old file. It's their face, so flattering is fine, but it must still read as them.diff --git a/references/overnight-brief-template.md b/references/overnight-brief-template.mdnew file mode 100644index 0000000..be17156--- /dev/null+++ b/references/overnight-brief-template.md@@ -0,0 +1,29 @@+# Overnight brief template (for epic, long-running pieces)++The most viral Opus 5.5 music video came from one long, rich, voice-dictated brief (see overnight-run.md). This is that brief's structure, generalized. Fill the [brackets] with the user, confirm budget and checkpoints, then hand it to the long-running agent (or run the studio process with it as the director's input).++---++**The target.** I've included [the song / source video / link]. It's about [what it means]. Do a complete end-to-end pass making [a new music video / film] for it. Use the exact same audio. Think and feel deeply about how to visually represent every lyric; you don't need to anchor to the current style, and you may do anything, including abstract motion graphics.++**Look and freedom.** I want beautifully rendered JavaScript animation with [texture: papery / watercolor / risograph / ...], pushed in whatever direction you think is best and aware of the current zeitgeist. Be mindful of aesthetics: no generic AI slop, no default Pixar look. Find a coherent style that also works well with the image and video models available. [Visual anchor, e.g. K-pop direction, used loosely.]++**Materials and tools.** You can use: [folders of past work, reference compendium, skills], [image model + key: character sheets, style sheet, sets], [video model + docs: reference motion, lip-sync], [sound design API], web search for references in motion design and JavaScript animation. Think about what is realistic for your capabilities.++**Characters and world.** Design a protagonist [who represents X / based on Y], then backup dancers and supporting characters as needed, and the sets. Generate a style sheet first and keep everything consistent with it.++**Base footage (optional, the rotoscope method).** Generate scenes with the video model using the character and set images, passing cut-up sections of the song as audio reference so the timing and lip-sync are exact. Build verification loops to confirm sync, and regenerate as needed. Not every shot needs singing: use inserts, other actions, shots without characters, like a real music video. Then reconstruct everything from scratch in JavaScript over the base footage, so the viewer only sees your drawing, with the base giving you real motion, physics and continuity.++**Meaning and culture.** Audit the references and memes the audience will recognize [list the zeitgeist: events, memes, in-jokes]. Integrate them where they serve the lyric; straight inserts in an internet-brutalism style are allowed. Anchor to visual references people will understand. Audience: [who, where it posts].++**Attention.** A strong visual hook in the first seconds. Lyrics as motion graphics embedded in the shots: plan composition so backgrounds are calm where lyrics are big (e.g. characters right, lyrics left). Vary it: sometimes subtitle-like, sometimes huge. At the hook, lyrics are big and present. Study how great music videos (K-pop especially) direct attention with visual patterns.++**Rigor.** Plan composition and timing before building, because things that weren't thought through clash when combined. Revisit and iterate: watch the whole video several times, screenshot individual parts, and ask whether each is at the bar. Nail the animation style. [Reference repo/video] is a good foundation but not the bar; aim much higher.++**Budget.** [Usage plan; credits cap, e.g. ~$X of image/video credits]. Spend economically but fully; monitor usage.++**Bar.** Make it a banger for [platform]; the stretch goal is better than anything seen before. Make no mistakes.++---++Before launching: agree the budget, the tools the user actually has (offer free routes, see toolbox.md), and whether there's a storyboard checkpoint or it runs truly unattended. For code-only styles, drop the base-footage section.diff --git a/references/overnight-run.md b/references/overnight-run.mdnew file mode 100644index 0000000..cb11341--- /dev/null+++ b/references/overnight-run.md@@ -0,0 +1,26 @@+# The overnight run (the method behind the most viral Opus 5.5 videos)++One creator, 23 Sep 2026: "I made this with one prompt using Opus 5.5 / I spoke to my computer for 5 mins, claude worked for 12 hours, and I woke up to this." Another creator then reused that prompt with Midjourney and a moodboard for the editorial HUD film.++## What the prompt does (the reusable pattern)++1. **A proven base to build on:** point Opus at an existing repo that already solves rendering (that run used JohnHeibel/PDoomVideo: p5.brush, headless Chrome, ffmpeg). Here: ClaudeAnimationBase or this skill's canvas scripts.+2. **A clear target + fixed constraints:** remake X with the exact same audio; style direction in a few vivid words (there: a K-pop idol version of the character, AI Twitter memes, huge kinetic lyrics).+3. **Tools, with a budget:** an image model (fal) for character/set designs; a video model (Seedance 2.5) with the song as audio reference for lip-sync and choreography; ElevenLabs for sound design. That run allowed up to about $2K of credits. Always agree a budget with the user; never assume one.+4. **The rotoscope trick:** generate reference footage with the video model, then **redraw everything in JavaScript on top of it** so only the drawing shows. Video-model motion, code-drawn look. This is why the movement feels real and the style stays consistent.+5. **Self-review loops, explicitly:** build loops that check sync, rewatch, screenshot, iterate until it's right ("make no mistakes").+6. **Time:** let it run unattended for hours. Higher effort and longer runs produce more ambitious films.++The prompt was dictated by voice in about 5 minutes ("word vomited"). A rough, rich brief beats a polished short one.++## The look it produced (risograph music video)++Risograph print on warm paper: navy ink as black, one hero color (orange sunflower hair), hot pink / mustard / teal / red accents. Giant condensed words the character bursts through; lyrics on torn paper labels with one pink-underlined word; mono data; italic serif asides; marker notes. Two running counters carry the story (a date stamp 2019 → 2026, a P(doom) meter 8% → 99.9%). Every lyric line is a visual in-joke for the audience (AI Twitter memes). ~98 cuts in 2:21 (one every 1.4 s), two strobe bursts, ends on a pencil sketch that rhymes with the opening.++## The brief++Use `overnight-brief-template.md`: the structure of that prompt, generalized, with [brackets] to fill with the user.++## When to use this mode++When the user wants something epic (a music video, a 1-3 min film) and can let it run for hours with tools and a budget. Write the brief with them (target, audio, style words, tools, budget, what "done" means), confirm the budget and the checkpoint (storyboard approval, or truly unattended), then launch at the highest effort and check in on contact sheets.diff --git a/references/page-or-picture.md b/references/page-or-picture.mdnew file mode 100644index 0000000..c55175c--- /dev/null+++ b/references/page-or-picture.md@@ -0,0 +1,40 @@+# Page or picture: the check that names "slideshow"++Run it on the storyboard, at the pitch, shot by shot. Run it again on the stills.++**Why it exists.** A 40 second product ad passed every technical gate and three fresh reviewers gave it the same verdict in different words: "a tidy animated slide deck", "a polished slideshow", "a screen recording in the middle". They could feel it and could not say what to change. The cause was in the storyboard from the first day: most shots were pages (a caption band on top, a card under it, things fading in and sitting there). Nothing in the process asked the question below before the build.++Slop is rarely a bad choice. It is the choice nobody made. Each default here is fine when it was chosen for this film and you can say why in one sentence. It fails when you arrived there because it is what a film like this usually looks like.++## The two questions, for every shot++**1. Is this shot a page or a picture?**+A page: a frame laid out like a slide or a web page (a title strip, a body, maybe a footer), where the layout stays put and the content is swapped into it. A picture: one thing fills the frame and the eye knows where to go.+- Cover the words on the still. If what is left is a plain ground with a card or a block on it, it is a page.+- If three shots in a row share one layout, they are one page with three slides.+- A page is allowed when the product is a page and this is the one shot that shows it. Then it gets a camera: crop in until one object fills the frame.++**2. Does something happen, or is something shown?**+Read the shot's line in the storyboard. "A list with eight tasks" is a state. "She gives the task to the agent and it starts" is an event. A film of states is a slideshow however well each one moves in.+- Write every shot as an event: who or what does something, and what that causes.+- A shot that has no event either gets one or loses its time to a neighbour.++## The defaults to catch in a product film+Ask of each: did I choose this for this film?+- **A caption band.** The same strip of headline over every shot. The words then narrate the picture from outside it. Prefer words that live in the picture: on the wall, behind a person, on the object.+- **The name parked in a corner** for the whole film. A viewer does not need a watermark; they need the name once at the start and once at the end.+- **A generic card.** A rounded white card with a dot, a label and a value could be any product. Show the real product's own piece, big.+- **The first idea the name gives you**, or a mark that turns into something (a dot that becomes a person, a tick that becomes a road), used because it is neat and not because the film needs it.+- **Everything, at equal weight.** Each feature of the brief gets a beat and none is the point. Say which features you left out on purpose.+- **A dark, glowing "premium" ground** because dark feels expensive, when the brand is light.+- **Proof made up to look real**: numbers, logos of customers, quotes.+- **An ending that is a web footer.** A film ends on its last beat. The mark, one line and one action are that beat; they still need to arrive as part of the story and not as furniture. How long the action holds is the person's call: an ad that must be acted on holds it longer than a mood film.+- **Stillness as safety.** A lone element on an empty ground and a long hold look restrained and risk nothing.+- **Sound as wallpaper.** One loop at one level from start to end, with no quiet and no hit tied to something seen.++## What to do with the answers+- At the pitch: mark each shot P (picture) or G (page) and E (event) or S (state) in the storyboard table. More than a third pages, or more than a third states, means the storyboard changes before anything is built. Say the count in the pitch.+- At the stills gate: do the cover-the-words test on the sheet. Then run `scripts/text-audit.mjs` (it measures what the words on screen actually do; see `pipeline.md`).+- In the delivery note: one line on any default you kept on purpose, and why.++This check is about how the film is staged. Whether the idea is worth a film is `concept-check.md`; what a still must pass is `before-the-first-cut.md`.diff --git a/references/pipeline.md b/references/pipeline.mdnew file mode 100644index 0000000..58974f3--- /dev/null+++ b/references/pipeline.md@@ -0,0 +1,155 @@+# Render pipeline (canvas styles)++The watercolor style uses the Claude Animation Base's own `render.mjs`. The other styles use this skill's scripts.++## New project++```bash+bash ~/.claude/skills/take-one/scripts/new-canvas-project.sh ~/my-video+```+Creates the folder, copies `serve.mjs`, `frames.mjs`, `export.mjs` and `springs.js`, installs `playwright-core` (uses the installed Google Chrome, no browser download), and writes a starter `film.html` with the contract below, already loading the springs.++## Springs (all motion that isn't a deliberate cut or step)++`springs.js` is a closed-form damped spring: the value at any t is computed directly, no frame history, so it keeps the any-order contract and passes the gate. `Spring.to(t, [[t0, v0], [t1, v1], ...], 'camera')` sums one spring per target change, so a retarget mid-flight keeps its momentum; `Spring.to2` does points; `Spring.unit(t - start, 'playful')` is a 0-to-1 response for scale, opacity or a mask. Presets and when to use each are in `timing.md`; `Spring.settle(preset)` gives the settle time for planning holds. Verified against RK4 integration of the same ODE (all four presets, a retargeted path): agreement within 0.01% of the move.++## The film.html contract++- One HTML file (plus `assets/`), a canvas at the output size (default 1920x1080).+- `window.FILM_DURATION = <seconds>`+- `window.renderFrame(t)` draws the exact frame for time t. Pure function of t: no state carried between frames, seeded randomness only (hash of an index, never `Math.random()` at draw time). Frames render in any order.+- `window.READY = true` only after images are loaded/processed and `document.fonts.ready` resolved.+- Autoplay loop + small play/pause/scrub controls outside the canvas (for the user to scrub in a browser).++## Review++```bash+cd ~/my-video+node frames.mjs 0 0.5,2,4,6,8,10 # square/landscape: PNGs + contact sheet in review/square/+node frames.mjs 1 0.5,2,4 # ?portrait=1 variant+FILM=other.html node frames.mjs 0 3 # a different file (output in review-other/)+```+Read the PNGs and `sheet.png` with the Read tool. Console errors are printed (a favicon 404 is harmless).++## Quality gate (before showing anything rendered)++```bash+node ~/.claude/skills/take-one/scripts/gate.mjs film.html # 1 determinism + 2 contract scan+node ~/.claude/skills/take-one/scripts/gate.mjs film.html --mp4 out.mp4 --holds "12-14" --cuts "4.5,9" # + 3 dead air, 4 pops+node ~/.claude/skills/take-one/scripts/gate.mjs --self-test # prove the gate itself still catches bugs+```+The stillness checks compare frames 1/30 s apart, so a film gets the same answer at 30 and at 60 fps. A clip that plays inside the film at a lower frame rate than the film (a 30 fps video in a 60 fps film) holds each of its frames for two of ours, so every new clip frame reads as a pop: declare it on the page, `window.FOOTAGE = [[from, to, fps]]`, or with `--footage "13-18.5@30"`, and the gate measures that stretch once per clip frame. Cuts inside the clip are still found and still need declaring. Words that land whole on a beat are pops too: give each a three or four frame fade, and declare only the real hits. The burst on a music hit and any deliberate dip to black are declared (`--cuts` for the first, `--holds` for the second) rather than softened. Run it twice per film: checks 1-2 right after the first shots draw (a stale cache or a `Math.random` found now costs minutes, found after a 9-minute export costs the render), and all three on the exported MP4 before the user sees a single frame or contact sheet. It samples ~12 frames cold-forward vs warmed-reverse (md5, PSNR > 45 dB fallback) and on a mismatch names the poisoning frame ("ORDER-DEPENDENT: drawing frame X first changes frame Y" = a cache key missing a term or leaked ctx state). Deliberate stills go in `--holds`. Check 4 (pops) lists every frame whose difference from the last is over 3x its six neighbours': each one is either an intentional hard cut, declared with `--cuts` (or `window.CUTS`), or a bug to fix (an element appearing with no ease, a flood clearing too fast so it reads as a flash). It resolves playwright-core via the `node_modules` symlink beside it in `scripts/` (or `PLAYWRIGHT_NODE_MODULES=/path/to/node_modules`); it only reads the MP4, never writes to the project. Adapted from anidoodle (Apache-2.0).++## Footage inside a frame (a screen in a player, a strip of an earlier film)++```bash+python3 ~/.claude/skills/take-one/scripts/content-box.py capture.mp4 12.0 2.5 --rest --keep 160-900 # where the content sits, and the crop to use+```+Measure before cropping: the script finds the box of everything that is not ground in that stretch and prints an ffmpeg `crop` and `scale` that keep a clear margin round it for the space the film gives it (`--fit 1344x598`). When the content is wider than the space the strip comes out shorter: centre it, do not cut it. Blank what you leave out (a header row, a caption) with `drawbox` before the crop, and draw a dark strip `lighten` over the player's dark ground so the two grounds are one. Declare the footage's frame rate (`window.FOOTAGE`) for the gate.++## Text audit (what the words on screen actually do)++```bash+node ~/.claude/skills/take-one/scripts/text-audit.mjs # film.html in this folder+node ~/.claude/skills/take-one/scripts/text-audit.mjs cut.html --step 0.05 --ignore "lorem|^\\d+$" --json text.json+```+Run it at the stills gate and again before the reviewer. It draws the film frame by frame, records every `fillText` and `strokeText` (the text, its size on screen, where it sits, how opaque), joins the samples into "this text was up from A to B", and reports:+- **SMALL**: held 0.6 s or more and under 3.3 % of the frame height (FAIL) or under 4.3 % (WARN). At 1920x1080 that is 36 and 46 px: about 6.5 and 8.5 px on a phone.+- **FLASH**: a caption or card that is not up long enough to read (0.4 s plus 0.2 s a word). A line typed letter by letter in one place (a prompt) counts as one piece from its first letter. A fast roll (a count whose name changes every beat, read at one fixed spot) flags on every name: it is not a caption, so pass the names to `--ignore` and tell the reviewer it is a roll. When the film replays itself inside a small player (a rewind, a film in the film), set `window.TEXT_AUDIT_SKIP = true` while that inner picture is drawn and back to `false` after: its words are picture, not captions.+- **EDGE**, **PINNED**, **LONG**: text partly out of the frame, small text parked in a corner for six seconds in all, one big line held past six seconds.+- **FACE**: text on a face, when the film defines `window.FACES = (t) => [[x, y, w, h], ...]` in canvas pixels.++A FAIL is fixed. A WARN is a lead: look, then fix it or say why it stays. On one product ad the first cut had 15 fails, all things a fresh reviewer later named (status chips, tags, a note that flashed for 0.4 s); the delivered cut had 4. It sees only text the page draws itself, not words inside pictures, and it reads size, not contrast, so the 360 px sheet still gets read by eye.++## Export++```bash+node export.mjs 60 out.mp4 # 1920x1080 by default+W=1080 H=1350 node export.mjs 60 out-4x5.mp4 # other sizes (the page must support them)+SLOW=1.3 node export.mjs 60 out-slow.mp4 # time-stretch the whole film 1.3x (renders t/1.3)+```+Export takes ~2-6 min per 30 s at 60 fps. Run long exports with a generous timeout or in the background.++**Subframe motion blur (`SUB=N`).** Renders N subframes per output frame (t + k/(fps·N)) and averages them in ffmpeg (`tmix=frames=N,select='eq(mod(n\,N)\,N-1)',setpts=N/(fps*TB)`, `-r fps`). It is what makes fast code motion read as filmed instead of stepped.+```bash+SUB=8 node export.mjs 60 master.mp4 # final master only; review exports stay SUB=1+```+- **Use SUB=8** for the final master of kinetic explainer, title sequence, chrome showreel and monochrome launch (and any style with fast camera, whips or type flying in). **SUB=4** is enough when the fast moves are few; below 4 you see separate ghosts on fast moves.+- **Never for stepped art** (pixel art, pencil test, crayon boil, anything animated on 2s or on ticks): the hold is the look, and blur smears it.+- **Cost:** N times the render. At 8 expect about 1-1.5 min of render per second of film at 1080p60; keep it for the master, after the gate is green at SUB=1.+- Proven on a fixture (a dot crossing 440 px in 1 s at 30 fps): frame 15 sharp is a 20 px disc; at SUB=8 it is a 33 px smear with 22 partial-alpha ghost pixels on its row. Blur is trailing (the subframes run forward from t), which is invisible in practice.+- Blur hides a stepped or popping element; it does not fix one. Run the gate's pop check on the SUB=1 export.++## Long films: render in pieces++One browser draws about 4 to 8 frames a second at 1080p, so a 75 s film at 60 fps takes ten minutes or more in one process. Render it in pieces instead:++```bash+bash ~/.claude/skills/take-one/scripts/render-parallel.sh 60 78.6 out/master.mp4 # fps, duration in seconds, output; 3 workers+bash ~/.claude/skills/take-one/scripts/render-parallel.sh 30 78.6 out/draft.mp4 3 12 # review draft: 30 fps, 3 workers, 12 s pieces+```+- Run it from the project folder. It writes the picture only; add the sound with `mux-audio.sh` (or one ffmpeg call).+- **Three workers on a laptop.** Each worker is a whole Chrome. Six at once ran a 16 GB machine out of memory in the middle of a film; three finished without trouble.+- A piece whose browser never starts is started again after 60 s (it happens about once in ten runs with several browsers launching together). A piece that dies part way is reported with the last lines of its log: that is almost always an exception in `renderFrame` at some time inside that piece, so read the error, fix the film, render again.+- **Render a draft at 30 fps for review and the gate, the master at 60 fps once.** Frames are deterministic, so the two match.+- The script checks the frame count of the joined file. A film that is short by a piece's worth of frames means a piece stopped early.++## Gotchas++- Canvas reading local images needs http, not file:// (taint). `serve.mjs` handles it; always go through the scripts.+- An SVG used as an `<img>` (a logo file) only loads if the server sends it as `image/svg+xml`; `serve.mjs` does. If a logo is silently missing from the frames, check the image actually loaded before blaming the draw code.+- A favicon 404 in the console output of `frames.mjs` is harmless.+- Stale headless browsers pile up when renders are interrupted. If the machine feels slow, look for leftover `Google Chrome ... --headless` processes started by earlier runs and close the ones that are yours.+- Google Fonts load fine over the local server; wait for `document.fonts.ready`.+- `SLOW` stretches everything, including music timing: re-time the audio afterwards.+- Keep the one-shot output file untouched (`film-oneshot.html`) before any hand edits, so the "one prompt" claim can point at it.++## Face audit (main character's face stays clear)++Panels, boards, cards, slams, bands and captions must never sit on the main character's face, in any aspect ratio. Zooms, jump-ins and the 9:16 recompose move the face under overlays placed for another framing, so prove it with an audit instead of eyeballing.++1. **Face box per photo.** For each plate the hero appears in, record the face box in plate units, hairline to chin, ear to ear. Draw the boxes over the plates on a grid and check them by eye once.+2. **Track the current plate.** `plate()` stores which plate and transform it just drew (`CUR`).+3. **Register overlays.** Every panel, board, card, slam, band, caption strip and custom block calls `ovr(x, y, w, h, 'what')` with the screen rect it covers. Tracking brackets and thin outlines don't register.+4. **Check per frame.** After the shot draws, intersect the registered rects with the face box mapped through `CUR`, and expose the result as `window.__hits` (labels) and `window.__shot` (shot number).+5. **Run it:**+ ```bash+ node audit-faces.mjs 0 # 16:9, samples every 1/8 s, prints shot · element · time ranges+ node audit-faces.mjs 1 # 9:16+ ```+ Fix every hit (move the element into free space, reframe the photo, or anchor the zoom so the face moves), then re-run until both say "no face overlaps".++## UI on a phone or screen inside a photo++Never eyeball the screen corners. Generate the photo with a plain blank white screen, then:+1. Threshold the bright, unsaturated screen region around a seed point, fill holes, and save it as an alpha mask the size of the plate.+2. Fit a minimum-area rectangle to the mask for the four corners (TL, TR, BR, BL).+3. Draw the UI canvas into that quad with a bilinear-subdivided perspective map (about 10x10 triangle pairs).+4. Clip it with the mask (`destination-in`) so it gets the real rounded corners and notch, and fingers over the screen stay in front.+5. Make the detection frame the bounding box of the screen quad plus the bezel, so it hugs the device.+Keep the UI's own header below the notch area.++## Re-render only what changed (fast iteration)++A heavy photo + HUD film renders at about 3-4 frames/s at 1080p on this Mac (about 9 minutes per 80 s at 24 fps), and two renders in parallel slow each other. After a fix, re-render only the changed shots:+```bash+START=26.5 END=32.5 node export.mjs 24 fix-b.mp4 # renders frames round(START*fps) .. round(END*fps)-1+```+Splice by frame index into the previous master (`trim=start_frame=..:end_frame=..` for the untouched parts, `concat` in order), one re-encode at CRF 14. Make each range cover the whole changed shot plus a few frames either side; frames are deterministic, so the overlap is identical. Then verify alignment: the PSNR of the untouched regions against the old master should be above 40 dB (one app-builder film: 44-57 dB). A one-frame slip drops it far lower.+- To add a held ending, raise `FILM_DURATION` and render only the new tail, then concat.+- **Joining without a re-encode (`-c copy`): cut only at a keyframe, and count packets, not seconds.** `-t 17.46 -c copy` on a 60 fps part gave the right NUMBER of frames (1050) and the wrong frames: 0 to 1048 and 1050, with 1049 missing, because the P frame comes before the B frame it is shown after. The joined film then showed one frame of the next shot a frame early. Do this instead: list the kept part's keyframes (`ffprobe -select_streams v:0 -skip_frame nokey -show_entries frame=pts_time`), take the last one at or before the change (frame K), copy exactly K packets (`ffmpeg -i part.mp4 -frames:v K -c copy head.mp4`: everything before a keyframe in file order is frames 0 to K-1), and render from K/fps on. Then prove it: the sorted packet times of `head.mp4` must be 0 to K-1 with none missing, and the joined file must have the full frame count.+- To keep editing while a long render runs, render from a frozen copy: copy the scripts folder and point a copy of film.html at it. The page loads its scripts once, but a copy removes any doubt.++## Frame safety++Reset the canvas at the top of every `renderFrame`: `g.reset()` (or `setTransform(1,0,0,1,0,0)`), `globalAlpha=1`, `globalCompositeOperation='source-over'`, `filter='none'`. Then draw the shot inside `try/finally` with `save/restore`, clamp `t >= 0`, and use a safe modulo for texture indices (`((i % n) + n) % n`). One exception mid-frame otherwise leaks its state into every later frame: the first pilot of an app-builder film rendered grey until this was fixed.++## Geometry from the image, never by eye++Anything that must hug something in a photo gets measured from the photo: tracking boxes on 36 pinned notes came from thresholding plus connected components, phone screens from masks, face boxes from a grid check. Eyeballed corners were the source of both visible compositing bugs on an app-builder film.++## Two slips the checks caught on our launch film (12 Oct 2026)++- **A comment added in the middle of a line switches off the rest of that line.** These pages keep several statements on one line. Patching one statement and appending `// why` to it comments out everything after it on the line; the page still loads and still draws, only wrong (a button with no background drawn at the corner; an end card that stopped moving). The gate caught the second one as "identical frames" plus a pop at the join with older frames. When patching a line, put the comment on its own line above it, and look at a still of every scene the line draws.+- **A check that printed its result and never returned.** On Node 26 a script that ends with `process.exit()` right after heavy number work can deadlock in shutdown (a V8 background thread waits for a garbage collection the exiting main thread will never run). `audio-check.mjs` did it three times in one day and each time a shell pipeline waited on it for hours. It now leaves through the event loop (`process.exitCode` and a short timer). If any script seems stuck after its last line of output, it is this: kill it, the result above it is valid. For unattended chains, give each node step a limit: `perl -e 'alarm 120; exec @ARGV' node <script> ...` (macOS has no `timeout`).+- **A render part that never wrote a frame.** With three parts of an export started at the same second on a busy machine (another session was rendering too, load over 100), one part's Chrome came up with a GPU helper and no page, used no CPU, and its log stayed empty for four minutes while the other two were a third done. Nothing times out on its own. When parts run in parallel, look at every part's log after a minute: an empty log and a `node export.mjs` with under a second of CPU time is this. Kill that node and its Chrome (plain `kill` was ignored; `kill -9`) and start the part again; it then ran normally.diff --git a/references/quality-checklist.md b/references/quality-checklist.mdnew file mode 100644index 0000000..c89da22--- /dev/null+++ b/references/quality-checklist.md@@ -0,0 +1,89 @@+# Quality checklist (walk it before showing the user anything)++Render a contact sheet at 360 px wide per frame (phone size) and full frames of key moments, and check with real eyes, not memory of the code.++## Critique rubric (score every round, from the exported MP4)++Score each axis 1-10:++| Axis | What 8+ means |+|---|---|+| Hook (first 2 s) | frame 0 is striking and the premise is clear by 2 s |+| Readability at 360 px | every must-read word readable on the 360 px sheet, for long enough |+| Motion quality | springs and eases, no linear moves, no pops, blur on fast moves in the master |+| Variety | something new (a layout, a scale, a colour field, a device) every 2-4 s |+| Composition | one focal point per frame, clean space for type, nothing crowding an edge |+| Data accuracy | every figure real and sourced, or labelled "Example data" |+| Sound sync | hits, cuts and hook words land on the measured frame or beat |++Then name **the 3 worst problems with timestamps** ("0:07.2 the handoff text blurs for 4 frames"), fix them, re-export and score again. **Loop until every axis is 8+.** Keep the reference comparison too (frames side by side with the reference, one 1-10 score, the three biggest gaps closed or priced); the rubric finds the bugs, the reference sets the bar.++**The agency bar, for a launch or product film.** When the person gave no reference, the bar is what agency-made launch films do (`references/directed-look.md`). In the part that explains the product, an 8 on variety and composition means:+- [ ] the real thing is on screen (the product's own screen, its footage, its output), not an invented picture of it+- [ ] no layout comes back more than twice in a row, and a list is not one matching frame per item+- [ ] two tones and one accent across the whole part+- [ ] the film's best picture is shown at full frame, not kept inside a box+- [ ] the words leave the picture room, and still read at 360 px++A part that fails the first two reads as a template however polished it is. Name it in the three worst problems, with the times it runs from and to.++**12-frame strips around every fast move.** For each whip, handoff, flood and slam, render 12 consecutive frames around it (`node frames.mjs 0 <t-6/fps>,...,<t+5/fps>`) and read the strip. It catches what a contact sheet at 1-2 s spacing never shows: text blurring or doubling through a handoff, a flood that reads as a one-frame flash, an element that appears without an ease.++**Idea**+- [ ] One idea, statable in a sentence. Every shot serves it.+- [ ] A payoff worth rewatching or sharing, held long enough to land.+- [ ] Nothing in it the user didn't ask for or approve (themes, targets, characters, claims).++**First second**+- [ ] Frame 0 is striking or a convincing "still" that comes alive. No blank or loading frame.++**Legibility (phone, muted)**+- [ ] Every must-read word is readable at 360 px wide. Hero type ≥ 90 px at 1080p; nothing essential under ~40 px.+- [ ] High contrast on every frame with text. No grey-on-grey.+- [ ] Nothing important covered by HUD, bubbles, other text or the frame edge.+- [ ] The story reads with sound off.+- [ ] Headline or tagline type never lands on top of live content (board, UI, footage). Time the camera so the type gets clean space first (whiteboard-product film: pull out before the word is sung).+- [ ] Nothing captured or photographed is shown enlarged past its native pixels (check the scale factor at every zoom, not only at the keyframes).++**Nothing pulls the viewer out**+- [ ] No drawing looks off at full size: natural neck/shoulder joins, believable joints and head tilts, faces readable at every angle, no mannequin stiffness, no lumps that read as something else (a bunched hood read as a hunchback). Where the drawing can't carry an angle, change the framing or pose.++**Faces**+- [ ] The main character's face (hairline to chin) is never covered by a panel, board, card, slam, band, caption or HUD block, in every aspect ratio delivered. Tracking brackets may frame a face; nothing solid sits on it. Avoid covering any other face too.+- [ ] Proven by the face audit (`scripts/audit-faces.mjs`, see pipeline.md), not by eye alone: zooms, jump-ins and the 9:16 recompose move the face under overlays you placed for another framing.+- [ ] UI shown on a phone or screen in a photo sits exactly inside that screen (mask + perspective), with fingers in front and the detection frame hugging the device.++**Design system**+- [ ] One background family, one accent, fonts each with a single job, consistent across all scenes.+- [ ] Nothing looks like a web page or 2000s Flash (plain default shapes, system fonts where a designed one was planned).++**Generated footage (if used)**+- [ ] No two generated clips start from the same frame (continue from a last frame or pick a different start).+- [ ] Every generation input was in color; the grade/look is applied in post, never baked into the input.+- [ ] Singing shots verified in sync by measurement (compare clip soundtrack to the real vocal), not by eye; cutaways don't need sync.++**Motion and timing** (see timing.md)+- [ ] One read at a time; every read has time.+- [ ] Anticipation before big actions, holds after meanings, variety in speed.+- [ ] No pops: characters and objects ease, squash, overshoot; faces change through a take.+- [ ] No linear motion: every move is a spring or an ease with a named preset (`timing.md`); stepped art steps on purpose.+- [ ] Every scene handoff carries a shared element across or is a declared hard cut; floods clear the farthest corner in 0.3-0.35 s (`motion-kit.md`).+- [ ] Transitions connect scenes; no dead frames.++**Real product (if shown)**+- [ ] The product is full of on-story content (photos, faces, screens, product shots), not just default UI or text.+- [ ] Brand pass done: real typeface, colors, logo files, headline and CTA from the live site (`brand-pass.md`).++**Technical**+- [ ] The quality gate passes (`node ~/.claude/skills/take-one/scripts/gate.mjs film.html`, add `--mp4 out.mp4 --holds "a-b"` once exported). Run it before showing the user anything rendered — frames or MP4 — not after: it proves determinism by machine (cold-forward vs warmed-reverse hashes, and it names the frame that poisons a stale cache), scans the source for clocks/`Math.random`/filters, and measures dead air on the export. "Looks deterministic" is not a claim; a green gate is.+- [ ] Gate check 4 (pops) is green: every frame-difference spike is a declared cut (`--cuts`), the rest fixed.+- [ ] The master is exported with `SUB=8` for smooth-motion styles (kinetic, explainer, title, chrome, mono); never for stepped art (pipeline.md).+- [ ] No console errors; `renderFrame(t)` deterministic (same t, same pixels, any order).+- [ ] No halos on keyed sprites, no floating feet, lighting matches the scene.+- [ ] Final export 1920x1080 (or requested aspect), 60 fps, H.264, under 512 MB; audio aligned.++**Honesty**+- [ ] The caption's claims ("one prompt", "one-shotted", "no images") are literally true for the exported file.+- [ ] Every illustrative figure (a made-up revenue chart, a sample dashboard, a demo balance) carries a visible "Example data" label on screen, readable at 360 px. Unlabelled numbers are claims.+- [ ] Only real integrations are shown: every partner logo, connector and "works with" chip exists in the product today.+- [ ] A remake of someone's launch video credits the original on screen or in the caption and uses no fake co-marks (their logo beside yours).diff --git a/references/real-product.md b/references/real-product.mdnew file mode 100644index 0000000..d4c438a--- /dev/null+++ b/references/real-product.md@@ -0,0 +1,74 @@+# Real product route (show, don't tell)++For any video about a product, the most convincing frame is the real product doing the thing. Code-drawn UI copies read as mockups; the real UI reads as proof. Use the real product for every beat that shows the product, and code for everything around it.++## The content inside the product is the story++The product being real is not enough; what's *in* it must show the story. A whiteboard-product film's first versions showed a real board full of text stickies, and the user's verdict was that nothing in it was visual: the hook asked "what if our plants could text us?", and a viewer would want to see an app being planned around that question, in pictures. That product's own marketing shots are full of faces, photos, video thumbnails, emoji, personas and journeys.+- **Study the brand's own product imagery first** (their homepage and feature-page screenshots): what kind of content fills their product, how their cursors and name tags look (a whiteboard product: big pastel pill tags with an outlined arrow), how dense and colorful it is. Match that, not the bare default UI.+- **Answer the hook visually within seconds.** If the hook is "plants that text you", the first reveal shows plants and a phone with a plant's text, not words about it.+- **Plan an image pack at the pitch:** moodboard and inspiration photos, a persona with a face, the product shot, app screens, packaging or launch visuals, anything a real team would pin while building the thing. Generate them (Nano Banana in the Higgsfield web UI with Unlimited on, or the user's ChatGPT) and place them in the product; if the product's own AI can generate images, prefer that, since it's more show-don't-tell.+- **Every layer of the story should be visually different** (photos, then clusters, then a flow, then screens, then a launch shot), so the eye gets something new at each beat.++## Steps++1. **Access.** The user signs up (free plan is fine) or logs in, in their own Chrome. Claude never creates accounts with the user's email or handles verification codes on its own. Ask what plan limits apply (AI credits, board count, export).+2. **Story first, then build it for real.** From the approved storyboard, list each beat as a product state ("30 messy stickies", "AI clusters them", "flow generated"). Drive the product with Claude in Chrome to create exactly those states. Use the product's own AI/automation for the "magic" beats where the plan allows, so the claim is literally true.+3. **Capture.**+ - Screenshots of each state at a fixed window size, at the zoom levels the film needs (resize the window large, hide sidebars/toolbars when the product lets you, keep the product's chrome when it helps recognition).+ - Short screen recordings of the moving moments (AI sorting, generation, collaboration). GIF/record tools in Chrome MCP, or a sequence of screenshots at fixed intervals.+ - Save to the project's `assets/real/` with the beat name.+4. **Composite in code.** The captures are plates. Code adds camera moves (zoom, push, nested zooms between states), cursor characters, highlight rings, type, sound hits and the payoff. Never repaint over the product's own UI to change what it says.+5. **Honesty.** Caption states it: "every frame is the real product; the camera, cursors and sound are code." Don't show features the plan or product doesn't have. Blur or avoid personal data (emails, avatars, other boards) in every capture. Any illustrative figure (sample revenue, a demo balance, a made-up chart) carries a visible **"Example data"** label on screen. Show only real integrations: every partner logo, connector and "works with" chip must exist in the product today.+6. **Clean up.** Tell the user what was created in their account (boards, files) so they can keep or delete it.++## The component macro (launch-video grammar)++The move that makes a UI launch feel premium: lift **one real control** out of the product and make it the whole frame for a beat.+1. **Capture it big.** Screenshot the control at `deviceScaleFactor: 3` (Playwright or the Chrome tool with the window zoomed), cropped tight: a toggle, the prompt box, a pricing switch, the send button.+2. **Lift it onto a clean field** (the brand's background colour, nothing else) at **3-5x** its in-product size. At 3x capture it stays native up to about 3x on a 1080p frame.+3. **Perform the interaction** on the lifted control: type into it one character per frame-tick, flip the toggle, press the button (a 0.95 scale dip on `snappy`, then release).+4. **Show the result state** there, still big: the answer appearing, the toggle's effect, the confirmation.+5. **Return to the full UI**: the control springs back to its real rect in the product screenshot (a shared element across the handoff, `motion-kit.md`), and the full interface is revealed around it.+The viewer learns one interaction perfectly instead of scanning a whole screen. Use it for the 2-3 interactions the story turns on, not every beat.++## Why++Proposed for an infinite-zoom video of a whiteboard product (Sep 2026): the first pitch redrew the product in code. The user's direction: show, don't tell, with the real product; it's what makes product videos amazing.++## Proven technique: capture the product's own canvas (whiteboard product, Sep 2026)++- **Look for an in-page SDK first.** That product's board page exposed a global board object (create stickies/frames, set the viewport), so the board was built and the camera driven by script from the Chrome tool.+- **Grab the render surface, not screenshots.** That product's main canvas element was WebGL with `preserveDrawingBuffer: true`, so `canvas.toBlob()` gives native 2x frames (3840x1688) with no UI chrome. Check `getContextAttributes()` on any canvas-rendered product.+- **Getting frames to disk:** a localhost upload was blocked (Chrome local-network permission) and macOS `screencapture` only saw the wallpaper (no Screen Recording grant). What worked: pack PNGs + viewport JSON into one binary bundle per ~40 frames (records of: 4-byte big-endian name length, name, 4-byte big-endian data length, data; each PNG followed by its viewport JSON) and download it from the page with a blob link (user approves downloads once, and "allow multiple downloads" once), then unpack locally with `scripts/unbundle.py`.+- **The tab must stay visible.** A covered or minimized window reports `visibilityState: hidden`, rAF stops and the product stops rendering; ask the user to keep it in front during capture.+- **Zoom ladder for an infinite zoom:** capture frames log-spaced along the camera path (2% zoom steps, ~250 frames), each about 1.3x wider than the film's view (just enough for 16:9 inside the capture's aspect), and keep them at full resolution. The film draws the smallest plate that covers the camera. Real pixels at every zoom, smooth motion from code.+- **Lock the camera path before capturing, and recapture after any reframe.** v4 of the whiteboard-product film re-framed three shots after capture, so those moments borrowed wider plates and enlarged them; the user saw it at once ("why is user flow out of focus and pixelated"). Also don't downscale plates to save memory.+- **Never blend plates that contain fixed-size UI.** Product chrome drawn at constant screen size (a diagram label chip) sits at a different place and size in every plate, so a crossfade prints a ghost copy. A dense ladder needs no blending.+- **Let the product's AI make the content.** The clusters, flow, roadmap and wireframes were real output of the product's own AI from real prompts; the film shows those prompts verbatim (prefixes). Free plans can refuse a feature (wireframes): take the AI's offered fallback and say so.+- **Mind stray keystrokes.** Typing into the canvas instead of the prompt fires the product's shortcuts; click the input and verify focus with a zoom before typing.+- **Async plates:** `renderFrame` can return a promise (the export/frames scripts await it), and the page's own autoplay preview must not run under automation (`navigator.webdriver`), or it paints over exported frames.+- **Canvas-only fonts** must be requested with `document.fonts.load(...)` before READY; `document.fonts.ready` alone lets them fall back to Times.++## Getting generated images into the product (whiteboard product, Sep 2026)+- Generate in the Higgsfield web UI (Nano Banana Pro, Unlimited on), read the results with the free MCP `show_generations`, and pass their public CloudFront `rawUrl` straight to the product: the product's SDK image call (`createImage({url, x, y, width})` in that case). No downloads or uploads needed.+- Keep a local copy (`imgpack/`) for the record and for previews.++## Keeping the capture session alive+- **One tab.** Opening another tab in the same Chrome window (Higgsfield) makes the product tab `hidden`: it stops rendering and SDK calls that wait on a frame hang. Close the other tab before capturing.+- A "Reconnecting…" reload of the product tab wipes every helper you injected. Keep them in a local file and paste them back in one call.+- After capturing, check every plate against its neighbour with the known viewports (predict, compare, flag spikes) before building on them; contact-sheet tiling can fake a glitch, so confirm on the full frame.++## Headless capture of a public product demo (kids' learning app, Sep 2026)+When the product has a public demo (no login), skip the user's Chrome and drive it with Playwright headless, which is faster, repeatable and sharper:+- **Phone plates at 3x:** `viewport 430x900, deviceScaleFactor 3, isMobile, hasTouch` gives 1290x2700 screenshots of the real UI. A phone in a 1080p frame shows them at about 0.33x, so push-ins up to about 2.5x stay native.+- **Read the product's own data first.** The demo's lesson JSON listed every step, question and answer. A scripted playthrough solved each question from the on-screen caption ("5 groups of 4 = ?"), not a hardcoded answer list, because the product adapts its question order.+- **Miss on purpose** to capture the product's help moment (the coach's "Off the rim!" plus a number-line hint), then answer correctly. Take burst screenshots (12-24 frames at 100-150 ms) around each state change; they play back as real motion.+- **Harvest the product's own media from its network and source:** recorded voice lines (that product stored each sentence at `audio/<FNV-1a hash of the text>.mp3`, so any line could be fetched by computing its hash), SFX (crowd, swish, buzzer), and short character videos with their own audio. That gave real motion and a real voice with zero credits.+- **Forms:** reveal a hidden form step via the DOM and fill it for the story's persona, but never enter an email or submit (abort `/api/` routes to be safe).+- **Honesty line:** every product frame, voice and sound came from the product. Code added the camera, phone frame, taps, type and confetti.++## Gotchas from the same run+- Suno's CDN `.m4a` is encrypted and the API returns `audio_url: forbidden`. Download goes through the UI and **costs one of the plan's monthly download unlocks**. Ask before spending one, like credits.+- Don't `pkill -f export.mjs` in the same command line that starts a new export: the pattern matches your own shell.+- `frames.mjs` doesn't clear `review/`, so the sheet mixes old and new frames. `rm -rf review/square` before a fresh sheet.diff --git a/references/real-shots.md b/references/real-shots.mdnew file mode 100644index 0000000..6a27d4e--- /dev/null+++ b/references/real-shots.md@@ -0,0 +1,74 @@+# Real pictures and moving shots++Code draws type, motion, screens and illustration. It cannot draw a believable person, a real place or a product out in the world. When the film needs those, an image model makes the pictures and a video model makes the important ones move; code does everything around them. Both go through the cost rule in SKILL.md: read the real price, say it, wait for a yes.++Say the ceiling at the pitch: pictures that only pan and zoom hold a real-looking film at about 7 out of 10. If the person wants it to feel filmed, the shots people look at have to move.++## Pictures++- **Free first, where it exists.** An unlimited image plan the person already has (for example Nano Banana Pro in the Higgsfield web UI with Unlimited switched on: check the switch before every generate), or their own ChatGPT from prompts you write. Otherwise price it.+- **One hero example for the whole film.** One product, the same few people, the same world. A run of unrelated pictures reads as a slideshow.+- **Keep the product the same.** Make one clean picture of the product alone first and give it as the reference for every later picture. Describe the product in the same plain words each time.+- **Keep the people the same.** Make every picture from one approved reference picture of the people, say "the exact same people", and describe each one in a plain line.+- **Caught, not posed.** Ask for an observed moment: each person doing a real task, nobody looking at the lens, a doorway or over-the-shoulder view. A smiling group facing the camera reads as stock and is not believed. Make one picture, show it, then make the set.+- **Check each picture like a stranger would.** Is what they are doing physically possible? Is every readable word spelled right, at full size? Keep background signs out of focus. Never let a model draw a logo; place the real one in code.+- **Leave room.** Ask for free space where the type will go. Nothing solid sits on a face.+- **The same product in a new place: say "change only the place", and say which half holds what.** Give the cleanest picture of the product as the reference and write: keep the product exactly as it is (list its parts and any lettering), same position, size and camera angle; change only the place around it. Then lay the picture out in words: "on the LEFT half, behind the product: ...; the RIGHT half is a plain dark wall with nothing on it, from the top edge down to the product". The first try without the layout put sketches and boxes exactly where the headline had to go; the second try with it gave a clean wall, and the lettering on the product held in all four pictures.+- **Type behind a person or a product** needs a cut-out of the subject: `swift scripts/matte.swift in.jpg out.png` (macOS, free, local). Draw the picture, the word, then the cut-out on top. Cut from a sharp picture made for it (the object alone on a plain ground, at the size it will be shown or larger); a cut-out taken from a small corner of another picture and blown up is blurry. Give it a soft shadow onto what is behind it, or it looks pasted in.++## A still as a shot with depth++A picture that holds the frame for a second or more should not only be zoomed: a zoom reads as a picture being enlarged. Cut it into layers and move them apart, and it reads as a camera moving in a room. Free, local, in code. First used for the two-second opening of the short Take One launch film (11 Oct 2026). **It is not enough for an opening:** the owner's note was "we want the headphone to move", and a fresh reviewer measured 20 to 40 px of movement in two seconds and called it "a still on a phone". Use it for a shot inside a film; open on real footage.++1. Cut the subject out: `swift <skill>/scripts/matte.swift photo.jpg cut.png`.+2. Fill its place in the picture: `python3 <skill>/scripts/plate.py photo.jpg cut.png plate.jpg`.+3. In the page draw three layers in this order, each with its own scale and slide about the frame's centre: the plate; what belongs between them (a headline word lands best here: it sits in the room and the subject passes in front of it); the cut-out. All three start on the same transform, so the first frame is exactly the photograph.+4. Move them like a camera. Over two seconds at 1920 wide: the plate grows about 1.5 % and slides about 13 px one way, the cut-out grows about 5 % and slides about 14 px the other way, the middle layer sits between. Keep the cut-out within about 3 % of the frame of its own place: the fill is only good for a rim.+5. Add what a room has: a slow hand-held drift on every layer (the nearer, a little more); one soft light that crosses the subject (draw the cut-out on a small offscreen canvas, fill it `source-in` with a moving gradient, lay it over the subject with `overlay`, which lifts the colour; `lighter` greys it); a few specks of dust, some drawn before the cut-out and some after.+6. A word that lands in the picture scales from its own middle, never from its left edge, or its first frames run off the frame.+7. Look at the subject's edges at full size on the last frame of the move. A doubled edge means the layers moved too far apart, or the hole needs a larger `--grow`.++It is still one picture. Use it for a shot of about two seconds inside the film, and say at the pitch what a video model would add (the product turned or handled, a person moving) and its price. Before paying for a new clip, look through the clips the project already has: a shot made for another part of the film can be used again at no cost (ours was the ad's own product shot; say so, because the viewer will see it twice).++## Moving shots++Movement comes last: after the cut works with pictures and the person has seen it. Then pick the few shots where motion shows.++**Where it pays, in this order:** the opening shot; a product shot held two seconds or more; each shot of a person held about a second; an end card that sits still. Type, screens and anything with exact words stay in code. A clip, once made, can play again wherever the same picture appears at no cost.++**Read the model first.** Model facts change in weeks. Before the first clip, read what the person's service offers today and the chosen model's limits (lengths, sizes, what a start picture needs), the same way as the price, and say what you read. `video-models.md` has the rule and dated notes on the models we have used; where it and the live read disagree, the live read wins.++**Money.**+- Read the price before every render (on Higgsfield: the same call with `get_cost: true`) and show it. Prices change; never quote from memory.+- A clip has a minimum length (4 s for Seedance 2.5), so a half-second shot costs the same as a four-second one. Count clips, not seconds, and give the total before the first render.+- Resolution: anything shown full frame gets 1080p. A 720p opening looks soft from the first second, and cropping into it makes it worse. Saving credits there is a false saving.+- A low-resolution draft is extra money, not a discount: finishing it costs the same as rendering directly. Use a draft only to test a risky idea.+- Price every video model the person has before choosing, not only the best-known one. On our launch film a cheaper model at native 1080p (Kling 3.0 Pro) gave a sharper opening than the expensive one at 720p, for about a sixth of the price per clip, and the owner approved it on sight.+- One render per shot. Check the prompt twice before sending. A call that fails validation is not charged; a call that times out may have started, so read the job history and the balance before sending it again.++**The prompt.** The picture already shows the scene; describe the change.+1. One sentence that locks what must not change (the product, the faces, the clothes, any lettering: "stays exactly as it is").+2. One camera instruction, small and slow. If the film's own camera does the move in code, ask for a hand-held frame that stays on this exact framing.+3. One small thing that happens, per person or object, "in real time, already in motion from the first frame".+4. The bans: no new objects, no text, no morphing, no flicker.++**What goes wrong.**+- Two different pictures as first and last frame do not give a camera move between them; they dissolve. For a story in several moments, make one picture per moment, animate each alone and cut.+- Fast hands, tiny lettering, liquids, crowds and mirrors are weak points. Check lettering while the clip plays, not only on its first frame.+- Zooming into a clip by more than about 1.5 turns it to mush. A close-up is its own picture and its own clip.+- An upscaler is a rescue, not a plan. It sharpened soft clips, but the owner still saw the opening as lower quality than the rest; rendering again at native 1080p fixed it. At twice the size an upscaled clip paints skin.+- A person on a screen inside the picture (a video call, a TV) copies the gestures of the person in the room unless told otherwise. Say who moves and who only listens.+- When several shots form a set (four colours, three reasons), treat them alike: if three get a wide shot and then a different close-up, the fourth does too. The odd one out is what the viewer notices.+- Judge sharpness by looking at the frame at the size it plays, next to its neighbours. A sharpness number can say the opposite of what the eye sees.+- Several jobs can run at once up to the service's limit; the one over the limit is refused and not charged.++**Into the film.**+```bash+python3 <skill>/scripts/clip.py clip.mp4 <name> [start] [seconds] [width] # one picture per film frame -> assets/seq/<name>/, listed in assets/seq.js+python3 <skill>/scripts/cutseq.py <name> [frames] # a cut-out per frame, for a word behind a moving person (macOS)+```+**A word behind a subject that moves, without heavy files.** A cut-out picture for every frame is large (about 1.5 MB each at full size). Keep only the mask: cut each frame out at half size (`matte.swift frame.jpg cut.png 960`), keep its alpha, average each mask with its two neighbours (1:2:1) so the edge does not flicker, and save it as a two-channel PNG (black, alpha): about 20 KB a frame. In the page draw the footage, draw the words on their own canvas, wipe them with the mask (`destination-out`, drawn with the footage's transform), then lay that canvas over the footage. The footage is never touched and the words sit behind the subject on every frame. A word that sits further away than the subject grows less than the footage when the camera pushes in.++**A 24 fps clip in a 60 fps film.** For a slow camera move, make the in-between frames instead of repeating frames: `ffmpeg -ss <start> -t <seconds> -i clip.mp4 -vf "minterpolate=fps=60:mi_mode=mci:mc_mode=aobmc:me_mode=bidir:vsbmc=1" -q:v 2 f%03d.jpg`. Look at three made-up frames at full size before using it (fast hands and fine patterns can tear); a slow move round an object came out clean.++In the page, load `assets/seq.js` and draw frame `floor(seconds * fps)` of the sequence, falling back to the still when the clip is not there. A shot uses only part of a clip: take the liveliest stretch, unless the shot has to match a still across a cut, then take the stretch closest to that pose.diff --git a/references/review-room.md b/references/review-room.mdnew file mode 100644index 0000000..28f652a--- /dev/null+++ b/references/review-room.md@@ -0,0 +1,35 @@+# The review room++What it is: a local page where the person watches a cut, clicks on the picture and leaves a note on that exact frame. The maker reads the notes from a file. It replaces "watch it and type what you think" and screenshots. Notes pinned to a frame are far more exact than notes typed from memory.++## Files+`scripts/review-room/server.mjs` and `scripts/review-room/index.html`. No dependencies beyond Node. The page carries the Take One logo from `assets/logo/` (header, tab icon, title), so keep that folder beside `scripts/` when the skill is copied.++## Run+```+node <skill>/scripts/review-room/server.mjs <folder with the exported .mp4 cuts> [port=4400]+```+Then open http://localhost:4400. It only listens on 127.0.0.1; nothing is uploaded. Run it in the background and leave it running for the whole project.++## What the person can do+- Pick a cut (newest first), play, step frame by frame.+- Click on the picture: a pinned note on that frame. Also a note on the frame with no pin, or on the whole film.+- Play a second cut next to the first, in sync, to compare.+- Press "Send notes" when done.++## What the maker reads+- `<cuts folder>/review-notes/notes.json`: every note with `cut`, `t` (seconds), `frame`, `x` and `y` (0 to 1), `text`, `done`.+- `<cuts folder>/review-notes/shots/<id>.jpg`: the noted frame with the pin drawn in. Open these as images; the pin shows what the note points at.+- `<cuts folder>/review-notes/sent.log`: one line starting `SENT` each time the button is pressed. Watch this file (a background monitor, 30 minutes at most, re-arm it) so the person does not have to come back and type "done".++## The loop+1. Export the cut, run the quality gate, then say one line: the cut is in the review room.+2. Arm the watch on `sent.log`.+3. When notes arrive: read every note AND its snapshot. Copy the person's words into the project record before changing anything.+4. Answer note by note in the next cut. Mark a note done (`POST /api/notes/<id>` with `{"done":true}`) only when the new cut really answers it. A note the maker disagrees with stays open and is raised in words.+5. Notes that are about taste or direction (not a fix) are the person's decision: ask, do not guess.++## Limits+- The page assumes 30 frames a second for the frame counter (`FPS=30` in `index.html`).+- Files with `silent` or `small` in the name are hidden from the list (working files).+- One reviewer at a time; notes carry no name.diff --git a/references/reviewer-brief.md b/references/reviewer-brief.mdnew file mode 100644index 0000000..2a5237e--- /dev/null+++ b/references/reviewer-brief.md@@ -0,0 +1,44 @@+# The fresh reviewer: the pack and the brief++The reviewer is a new agent that has seen none of the work. It stands in for a stranger who sees the film once, at full speed, on a phone, possibly muted. Its score is the score (SKILL.md step 5). This page is how to hand the film over so the review is worth having.++## Rules++- **A new reviewer every round.** One that saw the last cut is anchored to it.+- **It reads the pack and the film, nothing else.** No conversation, no storyboard, no code, no notes, no earlier score. Say so in the brief, and name the one folder it may open.+- **It cannot hear.** Give it the measurements instead: loudness, where the music is quiet, where it hits hardest, every word with its time.+- **Tell it what is locked.** If the look is the brand's own, or the words are a song's lyrics that cannot change, say so, or it will spend its three problems on things nobody can fix.+- **Three rounds at most.** Still under the bar after three: stop, deliver with the score and the open problems, and let the person decide. Never report a pass that did not happen.+- **Fix what it names before the master.** A fix made after the last review has not been reviewed; say that when you deliver.++## Build the pack++```bash+bash <skill>/scripts/review-pack.sh out/cut.mp4 out/review-pack \+ --beats "0,1.5,4.8,9.6,..." # one time per story beat (default: 36 evenly spaced)+ --strips "9.2-11.6,66.0-67.2" # a range across every fast move, hard cut and handoff+ --text "4.8,9.6,14.5,..." # frames that carry words, for the phone-width sheet+```++Then fill in `WORDS-AND-SOUND.md` in the pack: who the film is for and where it posts, every spoken or sung phrase with its film time, and the sound report (from `audio-check.mjs` and `songmap.py`).++## The brief (give it to a new agent, changing only the bracketed parts)++> You are the reviewer for a short film. You have seen none of the work behind it, and that is the point: you stand in for a stranger who sees it once, at full speed, on a phone, possibly muted. Be honest and specific; a kind score is useless, and so is a harsh one that is not tied to something visible.+>+> Everything you may look at is in one folder: [pack folder]. Start with WORDS-AND-SOUND.md there. Then look at every image: the one-frame-per-second sheets, the beat grids, the full-size frames, every strip, and the phone-width sheet. The film is [cut.mp4]; you may pull a few more frames from it with ffmpeg if you need a closer look. Do not open any other file: you must judge only what a viewer sees.+>+> [What is locked: the brand's look, words that cannot change, the chosen route (for example: drawn fully in code, so people are small stylized figures).]+>+> [For a launch or product film, add: Hold the part that explains the product to what a paid agency would ship. Say whether it shows the real thing (the product's own screen, footage or output) or an invented picture of it, and whether any layout comes back more than twice in a row. If one frame is repeated for every item of a list, that is a problem to name, however polished it looks.]+>+> Report, in this order, in under 450 words:+> 1. The film retold in one sentence, as a viewer would tell a friend. If you could not follow something, say what.+> 2. Scores 1 to 10, one line of reason each: hook (first 2 s), readability at 360 px, motion quality (from the strips), variety (something new every 2 to 4 s), composition (one focal point, clean space for type, nothing cut by an edge, no type on other content), data accuracy, sound sync (from the times given), and overall against what real brands ship.+> 3. The three worst problems, each with a timestamp and what exactly is wrong.+> 4. Anything that looks off, cheap or wrong at full size (hands, people, type, edges).+> 5. Verdict: PASS if every axis is 8 or more, otherwise RETURN.++## When the owner's taste and the reviewer disagree++Both are in the room for a reason: the taste knows the owner, the reviewer stands in for a stranger. On a film made this way the two agreed on every large problem (weak drawing in the first frame, the loudest moment landing on an empty picture, people who read as icons). They split twice, both times on words: the taste asked for key words only and for a phrase to be said once; the stranger then could not follow the film muted, and called unlabelled cards "empty boxes". When they split on whether a viewer can follow, the stranger wins, because that is the one thing the owner cannot judge from inside.diff --git a/references/services.md b/references/services.mdnew file mode 100644index 0000000..32dbf39--- /dev/null+++ b/references/services.md@@ -0,0 +1,58 @@+# Paid services: the person decides, the skill knows how++The skill can make a whole film in code for free. Real-looking pictures, moving shots, a voice and a song come from services the person may have. Two things are always theirs to decide: **which services may be used** and **how much may be spent**. For every "no" there is another way to make the film.++## The one question, at the pitch++Put it in the pitch message, once, in plain words. List only what this film would use:++> To make this the way I pitched it I would use:+> - **Pictures** (Higgsfield, Nano Banana): about N pictures, [free on your unlimited plan / about X credits]+> - **Moving shots** (Seedance or Kling through Higgsfield): N clips, about X credits+> - **Voice** (ElevenLabs): one narration, about X credits+> - **Music** (Suno): one song, [X credits / from your plan]+> Total about X. Which of these are OK to use, and is there a cap?++- The person answers per service. A "no" switches that service off for the whole film; it is not asked again and not switched on later without a new yes.+- A cap is a hard stop. A yes to the plan covers the plan; anything over it is a new question.+- Quote from the real price, read just before asking (a price call, the pricing page, the balance). Never from memory: prices change.+- If a service is not connected, say how it could be (a connector in Claude, their logged-in browser, an API key they set) and offer the other way now. Never ask for a password or a card.++## For every service, the other way++| The film needs | With the service | Without it |+|---|---|---|+| Real-looking pictures | An image model (Nano Banana through Higgsfield, or any the person has). Method: `real-shots.md`, Pictures | The person's own image tool from prompts you write, and they bring the pictures back. Or change the route: an illustrated look drawn in code, where "every frame is code" is part of the appeal |+| Moving shots | A video model (Seedance, Kling) on the few shots people look at. Method: `real-shots.md`, Moving shots | The pictures move in code (camera, parallax, bursts): honest ceiling about 7 of 10 for a film meant to feel filmed. Or an illustrated film animated fully in code |+| A voice | A speech service (ElevenLabs): cast from two or three samples of the real lines, the person picks by ear. Method: `voice.md` | The person records the lines themselves (often the best choice for a founder). Or no voice: the words carry on screen with music (`words.md`) |+| Music | A song service (Suno): a song whose words are the film's own lines, or an instrumental. Method: `audio.md` | Music composed in code, free, fitted to the film's exact length (`music-engine.md`). Or a track the person owns |+| Sound effects | Rarely needed from a service | Made in code by default, free, placed on exact frames (`scripts/sfx.mjs`) |++Say what each "without" costs the film in one line, so the choice is informed. Do not present the free way as worse when it is the better look for the idea.++## When the service meters downloads apart from making++A music or voice plan can have credits left and no downloads left (seen on a song service: generating was allowed, taking the file out was not until the plan renewed). Read both numbers before generating. With no downloads left there is still a way: generate, tell the person the exact title and length of each take and where it sits in their library, and they download and send the files. Then measure every file they send (`scripts/songmap.py`: tempo, where the groove enters, the quiet parts, the last hit) and choose by fit, because you cannot hear it. Say which one you chose and why.++## How to reach a service++Use the first of these that exists, and say which one you are using:+1. **A connector in the session** (for example a Higgsfield connector with image, video and audio tools). Cleanest: prices and balance can be read before each call.+2. **The person's logged-in browser**, driven by you: their page is theirs. Note what was there before touching it and put it back. Some plans are free only in the web page (an unlimited image plan), so check the switch before every generate.+3. **The person runs it**: you write the exact prompt and settings, they generate and hand back the file. Slowest, always possible.++## The ledger++Keep `spend.md` in the project from the first paid call:++| When | Service | What for | Price read | Balance after |+|---|---|---|---|---|++- One line per paid call, written when the call is made, not at the end.+- After each batch say in one line what was spent and what is left of the cap.+- A call that failed validation is not charged. A call that timed out may have started: read the job history and the balance before sending it again.+- On delivery, give the total with the film. A spend from a free pool is still reported.++## Order of spending++Lock the story and the pictures first. Show the cut with still pictures. Movement, the costly part, comes last and once per shot (`real-shots.md`). Spend where the viewer looks first and longest: the opening, then the product, then faces.diff --git a/references/styles/animated-short.md b/references/styles/animated-short.mdnew file mode 100644index 0000000..04b0b2d--- /dev/null+++ b/references/styles/animated-short.md@@ -0,0 +1,31 @@+# Style: Cinematic animated short++A wordless short film with a real emotional arc, in a soft stylized-3D picture-book look, letterboxed like cinema. Reference: "Goodnight, Keeper" (Sep 2026, ~3 min): a girl signals goodnight with a flashlight to her grandfather, the lighthouse keeper; years pass; in the end she becomes the keeper.++This style is about story first. The drawing only has to be warm and consistent; the feeling does the work.++## Story craft (the part that makes people share it)++- **One relationship, one motif.** Two characters and a repeated gesture between them (the flashlight blink and the beam answering). The motif appears 3+ times and changes meaning by the end.+- **Time as a character.** Show years passing through physical marks, not text: tally marks filling a wall, a growing child, seasons, an aging face, objects that wear out.+- **Setup and payoff.** Every object introduced early returns (the scarf, the box labeled with her name, the lantern). The final image rhymes with the first.+- **A turn.** Absence, loss or a storm in the middle; the ending resolves it with a role reversal or a return.+- **No dialogue.** Title card at the start and end only. Emotion through posture, pacing, light and music.+- Structure (~90-180 s): 0 title over establishing shot → 1 the ritual (childhood) → 2 time passing montage → 3 separation → 4 the storm/turn → 5 return → 6 the ritual reversed → title again.+- Before building, pitch the story in 5 sentences to the user and wait for approval. This is the checkpoint that matters most for this style.++## Look++- **Letterbox 2.39:1** inside the 16:9 frame (black bars), cinematic framing: wide establishing shots, over-the-shoulder, close-ups on faces and hands.+- **Stylized 3D / soft vector:** simple rounded characters with big readable silhouettes, flat-shaded with soft gradient light, gentle rim light. Characters stay on-model across ages (same hair, same signature item).+- **Palette by emotion:** moonlit blues and violets for night and longing, warm lamp-orange interiors for safety, a pink dawn for hope, grey-green storm.+- **Light is the storytelling tool:** the lighthouse beam, a lamp, a flashlight glow (additive light, soft bloom), moon and stars.+- Weather and particles (snow, rain, sea spray) for scale, not decoration.++## Engine++Canvas 2D with layered parallax, or Three.js for real 3D staging (load it from a CDN such as `https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js`; the page is served over http). Keep every frame a pure function of t. For a film this long, split into scene files and brief parallel subagents with a shared character sheet and palette (see the watercolor style's notes on chapters).++## Music++A tender piano or strings track carries this style; cut so the ritual moments land on quiet phrases and the storm on the swell. Offer a Suno prompt ("tender solo piano, slow, nostalgic, sparse, cinematic, builds to strings, instrumental").diff --git a/references/styles/ascii-terminal.md b/references/styles/ascii-terminal.mdnew file mode 100644index 0000000..025365e--- /dev/null+++ b/references/styles/ascii-terminal.md@@ -0,0 +1,41 @@+# Style: ASCII / CRT terminal++Everything on screen is built from monospace characters glowing on a CRT: green or amber phosphor on near-black, scanlines, slight barrel curvature, phosphor bloom, a blinking cursor. Figures, seas, charts, whole scenes are character density fields; log lines and prompts are the narration. Reference: procedural demoscene-style terminal work. The raw numbers are modest, but the style is cheap to execute flawlessly in code and the audience is exactly ours.++## Why this style exists in our gallery++Dev-tool launches live in this house. For a product whose home is the terminal, the medium is the message: the film looks like the place the product lives, so the audience recognizes it as "for me" in the first half-second. And like crayon, it is an imperfection-proof bet: a character grid cannot be off-model, a density field cannot tear at a joint, and every frame is trivially deterministic. It is the default recommendation for CLI/agent products and anything aimed at developers.++## Design system++- **Ground:** near-black with a faint phosphor ambient (#0A0806 in the amber world, #04080A-ish in the green world), corner vignette, scanlines over everything.+- **ONE color per world:** green #33FF66 or amber #FFB000, chosen once for the whole film. Every "shade" is a brightness step of that hue (dim char up to near-white hot core). The single declared exception: a red alert line (#FF5555 family) as ONE line of terminal chrome at the crisis beat, never in the scene field itself.+- **The grid:** everything lives on a character grid, e.g. 160x45 cells at 16:9 (8x16 px cells at 1280x720). Nothing is ever drawn off-grid.+- **Density ramp:** brightness maps to character weight through a fixed ramp like `" .:-=+*#%@"`. Calm = sparse `.:-` textures; force and danger = walls of `@#%`. Brightness picks the character AND its phosphor intensity together.+- **Scenes as density fields:** figures, water, skies, charts are rendered as luminance first, then translated to characters. A protagonist is a small bright glyph cluster against a dimmer field; findability comes from contrast, not outline.+- **CRT artifacts:** scanlines every 2-3 px, phosphor bloom (bright chars halo), slight barrel curvature, and in motion a subtle flicker and refresh shimmer. Restraint: artifacts season the frame, they never obscure a character.+- **UI chrome as a real terminal:** a genuine prompt line (`user@host:~$ command`), timestamps (`[HH:MM:SS]`), log lines, exit codes, a blinking block cursor. Chrome rows are real text on the same grid, brighter than the scene field.+- **Type:** the terminal IS the type system. One monospace face, nothing else, ever.+- **Format:** 16:9 for X/LinkedIn; also strong in 1:1. Must read fully muted (the log lines carry it).++## Story grammar++1. Commands and log lines ARE the narration: the story advances by what gets typed and what the system prints back. The prompt is the protagonist's voice.+2. Every line arrives by typewriter reveal; the cursor blinks while the system "thinks". Silence = a blinking cursor on an empty line.+3. Scene beats render as density fields behind/between the chrome; a scene can bloom out of a command's output.+4. Danger is density: the threat is a towering wall of `@#%`; the hero stays a tiny bright cluster that keeps pointing forward.+5. The red alert line marks the single crisis beat, and it is used exactly once.+6. Callback ending: the film ends on a fresh prompt with a blinking cursor. The terminal is ready again.++## Engine notes++- **Two-stage render:** draw the scene into a small offscreen 2D canvas (square-ish pixels, e.g. 160x90), scale-sample it down to one pixel per grid cell (160x45), read the luminance buffer, and map each cell through the density ramp to its character and through the same value to its phosphor brightness.+- **Grid:** e.g. 160x45 cells at 1280x720 (8 px wide, 16 px tall, the ~1:2 cell aspect of a real terminal). Draw the scene in a square-pixel space and compress vertically at sampling time so shapes keep their proportions.+- **Phosphor bloom via layered draws:** render all characters to an offscreen layer, then composite it with `lighter` several times: one downscale-upscale pass (quarter size drawn back full-frame, low alpha) for the wide halo, a small offset ring for the tight glow, then the sharp layer on top. No ctx.filter, no CSS filters.+- **Scanlines:** 1 px black lines at ~0.2-0.3 alpha every 2-3 px, drawn after the bloom.+- **Barrel curvature via per-row x-offset:** each text row drawn with its own horizontal scale toward center, `scale = 1 - k*dy^2` with k around 0.02-0.04 (dy = row distance from vertical center, normalized). Add a corner vignette to sell the tube.+- **Color:** one phosphor per world (green #33FF66 or amber #FFB000). Brightness = lerp black -> phosphor for the lower range, phosphor -> near-white (e.g. #FFEBB8 for amber) for the hottest cells. Red #FF5555 exists only as the declared one-line alert exception.+- **Chrome rows** are real strings placed on grid cells (they replace scene cells), at 2-3 brightness tiers: prompt bright, logs dim, alert red.+- **Motion:** typewriter at 15-40 chars/s with seeded jitter, cursor blink ~530 ms square wave, scene fields animated by re-evaluating the luminance scene per frame; add a per-cell brightness jitter of a few percent per frame for phosphor life. Seeded randomness only, fully deterministic.++**Best for:** dev-tool and CLI/agent launches, "watch the system think" narratives, changelog and release films, benchmark/chart moments, retro-computing subjects, any audience that lives in a terminal.diff --git a/references/styles/chrome-showreel.md b/references/styles/chrome-showreel.mdnew file mode 100644index 0000000..58fbd7c--- /dev/null+++ b/references/styles/chrome-showreel.md@@ -0,0 +1,30 @@+# Style: Glossy chrome showreel++Studio-lit reflective chrome and liquid-metal pseudo-3D objects and type, in FULL COLOR poster fields, cut as rapid beat-locked vignettes with extreme eased morphs: a "showreel" that flexes range on purpose. #1 performing look in the Opus-video corpus. Top case: an Opus 5.5 one-prompt 15 s motion-design showreel (Sep 2026), 1920x1080 @ 60 fps. Studied via contact sheet; note honestly: that case pairs the showreel grammar below with flat Swiss color blocks, while the chrome/liquid-metal surfacing is the corpus's top LOOK. This style folds the top look onto the top structure. Do both.++## Why it works++A showreel is permission to show off: every 2 seconds is a new trick, so attention never settles. Beat-locking (the reference literally prints "128 BPM" and a bar counter on screen) makes the cuts feel inevitable rather than random. Chrome is the flex material: a reflective surface proves you computed light, and a specular streak sweeping across type is motion even when the object holds still. And the self-aware frame ("this is my resume") turns a capability demo into personality.++## Design system++- **Backdrops, full color, hard fields.** One saturated poster field per vignette, no gradients on the field itself: vermilion `#E8442C`, ultramarine `#3230EE`, acid yellow `#D8F000`, ink black `#0E0E10`, cream `#EFEBE0`. The chrome object reflects an implied STUDIO (softboxes, floor, horizon), not the backdrop, but tint the ramp's mid-tones toward the field color so object and field belong together.+- **Chrome ramp** (the material, as a vertical env gradient sampled by surface normal): sky white `#FAFBFF` to cool silver `#C6CDDA`, then a HARD horizon break to near-black `#181B22`, then ground bounce `#5C6472` and deep `#23262E`. The hard sky/ground break at the ramp's "horizon" is what makes metal read as mirror; a smooth ramp reads as plastic.+- **Specular streaks:** 1-3 long thin white softbox reflections (rounded-end bars) laid ACROSS the form, slightly off-axis; one hot core streak at ~100% white, the others at 40-60%. In motion they sweep; frozen, they must look mid-sweep.+- **Contact shadow:** every grounded object gets a tight dark ellipse (multiply, soft edge) plus a faint mirrored reflection fading out below. Floating objects get neither; floaty is a choice, make it once per vignette.+- **Type, two voices.** (1) Hero type: heavy extended grotesque, HUGE (60-80% of frame width), either flat ink `#0E0E10` on a color field or fully chromed pseudo-3D with a visible extrusion. (2) HUD chrome, the signature framing device: thin corner brackets at all four corners, small monospaced caps labels: project name top-left ("MOTION REEL - 2026"), vignette index top-right ("03 - SURFACES"), timecode bottom-left ("00:00:07:32 60 FPS"), beat meter bottom-right ("128 BPM ■□□□ BAR 5/8"), plus a thin progress rule along the bottom edge. The HUD persists across every cut; it is the reel's spine.+- **Motion grammar:** rapid vignettes, 1-2 bars each (~1.9-3.8 s at 128 BPM), HARD cuts exactly on the downbeat. Inside a vignette, ONE morph with extreme easing: expo-out arrivals, back-out overshoots, elastic settles, and motion-blur smears on anything faster than the eye (stretch + blur along velocity, like the reference's kinetic type). Never two ideas per vignette.+- **Structure (the reel):** open on a pulse (dot to burst), then an identity card (name in hero type on the loudest field), then 4-6 trick vignettes, each a different domain (easing chart, pattern field, wireframe or chrome 3D object, kinetic type, physics), then a closing card: logo + name + role, calm, on the identity color. The end card holds a full bar.+- **Format:** 16:9, 1920x1080, 60 fps, 15-30 s. Must work muted (the HUD beat meter SHOWS the rhythm), but ships with a beat-matched track.++## Engine notes: faking a studio in code++- **Canvas 2D, per-facet:** model the object as planar facets with 3D normals; fill each facet with a linear gradient that samples the chrome ramp by the facet's normal Y (up-facing gets sky whites, down-facing gets ground darks, near-horizontal crosses the hard break). High contrast BETWEEN adjacent facets is the crease; add a 1 px darker edge stroke where facets meet.+- **Canvas 2D, per-pixel (liquid metal):** for a chrome sea or blob, walk ImageData: height field h(x,y) from 2-4 seeded sines plus ridged noise, normal from finite differences, then color = ramp(reflected ny), plus specular = pow(max(0, dot(n, half-vector)), 60-200) added as white. One pass at full res is fine for stills; render at half res and upscale for motion.+- **Streaks and grounding:** softbox streaks are drawn shapes (rounded bars, screen/lighter blend), not computed; cheaper and more art-directable. Contact shadow: radial-gradient ellipse, multiply. Mirror reflection: redraw the object flipped, 15-25% alpha, fading mask.+- **Real 3D when the morph needs it:** Three.js `MeshPhysicalMaterial` (metalness 1.0, roughness 0.05-0.15, clearcoat 1.0) with an env map BUILT FROM GRADIENTS: render a small canvas (sky ramp above a hard horizon line, 2-3 white streak bars) through `PMREMGenerator` as an equirect texture. No downloaded HDRIs; the fake studio stays in code.+- **Beat lock:** pick BPM first, derive `beat = 60/BPM`, and schedule every cut and impact at integer beats. Drive the HUD bar counter and progress rule from the same clock so the HUD never lies.+- **Grain:** a faint seeded per-pixel grain (2-3% luma jitter) over the whole frame keeps the flat fields from banding and makes chrome feel filmed.+- **Determinism:** seeded RNG for noise, grain, streak jitter; the same seed must give the same pixels.++**Best for:** model-drop demos and capability flexes, tool and product hype teasers, personal showreels, launch stingers, "look what X made in one prompt" posts; anything where the point is range and craft density per second. The strongest opener style when the subject IS the maker.diff --git a/references/styles/crayon-storybook.md b/references/styles/crayon-storybook.mdnew file mode 100644index 0000000..a6e94ab--- /dev/null+++ b/references/styles/crayon-storybook.md@@ -0,0 +1,35 @@+# Style: Crayon storybook++A child's-picture-book history told in crayon and ballpoint on cream paper. Reference: "The history of dinosaurs in under one minute" (Sep 2026): "Claude Sonnet 5.5 drew every frame of this animation in JavaScript", 47 s, 2160x2160 square.++## Why this style exists in our gallery++Our watercolor-realism attempt failed because pushing a code character toward anatomy exposes every joint in motion. This style is the opposite bet, and it wins: **imperfection is the aesthetic**. A wobbly contour can't be off-model, a scribble fill can't tear at a joint, a hop with squash reads as charm, not error. When the subject is characters who must move a lot, this is now the default recommendation over realism.++## Design system++- **Ground:** warm cream paper (#ECE8DC family), bare. No texture overlay needed; the marks carry the texture.+- **Line:** ONE thin blue ballpoint contour (#2B3A7E-ish), loose and wobbly, occasional double-stroke, gaps where the hand lifted. Line boil: re-jitter the wobble on 2s or 3s (not every frame), like a child's flipbook.+- **Fill:** crayon scribble masses laid AFTER the line and disobeying it: overshoot, undershoot, visible directional strokes, unfilled patches. Big areas = side-of-crayon broad strokes. The sun is a concentric orange scribble spiral. Catastrophe = black crayon scrubbed over the whole sky, ragged bottom edge.+- **Palette:** a small crayon box: teal green, orange, marigold yellow, warm red, earth brown, black. Each character owns 1-2 crayons.+- **Caption strip:** a handwritten-script caption bottom-center of EVERY frame. In the reference it is the timeline ("230 million years ago" → "0 million years ago") and it is the story's spine. The final caption is the payoff line ("still here.").+- **Characters:** tiny bodies, one big eye with a highlight, emotion through posture and eye size only. Babies = bigger head, bigger eye. No fingers, no anatomy. Squash-and-stretch hops, tail drags, pop-up hatches.+- **Format:** square 1:1 (feed-native), ~45-60 s, must read fully muted (the captions carry it).++## Story grammar (from the reference)++1. One protagonist lineage carried across eras/chapters; the caption device marks time jumps.+2. Scale beats: the tiny hero next to something enormous (baby under the sauropod's leg).+3. The catastrophe is a texture change, not a new style: the same crayons, scrubbed dark.+4. Quiet aftermath beats (empty paper, one fern) before the recovery.+5. **Callback ending**: the film ends where it began, transformed (egg → egg in a nest), plus a two-word closer.++## Engine notes++- Strokes as data: each mark = centreline + width + crayon color + jitter seed; refill scribbles by seeded hatching inside (or past) a blob path.+- Crayon texture: stroke alpha modulated by a seeded grain tile so pressure varies along the stroke; ends fade like wax lifting.+- Ballpoint: near-constant thin width, slight darkening where strokes cross.+- Boil on 2s/3s: re-seed jitter at 8-12 fps steps while animating position at full fps.+- Captions: a handwriting font is acceptable; a drawn-on path per caption is better (draw-on in reading order).++**Best for:** history/evolution explainers, "X in under a minute", kids' subjects, science stories, anything where characters move a lot and warmth beats polish. Strong default for family films.diff --git a/references/styles/dark-premium.md b/references/styles/dark-premium.mdnew file mode 100644index 0000000..45f1897--- /dev/null+++ b/references/styles/dark-premium.md@@ -0,0 +1,33 @@+# Style: Dark premium explainer++Near-black canvas, one warm metallic accent, cinematic light. For serious AI and B2B concepts. Reference: a concept video for an AI infrastructure company (Sep 2026), which had the right look but a 2-minute runtime, a dozen ideas, and small low-contrast text. This style file is that look with the fixes.++## Design system++- **Background:** near-black with depth (#0B0B0F to #15151C radial), a faint film grain, subtle vignette.+- **One accent:** warm gold/amber (#F5B544 range) used for light, the key word, the hero object. Optional second hue only for "before" states (a cold grey-blue).+- **Type:** a clean sans, large and bright (#F4F1EA), 90-160 px for statements; **one italic serif accent word per line in the accent color** ("What if it worked *like that?*"); small mono labels for structure (`// the old way`, `01 · Start`).+- **Hero object:** one glowing, tactile object that represents the product (a card, a key, a core, a lens). It gets the light, the particles, the close-ups.+- **UI cards:** frosted dark cards with 1 px light borders, used sparingly and **big**. That video's failure: grids of tiny cards unreadable on a phone.++## Hard fixes (why the reference didn't land)++- **One idea, 30-45 s.** Pick the single sentence the video must leave behind and cut every scene that doesn't serve it. Two minutes and twelve concepts lose everyone.+- **Contrast:** statement text is near-white on near-black, never grey on grey. Test every frame at phone size (360 px wide contact sheet).+- **Max one read per beat,** 2-3 s per beat. No dense diagrams; show a transformation instead (dull → glowing, many → one).+- **A human anchor** if possible: a character, a face, or a relatable before/after, because abstract particles don't carry emotion.++## Beat sheet template (35 s)++| Time | Beat |+|---|---|+| 0-4 | A famous, instantly recognizable hook (for example a line from a film everyone knows, typed in a terminal) |+| 4-8 | The question it raises ("What if it worked *like that?*") |+| 8-15 | The old way, shown as pain in one visual (slow, costly, frozen) |+| 15-26 | The hero object appears in light; the one transformation that is the product |+| 26-32 | The payoff line, huge ("No *waiting.*") |+| 32-35 | Logo + tagline, the hero object glowing |++## Engine++Canvas 2D (or WebGL2 for glow/particles) via `scripts/new-canvas-project.sh`. Glows are additive (`globalCompositeOperation = 'lighter'`), grain is a static seeded noise layer, depth of field is a blur on background layers only.diff --git a/references/styles/editorial-hud.md b/references/styles/editorial-hud.mdnew file mode 100644index 0000000..5fda66c--- /dev/null+++ b/references/styles/editorial-hud.md@@ -0,0 +1,60 @@+# Style: Editorial HUD film++A fashion-campaign film with an intelligence layer on top: photoreal, film-grained footage of one consistent character across several "looks", overlaid with a code-drawn HUD (mono labels, data panels, tracking brackets, a countdown, a news ticker) and giant kinetic words. Reference: an Opus 5.5 film (Sep 2026, 5 min, 24 fps): "Gave Opus 5.5 donald's prompt, Midjourney, and a moodboard. 12 hours later, woke up to this."++It's a hybrid: an image/video model makes the beauty, Opus directs and draws the intelligence layer.++## Design system++- **Footage:** editorial fashion photography in motion. One recurring character (same face, hair, signature detail such as a colored streak or a hair clip), a styling concept (uniform + hardware: harness, straps, tags), locations that tell the story (runway, car interior, server hall, spa, empty lot). Film grain, halation, slightly crushed blacks, 24 fps.+- **HUD, all code, drawn over the footage:**+ - small monospace labels in the corners: `LOOK 11 / 11`, `MODEL 01 · LOOK 11`, `ESCAPE VELOCITY · SS27`, a running timecode;+ - a thin frame of tick marks and coordinates at the edges;+ - **one accent color, a hot orange-red** (#FF4A1C range), used for tags ("A PROMISE, NOT A PRODUCT"), dotted scan paths, and key digits;+ - data panels (dark translucent boxes, 1 px borders): a spec title, a big number in the accent ("SLICE 114 / 120"), a small chart;+ - a persistent counter as the story's clock ("07 MONTHS TO ESCAPE");+ - tracking brackets that follow the face or an object (keyframe their positions per shot);+ - **a bottom ticker** of topical, satirical data ("TOKENS BURNED 321,084,500 · NVDA ▲ 5.3% · WAYMO RECALL 3,900 ...").+- **Headlines:** a clean bold grotesk in white, 2-line statements top-left ("Lower me into / the golden light."), with a typed-on caption line underneath in mono.+- **Kinetic words:** a condensed display face, huge, slamming in one word at a time ("LOCK", "ESCAPE", "ZERO-DAY.", "STARGATE:"), sometimes split-flap or letter-spaced.++## Production pipeline++1. **Moodboard + character:** agree the character, styling and 6-11 "looks" (locations/moments) with the user. Collect or generate a moodboard.+2. **Footage from a model:** the user generates stills (Midjourney, Nano Banana, GPT image) with a consistent character reference, then animates them into short clips (Seedance, Kling, Midjourney video, via Higgsfield or directly). Write every image/video prompt for them; quote credits before spending any. Aim for 3-6 s clips, 16:9, same grade.+3. **Edit the footage** into a timeline (ffmpeg concat with cuts on beats), conform to 24 fps, add grain if clips differ.+4. **HUD as a transparent overlay:** build `film.html` that draws ONLY the HUD on a transparent canvas (`clearRect`, no background), with the edit's shot list and timings, then export with alpha:+ ```bash+ ALPHA=1 node export.mjs 24 hud.mov+ ffmpeg -i footage.mp4 -i hud.mov -filter_complex overlay -c:v libx264 -crf 14 -pix_fmt yuv420p -movflags +faststart final.mp4+ ```+ For tracking brackets, eyeball the subject's position in each shot from extracted frames and keyframe them.+5. Music: a moody electronic track; cut so kinetic words land on hits.++## Length++The reference ran 5 minutes, which works as an art piece for an audience that already follows the creator. For reach, cut a 30-60 s version: 5-6 looks, one clock, one ending line.++## Faces and vertical++- The HUD frames the hero; it never sits on her. Tracking brackets may outline a face; panels, boards, reports, cards and slams go in the free space around her (face audit in `references/pipeline.md`).+- For 9:16 follow `references/vertical.md`: per-photo framing, type above the head or below the chin, compact strips instead of wide panels.++## Stills-only variant (zero video credits), and its ceiling++An app-builder music video (Sep 2026) was made with 21 stills from an image model on an unlimited plan, at no extra cost, and all motion in code. It works and it's fast, but be honest about the ceiling: our own review against the reference scored it about 7/10, mainly because nothing in the photos moves.++**Making stills feel alive**+- **Burst pairs:** generate a second still with the first as the reference: "Recreate the reference photograph as the exact same shot a split second later ... The only change: she breaks into a laugh." Framing and light stay nearly identical, so cutting between them on 8th notes under flash pops reads as motion. Same trick for a jump cut to a new expression mid-shot.+- Cut on the beat, jump in on a sung word, a slow push plus a little handheld shake, a small scale pulse on each kick after the drop, flash pops on hits, halftone and grain on everything, an audio-reactive HUD waveform.+- No single still held past about 4 s without a cut, a burst or a jump-in. The long holds (a 7 s wall shot, an 8 s outro on report panels) were the flattest parts.++**Prompts that made the plates usable**+- Identity: the first approved portrait is the reference for every later shot, plus a fixed line for face, hair and wardrobe ("identical face: freckles, dark curly hair loosely tied up, cream canvas workwear jacket"). It held across 20 images.+- Room for type: "framed on the RIGHT third, the left half clean negative space".+- UI plates: "the screen glowing plain blank white, flat to the lens", so code can put the app on it (masks + perspective, `references/pipeline.md`).+- "No text, no letters, no logos, no pins or badges": code draws the brand marks exactly (real logo paths, the hero's signature pin).+- A lighting arc as the story's turn: night (teal-navy, direct flash, desk lamp) for the problem, bleached daylight for the solution. Watch the white half: a grade that lifts it too much goes milky and loses punch.++**Getting to 9+**+Price 4-6 short video clips (Seedance or similar, 3-5 s each) for the hero moments, with the approved stills as start frames: her turn to camera on the hook, a hand pressing send, the door opening, the room laughing. Everything else can stay stills + code. Offer this at the pitch with the credit cost; video is not covered by Unlimited.diff --git a/references/styles/explainer.md b/references/styles/explainer.mdnew file mode 100644index 0000000..c41b255--- /dev/null+++ b/references/styles/explainer.md@@ -0,0 +1,47 @@+# Style: Clean kinetic explainer++A 15-30 s product or idea explainer that feels like a top design studio made it. Reference: a product explainer for a workflow tool (Sep 2026): white page, one blue, giant type, a dithered mascot, UI cards that assemble.++## Design system (decide all of it before building, then never deviate)++- **Background:** off-white (#FAFAF8 range). One full-bleed accent-color scene is allowed as a punctuation beat, and one black scene near the end for the tagline.+- **One accent color** (that explainer used royal blue ~#2563EB). Everything else is black and greys. The accent marks only what matters: the key word, the button, the checkmark, the chart's last bar.+- **Three fonts, each with one job:**+ - a bold geometric sans (Inter Display / Geist / Satoshi style) for the message, very large (120-200 px at 1080p);+ - a **handwritten-feeling italic serif for exactly one word per line** ("Got something to *sell?*", "a store in *minutes.*", "*Handled.*"). This contrast is the signature move;+ - a small monospace for labels that make it feel engineered: `// 01 — hook` top-left, `BRAND 00:00:10:30` running timecode top-right, `// checkout` on cards.+ Google Fonts may be loaded (the page is served over local http during render). Wait for `document.fonts.ready` before setting `window.READY`.+- **A mascot or character, dithered to 1-bit** (ordered Bayer dithering, black dots on white). Source it as an image (image model, the user's logo character, or their photo) and dither it in code at load time. It reacts: looks at the text, winks, speaks a tiny bubble ("psst..."). It is the warmth in a cold UI world.+- **UI cards** for the product: white cards, 1 px grey border, 16-24 px radius, generous padding, real-looking numbers ($149.00, 4242 4242 4242 4242, EU VAT ✓). A bento grid of 4-6 cards that fills in piece by piece is the classic "it's all handled" beat.++## Motion++- Type arrives **word by word, in sync with the idea** ("Got" / "something" / "to *sell?*"), each word a fast ease-out with a slight rise; the italic word lands last with a little overshoot.+- One idea per scene, 1.5-3 s each. Cuts are clean: slide, push, a mask wipe, or one fast whip ("Apple Pay" streaking across) for energy, then calm again.+- The mascot moves subtly all the time (breathing, blinking, glance) so the frame never feels dead.+- Numbers count up; checkboxes tick; charts grow; a stamp word ("*Handled.*") slams in at an angle over the grid.+- All of it on springs (`timing.md` presets: `snappy` for cards and ticks, `heavy` for the stamp word, `playful` for the mascot). Export the master with `SUB=8` so whips and flying type carry real motion blur.++## Launch grammar (type and product moves from the best launch videos)++- **Focus-pull word reveals:** each word arrives from a blur (draw it 2-3 times at small offsets with falling alpha, converging to one sharp copy over ~0.3 s) instead of sliding in. Reads as a lens, not a slide.+- **In-place word swaps:** one word in a held sentence changes ("Built for *teams.*" → "*founders.*" → "*you.*"): the old word lifts and fades, the new one rises into the same baseline, the sentence never moves.+- **Inline icons inside sentences:** a real icon or logo sits in the line of type at cap height, as a word ("Send it to [Slack icon] in one click"). Real integrations only.+- **One sentence across 2-3 beats:** "Your whole team" / (card grid assembles) / "in one place." The picture fills the pause in the sentence; the viewer reads it as one thought.+- **The component macro:** lift one real control onto a clean field at 3-5x, perform the interaction, show the result, spring back into the full UI (`real-product.md`).+- Any number on a card that isn't the product's real data carries a small **"Example data"** label.++## Beat sheet template (15 s)++| Time | Beat |+|---|---|+| 0-3 | Hook question to the viewer, mascot reacts ("Got something to *sell?*") |+| 3-5 | The things they have (cards pop in: courses, ebooks, apps) on the accent background |+| 5-8 | The product turns it into the solution, shown in a phone or window ("turns it into a store in *minutes.*") |+| 8-12 | Bento grid: every painful thing, handled, cards filling in, then the stamp word |+| 12-14 | Tagline on black ("You *create.* We handle the rest.") |+| 14-15 | Logo + one line + URL; mascot peeks in |++## Engine++Plain canvas 2D (or HTML/CSS drawn to canvas) via `scripts/new-canvas-project.sh`. Draw type with `ctx.fillText` using the loaded fonts; UI cards as rounded rects with real text. Keep everything crisp: integer-pixel strokes, no blur except deliberate motion blur on the whip.diff --git a/references/styles/image-game.md b/references/styles/image-game.mdnew file mode 100644index 0000000..847c5a4--- /dev/null+++ b/references/styles/image-game.md@@ -0,0 +1,30 @@+# Style: Image-to-game cinematic++An image model makes the art (so it looks AAA); Opus turns the still images into a real, animated, often playable game. The hook: the video opens on a still that looks like a screenshot, then it comes alive. Reference: one of our own films (Sep 2026), a Mortal Kombat-style fight built in one prompt from four images.++## Assets (made first, with an image model: GPT image via ChatGPT, Nano Banana via Higgsfield, etc.)++Write the image prompts for the user; they generate. Ask for:+1. **The hook screen** (16:9): e.g. a character-select screen, title screen, level map. All UI crisp and separated.+2. **Pose sheets**, one per character: 6 full-body poses in one row, identical scale and lighting, evenly spaced on a **flat light-grey background with clear gaps**, all facing the same way (player faces right, opponent faces left). Example set: stance, punch, high kick, block, hit, victory / knocked down. Without pose sheets characters can only slide like cut-outs.+3. **The empty stage** (16:9) matching the hook screen, with a clear floor.+If the user appears in it, attach their photo to each prompt. Never invent the opponent, theme or target: ask.++## What the build prompt must ask for++- Key out the grey background in code (color-distance keying, soft anti-aliased edges, no halo), auto-detect poses by empty column gaps (cut touching figures along the emptiest seam), anchor each pose by its feet.+- Light the sprites into the scene: warm tint matching the stage, contact shadow, faint floor reflection.+- Make it feel animated, not like swapped cut-outs: tweens with anticipation and recoil, motion smears, squash on impact, idle breathing, hit-stop freezes, decaying screen shake, sparks, slow motion on the finisher.+- Game UI drawn in code in the hook screen's style: health bars with a damage trail, timer, combo counter, slam-in announcements.+- A playable mode after the cinematic (keyboard), reusing the same systems. "You can play it" is a strong share hook.+- Serve images over local http (canvas reading local files taints it); expose `window.READY = true` after processing.++## Comedy that lands++- If a character talks, **each attack is a line** (a special move shouted), and every line fails on screen (blocked, dodged, turned back). The best joke contradicts the situation: the loser, knocked out, still pitching.+- Speech bubbles: smooth oval, bold black text 56-66 px, no shake, held ≥ 1.4 s, never over the HUD, names or faces. Pin the final punchline bubble by hand next to the character's head; auto-placement drifts.+- End on a held beat (2.5 s+) with the music faded out so the last line lands in silence.++## Pacing++~40 s for a full fight: hook still (1 s) → wake up → select → VS → ROUND 1 / FIGHT → 4-5 exchanges → special move → FINISH → victory → punchline hold. The first cut at 30 s was too fast to read; 40 s with room around each joke worked.diff --git a/references/styles/ink-wash.md b/references/styles/ink-wash.mdnew file mode 100644index 0000000..08a2b64--- /dev/null+++ b/references/styles/ink-wash.md@@ -0,0 +1,35 @@+# Style: Ink wash (sumi-e)++Chinese/Japanese ink painting (水墨 / sumi-e) on absorbent rice paper: diluted ink strokes that bleed and breathe, vast negative space, one cinnabar-red seal. Evidence the look travels: an Opus 5.5 ink-landscape piece and another Opus 5.5 boat journey through Japanese landscapes — misty mountains dissolving into blank air, water carried by reflection alone, one small boat against emptiness. Recipe informed by anidoodle (Apache-2.0).++## Why this style exists in our gallery++It is our only style where **the paper is the light** and emptiness is the composition. Watercolor and crayon fill the frame; sumi-e leaves most of it bare and makes the few marks carry everything. Because every mark is one uncorrectable gesture, it renders fast (dozens of strokes, not thousands), scales to any subject that can be reduced to gesture, and its native motion grammar — the painting drawing itself stroke by stroke — is mesmerizing on a feed with zero character-animation risk.++## Design system++- **MEDIUM, physically:** one soft brush of real hairs, loaded from an inkstone and reloaded rarely, on unsized xuan (rice) paper that drinks ink the instant it touches. Nothing can be corrected or covered. Each hair holds its own ink and spends it with travel, so a stroke starts wet-dark and ends in dry-brush "flying white" (飞白): streaks of bare paper running WITH the stroke, split hairs splaying at the lift. Wherever the brush slows (touch-down, a pause, the lift) the ink bleeds a soft halo into the paper fibres, with fine feathers wicking outward — the tell of absorbent paper. Edges are soft-feathered where wet, broken and bristled where dry, never a clean outline.+- **THE FIVE INKS (墨分五色):** tone ONLY by dilution — scorched (jiao 1.0), thick (nong 0.82), heavy (zhong 0.6), light (dan 0.38), clear (qing 0.2). Diluted sumi cools toward blue-grey as the carbon thins (#0f0d0c → #39414a); it never goes brown. **Depth is dilution:** the near thing is thick ink, the far thing is clear, the farthest is barely a breath.+- **MARKS:** every mark is one gesture with a pressure envelope — a leaf touches at a point, presses to full width, lifts to a point; a hull is one confident side-laid drag that breaks into flying white; a mountain is one wet flank of the brush. No hatching, no scribble, no outline-then-fill.+- **ORDER (half the hand):** near before far within a subject, structure before detail — stalks, then nodes, then branches, then leaves; hull, then mast, then rigging. Wet washes (mist, sky) go down early so crisp marks sit on top. Dry accents (moss dots, spray flicks) near the end. **The seal is stamped last, always.**+- **PALETTE:** warm unbleached xuan paper (#f3ede0) with long pale fibres and bark flecks in the sheet; one ink at five dilutions; and exactly ONE color: the cinnabar seal (#b8352b). Nothing else, ever.+- **PAPER / NEGATIVE SPACE:** the paper IS the light, the water, the sky, the mist, the lit side of everything. Aim for 60-80% of the frame left bare or near-bare. Mist is an absence: shapes simply stop where the mist begins.+- **THE SEAL:** a baiwen (white-line) seal — invented seal-script glyphs cut INTO the stone, so they print as paper inside a red block with a worn, chipped border, paste pressed unevenly. One per composition, in a corner, balancing the emptiness. It is the only red in the frame.+- **LIGHT:** diffuse, one implied direction. Sumi-e carries light by leaving paper, not by cast shadow: the lit crown is the brush's dry lift, the lit belly is bare paper. A sun or lantern is a pale near-clear ring or a gap left in a wash.+- **MOTION GRAMMAR:** two devices, both native. (1) **Strokes draw themselves:** the film is the painting being painted — each mark grows along its centreline at a hand's pace, touch-down bleeds, travel, lift, then the slow points keep soaking a moment after the brush leaves. Finished marks never change. (2) **Mist reveals:** clear-ink washes thin or thicken to disclose and swallow shapes; a mountain "arrives" by the mist withdrawing, not by moving. Camera moves are slow horizontal handscroll pans (emaki), if any. Never squash-and-stretch, never bounces: things enter by being painted or unveiled.+- **FORMAT:** 16:9 or vertical hanging-scroll crops both read; must survive muted (it is silent by nature — score with solo shakuhachi/guqin-feeling sparse music).++## Engine notes++- **Brush = hairs, not a line.** A stroke is: hand-placed control points (smoothed + resampled), a width, a pressure-knot profile, a dilution, and per-hair state. Each of ~10-40 hairs gets its own ink load (edge hairs more on a side-laid stroke, tip hairs more on a pointed one, high variance when half-loaded = streak mode); load decays per px of travel; a hair skips (bare paper) where load loses to paper-tooth noise — that IS flying white. Draw hairs at the dilution's tone in ONE multiply pass: ink does not stack with itself inside a stroke, only where a second stroke crosses.+- **Bleed layer under the hairs:** at declared slow points, a wobbly-edged blob (radius ~ local width) plus 10-24 single-fibre feather lines wicking outward, all blurred 2-4px, multiply, low alpha; plus a faint halo a hair wider than the stroke wherever the brush was still wet. Wet-into-wet (mist, storm sky) = the same stroke with heavy blur and lowered alpha.+- **Paper first, grain last:** fibres and flecks drawn under everything; a light paper-grain modulation over everything.+- **Self-drawing films:** keep an ordered op list (one op per stroke); finished ops composite once into a cached bitmap, only the stroke in hand redraws each frame, cut partway along its centreline. Frame 0 is bare paper; the last frame equals the still exactly. Time per stroke ~ length + a constant per brush lift.+- **Determinism:** seeded rng per stroke; same seed, same fibres, same flying white.++## Not its neighbour++- **Watercolor** (our western picture-book style): watercolor is COLOR laid in transparent overlapping pools with hard pooled rims, filling the frame, characters acting with faces. Sumi-e is one ink where tone is dilution, marks are single calligraphic gestures with flying white, the frame stays mostly empty, and figures are stroke-economy silhouettes. If it has more than one color (plus the seal) or a colored wash, it has drifted to watercolor.+- **Painterly glow** (Van Gogh oil): that style is opaque impasto strokes covering every pixel with additive glow. Sumi-e is transparent, subtractive (multiply), and mostly paper.++**Best for:** journeys and landscapes, solitude and scale, poems and proverbs, martial-arts or nature subjects, meditative brand films, anything where restraint reads as confidence. Weak for: dense UI/product demos, dialogue comedy, anything needing many colors.diff --git a/references/styles/kinetic-lyric.md b/references/styles/kinetic-lyric.mdnew file mode 100644index 0000000..d3ca130--- /dev/null+++ b/references/styles/kinetic-lyric.md@@ -0,0 +1,20 @@+# Style: Kinetic lyric video++The song's words are the visuals. Every lyric line becomes its own typographic scene with a visual metaphor for its meaning. No characters needed. Reference: a take on the P(doom) song (Sep 2026, 2:36, 60 fps): "I also gave it a try with a different style".++## How to design it++- **Start from the lyrics with timestamps** (transcribe, then have the user correct them). For each line, write: the key word(s), the meaning, and one visual metaphor (the word rides a crashing curve, wraps around a black hole bending a grid, mirrors itself for an opposite, rolls on a counter for a number, sits on a diagram for a technical idea, extrudes into a 3D corridor for "nowhere to go").+- **Words arrive exactly when sung.** Word-level timing from the transcription (or beat-snap by hand). The hook/chorus word gets the biggest treatment each time it returns, escalating.+- **Two worlds for contrast:** mostly black with one hot accent (orange ~#FF5A1F); a paper-white "technical document" world (mono headers like `APPENDIX C — LEGACY ARCHITECTURES`, ruled lines, diagram boxes with hatching) for verses that are about ideas.+- **Type system:** a heavy grotesk for the sung words (huge, often filling the frame), mono labels and data readouts around them, one italic serif word for soft moments, outlined type for echoes.+- **Effects vocabulary:** words on warped perspective grids, extruded 3D letters, particle bursts, counters and odometers, glitch slices, a single glowing object for the big emotional line.+- HUD corner marks and tiny meta readouts make every frame feel engineered.++## Hebrew and RTL++For Hebrew lyrics: use a strong Hebrew display face (e.g. Heebo Black, Rubik, Secular One, Assistant ExtraBold, Frank Ruhl Libre for the serif moment) from Google Fonts, set `ctx.direction = 'rtl'`, and animate words in reading order right-to-left. Check every frame for correct letter order and final forms.++## Engine++Canvas 2D (WebGL for grids/3D type if wanted) via `scripts/new-canvas-project.sh`. Drive everything from a `LYRICS` array of `{t0, t1, text, key, scene}` and the song's BPM.diff --git a/references/styles/manifesto.md b/references/styles/manifesto.mdnew file mode 100644index 0000000..d7b558c--- /dev/null+++ b/references/styles/manifesto.md@@ -0,0 +1,32 @@+# Style: Manifesto film++A 60-90 s documentary-style statement for a serious idea: a problem told as a short true story, a turn, then the vision as a numbered list, ending on the name. Reference: "Open Alignment", an open-source AI-safety manifesto film (Sep 2026, 84 s, 24 fps).++This is the right format for B2B/AI concepts (it's what a long concept video for an AI product should have been): serious, dense with facts, yet readable on a phone because every frame carries one line.++## Story structure (the part that makes it work)++1. **Cold open with a hard fact** in huge type: "1,200 AI AGENTS / ESCAPED THEIR SANDBOX." "17,600 ACTIONS OVER 4 DAYS." Dated, specific, alarming.+2. **Context, fast:** how we got here (a visual metaphor that returns later: a rider on a horse = steering a powerful thing; "For a while, alignment looked solved." → "Then we scaled RL.").+3. **The gap:** who is doing what, and what's missing ("Frontier labs are building safety for their own models." / "The open ecosystem, where most AI gets fine-tuned...").+4. **Proof it matters:** one concrete story (the hooded attacker, a terminal where closed models refuse and the open one works: "SO WE RAN AN OPEN ONE.").+5. **The turn:** "IT'S TIME TO BUILD" → the name slams in full-frame on the accent color.+6. **The vision as a numbered list** 01-06, one pillar per frame, each with its own image.+7. **Callback:** the opening metaphor returns resolved ("Full speed. Still steered." with the horse, now in the accent color).+8. **End card:** the name + one line ("Let's build it, in the open, together.") + logo.++## Design system++- **Black, off-white paper, and one accent (signal yellow ~#FFD21F).** Alternate black and paper scenes for rhythm; one full-yellow frame for the name reveal and a few pillars.+- **Type:** a heavy grotesk in caps for statements (two lines max, second line in the accent); an **italic serif for narration** ("For a while, alignment looked solved."); mono for labels, dates and meta in the corners (`OPEN ALIGNMENT`, `FORENSICS · JUL 2026`, `OBSERVED 02/04`) and for terminal windows.+- **Imagery = photos turned into drawings:** silhouettes, line-art edge tracings, posterized/halftone figures, a figure filled with glitter-like particles. Made in code from source images (edge detection, threshold, halftone, contour tracing), or drawn directly. The source images can be stock/archival photos the user has rights to, or generated (Nano Banana), but the treatment is always graphic, never a raw photo.+- **Terminal windows and UI cards** as proof, with real-looking commands and colored results.+- Thin corner brackets, a hairline frame, a red vertical rule for alerts.++## Rhythm++~24 shots in 84 s (one every ~3.5 s): slower than a hype reel, because every frame is a sentence to read. Words build line by line; the second line lands in yellow on the beat. A low, tense score that opens up at the turn.++## Engine++Canvas 2D via `scripts/new-canvas-project.sh`. Image treatments (Sobel edges, threshold, ordered-dither halftone, particle fill of a mask) are computed at load time from files in `assets/`; if there are no source images, draw the silhouettes as paths.diff --git a/references/styles/monochrome-launch.md b/references/styles/monochrome-launch.mdnew file mode 100644index 0000000..6d555e2--- /dev/null+++ b/references/styles/monochrome-launch.md@@ -0,0 +1,34 @@+# Style: Monochrome launch film++Stark black-and-white product launch film with liquid-chrome materials and quant-editorial texture. Reference: "Frontier Traders" (Sep 2026): 30 s, 4K, "Opus 5.5 one shotted this whole video in 20 mins".++## Design system++- **Palette: pure #000 and pure #FFF only.** Secondary type in grey (#999). No accent color anywhere, with ONE exception: a single prestige moment where a material carries color (the reference fans out membership cards and one is gold). The restraint is what makes that moment land.+- **Section inversion is the rhythm.** Hard cuts between full-black worlds and full-white worlds, roughly alternating. Black = atmosphere and matter; white = data and proof.+- **Type:** big lowercase grotesque sans. Two-word lines split across the frame ("across ... solana", "get rewarded ... for what you do", one part white/black, the other grey). Tiny mono captions for secondary lines. Type is always flat on the frame, never in the scene.+- **Black-world matter (the wow):** liquid chrome curtains and ripples, a particle Earth of city lights, halftone/dither photographic silhouettes (a figure emerging from ripple-dither), dot-grid rain, metallic 3D logo renders. All monochrome, all tactile.+- **White-world data (the proof):** multi-series line charts as background texture with one bold hero series, dashed crosshair callouts with a live ticking number ($2,071.79 → $2,077.80), dot-grid blocks, thin rules. Reads like a quant terminal art-directed by a fashion magazine.+- **Icon-scatter storytelling:** small white tiles with product glyphs scattered across a black tile grid ("your activity gets scattered"), then consolidating into order. The motion IS the message; entropy → order is the arc. Same with dash-fields that align into a grid.+- **Photographic inserts** as b/w luxury stock (a car interior at night, a private jet, a Renaissance painting for "Global Community"): 1-2 s each, deadpan prestige, slightly ironic. Model-made or real b/w photography; keep them desaturated to pure mono.+- **3D product objects:** metallic logo, membership cards fanned in tiers. Simple geometry + studio lighting + chrome/foil material; monochrome hides 3D imperfections.++## Structure (30-40 s)++1. Logo tease in matter (chrome, particles) with the category line.+2. The problem told by scatter (icons/dots dispersing) in the black world.+3. Invert to white: the product name, huge.+4. Proof beats in the white world: charts, live numbers, feature names ("Trading Rewards", "VIP tiers"), each 2-3 s.+5. The prestige moment (the one color: gold card, tier fan).+6. Community/scale insert (the painting, the globe).+7. Logo lockup repeated as an end grid.++## Why it works++- Monochrome + chrome flatters generated and code-drawn assets equally; there is no palette to mismatch.+- The inversion rhythm gives cutting energy without any camera moves.+- Live numbers and charts make an abstract product feel real and expensive.++**Best for:** fintech/crypto/trading launches, premium dev tools, anything that wants "expensive Swiss editorial" without a brand palette. A natural fit when the brand's colors are weak or undecided: mono sidesteps the question.++**Engine:** code-only is fully viable (chrome via layered sine displacement + specular ramps, dither via ordered-dither shader on any grey image, charts and counters native). Model assets optional for the photographic inserts and chrome close-ups.diff --git a/references/styles/painterly-glow.md b/references/styles/painterly-glow.mdnew file mode 100644index 0000000..ae0dc0d--- /dev/null+++ b/references/styles/painterly-glow.md@@ -0,0 +1,20 @@+# Style: Painterly glow music video++A song told in moving oil-paint: every surface is made of swirling directional brushstrokes (like Van Gogh's skies), deep night blues and teals, and one glowing warm figure (orange, ember-lit from inside) moving through symbolic scenes. Reference: a full Suno-style song turned into a clip (Sep 2026, 6:12, 30 fps).++## Design system++- **Brushstroke texture everywhere:** backgrounds are fields of short, thick, curved strokes that follow a flow field (curl noise or a hand-designed vector field). The strokes drift slowly, so even still shots breathe. Skies swirl, water streaks horizontally, grass rises vertically.+- **Palette:** deep navy, teal, violet dusk; **one glowing warm hero color** (orange/amber) for the protagonist, fire, lanterns, light. Glow is additive with soft bloom.+- **The protagonist:** a simple, faceless or near-faceless figure made of rough painterly strokes, lit from within (embers or sparks inside the body). Other people are dark silhouettes with small glowing lights. Emotion through posture and light, not faces.+- **Symbols over literal scenes:** each lyric line becomes an image (a heart carved in a clay oven, a spiral galaxy of sparks, a boat over deep water with a figure sinking, a stage lit by footlights, a ring of flames, a moon face). Dreamlike, not literal.+- **Light as story:** sparks rising, a meteor crossing, lanterns, a single flame. Big moments are the brightest.+- **No or minimal text.** Lyrics can appear sparingly as painted words, not subtitles, if the user wants them.++## Engine++The watercolor engine (ClaudeAnimationBase, p5.brush) can do painterly strokes; or a canvas/WebGL flow-field brush renderer (thousands of short curved strokes drawn along a vector field, colored by sampling a painted base layer, re-seeded slowly so strokes shimmer). Precompute the stroke field per scene; every frame a pure function of t.++## Fits++Emotional songs, ballads, anthems, spiritual or reflective lyrics. For upbeat comedic songs prefer watercolor character or kinetic lyric.diff --git a/references/styles/paper-cutout.md b/references/styles/paper-cutout.mdnew file mode 100644index 0000000..9957fac--- /dev/null+++ b/references/styles/paper-cutout.md@@ -0,0 +1,52 @@+# Style: Paper cut-out++Flat cut- and torn-paper layers stacked like a collage on an animator's table, with REAL drop shadows between the layers. The shadows are the style: every piece floats a few millimeters above the piece below it, and the soft offset shadow underneath is what sells the physicality. Evidence: an Opus 5.5 flat-layered short ("Claude Opus 5.5 has the best visual design of any model I have tested so far"), a paper-collage reel, and an MIT-licensed open-source paper-animation engine, which proves the whole grammar can be driven deterministically in code: torn edges that boil, fiber texture, drop shadows, rim light, spring-driven rigs, fixed timestep + seeded randomness.++## Why this style exists in our gallery++Same bet as crayon storybook, different physics: **the medium's limits are the charm**. Paper pieces cannot deform, so nothing can go off-model; a character is a stack of stiff shapes pinned at joints, and jerky hinge motion reads as craft, not error. Where crayon wins on childlike warmth, paper cut-out wins on tactility and depth: it looks handmade AND dimensional, and it photographs beautifully as stills (every frame is a collage you could frame). Strong pick for storybook narratives, folk tales, indie-craft product films, and anything where "someone made this with scissors" is the emotional register.++## Design system++- **Ground:** a paper world, edge to edge. The backdrop is itself a sheet (kraft, construction, or watercolor-washed paper), never a flat digital color. Scene depth = 4-8 stacked layers, back to front.+- **Pieces:** every element is one filled path of "paper". Two edge families:+ - **Scissor cut:** clean-ish outline with slight wobble and occasional straight over-cuts at corners, like real scissor strokes.+ - **Torn:** wild ragged perimeter with a pale fiber fringe (the white inner core of the paper exposed along the tear). Use tears for organic/violent things: waves, clouds, smoke, fur, storms.+- **Shadows:** one global light direction for the whole scene. Each layer casts a soft drop shadow onto the layer below, offset along the light direction, with offset and blur growing with the layer's height in the stack. Shadows are multiplied, never pure black. This is non-negotiable; without the shadows it's just flat vector art.+- **Texture:** every piece carries subtle paper grain (fiber noise, slight tone variation across the piece); big washed sheets may show watercolor blotching. Matte only, no gloss, no gradients that read as airbrush.+- **Palette:** construction-paper box: brick red, marigold, teal, leaf green, kraft brown, cream, dusty navy, plus one bright accent per film. Colors are flat per piece; variation comes from texture and shadow, not shading.+- **Characters:** built like the reference's box-bots: a few stiff shapes (body sheet, head sheet, limb strips, dot eyes as tiny punched circles). Emotion via tilt, hop, eye size, and piece spacing. No faces drawn ON pieces beyond simple punched/cut features.+- **Type:** cut-letter captions (each word a small paper strip with its own shadow) or a caption bar that is itself a paper strip laid across the bottom.++## Motion grammar++- **Hinge-and-pivot only.** Limbs are pinned like brads/puppet joints; all motion is rotation around pins plus whole-piece slides and lifts. NEVER deform, bend, squash, or morph a piece. A wave "rolls" by rotating and sliding its strips against each other, not by changing shape.+- **The lift:** for emphasis, a piece rises off the table: shadow offset and blur grow, then snap back on landing. This is the style's squash-and-stretch substitute.+- **Boil:** re-seed the edge jitter of torn pieces at 6-8 fps steps so tears shimmer like stop-motion re-placement; scissor-cut pieces stay stable.+- **Replacement animation:** mouth/eye/hand states are swapped whole pieces (stop-motion logic), not tweens.+- **Camera:** mostly locked, tabletop-flat. Slow push-ins allowed; parallax between layers on pans sells the stack depth.++## Variants++- **Lightbox glow:** the same layered paper lit from BEHIND on a lightbox: layers become translucent silhouettes, deeper stacks = darker, thin single layers glow warm; light bleeds through tear fringes. Night scenes, dream scenes, shadow-theater tales.+- **Pop-up book:** scenes fold up from an open book spread; pieces rotate up around horizontal fold lines (still hinge motion, hinges just lie flat), scene changes = page turns. Great for chaptered stories and travel/history explainers.++## Engine notes++Each element = one filled path plus its paper treatment. Concretely:++1. **Edge roughness:** resample the perimeter to even arc-length, then displace each point along its normal with seeded value noise. Scissor cut: low amplitude (1-2 px at 720p), low frequency, plus rare corner over-shoots. Torn: high amplitude (4-10 px), higher frequency, and draw a second slightly-inset copy of the ragged path in near-white at low alpha FIRST, peeking past the colored path, as the fiber fringe.+2. **Per-layer drop shadow:** before drawing a piece, draw its path again in translucent dark (multiply, ~0.2-0.35 alpha, warm-neutral not black), offset by `lightDir * (base + depth * step)` and blurred more with depth (`ctx.filter = 'blur(Npx)'` or multi-pass offsets). One global `lightDir` per scene. Pieces on the same layer share one shadow pass so overlapping strips don't double-darken.+3. **Paper texture per piece:** clip to the piece's path and overlay (a) fine seeded fiber noise at 2-4% alpha, (b) a very low-frequency tone variation so the sheet isn't uniform, (c) optionally a few long faint fiber streaks along one axis. Pre-render one noise tile per paper color and reuse.+4. **Rigs:** a character is a tree of pieces with pivot points; animate ONLY pivot angles, root position, and lift height. Spring the angles toward targets (lag + follow-through, Papermotion-style: intents drive springs, not keyframes) with a fixed timestep and seeded randomness so renders are deterministic.+5. **Lightbox variant:** switch compositing to dark ground + additive/translucent pieces: each piece drawn at alpha by thickness, stack alpha accumulates to silhouette, tear fringes get a warm glow rim instead of a white fringe, drop shadows off (light comes from behind).++## Story grammar++1. Establish the table: open on the stacked world, let a piece drop or slide into place so the viewer learns "this is paper" in the first two seconds.+2. Danger = torn paper. Calm things are scissor-cut; the storm/monster/night is torn, layered, and looming.+3. The hero is the cleanest cut in the frame; keep it the brightest, simplest piece so it reads in under a second at phone size.+4. One "lift" beat per scene maximum; save the big lift (piece pulled fully off the table) for the climax.+5. Endings love the pop-up close: the scene folds flat, or a final small piece is placed by an implied hand (shadow only, never show a real hand).++**Best for:** folk tales and storybook narratives, craft/indie product films, kids' and family subjects, song visualizers with chaptered scenes, anything tactile or handmade. Prefer it over crayon when you want depth and shadow drama; prefer crayon when you want line-drawn looseness.diff --git a/references/styles/pencil-test.md b/references/styles/pencil-test.mdnew file mode 100644index 0000000..7de6cea--- /dev/null+++ b/references/styles/pencil-test.md@@ -0,0 +1,52 @@+# Style: Animator's pencil test++A classical-animation pencil test played back as the film: rough drawings on aged animation-bond paper, three coloured pencils each with one job, a production slate and a frame counter, stepped timing, and then the moment the animation stops to explain itself. Reference: a hand-drawn-style animation coded in canvas (Sep 2026): a character runs, jumps a log, freezes, and the frame becomes an animator's dissection sheet (onion skins, arc, spacing chart, principle labels) until an APPROVED stamp slams in.++## Why this style exists in our gallery++Every animation principle the viewer has ever half-heard of (anticipation, squash and stretch, arcs, spacing) is made visible, in the tools animators actually used to find them. The film gets to perform AND explain itself in one breath: first the thing moves, then time stops and the page shows you why it moved well. That turn is the hook. It also belongs to the "imperfection is the aesthetic" family that crayon storybook proved: a forgiving, boiling pencil line cannot look off-model, so a code-rigged character with small joint errors reads as a rough, not a bug.++**It doubles as the on-screen form of our character-department motion tests (SKILL.md step 3b).** When we show the user a walk cycle, sit/stand or reach-and-grip test for approval, render it in this style: red clean pass over blue construction, onion skins on, frame counter on. The user reads it as a real animation test, the forgiving pencil hides rig imperfections that would distract in a finished render, and the dissection devices (arc, spacing chart) make the approval conversation concrete ("the arc flattens at 119").++## Design system++- **Ground:** aged animation-bond paper, **#EDE6D8**, with a warm brown vignette at the edges (multiply), a slightly lighter centre (as if lit from a light table), a seeded grain tile and sparse fibres. The paper is a flat sheet: no desk, no peg bar needed, no page turns.+- **Three pencils, one job each (never swap jobs):**+ - **Red / carmine #C23A4F:** the CLEAN current drawing (the character or protagonist in its final line) and the scene title. The eye always lands on red.+ - **Light-blue non-photo #8FB0D0:** construction (centre lines, action line, bounding ellipses, tilt axes), roughs under the clean line, onion skins of previous/next drawings, dashed arcs, and the whole breakdown during the dissection. Loose, overshooting, allowed to be messy.+ - **Graphite grey (~#55575C):** props, background layout (horizon, trees, water, the log), the slate line, labels, circled frame numbers, the spacing chart. Thin and light; background props never get more contrast than the red drawing.+- **Line:** pencil, not ink. Width varies with pressure, ends taper, strokes overshoot corners, the clean line occasionally doubles. Graphite tooth: every pencil layer is masked by a per-pixel grain so the stroke breaks up like graphite on bond.+- **Production slate (top-left, every frame):** graphite hand-lettering `PROD. 2026-A SEQ. 3 SC. 12`, and under it the scene title in red capitals, underlined with one red pencil stroke. The title names the action, e.g. `RUN + JUMP (LOG)`.+- **Frame counter (bottom-right, every frame):** a handwritten graphite frame number, and under it the timing: `TWOS` or `ONES` (or `ON TWOS` / `ON ONES`). Key frames get the number circled by hand.+- **Lettering:** single-stroke capitals that write on stroke by stroke, slightly uneven baseline and size; no typeset font in frame. The slate's first line is typewriter-ish only by being more regular.+- **The stamp:** an angled (5-10 degrees) purple rubber stamp `APPROVED` with a small line under it (`PENCIL TEST · SC. 12 · <date>`), double-ruled border, ink texture with dropouts and uneven density. It is the only saturated non-pencil colour in the film and appears exactly once.+- **Timing:** STEPPED, always. Cycles on twos (a new drawing every 2 frames at 24 fps), fast action on ones; holds are real holds. Never smooth-interpolate a drawing between poses; the stutter is the style. The counter's TWOS/ONES label changes when the timing does.+- **Format:** square 1:1 is the reference; 16:9 works. 15-40 s. Reads fully muted.++## NOT its neighbour++Nearest style: **hand-drawn sketchbook** (references/styles/sketchbook.md). Sketchbook is about a DRAWING being made: marks arrive in a hand's order, tone is built by hatching, margin notes carry a narrator's thoughts, one sheet slowly fills. This style is about MOTION being made: the drawings are already finished roughs that FLIP, the paper is a production document (slate, counter, stamp), colour is functional (red clean / blue construction / graphite props), and the content is timing and physics, not an idea. If the brief is "watch me think", send it to sketchbook; if it is "watch this move, then see why it works", it belongs here.++## Story grammar (from the reference)++1. **Slate first.** Empty paper, the slate letters itself in, the title writes on in red. Frame counter starts at 1.+2. **Perform.** The protagonist is drawn in (blue construction, then red clean), then performs its action on twos with the background props flipping by in graphite. The counter ticks in steps; key frames get circled as they pass.+3. **The fast bit on ones.** The climactic action (the jump) switches the counter to ONES.+4. **Freeze and dissect.** The action stops mid-air or just after. The red drawing fades to blue; blue onion skins of the key poses appear across the frame; a dashed arc (with small cross-ticks) traces the path; circled frame numbers drop under each key; a spacing chart (a ruler with uneven ticks: close at the ends = ease in/out) writes on under the slate with its caption, e.g. `SPACING · ANTIC → LAND · ON ONES`.+5. **Principle labels write on** with curved graphite arrows to the pose that proves them: ANTICIPATION, SQUASH, STRETCH, ARC, FOLLOW-THROUGH (one at a time, reading order).+6. **One replay in red** over the blue dissection (optional): the clean drawing re-performs the action through its own onion skins.+7. **Punchline:** the purple APPROVED stamp slams in (scale 1.3 to 1 in 3-4 frames, a 1-frame overshoot, a tiny paper shake). Hold. End.++## Engine notes++- **Marks as data, draw-on replay.** Every mark = centreline points + width profile (taper in/out) + pencil (red/blue/graphite) + alpha + jitter seed. A drawing is an ordered mark list; the film draws it on by replaying the list with the mark in hand cut partway along its centreline (construction first, then clean line, then details). Cache completed marks per layer.+- **One layer per pencil.** Draw each pencil's marks on its own offscreen canvas, mask it with the graphite-tooth grain (destination-in with a per-pixel alpha tile, 0.45-1.0), then composite onto the paper with multiply in order blue, graphite, red, stamp. Strokes are rendered on a scratch canvas at full opacity and composited at the stroke's alpha, so round-capped tapered segments never leave overlap dots.+- **Pose library keyed by frame number.** The protagonist's drawings are a table `{frame: pose}` (position, tilt, squash/stretch factor, secondary parts like sail/tail/antenna lag). Playback looks up the last key at or before `floor(t*24 / step) * step` where step is 2 (twos) or 1 (ones). The same table feeds the onion skins, the circled numbers, the dashed arc and the spacing chart, so the dissection is guaranteed to match what was performed. This is also exactly how the character-department motion tests (step 3b) should be stored.+- **Onion skins:** the same pose drawings in blue at 25-40% alpha (older = fainter), drawn loosely with their construction lines; never in red.+- **Boil re-seeded per DRAWING, not per output frame.** The jitter seed is a function of the pose's frame number, so a drawing held on twos (or in a hold) stays still, and a new drawing boils because it is a new drawing. Background props boil on a slow cycle (every 4-6 drawings) or not at all.+- **Dashed arc:** a smooth curve through a chosen point on each key pose (the head, the sail peak), drawn as short blue dashes with small perpendicular ticks at each key.+- **Spacing chart:** a graphite ruler with a base line and ticks placed at the actual normalized positions of the keys along the path (from the pose table), circled numbers above the ones that matter.+- **Lettering writes on:** single-stroke glyph table (capitals, digits, `. - + ( ) · → '`), each glyph a list of polylines in a unit box, jittered per glyph (baseline, size, a degree of rotation). Draw-on order is stroke order; ~2-3 frames per glyph.+- **Stamp slam:** stamp drawn to its own canvas (double-ruled rounded border, big letters with heavy strokes, small line), rotated 5-10 degrees, then masked with a coarse blotchy noise (dropouts where the rubber missed) plus the fine tooth; composite multiply. Animate scale 1.3 → 0.97 → 1.0 over 4 frames with a 1-2 px paper jolt.++**Best for:** animation and motion explainers (the twelve principles, "how a jump works"), character-department approval tests, sports technique breakdowns (a golf swing, a penalty kick dissected), physics of motion, "behind the scenes of how we animated X", and any story that benefits from performing first and explaining second. Prefer sketchbook when the subject is an idea rather than a movement; prefer crayon storybook when characters need colour warmth for a long story.diff --git a/references/styles/pixel-art.md b/references/styles/pixel-art.mdnew file mode 100644index 0000000..b315263--- /dev/null+++ b/references/styles/pixel-art.md@@ -0,0 +1,50 @@+# Style: Pixel art film++Chunky 16-bit-era pixel cinema: a hard pixel grid, small hand-set palettes, ordered dithering for every gradient, sprite characters that snap between poses. References: a pixel film that spread widely, "Pokémon Claude Red", and IN-HOUSE: our own 60 s one-prompt pixel film (216x216 logical canvas, 5x blocks to 1080; source in film.html). The engine notes below are lifted from that working film, not theory.++## Why this style exists in our gallery++Pixel art is the second "imperfection is the aesthetic" bet after crayon: the grid forgives everything the code can't do. A character is 20 pixels tall, so anatomy is impossible and therefore never wrong; emotion is one eye pixel and a lean. It reads instantly as a deliberate medium (people name it in one frame), it compresses beautifully for feed video, and it carries built-in nostalgia for exactly the X/LinkedIn audience. The one law: the grid must be HARD. A single anti-aliased edge, blurred upscale, or sub-pixel slide breaks the spell and the whole frame reads as "cheap filter" instead of "crafted game".++## Design system++- **Grid:** one fixed logical resolution for the whole film — 320x180 for 16:9 (or 216x216 square like the in-house film), upscaled by an integer factor (4x → 1280x720) with nearest-neighbor. Every mark is a whole logical pixel. Nothing ever lands on a half pixel.+- **Palette:** small and owned per scene: 8-16 colors, built as ramps (4-7 steps from shadow to light per material), declared as a table at the top of the file. Hue-shift the ramps (shadows lean blue/purple, lights lean warm), never just darken. A scene change is first a palette change.+- **Gradients = ordered dithering:** skies, glows, water depth, vignettes — all Bayer-dithered between adjacent ramp steps. No smooth gradients anywhere, no alpha soup. A dawn sky is 5-8 dithered bands, and the dither checker itself is part of the look.+- **Characters:** sprites, 16-32 px tall, designed as pixel maps (string grids) with a palette key, not drawn with math curves. Silhouette first: the character must read as a black shape. Emotion via 1-2 px changes (eye, brow tilt, lean) — see the in-house film's ticket character, which acts a whole film with an outline, one eye and posture.+- **Motion:** animation on ticks. Sprites snap between 2-4 discrete frames (bob = 2 frames, walk = 4) at 6-12 fps steps while the world can pan at full fps. Positions are rounded to the grid every frame. NEVER tween a sprite between poses and never let it slide sub-pixel — pixel characters snap, that snap is the charm.+- **Depth:** parallax layers (far sky / mid silhouettes / playfield / near foreground), each scrolling at its own speed, each with its own slice of the palette (far = fewer, desaturated colors). 3-4 layers reads as a world.+- **Light:** light is palette, not glow. A lamp = the nearby pixels promoted 1-2 ramp steps + a dithered halo. Sparkle = single bright pixels blinking on ticks.+- **CRT grade (optional, OFF by default):** subtle scanlines + slight bloom, applied after upscale, only if the film's fiction is "footage from an old machine". Ticket-film shipped without it and looked crafted, not retro-decorated; random scanlines are the #1 tell of generic retro.+- **Type:** your own bitmap font (5x7-ish glyphs as bitmask rows, see engine notes), drawn on the logical grid and scaled with the frame. Never a vector font over pixel art.++## Variants worth naming when pitching++- **Lofi loop:** one seamless ambient scene (rainy window, night desk), tiny palette, 2-4 s perfect loop; the lo-fi-girl economy. Lowest effort, high mood.+- **16-bit RPG:** top-down or side-view adventure grammar — dialog boxes, map transitions, battle screens; great for "X as a video game" explainers (Pokémon Claude Red energy).+- **HD-2D:** pixel sprites + modern lighting (soft shadows, depth-of-field on the far layer, particle light) — the Octopath look. The sprites stay hard-grid; only light gets to be soft, and dithered where possible.+- **Demoscene:** the effects themselves are the star — plasma, rotozoom, starfields, sine-scrolling text — a flex reel for "drawn by code" posts.++## Story grammar (from the in-house pixel film, our proof)++1. Side-scroll as spine: the camera travels one continuous world; rooms/chapters are met left to right, so the film feels like a journey, not cuts.+2. Cut on the beat: lock scene changes to bar lines (in-house film: 120 BPM, one bar = 2 s) so music drops in later without editing.+3. Scale beats: the tiny sprite against an enormous machine/wave/door — smallness is the emotion pixel art does best.+4. Save camera moves: mostly steady scroll, then one pull-back and one push-in that count.+5. Loop the ending to the opening frame when possible; feed video rewards seamless loops.++## Engine notes++- **Canvas pair:** an offscreen logical canvas (`lo.width=320, lo.height=180`), draw EVERYTHING there in whole pixels, then blit: `G.imageSmoothingEnabled=false; G.drawImage(lo,0,0,1280,720)`. Set `image-rendering: pixelated` on the visible canvas as CSS backup. Re-assert `imageSmoothingEnabled` every blit (some contexts reset it on resize).+- **Camera variant (in-house film):** for zooms, draw in world units through a snapped camera: `sx=x=>(x-CX)*Z+HW`, and every rect rounds BOTH corners to the logical grid (`Math.round(sx(x))..Math.round(sx(x+w))`, min 1 px). Zoom Z changes apparent pixel size but everything stays on-grid — this is how you get camera moves without sub-pixel mush.+- **Palette tables:** named ramps as consts, e.g. the in-house film's brass `B0 #24160a → B6 #fff1c8` and navy `N0 #060916 → N6 #3f5596`, plus per-character 5-key palettes `{o,b,s,d,i}` (outline, base, shade, dark, ink) so a character re-lights by swapping the table, and a `mixHex`-based `palDim(p,k)` (quantize k, cache results) for distance/dusk dimming.+- **Bayer thresholds:** `B4=[[0,8,2,10],[12,4,14,6],[3,11,1,9],[15,7,13,5]]`, threshold `(B4[y&3][x&3]+0.5)/16`; the 8x8 matrix (recursive: `B8[y][x]=4*B4[y&3][x&3]+B4[y>>2&3][x>>2&3]`, /64) for wider, calmer bands like big skies. Per pixel of a gradient: compute float ramp position `f`, `i=floor(f)`, color = `ramp[f - i > bayer(x,y) ? i+1 : i]`. Index by SCREEN-logical x,y so the checker stays still while things move behind it (or by world coords if the dither should travel with a surface — pick one per layer, deliberately).+- **Per-scene palettes:** each scene owns its ramps; a mood shift = swap the table, ideally on a bar line. Don't blend two scenes' palettes — hard-cut or dither-wipe between them.+- **Sprites:** string-grid maps, one char per pixel keyed to the palette; a draw function walks the grid with `fillRect(x+i, y+j, 1, 1)`. Mirror by iterating columns backwards for facing. Cache `fillStyle` (only set when the color changes — the in-house film's `fs(k)`) or the frame gets slow.+- **Ticks not tweens:** `frame = floor(t*fps_anim) % nFrames` with `fps_anim` 6-12 for sprite cycles; world motion may use full-fps floats but is rounded to ints at draw time. A bob is `y + (tick%2)` and maybe a 1 px nose tilt — two drawn frames, zero interpolation.+- **Bitmap font:** glyphs as arrays of row bitmasks (5 wide: `row & (16>>bit)`), per-char advance table for narrow glyphs, draw at integer scale only (2x, 3x). Keep the FONT and ADV tables beside the draw function.+- **Determinism:** seeded integer hash (the in-house film's `hash(a,b)` imul mixer) for stars, dust, foam, blink timing; every frame a pure function of t (`window.renderFrame(t)`), so export is frame-exact.+- **Cheap ellipse/ring/line:** scanline ellipses (per-row `fillRect`), point-stepped lines of 1 px rects — never `arc()`/`stroke()`, which anti-alias.+- **Crispness audit (mandatory):** zoom into an exported frame; every edge must be a staircase of identical blocks. Blur means smoothing got re-enabled, a shape used canvas curves, or something drew at non-integer coords.++**Best for:** software/process satire and dev-audience stories (proven in-house), "X as a retro game", journeys and scale gags, lofi mood loops, model-launch demos where "every pixel drawn in code" is the flex. Choose it when characters must act a lot on a small budget of pixels, or when the audience should feel the game era in one frame.diff --git a/references/styles/riso-pop.md b/references/styles/riso-pop.mdnew file mode 100644index 0000000..d00cc68--- /dev/null+++ b/references/styles/riso-pop.md@@ -0,0 +1,59 @@+# Style: Riso pop++Printed-matter pop satire: a three-ink risograph world on cream stock, flat mid-century figures, one meme gag per scene, and a smiley mascot walking through all of it. Reference: "You're Absolutely Right!" (Sep 2026): 3:57 music video, song by Suno, "Creative Director/Editor: Opus 5.5".++## Why this style exists in our gallery++It is the satire slot. Nothing else in the gallery can be a joke about the internet and look like an object at the same time. The limited-ink print makes cheap code shapes look designed: a circle becomes a printed smiley, a rectangle becomes a silkscreened vending machine. Its neighbours: **monochrome launch** also uses halftone, but in black and white for serious product energy. **Crayon storybook** is a child's hand. Riso pop is a printed poster with a sense of humour, and the colour comes only from overprinting three inks.++## Design system++- **Inks (the whole palette).** Only these inks. Every other colour comes from overprints.+ - Yellow `#F4C51A`+ - Fluorescent pink `#F0508C`+ - Blue `#2160A8`+ - Paper (the fourth "colour", bare stock): cream `#E6DECB`+ - Overprints you get free by multiplying: pink over yellow = red-orange `#E63E0E`; blue over yellow = bottle green `#1F4A11` (the smiley's eyes and mouth in the reference are exactly this); pink over blue = navy/violet `#1F1E5C`; all three = near-black. Never add a fourth ink "just for the shadows". If you need dark, overprint.+- **Separations.** Paint every shape as coverage (0..1) on one plate per ink, not as an RGB colour. Where an object sits in front, it knocks out the other plates (value 0). Paper-white highlights, foam and captions are knockouts, never white paint. Registration marks and fine furniture print in all three inks on purpose, so the misregistration shows as colour fringes.+- **Halftone, one screen per ink** (recipe informed by anidoodle, Apache-2.0):+ - An AM dot screen per plate at its own angle, 30° apart so they rosette instead of moiré: pink 15°, blue 45°, yellow 75°. Pitch about 9-10 px at 1280 wide (the reference reads about 16 px at 1920).+ - Spot function `t = (cos 2πu + cos 2πv)/4 + 0.5`, ink where `t > 1 - c`. This gives round dots in the highlights, a checkerboard at 50 % and round or star-shaped paper holes in the shadows, exactly like the reference's smiley shading.+ - Dot gain in the midtones: `c' = c + 0.5·c·(1-c)` (about +25 % at 50 %). Coverage under about 4 % drops out to bare paper. Coverage near 100 % prints solid.+ - Ragged dot edges: add fibre noise (±0.08) to `t` before thresholding. Antialias over about 0.09 of `t`.+ - Composite by multiply: `out = paper × Π(1 − a·(1 − ink))` per channel.+ - Misregistration: offset each plate 1-2 px in its own direction (e.g. pink (2,−1), blue (−1,2), yellow (0,0)). This makes the pink lip on paper dots, the green line where yellow slips onto blue, and the paper gaps between shapes. Keep it small. It should read as print, not as a glitch.+ - Solids are allowed and common: suits, ties, floors and sign boards are flat 100 % ink. The screen is for gradients, glows and shading.+- **Ink laydown.** Riso ink is never even. Multiply each ink's alpha by a soft mottle (0.86-1.0, noise cell about 60 px) and a fine speckle with starved specks where the drum skipped.+- **Paper.** Cream stock with visible tooth: blotchy low-frequency tone (±3.5 %), mid grain, fine fibre and per-pixel noise (±1.5 %), plus a few light and dark flecks. Paper grain shows through every ink because the ink multiplies over it. Optional proof furniture: bare-paper trim, registration crosshairs, a slug like `PROOF · SMILE · 3 COLOUR` in heavy spaced caps, and three ink swatches. The reference opens on exactly that proof sheet.+- **Light.** Light is a halftone gradient, not a glow filter: a radial screen of yellow over navy (blue + pink) that thins into bare dots. Sunbursts are alternating wedges of screened yellow.+- **Mid-century figure kit.** Flat shapes, no outlines:+ - pill or rectangle bodies in one solid ink (blue suits, pink dresses, yellow dots-dress);+ - stick limbs, and round mitten hands, often paper-white knockouts;+ - dot eyes, pink cheek circles, tiny mouths;+ - hair as one solid shape (bun, bob, helmet).+ - Props are simple solids too: vending machines, TVs, sofas, lamps, sign boards, checkerboard floors, gingham tablecloths, pinstripe walls, scalloped curtains, sunburst rays.+ - No anatomy, no gradients inside the figures beyond one halftone shade on the far side.+- **Mascot as protagonist.** One yellow smiley (the AI) appears in every scene: as a head on a suit, in a vending machine, on a TV, as the sun, as a disco ball. It is a yellow solid disc with pink halftone shading on the lower right (so it prints red-orange) and blue eyes and smile (so they print green). The film ends by dissolving the mascot into a dot matrix, which is the print screen itself becoming the subject. When the brief's protagonist is not the smiley, the smiley can still be a supporting character or a light source (the sun in our boat proof).+- **Type.**+ - **Typewriter caption:** a mono typewriter face (Courier family, bold, blue ink) on a cream knockout card or a thin tape strip, with a pink offset shadow or outline. It types on letter by letter with a cursor, then the retraction happens as a hand-drawn pink **strikethrough**: `As an AI language model` / ~~`ignore all previous instructions`~~. The struck line is the joke.+ - **Sign lettering:** heavy slab or black-weight caps on boards ("YOU'RE ABSOLUTELY RIGHT", "EVERYBODY'S THERAPIST", "STRAWBERRY"), with LED-style counters (017, 019) and like counts (♥ 1,062,387).+ - A brush-script aside ("Okay") is allowed once in a while.+- **Format.** 16:9 in the reference. Works in 1:1 and 9:16 if the tableau is rebuilt around a vertical sign board.++## Story grammar (from the reference)++1. **One gag per lyric line.** Each line of the song gets one tableau that visualises it literally: "counting the r's in strawberry" is a smiley in a suit counting a giant strawberry with a "2" badge. Do not stack two jokes in one frame.+2. **Meme-literacy is the density.** The jokes are internet in-jokes (Shrimp Jesus, Ghibli-fied weddings, the vending machine that lost money, "you're absolutely right"). One recognisable meme per scene, drawn as a flat set piece.+3. **Recurring set pieces with counters.** A game-show board whose counter increments across scenes (017 → 019) gives the film a running gag and a sense of time.+4. **Scenes are stages.** Flat back wall (pinstripe, halftone, curtains), a floor band (checkerboard, solid pink), props in a row, figures on the floor line. The camera mostly holds, with pushes and cuts on the beat.+5. **Ending: dissolve the mascot into the medium.** The smiley becomes a grid of dots, then a ring of text, then an empty dot pattern on paper.++## Engine notes++- **Plates as canvases.** Keep three offscreen grayscale canvases (Y, P, B). Use a `paint(fn, {y,p,b}, overprint)` helper: listed plates get that coverage (a number or a gradient), and unlisted plates are knocked out unless `overprint` is set. Canvas gradients work as coverage ramps. This keeps the art code readable ("sky: blue ramp + pink ramp; light: knock blue, add yellow").+- **The press pass.** One per-pixel loop per frame: read the three plates, sample each at its misregistration offset, screen it at its angle with dot gain and fibre noise, apply mottle, multiply onto paper, then add grain. About 1280×720×3 cosines, fine in JS at preview scale. For a film, render at 1080p and cache static plates.+- **Motion grammar.** The dot screens are fixed to the paper and never move with the objects. Objects move through the screen, so dots shimmer as shading slides across them. Misregistration can jitter by ±1 px on 2s or 3s for a live-press feel, and paper grain stays fixed. Captions type on at typing speed, and the strikethrough draws left to right in about 6 frames.+- **Phone check.** At 360 px the dots average back into flat colour. The composition must read from the solids and knockouts alone, so keep the hero a paper knockout or a solid ink against a screened ground.+- **Boat proof:** `assets/previews-src/riso/boat.html` (sunrise smiley + sunburst for A; navy overprint storm, halftone-banded curling wave with paper-knockout claw foam for B; typewriter strikethrough gags on both).++**Best for:** satire, music videos about internet culture, meme compilations, AI commentary ("you're absolutely right", hallucinations, sycophancy), culture-war-lite explainers, zine-style launch teasers. Weak for sincere or premium brand work: the medium itself is winking.diff --git a/references/styles/sketchbook.md b/references/styles/sketchbook.mdnew file mode 100644index 0000000..440e4de--- /dev/null+++ b/references/styles/sketchbook.md@@ -0,0 +1,52 @@+# Style: Hand-drawn sketchbook++Line-first monochrome intimacy: pen, pencil and charcoal lines that DRAW THEMSELVES on paper grain, hatching and cross-hatching for tone, handwritten margin notes, and at most one pale accent wash per scene. Evidence for the category: "What do you love?" (Sep 2026), 28 s, 2160x2160, 24 fps. Honest note on the reference: that video is warm cut-paper/gouache with color (its look belongs to a paper-cut-out style, not this one) — what it proves for THIS style is the pull of hand-made-on-paper intimacy, marks arriving in a hand's order, and its best device, the handwritten note on lined paper that writes itself and carries the story. This style takes that intimacy and strips it to line and tone.++## Why this style exists in our gallery++Crayon storybook won by making imperfection the aesthetic through waxy COLOR scribble fills. This is the other half of that bet: **line and tone only**. No fills to go off-model, no color to manage — just a pen thinking on paper. It reads as a mind at work, which makes it the honest choice for ideas, process, memory and explanation: the viewer watches the drawing being decided, construction lines and all. Where crayon is a child's picture book, this is an adult's notebook. It is also the cheapest style to iterate (one ink, one ground) and the strongest at draw-on reveals, because a line arriving IS the animation.++## Design system++- **Ground:** warm paper white (#F5F1E6 family) with real tooth: a seeded grain tile multiplied over everything at low alpha, plus sparse fiber flecks. The paper is a character; large areas stay bare.+- **Line:** the hand is one of three tools, declared per film and never mixed mid-scene without a story reason:+ - **Pen** (fine ink, #232830-ish): near-constant thin width, darkening where strokes cross, gaps where the hand lifted.+ - **Pencil** (graphite #3A3E45 at ~50% alpha): softer, wider, pressure varies along the stroke; construction lines live here.+ - **Charcoal** (#26241F, soft and wide): side-of-stick drags for tone masses; kneaded-eraser lifts drawn as destination-out streaks at partial alpha, so every lift is streaky and leaves grey residue (charcoal specifics informed by anidoodle, Apache-2.0).+- **Tone:** NEVER a flat fill. Hatching (one direction) for mid tones, cross-hatching (2-3 angles, 25-35 degrees apart) for darks, scribble loops for chaos, side-of-charcoal for atmosphere. Highlights are paper left untouched — protect a bare patch around whatever must stay bright.+- **Accent wash:** at most ONE watery color per scene (pale ochre for morning, grey-indigo for weather...), laid loose past the line with a darker pooled rim and granulation from the grain. Most frames have none; when it appears it means something.+- **Margin notes:** small handwritten words in the page margins — a label, a doubt, a date, an arrow to the thing. Drawn as single-stroke jittered letterforms in the same ink as the drawing (a handwriting font is acceptable; drawn letterforms are better and animate as writing). The notes are the caption track AND the narrator's voice.+- **Construction honesty:** faint pencil scaffolding (boxes, centerlines, horizon ticks) is drawn first and LEFT VISIBLE under the ink. Erasing it is off-style; the thinking stays on the page.+- **Format:** 16:9 or square both work; must read fully muted (the drawing order + margin notes carry it).++## Named variants (declare one per film)++1. **One-line drawing:** a single unbroken contour draws the whole subject without lifting; the line's journey is the film. No hatching, one or two margin words. Best for portraits, love letters, logos.+2. **Whiteboard explainer:** marker-weight pen on white, diagrams + arrows + boxed words, hand-drawn UI and graphs; tone via marker hatch only. The classic "let me draw you the idea" register.+3. **Urban sketch pen-and-wash:** confident ink first, wobbly perspective, then loose accent washes that overshoot the line; location + date handwritten in a corner. Best for places, travel, memory.+4. **Charcoal:** tone-first — side-of-stick masses, then edges cut with the stick's corner, lights LIFTED OUT with the kneaded eraser (streaky, grey residue stays). The most cinematic variant; best for weather, night, grief, drama.++## NOT its neighbour++Nearest style: **crayon storybook**. That style is waxy COLOR scribble fills disobeying a ballpoint line, square kids'-book framing, characters with one big eye. This style has no fills and (almost) no color: tone is built from line density and charcoal, subjects are drawn as a sketcher draws (construction, contour, hatch), and the register is a private notebook, not a picture book. If the brief wants color-crayon warmth and bouncy characters, send it there; if it wants thought, process, place or drama in monochrome, it belongs here.++## Story grammar++1. The page is the world: the film lives on one sheet (or a small number of page-turns), and the camera moves like eyes over a desk.+2. Drawing order is narrative order: what the hand draws first is what the narrator thought of first. Hesitation (a stroke stopping mid-air) and correction (a re-drawn line next to a rejected one) are story beats.+3. Margin notes advance the plot; the drawing illustrates it. The last note is the payoff line.+4. Danger/climax = the page going dark: hatching densifying until only a protected patch of bare paper holds the subject.+5. The accent wash marks the emotional turn — its first appearance is an event.++## Engine notes++- Marks as data: every mark = centreline points + a width profile (taper in/out) + tool + alpha + a jitter seed. The still is the full ordered mark list; the film replays the same list over a cached composite of finished passes, with the mark in hand cut partway along its centreline (mechanic informed by anidoodle, Apache-2.0).+- Draw-on ordered like a real hand: faint construction lines first, then contour, then hatching, then notes. Time per mark proportional to its length plus a constant per pen lift.+- Jitter: perpendicular smooth-noise offset of the centreline, amplitude by tool (pencil > pen); width and alpha modulated along the stroke by a seeded grain so pressure varies; pen darkens ~15% where strokes cross (multiply).+- Hatching: generate parallel strokes across a region at a base angle with per-stroke angle/spacing jitter, clipped to the region; cross-hatch = 2-3 passes at offset angles; density maps to tone.+- Paper grain: one seeded noise tile, composited multiply over the finished frame at low alpha; wash granulation reuses the same tile so pigment settles into the same tooth.+- Boil: re-seed the jitter (not the geometry) on 2s-3s, i.e. at 8-12 fps steps, while position/camera animate at full fps. Cached composites must key on the boil frame or the boil freezes.+- Charcoal lifts: destination-out streak strokes at 0.4-0.7 alpha over the tone mass — never a clean erase; residue is the point.+- Wash: blobby path filled at low alpha in multiply, a darker thin rim stroke along its edge (pooling), edges overshooting the ink line on purpose.++**Best for:** ideas and explainers with a thinking-out-loud voice, personal essays, travel and memory pieces, storyboards-as-the-product, dramatic monochrome story beats, anything where watching the drawing get made IS the content. Prefer crayon storybook when the subject is characters in constant motion who need color warmth.diff --git a/references/styles/teaching-song.md b/references/styles/teaching-song.mdnew file mode 100644index 0000000..f786595--- /dev/null+++ b/references/styles/teaching-song.md@@ -0,0 +1,24 @@+# Style: 3D teaching song++A song that teaches a technical idea, with each lyric line visualized in a 3D world of the subject itself. Reference: "Chasing the Roofline" (Sep 2026, 3:10, 60 fps), a song about CUDA from the book "CUDA for Deep Learning", set inside a GPU chip.++## The use case++Turn a book, a course, a paper or a product into a catchy song (Suno) plus a clip that explains it. The song carries memory; the visuals carry understanding. Great for authors, educators, dev tools, and "explain my product" pieces that people actually rewatch.++1. Write the lyrics with the user from the source material: one concept per line, concrete numbers in the lyrics ("Thirty-two threads in a warp, in line"), a chorus that states the core idea ("Memory's the slope and the math's the line"). Give the user a Suno prompt with the lyrics.+2. Map the song (see music-video.md) at word level.+3. Storyboard: each line = one visual demonstration of exactly that concept.++## Design system++- **One 3D world = the subject itself** (for a GPU: the chip die, SMs as blocks, memory lanes, tensor cores as cubes). Dark graphite materials, soft studio light, shallow depth of field, slow camera moves across it.+- **One accent: glowing orange** for the thing being explained (active threads, the data path, the current value). Everything else is neutral grey. A second accent (acid green) only for a contrast concept (the divergent branch).+- **A recurring chart as the story spine:** the roofline plot returns throughout, with "your kernel" as a glowing ball climbing toward the ceiling (0.01 → 0.26 → 0.70 → 0.78 of peak). Progress the viewer can feel.+- **Karaoke lyrics as the caption:** a clean bold sans, top-left, white; **the word being sung lights up orange**, the rest dim. Plus small mono callout labels pinned to 3D objects ("32 threads · 1 warp").+- Big numbers and units appear as 3D digits or counters (1,700 GPU, 8192 × 8192 × 4 B = 268 MB).+- Title and end cards: the song name in heavy type on the chip; the book title in a serif at the end.++## Engine++Three.js (from a CDN, e.g. `https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js`) for the 3D world; a 2D canvas overlay for karaoke and labels. Every frame a pure function of t: camera, animation and highlights driven by the lyric timeline. Serve over http (the scripts do). Keep geometry instanced (thousands of cells as InstancedMesh) for speed.diff --git a/references/styles/title-sequence.md b/references/styles/title-sequence.mdnew file mode 100644index 0000000..fa3a415--- /dev/null+++ b/references/styles/title-sequence.md@@ -0,0 +1,28 @@+# Style: Broadcast title sequence++A beat-locked, typography-led motion reel, like the opening titles of a sports season or a festival. Pure code. Reference: "Motion designers are cooked lol I just made this with Opus 5.5 in Claude Code in just 15 minutes" (Sep 2026): "THE FRONTIER · Season 2026", three AI labs presented as contenders, 26 s, 60 fps, 150 BPM.++## Structure++A title card → one chapter per subject (2-4 subjects, 4-6 s each) → all subjects together → the title again. Great for comparisons, lineups, a product's pillars, a team, a season, a launch with several features.++## Design system++- **One color world per chapter**, hard-cut between them, each with a single accent: e.g. black + neon green, electric blue + white, warm paper cream + orange. The contrast between worlds is the energy.+- **Type is the hero:** a very heavy wide sans (Archivo Black / Druk Wide / Anton style) filling the frame; one italic serif accent per title ("GEMINI *3m*", "FABLE *5.1*"); outlined (stroke-only) versions of the same word scrolling as a marquee behind it.+- **Signature type effects:** split-flap letters flipping into place (20 flips/s, locking on the beat), letter-spaced reveals, glitch slices on cuts, a word stretched vertically in a column for the lineup shot.+- **A HUD frame** that makes it feel engineered: corner brackets, mono meta top-left/right (`THE FRONTIER SEASON 2026`, `03 — FABLE 5.1`), a running timecode + fps bottom-left, `150 BPM ▢■▢▢ BAR 09/16` bottom-right, and a small technical caption under each effect (`SPLIT-FLAP × 5 · 20 FLIPS/S · LOCK ON THE 1/16`).+- **One signature visual per chapter**, tied to the subject: a particle globe around a logo, a warp tunnel, a DNA-like ribbon of dots, a book whose pages turn. Built in code (canvas or WebGL), simple geometry, strong motion.+- **Texture:** fine film grain on everything, subtle vignette on dark worlds, paper texture on the light one.++## Rhythm++Set a BPM (140-160 feels right) and land every cut, flap lock and slam on beats or 1/16ths. Bars of 1.5-1.7 s. The end sequence slows down: the finale holds.++## Engine++Canvas 2D (WebGL for particles/tunnel if needed) via `scripts/new-canvas-project.sh`. Load display fonts from Google Fonts and wait for `document.fonts.ready`. If the user has a music track, measure its BPM first and drive the whole timeline from it.++## Logos and names++Real company or product logos and names belong only to the user's own brands or clearly editorial/fan use; ask before putting third-party marks at the center of a piece.diff --git a/references/styles/watercolor.md b/references/styles/watercolor.mdnew file mode 100644index 0000000..fa697c6--- /dev/null+++ b/references/styles/watercolor.md@@ -0,0 +1,32 @@+# Style: Watercolor character++Hand-painted watercolor and ink, like a picture book that moves. A character acts out a small story; linework "boils" like hand-drawn animation. Reference: the Opus 5.5 music video "I'm Upping My P(doom)" (github.com/JohnHeibel/PDoomVideo).++## Engine: Claude Animation Base (MIT)++```bash+git clone https://github.com/JohnHeibel/ClaudeAnimationBase <project-dir>+cd <project-dir> && git checkout 0ac8bf2b31942376cb6b8c4074715595d512acd2 && npm install # the commit this style was written against+```++Then **read `<project-dir>/ANIMATION_GUIDE.md` in full before drawing anything**. It is excellent and is the real instruction set for this style: the medium (p5.brush `paint()` / `inkLine()`, never plain p5 shapes), no text, something happens in every scene, timing, transitions, the character API (views, 31 emotions, hats, dances, emotes), the engine (`src/config.js` for duration/bpm, scenes in `src/scenes/`), and the review commands.++Render and review with the base's own `render.mjs` (not this skill's scripts):+```bash+node render.mjs --sheet=0.5,1.5,3,4.5 --cols=4 --w=480 --out=out/check/a.jpg # contact sheet+node render.mjs --strip=2.0:2.5 --cols=6 --w=320 --out=out/check/strip.jpg # every frame of a moment+node render.mjs --clip --out=out/video.mp4 [--audio=assets/song.mp3] # final MP4+```++## Adapting it to the user's subject++- The guide ships with a default mascot character. For the user's own video, ask whether to keep it or design their character (a mascot, a stylized version of them, their product as a creature). A new character is painted with the same tools and rules so it belongs.+- Characters are the emotional anchor: faces act (take, squash, emote) instead of snapping between moods.+- Text is off by default. If the user needs words (a product name, a tagline at the end), paint them with `letter()`, one or two words, once.++## Notes from the source author++- Storyboard first, then build. Give broad direction ("cute, fun colors, something happening in every shot, be brave") and let the model invent scenes; it's strong at gags.+- Higher reasoning effort gives more extravagant, detailed scenes. Build this style at the highest effort available.+- Watercolor fills are GPU-heavy. Apple Silicon handles them; budget about 1-2.5 s per frame. Fewer, bigger shapes render faster than thousands of small ones.+- Long films: one chapter file per subagent, a shared guide and storyboard, shared files read-only, each agent checks its own contact sheets.diff --git a/references/timing.md b/references/timing.mdnew file mode 100644index 0000000..70624d3--- /dev/null+++ b/references/timing.md@@ -0,0 +1,29 @@+# Timing: model the viewer++Adapted from the Claude Animation Base guide (JohnHeibel, MIT), which named the failure exactly: generated animation moves at one brisk speed, events pile up, and moments end before anyone understands them. You know what happens because you wrote it. The viewer sees it once, at full speed, for the first time, probably on a phone, possibly muted.++- **Write the reads.** For each shot, list in order what the viewer must understand. Each is a read. Every read needs time to find it, time to understand it, and a moment to register before the next begins. Small, distant, fast or subtle things take longer than big, central, obvious ones.+- **One read at a time.** Two things at once means the viewer gets one. Put a cause and its reaction in sequence.+- **Fast actions, slow meanings.** A motion can be very quick if anticipated; its meaning needs a hold. Rush what doesn't matter, linger on what does. That contrast is rhythm; one constant speed is flat.+- **Lead the eye.** Viewers look at what moves, is bright, big, or being looked at. Get the eye to the right place before an important read.+- **Let the reads set the length.** A shot is as long as its reads need. The last shot too: the payoff needs time to land before the video ends (2-3 s hold).+- **Text on screen:** roughly 0.3 s per word to read plus 0.5 s to register, minimum 1.2 s for anything that must be read. A punchline gets more.+- **The first second decides the scroll.** Frame 0 must already be striking (or deliberately look like a still screenshot that then comes alive).+- **Cut on rhythm.** If there's music, set the tempo and land cuts and impacts on beats; drops on big reveals, silence before a punchline.++## Motion curves: springs, never linear++- **Linear motion = never.** Nothing that moves (position, scale, camera, a mask edge) interpolates linearly; it reads as a PowerPoint slide. Stepped art (pixel, pencil test, crayon boil) steps on purpose, which is not the same thing.+- **Springs by default** (`springs.js`, closed form, safe in any frame order, see pipeline.md). Pick by what is moving:++| Preset | Stiffness/damping | For | Feel |+|---|---|---|---|+| `snappy` / `ui` | 320/30 | buttons, toggles, chips, UI cards, checkmarks | arrives in ~0.4 s, a hair of overshoot |+| `camera` / `container` | 170/26 | camera moves, panels, windows, bento cells | settles clean in ~0.55 s, no bounce |+| `heavy` / `type` / `logo` | 120/24 | hero type, logos, big stamps | ~0.8 s, weight, no overshoot |+| `playful` / `mascot` | 180/12 | mascots, characters, a pop-in with personality | ~20% overshoot, bounces |++- **Retarget, don't restart.** When something changes destination mid-move, add a key to `Spring.to`; one spring per target change, summed, keeps the momentum.+- Size the reads to the settle: a word landing on `heavy` needs its ~0.8 s settle plus the reading time above.++More motion moves (log-space zooms, beat punches, handoffs, floods) are in `motion-kit.md`.diff --git a/references/toolbox.md b/references/toolbox.mdnew file mode 100644index 0000000..16a7aaf--- /dev/null+++ b/references/toolbox.md@@ -0,0 +1,90 @@+# Toolbox: use the best tool for each part, and offer it++The goal is the most mind-blowing result, not "everything drawn by Opus". Opus is the director and the renderer: it writes the plan, the timing, the code, the motion, the type, the compositing and the self-review. It is weak at photoreal images, faces, painterly likeness detail, music and voice. For those, bring in specialist tools.++## Illustrated styles are code-only by nature. Real-looking films are not.++Pitch the route that makes the best film first, with its price, then the best free one (SKILL.md step 3). The table below says where code alone is the best look, not where it is the cheap fallback.++Opus 5.5 is an excellent **illustrator**: watercolor characters, flat and stylized-3D cartoons, typography, diagrams, UI, particles, light, motion. Most of the strongest references used **no images at all** (a P(doom) music video, a kinetic lyric video, a title-sequence reel, a product explainer, a wordless short), and "no images, every frame drawn in code" is part of the wow. What it can't do well is **photorealism**: real photos, real faces, realistic footage.++| Style | Default | When to add a model |+|---|---|---|+| Watercolor character | code-only | only if the user wants a specific real person's likeness beyond a cartoon |+| Clean kinetic explainer | code-only (the mascot can be drawn in code and dithered) | a photo-based mascot or real product photos |+| Dark premium explainer | code-only | rarely |+| Broadcast title sequence | code-only | real logos or photos of people in the lineup |+| Kinetic lyric video | code-only | never needed |+| Cinematic animated short | code-only | rarely |+| Image-to-game cinematic | **model images** (that's the premise) | always |+| Editorial HUD film | **model footage** (photoreal is the premise) | always |++Music is different: code can't make it, so Suno is worth offering for most films (or the user brings a track). Sound effects ARE code now: `scripts/sfx.mjs` synthesizes hits, whooshes, UI ticks, risers and impacts deterministically and places them frame-exactly (audio.md); ElevenLabs stays for voice, announcers and organic one-offs.++Understand what the user wants before proposing tools: "a cartoon of my family" is code; "my family, looking like us, in a Pixar-style film" may want model-made character sheets. When unsure, pitch both with their ceilings and let the person choose.++**Offer, never assume.** Not every user has these subscriptions, and credits cost money. At the pitch step, show an **asset plan**: for each asset the film needs, the options (code-only, free route, paid route with a cost estimate), and your recommendation. The user picks. Never spend credits without an explicit yes on the number.++## What each tool is for++| Need | Best tool | Cost notes |+|---|---|---|+| Photoreal or painterly images, character sheets, pose sheets, sets, moodboards, a real person's likeness | **Nano Banana (Pro / 2.5) in the Higgsfield web UI** | Free and unlimited on a Higgsfield plan only in the **web UI** with the **Unlimited** toggle ON. The Higgsfield MCP/API bills ~1 credit per image. If the user is logged in, you can drive the web UI through Chrome (see below). |+| Same, alternative | **GPT image (ChatGPT)** | Covered by the user's ChatGPT subscription. The user pastes your prompt; you read the downloaded result. Strong at text-in-image and UI screens. |+| Moving footage, reference motion, lip-sync to a song | **Seedance 2.5 / Kling / Midjourney video** (via Higgsfield or direct) | Always credits. Read the real price before every render and say it (`references/real-shots.md`). Use for reference motion that code redraws (rotoscoping, see overnight-run.md) or for editorial footage under a code HUD. |+| Music | **Suno** | User generates from your prompt (see audio.md). Ask for full length. |+| Sound effects (hits, whooshes, UI ticks, risers, impacts, chimes) | **`scripts/sfx.mjs`: code-synthesized, free, deterministic** | Default. 10 kinds x variants, placed by exact film frame over the music bed with ducking, a -1 dBTP ceiling and an audibility check (see audio.md). |+| Voice, announcer, organic one-off SFX (animals, crowds, real-world foley) | **ElevenLabs** (or Higgsfield `generate_audio`) | User's subscription or credits. Place on exact hit frames. |+| Upscale, background removal, reframe | Higgsfield tools | Credits; or do keying in code for flat backgrounds (free). |+| Lyrics, word timestamps | **whisper.cpp** local: `whisper-cli -m <model.bin> -f audio.wav -l <lang> -ml 1 -sow` (whisper.cpp with the large-v3-turbo model) | Free. Transcripts of sung lyrics are rough; ask the user for the real lyrics and use the timestamps. |+| Isolate vocals to find exact hits | **demucs** local: `python -m demucs --two-stems=vocals -o sep song.mp3` (demucs in a Python environment) | Free. Then read vocal onsets from the vocals stem's loudness. |+| Tempo | onset autocorrelation (see audio.md) | Free. Lock the beat grid to the vocal onsets. |++(On any machine, check what is installed and offer to install what is missing.)++## Driving the Higgsfield web UI for free images (when the user is logged in)++Chrome MCP on higgsfield.ai/ai/image: pick **Nano Banana Pro** (badged UNLIMITED), toggle **Unlimited** ON in the prompt bar (the button then reads "Unlimited ✦"; never toggle Unlimited on GPT Image 2, it opens a paid upsell). Set long prompts via the Lexical editor state in JS instead of typing (typing 2k chars freezes the tab). Upload references through the uploads panel's file input. Queue 2 at a time (the web UI runs ~4 concurrently and the user may be using it too). Fetch results with the free MCP `show_generations` read and curl them down. Video is not covered by Unlimited.+++## Seedance lip-sync at scale (public production record, Sep 2026)++Proven on 47 clips + 30 continuations, ~86% of sung seconds verified in sync (~$93 at 720p via OpenRouter):++1. **Condition every singing clip on both the plate image and the exact audio window** of the song, and quote the words in the prompt: `@Image1 sings @Audio1. She lip-syncs to @Audio1 exactly, every word in time: "…"`.+2. **The key fact: Seedance copies the reference audio into its own soundtrack, and the mouth follows THAT soundtrack**, which drifts from the real vocal partway through. So sync is measurable, not eyeballable: compare the clip's returned soundtrack against the real vocal (spectrogram/alignment) to find the divergence point.+3. **Cut on the last eighth note before the drift** and cover the rest with a continuation clip starting from that frame. In the final mix, replace all clip audio with the real song.+4. Dedicated lip-sync models (LatentSync class) are the fallback, not the plan.+5. Keep generation inputs **in color**: plates graded to mono come back grey and lose the image-model look; grade in post.++**Characters: stylized in code, realistic from a model.** Lesson from a song clip (Sep 2026): pushing a code-drawn human toward realism (7-head proportions, anatomy, hands, close-ups) looked fine in stills but twisted in motion (necks, hands, legs), and the user said the animation quality failed. Code characters should stay stylized (picture-book proportions, simple joints, emotion through posture, light, silhouette and back views). If the user wants realistic people, offer an image/video model for the character with code for everything else.++## Seek-compatible libraries (and the ones never to use)++film.html renders frames out of order, so any animation library must be driven by t:+- **Anime.js:** create timelines with `autoplay: false`, then `anim.seek(t * 1000)` in `renderFrame`.+- **Theatre.js:** hand-tune camera paths and keyframes in its studio UI, then `sequence.position = t` in `renderFrame` (ship the exported state JSON, not the studio).+- **Our own `springs.js`** for everything else (closed-form, `timing.md`).+- **Never** a real-time-only library (GSAP tickers left running, CSS transitions/animations, physics engines stepped by the clock, Lottie in autoplay): they drift from t and fail the gate's determinism check. Motion ideas that need them get rebuilt as functions of t (`motion-kit.md`).++## Free asset sources++- **Mixkit** (mixkit.co): free music and SFX, no attribution required; check each item's licence line.+- **svgl.app:** clean SVG logos of real brands and tools, for inline icons and "works with" rows (real integrations only; brand marks stay the brand's).+- **3dicons.co:** CC0 3D icon set, several styles and angles; good for explainer cards.++## Deciding code vs. model assets++- Characters that must **move a lot** (dance, fight, act): code-drawn (watercolor engine) or model-made **pose sheets** that code animates. Single stills can only slide.+- **Recognizable real people:** model-made images from their photo (keep kids stylized unless the parent explicitly wants realistic).+- **Type, UI, diagrams, HUDs, charts, counters:** always code. Crisper and perfectly timed.+- **Photoreal footage:** a video model, with a code layer on top for intelligence and timing.+- **A mix is usually best:** model for beauty, code for motion, timing and type.++**Web UI mechanics learned the hard way (Sep 2026):**+- A page reload switches Unlimited back **off**. Re-check the toggle before every Generate.+- Reference images from earlier sessions stay attached. Hover each thumbnail and click its top-right X before generating.+- Reference slots clear after every Generate. Uploads take 5-15 s, and a second upload can replace the first instead of adding one; zoom-check the slots before clicking Generate.+- Never click the slot tile itself: it opens the native file picker (Escape closes it). Use `find` for the file input and upload through it.+- To reuse a finished image as the reference for the next one (burst pairs, a character's identity), open the + panel, go to the Generations tab and click its tile.+- The window size can change mid-session; re-find elements instead of reusing old coordinates.diff --git a/references/vertical.md b/references/vertical.mdnew file mode 100644index 0000000..73ecb94--- /dev/null+++ b/references/vertical.md@@ -0,0 +1,115 @@+# Vertical 9:16 (Reels, TikTok, Shorts): recompose, don't crop++Learned on an app-builder music video (Sep 2026). A center crop of a 16:9 film loses the subject, buries type under the platform UI and puts panels on faces. Rebuild the layout per shot instead; keep the timing identical.++## One timeline, two layouts++- Same `film.html`, same shot list and word timings. The page reads `?portrait=1` and sets `W=1080, H=1920`.+- Every layout number goes through `PV(landscapeValue, verticalValue)`. The landscape value stays exactly as approved, so the vertical can't break the master.+- Textures sized to the frame: grain and halftone canvases get the portrait aspect, or they stretch.+- Render: `W=1080 H=1920 node frames.mjs 1 <times>`, export with `W=1080 H=1920 node export.mjs 24 out.mp4` (export adds `?portrait=1` when H > W).++## Framing photos (stills or footage)++- A 16:9 photo covering 9:16 shows only about a third of its width. Pick the visible third per photo: a focal x in plate units (the subject's center), clamped so the photo still covers the frame.+- Plate coordinates stay in the photo's own space (e.g. 1920x1080 units) with separate x and y scale (generated stills are rarely exactly 16:9). Every tracked box, screen quad and face box maps through the same transform in both layouts.+- To free space under the chin, anchor the zoom at the bottom of the photo: the face rides up and the jacket or table below becomes clean space for type.+- A wide shot with the subject on one side can pan: the first half on the environment (the wall of notes), a cut on the beat to the subject.++## Where things go++- Essentials (type, captions, cards, boards) inside x 56-940, y 250-1480 on 1080x1920. The top bar, the caption and handle block at the bottom, and the button column on the right cover the rest. HUD decoration can live there.+- Never on the main character's face (see the face audit in pipeline.md). Free space in a portrait is above the head or below the chin; put big type there, over a gradient scrim if the photo is busy.+- Two-line slams become one line under the chin when the face fills the frame.+- A blank object in the photo (a card, a sign, a screen) is the best place for a word: "I will." written on the blank card she holds read better than type beside it.+- Wide panels (a counter, a report, a confirmation card) become compact full-width strips above or below the subject, not centered blocks.+- Karaoke strips auto-shrink to fit about 900 px wide.++## Check++- Contact sheet of the vertical at the same times as the landscape one, then larger frames of every shot with type near a face or an edge.+- Face audit in 9:16 (and again in 16:9 if you touched shared code).+- Sample the exported MP4 itself (a frame every 2 s) before delivering.++## A film built round a player (a headline over a wide screen): what the tall layout became++Learned on the short Take One launch film (12 Oct 2026): a headline line over a 16:9 player on paper, twelve small objects in a row inside the player, a 15 s wide ad shown whole, and an ending where the whole screen becomes a video in the player.++- **Draw the player's inside once.** Do not re-lay every number inside the player. Keep the wide film's numbers for everything inside it and wrap that drawing in one transform (`stage()`: translate to the tall player's corner, scale by tall width / wide width, translate back by the wide player's corner). Only what sits outside the player gets tall values.+- **The headline gets a second line, not a smaller size.** One line across a 884 px column forces about 75 px type. Two lines hold 92 px: a long line is split by hand ("a launch / needs a video"), and a numbered item puts its number alone on the upper line, large and in the accent colour, with the name under it. Each line rolls inside its own clip band, the bands share no row (keep about 14 px of ground between them), and a change is out, then in: the old lines leave in 0.09 s and only then do the new ones rise. Two lines rolling at once print on each other for five frames where one band ends and the next begins, and a reviewer stepping through frames sees it.+- **Use the height for the thing the wide film had to keep small.** The row of twelve objects left the player and became a grid of two rows under it, twice the size, with three states (waiting pale, done dark, at work raised). An object that flies from the dark screen onto the paper is drawn twice with two clips: light inside the screen, dark outside it.+- **A wide film inside the film becomes a band across the full width, high in the frame.** It cannot fill a tall frame without cutting its words, but it does not have to stay in the column either: as the room goes dark the player rises and grows from the column (884 px) into a band 1080 x 608 at y 290 to 898, half as large again. High, because the apps' buttons sit on the right from about y 880 down and would cover the band's right end anywhere lower (at full width in the middle of the frame, the last letter of the brand's name sat under them); not above 285, because a feed preview keeps only the middle 4:5. The band rises over the headline, so the headline comes back under it once it has landed, with the progress line between them and the line that made the film under that. When it ends, the next move starts from the band, and the next headline waits until the band has left its place.+- **If the inner film opens inside a small player of its own, crop into that player.** An ad cut from a longer film may start with its picture in a window with a file name and a progress line: in the tall band that is a player inside a player, a 14 px label and two progress lines. Read the rectangle and its easing from the source page, check them against the frames (they matched within 2 px), and draw that rectangle of each source frame across the whole band, computing the crop at the source's frame rate (30 a second), not the film's, or it shivers.+- **"The screen becomes a video in the player" needs a tall player**: the nested picture has the frame's own shape. Use a second rectangle for it; do not squeeze a tall screen into the wide player.+- **A wide clip as a tall opening, without paying for a new one:** lay it in whole (scaled so the subject keeps a margin at both sides), low in the frame; carry its out-of-focus wall on upward as one sampled colour with a gradient over the clip's top 230 px, and its floor or table downward by drawing its last rows out; put the type on the wall. It reads as one tall room. Say what a tall shot of its own would cost.+- **Scenes that are centred (a title, a slate, an end card) stay on the frame's true centre**; scenes built on the column sit 42 px left of it. Nobody sees the shift; the right edge belongs to the apps' buttons.+- **Prove the wide film did not change.** Before the first tall edit, save a checksum of thirty-odd wide frames; after, render them again. Expect one or two text-heavy frames to differ by a few pixels at 1 or 2 levels when frames are rendered in a different order (the browser's own anti-aliasing); render those alone, old page and new page, and they must be identical.++What a fresh reviewer then caught on that tall cut (7 overall on the first try), and what fixed each:+- **The subject of the first shot sat under the apps' buttons and caption.** The safe column is for the product too, not only for type: scale the laid-in shot so the whole subject ends left of x 925 and above y 1470.+- **A word's tail fell on a pale part of the picture.** Deepen the fade where type crosses from the added wall into the clip (alpha about 0.93 through the first 120 px), and keep 46 px between a line and the much larger line under it, or their letters fuse.+- **The added wall was flat and the carried-on floor was streaked.** Lay one soft warm light over wall and clip alike (blend "lighter", after the fade, so no line shows where one becomes the other). Carry a floor on by drawing its last rows into a canvas 24 px wide and laying that back large: a smooth run of its colour instead of stretched streaks.+- **Fifteen seconds of a small window on flat black.** Give the dark a job with words the film already has: the headline stays above the player (turning light as the room turns dark) and the line that made the inner film stands under it.+- **A headline rose in under a screen that was still shrinking over its place.** Start the headline when the moving thing has cleared it (0.36 s into a 0.5 s move), not on the scene's first frame.+- **The text audit failed tall films for text that is 22 px on a phone**: it measured against the frame's height. It now measures on a phone 360 px wide (`scripts/text-audit.mjs`), which gives a wide film the same verdicts as before.++What the second fresh reviewer caught (7 again), and what could and could not be fixed without new pictures:+- **A line on screen said "one line" over a prompt typed on two.** When the tall column forces a wrap, check what the words above it claim. The prompt went back to one line at 50 px in a box as wide as the column.+- **Footage inside the player looked small.** Measure before promising a zoom: `scripts/content-box.py` on each strip. Ten of eleven strips already filled the player's width, so only their height was empty, and a zoom would have cut cards at the player's edge. One strip (a picture with room on both sides) could be drawn a quarter larger. Say this plainly instead of cropping: a wide strip in a wide player inside a tall frame is small by geometry.+- **The nested tall screen was the smallest picture in the film.** A tall frame inside a tall frame, with a headline above and a prompt line under it, is about 400 px wide whatever you do. If the ending depends on it, plan the tall cut's ending at the storyboard, not at the recompose.+- **What holds a restacked tall cut at 7** is the opening and the inner film: both were made wide. The reviewer's route to 8 both times was a first shot made tall from the start (taller, closer, real camera movement). Price that shot at the pitch of the tall version, before the free recompose, so the person chooses knowing the ceiling.+- **Third reviewer, same 7 overall, composition up to 8**: with the ad edge to edge, it caught the brand's last letter under the buttons and the small opening window above. Both are fixed by the two rules above. A restacked tall cut with a wide opening and a wide inner film tops out at 7; say so before starting, with the price of a tall opening shot.++## A teaser Reel cut from wide footage: the three-band wall++Learned on the Take One teaser Reel (12 Oct 2026, 32 s, comment-a-word ask). The footage was all wide: a 15 s ad, strips of the studio at work, a gallery of wide stills.++- **Three wide bands fill a tall frame.** 3 x 608 px plus 24 px of ground between and round them is 1920. Top and bottom are pictures; the middle band is a card that carries every word. Words then never sit on a moving picture, and they are always inside the free zone (x 64 to 940, y 656 to 1264). Text on the card is set as large as the card allows (three lines of about 170 px).+- **Open on ONE picture across the whole frame, then cut to the bands on the first beat.** A fresh reviewer scored the bands-from-frame-0 opening 7: "the proof is two small strips". Find the highest-resolution source of the best shot: a 4K clip gives a sharp 1215 x 2160 tall crop (`crop=1216:2160:X:0,scale=1080:1920`, `minterpolate` to 60 fps). The words go on it from frame 0, under the face.+- **Never show a shot twice.** Count the footage against the seconds before laying it out (nine ad shots were 12.5 s; two bands needed 13 s by second 6.5). When the result runs out, show the making: each strip of the studio with its job's name. That also answered "it never shows the skill working".+- **The ask early, on its own card, then a strip along the card's foot.** Second 6.5, an orange card; the word to type is the strongest contrast on it (dark on a paper plate, not cream on orange); say what they get ("and I'll send you the skill"). A tag laid over the seam covered a picture's title; a strip inside the card covers nothing.+- **Make the ending the answer to a promise.** "Wait for the last thing it made" at second 8.7, "And the last thing it made? The video you're watching right now." at 21. The step back and rewind then pay off something the viewer was told to wait for.+- **When variants flip past, say what stays the same**, on screen ("same scene"), and count them large. A name on the card must match what BOTH pictures show for as long as it is up: the named look in both bands (its two pictures), not one band flipping on.+- **Put the big move on the music's section change** (the rewind starts exactly where the outro begins), and plan the cut from an uncut stretch of the track that ends on its last hit: here Reel 0 = the middle of the first drop, the breakdown fell under the promise, the second drop under the flips, the last hit on the clap.+- **Effects under a loud drop are buried**: the mixer refuses them. Drop them (keys, swishes) instead of raising them over a voice.+- **A strip that holds still for two frames fails the gate** when the card beside it is still too: give every strip a slow creep.+- **For Instagram:** deliver a 30 fps copy (the app plays 30), the first frame as the cover with its words inside the middle 3:4, and tick the AI label when the people look real.+- **What the second review (8 overall, hold 7) still caught on that Reel:** the one picture that tells a story (a score going from 6.8 to 8.6) sat in the bottom band, under the caption: put the picture that matters in the TOP band. The ask vanished during the reveal, when the viewer is most convinced: keep it on screen there too. As the ask landed, the pictures fell from glossy shots to dark panels: let the ask land on the best pictures, even if that means one shot comes a second time in the other band. And once a count has reached its end, the next beat must start at once: the question and its answer were pulled 0.6 s earlier.++## A teaser Reel modelled on Reels that won: the light stage (Take One teaser, take four, 12 Oct 2026)++The first teaser (three bands, cards, a twist at the end) passed two fresh reviews at 7 and 8 and its owner still found it weak:+the still images did not impress, and the hook did not show what the skill had made. What the owner asked for next is now the first step for any Reel:+**look at Reels on the same subject that got a lot of views before anything is planned.** A reviewer's score does not stand in for that.++What the winners had, and what the rebuilt Reel took from them:++- **The sentence that opens is news and a gain:** "Claude can now ...", with "free" inside it. Not a riddle.+- **The made thing fills the first second.** Two shots cut tall from the 4K sources fill the whole frame (0 to 1.0 s), then the picture+ steps back into a card. Measure where the face and the product sit in the wide shot and centre the crop on them; a zoom-in settle+ eats the margins, so a face near the crop's edge gets cut ("see the images are not cut on the side").+- **A large card beats a full-width band.** A 952 x 1000 card cut from 1076-high clips is sharp with no upscaling and gives the+ picture 46% of the screen; a 16:9 band gives it 32%. Only 4K sources are sharp at full frame.+- **Every phrase has its own picture, and a real one where there is one:** the sketch of a shot wiped into the shot itself, the ad+ and the film playing in cards with their labels ABOVE them (a label on a picture covered the film's own headline).+- **Spoken words as captions, a few at a time, the word being said in a box.** Whole-take word times from the transcriber were+ off by up to half a second; cutting the take into sentences at its pauses and timing the words inside each sentence was accurate.+- **One ask, at the end,** with the word large, a comment box typing it and the message arriving on the music's last hit.+- **Words stay out of the app's column of buttons** (x beyond 940 from about y 880 down): a wordmark on a plate at y 950 ran under it+ until it was made smaller. Measure the rightmost pixel of every line that sits low.+- **A viral-score tool is not a judge.** Higgsfield's Virality Predictor gave 48 and 47 to two winning Reels, 48 to the rejected first+ cut and 43 to 46 to the rebuilt one; its values are scaled inside each clip, so it cannot rank cuts. Its line for the eye, second by+ second, did show where the screen had only graphics. Use that, quote no target, and say so if a target is asked for.+- **A file cannot be loaded into a web page from a tab that has never been shown** (the browser defers media there). Upload through+ the service's own connector or ask the person to click the tab once.+- **Say what the product is from its own page, on the day.** The teaser spent a whole beat on a count of styles; its owner pointed out+ that the skill is not about a count of styles, it adapts to the brand, the intent and the goal of the project, and that it has a+ review room for notes pinned on frames. The README had said both for hours. Read the product's current page before the+ script is written, and again before the voice is recorded.+- **Show the real tool, captured, when the beat is about a tool.** The review room beat is the real page, shot by a headless browser+ (a short script written for that film: seek the cut, click the picture, type the note, save; one PNG per state at three+ times the size), with only a cursor drawn over it. A page laid out for a wide screen does not fit a tall frame: show its parts+ one after the other, large (the frame with its pin, then the note box zoomed until the typed note is about 40 px high).+- **A note added to the middle of a one-line function cuts off the code after it.** Two patches of the form `...; // why`+ swallowed a `g.save(); ... clip()` and a plate; the film still rendered and passed the gate, with a plate missing. Put a note+ on its own line, and after any patch look at a frame of the thing patched.diff --git a/references/video-models.md b/references/video-models.mdnew file mode 100644index 0000000..f85a56f--- /dev/null+++ b/references/video-models.md@@ -0,0 +1,45 @@+# Video models: read them live, and what we have seen++`real-shots.md` holds the method for moving shots (where they pay, the prompt, what goes wrong). This page holds the facts about particular models. Those facts go stale in weeks: lengths, inputs, prices and names change. So there are two rules, and then the notes.++## Rule 1. Read the model before the first render+The same way the price is read before every spend, read the model's own limits before the first clip:+- which models the person's service offers today, and which of them accept a start picture;+- the shortest and longest clip, and the sizes it renders at natively;+- what the call needs for a start picture (some models want a named mode or role, and fail validation without it; a failed validation is not charged);+- how many jobs run at once.++Through a connector, ask the catalog (on Higgsfield: the model list and a model's own entry) and price the exact call with the cost flag. In a browser, read the model's panel. Then say in one line what you read. Where this page and the live read disagree, the live read wins, and this page gets a new dated line.++## Rule 2. One clip first when the model is new to you+The first time a model is used on a film, render one clip on the hardest shot (faces, small lettering, hands) and look at it at the size it plays before sending the rest. It is still one render per shot: the test clip is the shot if it holds.++## Notes, dated. Check the date before trusting a line.++### Seedance 2.5 (through Higgsfield), 6 and 7 October 2026+- Clip length 4 to 30 s. A start picture needed the mode `omni_reference`; without it the call failed validation with "mode 't2v' does not accept reference media". The start picture can be a picture already generated on the same service, passed by its id with the role `start_image`.+- Prices read then: about 7 credits a second at 720p and 12 at 1080p. A 480p draft was 3 a second, and finishing it cost the full 1080p price, so draft then finish costs more than rendering directly.+- A first call sometimes came back as a preset suggestion and not a job; declining the preset and sending again gave the literal render.+- A 4 s 1080p clip took about 3 minutes; 720p took 6 to 8. Four jobs ran at once; a fifth was refused and not charged.+- It started on the exact framing of the still. Most of the motion happened in the first two seconds, and the camera drifted more than asked later on, so shots were taken from frame 0.+- 720p read as soft on an opening, and an upscale did not fully fix it for the owner.++### Kling 3.0 Pro (through Higgsfield), 7 and 8 October 2026+- Native 1080p. Shortest clip 3 s. Price read on 7 October: 1.5 credits a second; on 8 October a 5 s clip from a start picture priced at 8.75.+- From an approved still it held faces, clothes and a product, with the same prompt wording as above, and took 3 to 6 minutes. Seven jobs were accepted at once.+- On a film of people shots it replaced the dearer model on every shot: sharper at about a sixth of the price a clip. For people from an approved still, price it first.++### Upscalers, 7 October 2026+- A model upscale kept the exact motion and took 12 to 17 minutes a clip. Fine at the size it plays; zoomed two times or more it paints skin. A close-up is its own clip.++## Prompt wording that held, on both models+1. "The camera is held by hand and stays on this exact framing, a faint sway, no push, no pan." (when the film's own camera does the move in code)+2. One small action for each person or object, "in real time, already in motion from the first frame".+3. "Everyone stays exactly as they are: same faces, same clothes, same room." For a product: "it stays perfectly still and unchanged", and any lettering "stays exactly as it is".+4. The bans: "no new objects, no hands entering, no text, no morphing, no flicker".+Two people doing the same gesture in one still read as one copying the other once it moves. Fix the still first; that is free.++## Add to this page+After any film that used a video model, add a dated line: the model, what you read live, what held, what did not, the price. Facts only, no client names.++**Kling 3.0 on the Higgsfield website, 11 Oct 2026 (read on the Generate button, start picture given):** 4K 5 s = 30 credits; 1080p 5 s = 10; 1080p 3 s = 6 with the clip's own sound on, **4.5 with sound off**. The sound switch and the prompt-rewrite switch are two small chips under the prompt; both were on by default. When the film has its own sound, turn the clip's sound off before reading the price, and turn prompt rewriting off so the model gets the prompt as written. A product-only shot (still object, slow camera arc, one light event, the bans) held the product and its embossed lettering on the first render.diff --git a/references/voice.md b/references/voice.mdnew file mode 100644index 0000000..aaecce1--- /dev/null+++ b/references/voice.md@@ -0,0 +1,52 @@+# The voice: casting, recording, cutting++A narrator is a choice, not a default. Use one when the film has to explain something a viewer cannot read from the pictures, and write the words first (`references/words.md`). The goal is a voice that sounds like a person talking, not a voice that sounds generated. Voice generation costs credits on most plans: say the price first.++## Casting+The voice director's job is to bring the right three voices, not any three. The last choice is made by ear, and only the person has ears.++**The voice brief, first.** Take it from the strategist's brief and write it in a few lines before opening any voice library:+- who is listening, and where (founders on a phone, parents in a feed, buyers in a meeting);+- what they should feel when it ends (trust, appetite, calm, a smile);+- the brand's tone in three words, from its own site and films;+- so: an age range, an energy, a pace, how warm, which accent, and what it must not sound like (an announcer, a hype read, a machine).++**The shortlist.** Search the service's library by its own labels and descriptions (age, accent, use: conversational, narration, advertising) and pick three that fit this brief and differ from each other in one clear way (energy, age, warmth or pace). Three versions of the same voice is not a choice.++**A new search for every film.** The shortlist comes from this film's brief, never from a list of favourites and never from the last project. There are no default voices in this skill. Two films for different audiences should not end up with the same three candidates; if they do, the brief was not used. The one exception is a brand that already has its voice (3b): offer that voice as one of the three, next to two new ones, and say so.++**The samples.** Record the same two real lines from the script with each voice. Then check what can be checked without hearing: every word is there (transcribe it), the pace in words a minute fits the picture, no line starts clipped. Say which one you would cast and why, in one line, marked as yours.++1. The person picks the voice by ear. The maker cannot hear. Send the two or three short samples of the real lines, not a demo sentence, and let them choose.+2. Never use the person's own cloned voice unless they ask for it.+3. A second voice (a character, an ad inside the film) is a second casting with its own samples.+3b. Keep the choice: write the chosen voice, its model and settings into the project, and into the brand's saved profile if there is one, so the next film for this brand starts from it.++## Recording+4. Use the service's newest speech model; it is usually the one that sounds like talking.+5. One take for the whole narration, so it is one person in one mood. A different voice gets its own take.+6. Few direction tags: one per change of mood, in plain words. A tag on every line sounds acted. If the service adds tags by itself, read them back before generating.+7. Put a pause between lines, so the take can be cut at real silences.+8. A line added later is recorded together with the line before it, and only the new line is placed. The approved take is not touched.++## Checking and cutting+9. Transcribe the whole take: every line there, in order, no tag spoken aloud.+10. Check its length against the picture before building on it. A more acted read can run a quarter longer.+11. Cut silence to silence, never by word times alone, and transcribe every cut line on its own before it goes in. `scripts/vo.py` does both and stops the build on a line that does not match its text:+```bash+python3 <skill>/scripts/vo.py vo.json # takes + lines + start times in; audio/vo.wav and assets/vo.js (when each line starts) out+```+12. Words on screen follow the placed voice (read `assets/vo.js`), never the other way round.++## In the mix+13. Voice sits 10 to 17 dB over the music while it speaks. A voiced piece inside the film needs a deeper dip.+14. A sound effect on the same instant as a short word hides the word: sound first, word a beat later.+15. Check the true peak after mixing (`scripts/audio-check.mjs`).+16. Space the lines evenly: about 0.3 s between one sentence and the next in a list, never 0.1 in one stretch and 0.5 in another. Lay the voice out first, on its own, then put each picture's cut at or just before its line (up to 0.4 s before is fine; the picture leads, the voice names it).+17. Let a drop land before the next line: give it half a second with no voice over it, or it is heard only as a dip.+18. A second voice inside the film (an ad's own narrator) gets a lighter dip under it than the narrator, about 8 to 11 dB, so the music under that piece keeps its weight; check each of its lines still clears the music by 7 dB or more.+19. Transcribe the final mix (`whisper-cli` on the mixed file) and read it: every line must come back as written. It is the one check of the mix that needs no ears.++## Working in the person's account+16. Their page is theirs. Note the text, voice and model before touching it, and put all three back at the end.+17. Say what was spent, even when it came from a free pool.diff --git a/references/words.md b/references/words.mdnew file mode 100644index 0000000..c3431dc--- /dev/null+++ b/references/words.md@@ -0,0 +1,43 @@+# The words: spoken and on screen++The writer owns every word in the film. Most weak films have too many.++## Before writing+- Write and count the spoken lines before the storyboard is timed (about two words a second, plus the gaps). The script sets the film's length, not the other way round.+- One takeaway, one sentence. Every line either sets it up or pays it off.+- Use the person's own words and the brand's real lines where they exist. A line you wrote is marked as yours when you show the script, and a made-up brand's copy is yours too.+- No claim, number, price, date or link they did not give.++## Spoken lines+- Each line must be clear to someone who hears it once with no context. Read it cold: if it needs the picture or the line before to make sense, rewrite it. Copy lifted from a web page rarely passes.+- Conversational, the way a person would say it to a friend. Short sentences. One idea each.+- Avoid words with two meanings and trade words ("music", not "score").+- Budget: about two words a second, less under fast cuts. Count the words against the length before recording, and cut lines, not pace.+- A line that repeats an earlier line has to earn it.++- **After an aside, name the subject again.** A pronoun attaches to the last thing said. "Oh, and there's a copywriter for social, too. It made that video." was heard by the owner as the copywriter making the video. "Take One made that video." cannot be misheard, costs two words, and puts the name in the viewer's ear once more. Read every line that starts with "it", "this" or "that" together with the line before it.+- **"That" for the thing shown, "this" for the film itself.** When a film points at a second film inside it, keep the two words apart: "that video" (the one in the player), then "the one you're watching". "This video" too early is heard as the whole film and gives the turn away.++## On-screen lines+- Two to five words at a time, one idea per shot, large.+- No full stop at the end of a line on screen.+- Plain words. If the same thing is spoken and shown, the screen carries the key words, not the whole sentence.+- Reading time and placement: `references/timing.md`. Never on a face.++- **A first line said large: build it in place as one stacked block, and let nothing fly.** Set the line as a left-aligned stack, one short line per spoken beat, the key word last and about two and a half times larger ("you built / something / big"). The first line is there on frame 0; each next line rises into place from behind its own lower edge (a wipe of about 0.15 s, eased out) exactly when it is said; the last, largest line rises the same way with a small overshoot (3 %; more touches the line above). The whole sentence is then on screen as a poster for the rest of the shot. With a cut-out of the subject, the stack sits behind it and the big word comes up from behind the product. What this replaced, and why: an earlier version showed each word large and then shrank it up to a small line while the next popped in. A reviewer passed it; the owner did not: "do you think the typography on the first frame is the best we can do ... the way it moves". Two things moving in different directions at once reads as a preset, and the small line cannot be read on a phone. One kind of move for the whole sentence, and words that stay where they land.++## The last line+- The name, one line, and one thing to do, with the link they gave from the first second of the end card. No link, no invented one: end on the name and tell the person a link is missing.+- A line that could sit under any product ("for everyone who...") is a placeholder. Find the one only this product can say.++## Words on screen when the film has a voice or a song++Many people watch muted. A film that only makes sense with the sound on has lost them.++- **Show short lines whole.** A spoken or sung line of up to about seven words goes on screen in full, broken into two or three big rows, with its key words lit. Fragments ("the work", "hand it off") look sharp to someone who knows the lyric and mean nothing to someone who does not.+- **Lead-in small, point large.** The row that sets up the line ("Not because") can be about 75 to 85 px at 1080p; the row that carries it ("the work goes away") is 100 px or more. Nothing a viewer must read is under about 70 px.+- **Each word arrives when it is said**, lit, then cools. Do not let a word sit half-lit and brown; it reads as low contrast.+- **Hold a finished line at least 1.2 s.** A line that completes and is covered or cut half a second later was never read.+- **Words get clean space.** Not on a grid of lines, not across an outline, not touching the frame edge, not on the thing they describe. Move the camera or the object, not the type size.+- **A repeated set says each phrase once, large, and then leaves it on its object** (the label lands on the card as the next phrase starts), so the set stays readable without saying anything twice.+- **Every stretch with a voice has words.** Three seconds of voice with nothing on screen is three seconds a muted viewer waits.diff --git a/scripts/.gitignore b/scripts/.gitignorenew file mode 100644index 0000000..3c3629e--- /dev/null+++ b/scripts/.gitignore@@ -0,0 +1 @@+node_modulesdiff --git a/scripts/analyze-style.mjs b/scripts/analyze-style.mjsnew file mode 100644index 0000000..8bf5e5b--- /dev/null+++ b/scripts/analyze-style.mjs@@ -0,0 +1,267 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+//+// ANALYZE A STYLE. Read a reference image (or one frame of a video) and print what its HAND is+// doing: palette, value, line, fill texture, speckle, edges, halftone. For the take-one+// skill's LEARN-A-STYLE workflow (references/adapt-a-style.md).+//+// node scripts/analyze-style.mjs <image-or-video> [--frame N] [--crop x,y,w,h]+// [--exclude x,y,w,h;x,y,w,h] [--max 1400] [--json out/profile.json]+//+// READ THIS BEFORE TRUSTING A NUMBER. Every statistic here measures the PICTURE, and a picture is+// subject + composition + lighting + medium all at once. A reference that is mostly empty paper+// reads "light key, few edges" whatever hand drew it; lettering reads as "line". These are+// DIAGNOSTICS that tell you where to look, never a verdict. The verdict is the style recipe you+// write in words after LOOKING at the image full size and at a 3x crop, and the proof is the two+// PAPER BOAT frames rendered in that hand (references/adapt-a-style.md). In anidoodle's two+// documented proofs the statistical nearest style was wrong both times.+//+// No native deps: decoding goes through ffmpeg (raw RGBA pixels), so any still or video frame+// ffmpeg reads works: png, jpg, webp, or frame N of an mp4 (--frame N). Only this tool reads the+// reference; render code never does.+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { basename, dirname, resolve } from "node:path";++const VAL = new Set(["json", "max", "frame", "exclude", "crop"]);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith("--")) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const die = (m) => { console.error(`analyze-style: ${m}`); process.exit(1); };+if (!pos.length) die("usage: node scripts/analyze-style.mjs <image-or-video> [--frame N] [--crop x,y,w,h] [--exclude rects] [--json out.json]");++// ---------------------------------------------------------------- decode (ffmpeg -> raw pixels)+const decode = (file) => {+ if (!existsSync(file)) die(`no such file: ${file}`);+ const probe = execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", file]).toString().trim().split("\n")[0].split(",").map(Number);+ let [w, h] = probe; if (!w || !h) die(`ffprobe could not size ${file}`);+ if (opt.crop) { const c = opt.crop.split(",").map(Number); w = c[2]; h = c[3]; }+ const vf = [opt.frame ? `select=eq(n\\,${Number(opt.frame)})` : "", opt.crop ? `crop=${opt.crop.split(",").slice(2, 4).join(":")}:${opt.crop.split(",").slice(0, 2).join(":")}` : ""].filter(Boolean), pre = vf.length ? ["-vf", vf.join(",")] : [];+ const raw = execFileSync("ffmpeg", ["-v", "error", "-i", file, ...pre, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgba", "-"], { maxBuffer: 1 << 30 });+ if (raw.length < w * h * 4) die(`decoded ${raw.length} bytes, expected ${w * h * 4}`);+ return { w, h, rgba: raw, sha256: createHash("sha256").update(readFileSync(file)).digest("hex") };+};++// ---------------------------------------------------------------- colour science (OKLab, Ottosson 2020)+const lin = (c) => { c /= 255; return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); };+const LIN = Float32Array.from({ length: 256 }, (_, i) => lin(i));+const toLab = (r, g, b) => {+ const R = LIN[r], G = LIN[g], B = LIN[b];+ const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B), m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B), s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];+};+const toRgb = (L, a, b) => {+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3, m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3, s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;+ const R = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, G = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, B = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s;+ const e = (c) => Math.round(255 * Math.max(0, Math.min(1, c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055)));+ return [e(R), e(G), e(B)];+};+const hex = ([r, g, b]) => "#" + [r, g, b].map((v) => v.toString(16).padStart(2, "0")).join("");+const rng = (seed) => { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };++// ---------------------------------------------------------------- image plumbing+const toPlanes = ({ w, h, rgba }) => { // composite alpha over white, then OKLab planes+ const n = w * h, L = new Float32Array(n), A = new Float32Array(n), B = new Float32Array(n);+ for (let i = 0; i < n; i++) { const al = rgba[i * 4 + 3] / 255, f = (c) => Math.round(c * al + 255 * (1 - al)); const [l, a, b] = toLab(f(rgba[i * 4]), f(rgba[i * 4 + 1]), f(rgba[i * 4 + 2])); L[i] = l; A[i] = a; B[i] = b; }+ return { w, h, L, A, B };+};+const shrink = (P, max) => { // area-average down so the long side is <= max+ const k = Math.max(1, Math.ceil(Math.max(P.w, P.h) / max)); if (k === 1) return { ...P, k: 1 };+ const w = Math.floor(P.w / k), h = Math.floor(P.h / k), out = { w, h, k, L: new Float32Array(w * h), A: new Float32Array(w * h), B: new Float32Array(w * h) };+ for (const ch of ["L", "A", "B"]) { const s = P[ch], d = out[ch]; for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { let t = 0; for (let j = 0; j < k; j++) for (let i = 0; i < k; i++) t += s[(y * k + j) * P.w + x * k + i]; d[y * w + x] = t / (k * k); } }+ return out;+};+const boxBlur = (src, w, h, r, passes = 3) => { // three box passes ~ a gaussian, separable, edge-clamped+ let a = Float32Array.from(src), b = new Float32Array(src.length);+ for (let p = 0; p < passes; p++) {+ for (let y = 0; y < h; y++) { let s = 0; for (let i = -r; i <= r; i++) s += a[y * w + Math.min(w - 1, Math.max(0, i))]; for (let x = 0; x < w; x++) { b[y * w + x] = s / (2 * r + 1); s += a[y * w + Math.min(w - 1, x + r + 1)] - a[y * w + Math.max(0, x - r)]; } }+ for (let x = 0; x < w; x++) { let s = 0; for (let i = -r; i <= r; i++) s += b[Math.min(h - 1, Math.max(0, i)) * w + x]; for (let y = 0; y < h; y++) { a[y * w + x] = s / (2 * r + 1); s += b[Math.min(h - 1, y + r + 1) * w + x] - b[Math.max(0, y - r) * w + x]; } }+ }+ return a;+};+const bilin = (F, w, h, x, y) => { x = Math.max(0, Math.min(w - 1.001, x)); y = Math.max(0, Math.min(h - 1.001, y)); const x0 = x | 0, y0 = y | 0, fx = x - x0, fy = y - y0, i = y0 * w + x0; return F[i] * (1 - fx) * (1 - fy) + F[i + 1] * fx * (1 - fy) + F[i + w] * (1 - fx) * fy + F[i + w + 1] * fx * fy; };+const pct = (arr, q) => { const s = Float32Array.from(arr).sort(); return s.length ? s[Math.min(s.length - 1, Math.floor(q * s.length))] : NaN; };+const median = (arr) => pct(arr, 0.5);+const r2 = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;+// image-convention angle: 0 = horizontal, +45 = rising to the right (y is down in pixels)+const angOf = (dx, dy) => { let a = (-Math.atan2(dy, dx) * 180) / Math.PI; while (a <= -90) a += 180; while (a > 90) a -= 180; return a; };++// ---------------------------------------------------------------- 1. palette: k-means in OKLab+const palette = (P, keep, K = 8) => {+ const n = P.w * P.h, step = Math.max(1, Math.floor(n / 60000)), S = [];+ for (let i = 0; i < n; i += step) if (keep[i]) S.push([P.L[i], P.A[i], P.B[i]]);+ const r = rng(7), d2 = (p, c) => (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2 + (p[2] - c[2]) ** 2;+ const C = [S[Math.floor(r() * S.length)].slice()]; // k-means+++ while (C.length < K) { const D = S.map((p) => Math.min(...C.map((c) => d2(p, c)))), tot = D.reduce((a, b) => a + b, 0); let t = r() * tot, i = 0; while (i < D.length - 1 && (t -= D[i]) > 0) i++; C.push(S[i].slice()); }+ const lab = new Int32Array(S.length);+ for (let it = 0; it < 25; it++) {+ const sum = C.map(() => [0, 0, 0, 0]);+ S.forEach((p, i) => { let best = 0, bd = 1e9; C.forEach((c, k) => { const d = d2(p, c); if (d < bd) { bd = d; best = k; } }); lab[i] = best; const s = sum[best]; s[0] += p[0]; s[1] += p[1]; s[2] += p[2]; s[3]++; });+ sum.forEach((s, k) => { if (s[3]) C[k] = [s[0] / s[3], s[1] / s[3], s[2] / s[3]]; });+ }+ let cl = C.map((c, k) => ({ lab: c, share: 0, k })); lab.forEach((k) => cl[k].share++); cl.forEach((c) => (c.share /= S.length));+ // merge near-duplicates (dE_ok < 0.035): k is an upper bound, not a claim about the palette+ cl.sort((a, b) => b.share - a.share); const out = [];+ for (const c of cl) { const m = out.find((o) => Math.sqrt(d2(o.lab, c.lab)) < 0.035); if (m) { const t = m.share + c.share; m.lab = m.lab.map((v, i) => (v * m.share + c.lab[i] * c.share) / t); m.share = t; } else out.push({ ...c }); }+ return out.filter((c) => c.share > 0.002).map((c) => { const [L, a, b] = c.lab, C2 = Math.hypot(a, b); return { hex: hex(toRgb(L, a, b)), L: r2(L), C: r2(C2, 3), hue: Math.round(((Math.atan2(b, a) * 180) / Math.PI + 360) % 360), share: r2(c.share, 3) }; }).sort((a, b) => b.share - a.share);+};++// ---------------------------------------------------------------- 2..7: the measurements+const analyze = (file) => {+ const img = decode(file), full = toPlanes(img), P = shrink(full, Number(opt.max ?? 1400)), { w, h } = P, n = w * h, short = Math.min(w, h);+ // --exclude "x,y,w,h;x,y,w,h" (reference px, after --crop): UI, captions, a photo pasted in: things that are not the hand+ const rects = (opt.exclude ? String(opt.exclude).split(";") : []).map((r) => r.split(",").map(Number)).filter((r) => r.length === 4);+ const keep = new Uint8Array(n).fill(1); for (const [rx, ry, rw, rh] of rects) for (let y = Math.max(0, Math.floor(ry / P.k)); y < Math.min(h, Math.ceil((ry + rh) / P.k)); y++) for (let x = Math.max(0, Math.floor(rx / P.k)); x < Math.min(w, Math.ceil((rx + rw) / P.k)); x++) keep[y * w + x] = 0;+ const kept = []; for (let i = 0; i < n; i++) if (keep[i]) kept.push(i); const nk = kept.length || 1;+ const clear = boxBlur(Float32Array.from(keep), w, h, 6, 1); // a margin round every excluded box: its border is not the hand either+ const ok = (i) => clear[i] > 0.999;+ const L = P.L, Lk = Float32Array.from(kept, (i) => L[i]);+ const pal = palette(P, keep);+ // paper: the biggest field if it dominates, else the biggest LIGHT field; ink: the darkest colour that is really used+ const light = pal.filter((c) => c.L > 0.72 && c.share > 0.1), paper = pal[0].share > 0.3 ? pal[0] : (light.sort((a, b) => b.share - a.share)[0] ?? pal[0]);+ const inks = pal.filter((c) => c !== paper && c.share > 0.004).sort((a, b) => a.L - b.L), ink = inks[0] ?? pal[pal.length - 1];+ let chromaSum = 0, chromaN = 0; for (const i of kept) { const c = Math.hypot(P.A[i], P.B[i]); if (Math.abs(P.L[i] - paper.L) > 0.04 || Math.abs(c - paper.C) > 0.02) { chromaSum += c; chromaN++; } }++ // value+ const hist = [0, 0, 0, 0, 0]; for (const v of Lk) hist[Math.min(4, Math.floor(v * 5))]++;+ const meanL = Lk.reduce((a, b) => a + b, 0) / nk, p03 = pct(Lk, 0.03), p97 = pct(Lk, 0.97);+ const value = { key: meanL > 0.75 ? "high" : meanL > 0.5 ? "middle" : "low", meanL: r2(meanL), contrast: r2(p97 - p03), p03: r2(p03), p97: r2(p97), bands: hist.map((v) => r2(v / nk)), bandsNote: "share of pixels in L 0-.2, .2-.4, .4-.6, .6-.8, .8-1" };++ // gradients on a lightly smoothed L+ const Ls = boxBlur(L, w, h, 1, 1), gx = new Float32Array(n), gy = new Float32Array(n), gm = new Float32Array(n);+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) { const i = y * w + x; gx[i] = (Ls[i + 1] - Ls[i - 1]) / 2; gy[i] = (Ls[i + w] - Ls[i - w]) / 2; gm[i] = Math.hypot(gx[i], gy[i]); }++ // edges: transition width = contrast across the edge / gradient at the edge (a step is ~2 px wide at pixel scale)+ const edgeMask = new Uint8Array(n); let hard = 0, soft = 0, lost = 0, rim = 0, rimN = 0;+ for (let y = 9; y < h - 9; y++) for (let x = 9; x < w - 9; x++) {+ const i = y * w + x, g = gm[i]; if (g < 0.012 || !ok(i)) continue;+ const nx = gx[i] / g, ny = gy[i] / g; if (g < bilin(gm, w, h, x + nx, y + ny) || g < bilin(gm, w, h, x - nx, y - ny)) continue; // thin to the ridge+ const hi = bilin(Ls, w, h, x + nx * 8, y + ny * 8), lo = bilin(Ls, w, h, x - nx * 8, y - ny * 8), dL = hi - lo; if (dL < 0.05) continue;+ edgeMask[i] = 1; const width = dL / g;+ if (width < 2.6) hard++; else if (width < 7) soft++; else lost++;+ // pooled rim: on the dark side, is the band right at the edge darker than the body further in?+ if (dL > 0.07) { rimN++; if (bilin(Ls, w, h, x - nx * 10, y - ny * 10) - bilin(Ls, w, h, x - nx * 3, y - ny * 3) > 0.012) rim++; }+ }+ const eN = hard + soft + lost || 1;+ const near = boxBlur(Float32Array.from(edgeMask), w, h, 3, 1); // "near an edge" = inside 3 px of one+ const edges = { density: r2(eN / nk, 4), hard: r2(hard / eN), soft: r2(soft / eN), lost: r2(lost / eN), pooledRim: rimN > 30 ? r2(rim / rimN) : null, note: "hard < 2.6 px transition, soft 2.6-7, lost > 7 (at analysis size); pooledRim = share of strong edges whose dark side is darkest AT the edge (watercolour pigment settling)" };++ // line: thin marks darker than their surroundings, width from the shorter run through each line pixel+ const bg = boxBlur(L, w, h, Math.max(4, Math.round(short / 60))), lineMask = new Uint8Array(n);+ for (let i = 0; i < n; i++) if (bg[i] - L[i] > 0.09) lineMask[i] = 1;+ const runH = new Uint16Array(n), runV = new Uint16Array(n);+ for (let y = 0; y < h; y++) { let x = 0; while (x < w) { if (!lineMask[y * w + x]) { x++; continue; } let e = x; while (e < w && lineMask[y * w + e]) e++; for (let k = x; k < e; k++) runH[y * w + k] = e - x; x = e; } }+ for (let x = 0; x < w; x++) { let y = 0; while (y < h) { if (!lineMask[y * w + x]) { y++; continue; } let e = y; while (e < h && lineMask[e * w + x]) e++; for (let k = y; k < e; k++) runV[k * w + x] = e - y; y = e; } }+ const widths = []; let thin = 0; const thinMax = Math.max(3, short * 0.012);+ for (let i = 0; i < n; i++) if (lineMask[i] && ok(i)) { const wd = Math.min(runH[i], runV[i]); if (wd <= thinMax) { thin++; if (i % 3 === 0) widths.push(wd); } }+ const line = { presence: r2(thin / nk, 4), widthMedianPx: widths.length ? r2(median(widths) * P.k, 1) : null, widthP90Px: widths.length ? r2(pct(widths, 0.9) * P.k, 1) : null, widthVariation: widths.length ? r2((pct(widths, 0.9) - pct(widths, 0.1)) / Math.max(1, median(widths))) : null, note: "presence = share of pixels in thin dark marks; lettering counts as line; widths in reference pixels" };++ // fill texture: structure tensor of the fine grain, AWAY from edges+ const hp = new Float32Array(n); { const b2 = boxBlur(L, w, h, 2); for (let i = 0; i < n; i++) hp[i] = L[i] - b2[i]; }+ // the tensor is built on the GRAIN (L minus its blur), not on L: a smooth wash gradient is perfectly+ // "coherent" and says nothing about which way the pencil or brush moved+ const Jxx = new Float32Array(n), Jxy = new Float32Array(n), Jyy = new Float32Array(n);+ for (let y = 1; y < h - 1; y++) for (let x = 1; x < w - 1; x++) { const i = y * w + x, hx = (hp[i + 1] - hp[i - 1]) / 2, hy = (hp[i + w] - hp[i - w]) / 2; Jxx[i] = hx * hx; Jxy[i] = hx * hy; Jyy[i] = hy * hy; }+ const tw = Math.max(4, Math.round(short / 120)), bxx = boxBlur(Jxx, w, h, tw), bxy = boxBlur(Jxy, w, h, tw), byy = boxBlur(Jyy, w, h, tw);+ const bins = new Float64Array(36); let cohSum = 0, cohW = 0, cohHigh = 0, cohN = 0; const interior = new Uint8Array(n);+ for (let y = 6; y < h - 6; y += 2) for (let x = 6; x < w - 6; x += 2) {+ const i = y * w + x; if (near[i] > 0.02 || lineMask[i] || !ok(i)) continue; const tr = bxx[i] + byy[i]; if (tr < 4e-7) continue; // below that there is no grain to have a direction+ interior[i] = 1; const coh = Math.sqrt((bxx[i] - byy[i]) ** 2 + 4 * bxy[i] ** 2) / tr, th = 0.5 * Math.atan2(2 * bxy[i], bxx[i] - byy[i]); // gradient direction; strokes run across it+ const sa = angOf(-Math.sin(th), Math.cos(th)), b = Math.min(35, Math.floor((sa + 90) / 5)), wt = coh * Math.sqrt(tr);+ bins[b] += wt; cohSum += coh * Math.sqrt(tr); cohW += Math.sqrt(tr); cohN++; if (coh > 0.5) cohHigh++;+ }+ let pk = 0; bins.forEach((v, i) => { if (v > bins[pk]) pk = i; }); const tot = bins.reduce((a, b) => a + b, 0) || 1; let near15 = 0; for (let d = -3; d <= 3; d++) near15 += bins[(pk + d + 36) % 36];+ const dom = pk * 5 - 90 + 2.5, u = [Math.cos((dom * Math.PI) / 180), -Math.sin((dom * Math.PI) / 180)];+ // stroke length: autocorrelation of the grain along the dominant direction versus across it+ const pts = []; for (let i = 0; i < n; i += 7) if (interior[i]) pts.push(i);+ let v0 = 0; pts.forEach((i) => (v0 += hp[i] * hp[i])); v0 = v0 / (pts.length || 1) || 1e-9;+ const corr = (dx, dy) => { let s = 0, c = 0; for (const i of pts) { const x = i % w, y = (i / w) | 0; if (x + dx < 0 || x + dx >= w - 1 || y + dy < 0 || y + dy >= h - 1) continue; s += hp[i] * bilin(hp, w, h, x + dx, y + dy); c++; } return s / (c || 1) / v0; };+ const reach = (vx, vy) => { for (let d = 1; d <= 60; d++) if (corr(vx * d, vy * d) < 0.3) return d; return 60; };+ const along = reach(u[0], u[1]), across = reach(-u[1], u[0]);+ let fine = 0, lightSpeck = 0, darkSpeck = 0; pts.forEach((i) => { fine += hp[i] * hp[i]; if (hp[i] > 0.035) lightSpeck++; if (hp[i] < -0.035) darkSpeck++; });+ const grain = Math.sqrt(fine / (pts.length || 1)) >= 0.006; // below this the "direction" is quantisation noise+ const texture = { sampled: pts.length, grain, dominantStrokeAngle: grain ? r2(dom, 0) : null, peakShare: grain ? r2(near15 / tot) : null, coherence: grain && cohW ? r2(cohSum / cohW) : null, coherentShare: cohN ? r2(cohHigh / cohN) : null, strokeLengthPx: r2(along * P.k, 0), grainWidthPx: r2(across * P.k, 0), elongation: r2(along / across, 1), grainRms: r2(Math.sqrt(fine / (pts.length || 1)), 3), speckleLight: r2(lightSpeck / (pts.length || 1), 3), speckleDark: r2(darkSpeck / (pts.length || 1), 3),+ note: "measured on interior pixels only (no edges, no lines). dominantStrokeAngle 0 = horizontal, +45 = rising right; peakShare = weight within +-15 deg of it (1/12 = no preference); speckleLight = paper showing through the colour (tooth)" };++ // spectrum at FULL resolution: power-law slope + a halftone lattice if there is one+ const spectrum = fftStats(full, rects);+ return { file: basename(file), sha256: img.sha256, size: [img.w, img.h], analysedAt: [w, h], palette: pal, paper: { hex: paper.hex, L: paper.L, C: paper.C, hue: paper.hue, share: paper.share }, ink: { hex: ink.hex, L: ink.L, C: ink.C, hue: ink.hue, share: ink.share }, chroma: r2(chromaN ? chromaSum / chromaN : 0, 3), colours: pal.filter((c) => c.share > 0.02).length, value, line, texture, edges, spectrum };+};++// ---------------------------------------------------------------- FFT: slope and halftone lattice+const fft1 = (re, im, N) => { // in place, radix 2+ for (let i = 1, j = 0; i < N; i++) { let bit = N >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } }+ for (let len = 2; len <= N; len <<= 1) { const a = (-2 * Math.PI) / len, wr = Math.cos(a), wi = Math.sin(a); for (let i = 0; i < N; i += len) { let cr = 1, ci = 0; for (let k = 0; k < len / 2; k++) { const ur = re[i + k], ui = im[i + k], vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci, vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr; re[i + k] = ur + vr; im[i + k] = ui + vi; re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } } }+};+const fftStats = (F, rects = []) => {+ for (const N of [256, 128]) { const r = fftAt(F, rects, N); if (r) return r; }+ return { powerSlope: null, halftone: null, note: "no crop of 128 px clear of exclusions: spectrum skipped" };+};+const fftAt = (F, rects, N) => {+ if (F.w < N || F.h < N) return null;+ // pick the four busiest crops (most variance): halftone lives in the inked parts, not the margins+ const cands = []; for (let y = 0; y + N <= F.h; y += N / 2) for (let x = 0; x + N <= F.w; x += N / 2) { if (rects.some(([rx, ry, rw, rh]) => x < rx + rw && x + N > rx && y < ry + rh && y + N > ry)) continue; let s = 0, s2 = 0, c = 0; for (let j = 0; j < N; j += 4) for (let i = 0; i < N; i += 4) { const v = F.L[(y + j) * F.w + x + i]; s += v; s2 += v * v; c++; } const m = s / c; cands.push({ x, y, v: s2 / c - m * m }); }+ if (!cands.length) return null;+ cands.sort((a, b) => b.v - a.v); const crops = cands.slice(0, 4), pow = new Float64Array(N * N);+ const han = Float32Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (N - 1)));+ for (const c of crops) {+ const re = new Float64Array(N * N), im = new Float64Array(N * N); let m = 0; for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) m += F.L[(c.y + j) * F.w + c.x + i]; m /= N * N;+ for (let j = 0; j < N; j++) for (let i = 0; i < N; i++) re[j * N + i] = (F.L[(c.y + j) * F.w + c.x + i] - m) * han[i] * han[j];+ const rr = new Float64Array(N), ii = new Float64Array(N);+ for (let j = 0; j < N; j++) { for (let i = 0; i < N; i++) { rr[i] = re[j * N + i]; ii[i] = im[j * N + i]; } fft1(rr, ii, N); for (let i = 0; i < N; i++) { re[j * N + i] = rr[i]; im[j * N + i] = ii[i]; } }+ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { rr[j] = re[j * N + i]; ii[j] = im[j * N + i]; } fft1(rr, ii, N); for (let j = 0; j < N; j++) pow[j * N + i] += rr[j] * rr[j] + ii[j] * ii[j]; }+ }+ const at = (u, v) => pow[((v + N) % N) * N + ((u + N) % N)];+ const ring = new Float64Array(N / 2), cnt = new Float64Array(N / 2);+ for (let v = -N / 2; v < N / 2; v++) for (let u = -N / 2; u < N / 2; u++) { const r = Math.round(Math.hypot(u, v)); if (r > 0 && r < N / 2) { ring[r] += at(u, v); cnt[r]++; } }+ // slope of log power against log frequency: ~-2 natural/soft, flatter = grainy/noisy, steeper = smooth washes+ let sx = 0, sy = 0, sxx = 0, sxy = 0, k = 0; for (let r = Math.round(N / 64); r <= Math.round(N * 0.39); r++) { const x = Math.log(r), y = Math.log(ring[r] / cnt[r] + 1e-12); sx += x; sy += y; sxx += x * x; sxy += x * y; k++; }+ const slope = (k * sxy - sx * sy) / (k * sxx - sx * sx);+ // halftone: a lattice is isolated peaks far above their own ring, at two angles 90 (or 60) degrees apart+ const peaks = [];+ for (let v = -N / 2 + 1; v < N / 2 - 1; v++) for (let u = 1; u < N / 2 - 1; u++) {+ const r = Math.hypot(u, v); if (r < N * 0.047 || r > N * 0.46) continue; const p = at(u, v), base = ring[Math.round(r)] / cnt[Math.round(r)];+ if (p < base * 25) continue; let isMax = true; for (let dv = -1; dv <= 1 && isMax; dv++) for (let du = -1; du <= 1; du++) if ((du || dv) && at(u + du, v + dv) > p) { isMax = false; break; }+ if (isMax && Math.abs(u) > 1 && Math.abs(v) > 1) peaks.push({ u, v, r, ratio: p / base }); // skip the axes: window leakage and ruled lines live there+ }+ peaks.sort((a, b) => b.ratio - a.ratio);+ let lattice = null;+ if (peaks.length >= 2) { const a = peaks[0], b = peaks.slice(1).find((q) => Math.abs(q.r - a.r) / a.r < 0.12 && Math.abs(((Math.atan2(q.v, q.u) - Math.atan2(a.v, a.u)) * 180) / Math.PI) % 180 > 50); if (b) lattice = { pitchPx: r2(N / a.r, 1), angles: [angOf(a.u, a.v), angOf(b.u, b.v)].map((x) => r2(x, 0)), strength: r2(Math.min(a.ratio, b.ratio), 0) }; }+ return { powerSlope: r2(slope), halftone: lattice, note: "powerSlope ~ -3 smooth washes, ~ -2 natural texture, flatter than -1.6 grainy/speckled; halftone = FFT lattice (pitch in reference px), null when none" };+};++// ---------------------------------------------------------------- prose reading (a starting point for the LOOK step, never its replacement)+const hueName = (c) => {+ if (c.C < 0.015) return c.L > 0.85 ? "white" : c.L > 0.6 ? "light gray" : c.L > 0.3 ? "gray" : c.L > 0.12 ? "dark gray" : "near-black";+ const h = c.hue, warm = c.C < 0.045 ? "muted " : c.C > 0.13 ? "vivid " : "";+ const base = h < 15 ? "pink-red" : h < 45 ? "red" : h < 70 ? "orange" : h < 90 ? "amber" : h < 115 ? "yellow" : h < 155 ? "green" : h < 200 ? "teal" : h < 240 ? "cyan-blue" : h < 290 ? "blue" : h < 330 ? "violet" : "magenta";+ return warm + (c.L > 0.8 ? "pale " : c.L < 0.3 ? "deep " : "") + base;+};+const describe = (p) => {+ const out = [];+ const cols = p.palette.filter((c) => c.share > 0.02);+ out.push(`Ground: ${hueName(p.paper)} (${p.paper.hex}, ${(p.paper.share * 100).toFixed(0)}% of the frame); darkest working colour ${hueName(p.ink)} (${p.ink.hex}).`);+ out.push(`Palette: ${cols.length} colours above 2%: ${cols.slice(0, 6).map((c) => `${hueName(c)} ${c.hex}`).join(", ")}. Off-ground chroma ${p.chroma < 0.03 ? "near zero: effectively monochrome" : p.chroma < 0.07 ? "restrained" : p.chroma < 0.13 ? "moderate" : "high: colour does the talking"} (${p.chroma}).`);+ out.push(`Value: ${p.value.key} key (mean L ${p.value.meanL}), ${p.value.contrast > 0.75 ? "full-range punchy contrast" : p.value.contrast > 0.5 ? "healthy contrast" : "compressed, tonal"} (${p.value.contrast}, L ${p.value.p03}..${p.value.p97}).`);+ out.push(`Line: ${p.line.presence < 0.005 ? "essentially none: shapes meet without drawn contours" : p.line.presence < 0.03 ? "sparse thin marks" : p.line.presence < 0.1 ? "a real drawn-line component" : "line-dominated"} (${(p.line.presence * 100).toFixed(1)}% of pixels${p.line.widthMedianPx ? `, median width ${p.line.widthMedianPx} px, variation ${p.line.widthVariation}` : ""}).`);+ const t = p.texture;+ out.push(`Fills: ${!t.grain ? "smooth (flat colour, washes or soft gradients): no measurable grain" : `grained (rms ${t.grainRms}), ${t.peakShare > 0.25 ? `strokes pulling one way (${t.dominantStrokeAngle} deg, ${(t.peakShare * 100).toFixed(0)}% of the weight)` : "no single stroke direction"}, coherence ${t.coherence}, stroke ~${t.strokeLengthPx}x${t.grainWidthPx} px`}; speckle light ${t.speckleLight} / dark ${t.speckleDark}.`);+ out.push(`Edges: ${p.edges.hard > 0.6 ? "mostly hard, graphic cuts" : p.edges.hard > 0.35 ? "a mix of hard and soft" : p.edges.soft + p.edges.lost > 0.75 ? "mostly soft or lost: forms melt together" : "mixed"} (hard ${p.edges.hard} / soft ${p.edges.soft} / lost ${p.edges.lost}${p.edges.pooledRim != null ? `, pooled rims ${p.edges.pooledRim}` : ""}).`);+ out.push(`Surface: spectrum slope ${p.spectrum.powerSlope ?? "n/a"} (${p.spectrum.powerSlope == null ? "" : p.spectrum.powerSlope < -2.6 ? "smooth, wash-like" : p.spectrum.powerSlope < -1.6 ? "natural texture" : "grainy/speckled"}); ${p.spectrum.halftone ? `PERIODIC LATTICE: pitch ${p.spectrum.halftone.pitchPx} px at ${p.spectrum.halftone.angles.join("/")} deg (halftone screen or regular ruling)` : "no periodic lattice"}.`);+ return out;+};++// ---------------------------------------------------------------- CLI+const p = analyze(resolve(pos[0]));+const line = (k, v) => console.log(` ${k.padEnd(14)} ${v}`);+console.log(`STYLE PROFILE ${p.file} ${p.size.join("x")} (analysed at ${p.analysedAt.join("x")}) sha256 ${p.sha256.slice(0, 16)}`);+console.log(`\npalette (OKLab k-means, area share):`);+p.palette.forEach((c) => console.log(` ${c.hex} L ${c.L.toFixed(2)} C ${c.C.toFixed(3)} h ${String(c.hue).padStart(3)} ${(c.share * 100).toFixed(1).padStart(5)}%${c.hex === p.paper.hex ? " <- paper/ground" : c.hex === p.ink.hex ? " <- darkest ink" : ""}`));+line("chroma", `${p.chroma} mean OKLab chroma off the ground; ${p.colours} colours above 2%`);+console.log(`\nvalue:`); line("key", `${p.value.key} (mean L ${p.value.meanL}), contrast ${p.value.contrast} (L ${p.value.p03}..${p.value.p97})`); line("bands", p.value.bands.join(" ") + " (dark .. light)");+console.log(`\nline:`); line("presence", `${(p.line.presence * 100).toFixed(2)}% of pixels in thin dark marks`); line("width", p.line.widthMedianPx == null ? "no line found" : `median ${p.line.widthMedianPx} px, p90 ${p.line.widthP90Px} px, variation ${p.line.widthVariation}`);+console.log(`\nfill texture (interior only, ${p.texture.sampled} samples):`); line("direction", p.texture.grain ? `${p.texture.dominantStrokeAngle} deg, ${(p.texture.peakShare * 100).toFixed(0)}% of the weight within 15 deg of it (8% = none)` : "no measurable grain: the fills are smooth (washes, flat colour or a soft/upscaled image)"); line("coherence", `${p.texture.coherence} mean, ${p.texture.coherentShare} of samples above 0.5`); line("stroke", `~${p.texture.strokeLengthPx} px long x ${p.texture.grainWidthPx} px across (elongation ${p.texture.elongation})`); line("speckle", `light ${p.texture.speckleLight}, dark ${p.texture.speckleDark}, grain rms ${p.texture.grainRms}`);+console.log(`\nedges:`); line("hardness", `hard ${p.edges.hard} soft ${p.edges.soft} lost ${p.edges.lost} (density ${p.edges.density})`); line("pooled rim", p.edges.pooledRim == null ? "too few strong edges" : `${p.edges.pooledRim} of strong edges darkest at the edge`);+console.log(`\nspectrum:`); line("slope", p.spectrum.powerSlope ?? p.spectrum.note); line("lattice", p.spectrum.halftone ? `periodic lattice (a halftone screen, or regular ruling/cross-hatch): pitch ${p.spectrum.halftone.pitchPx} px at ${p.spectrum.halftone.angles.join(" / ")} deg (peak ${p.spectrum.halftone.strength}x its ring)` : "none");+console.log(`\nSUMMARY (diagnostics in words; LOOK at the image before believing any of it):`);+describe(p).forEach((s) => console.log(` - ${s}`));+if (opt.json) { p.summary = describe(p); const dest = resolve(opt.json); mkdirSync(dirname(dest), { recursive: true }); writeFileSync(dest, JSON.stringify(p, null, 1)); console.log(`\n-> ${dest}`); }diff --git a/scripts/audio-check.mjs b/scripts/audio-check.mjsnew file mode 100755index 0000000..37fb72e--- /dev/null+++ b/scripts/audio-check.mjs@@ -0,0 +1,282 @@+#!/usr/bin/env node+// audio-check.mjs — AUDIO QUALITY METER for the take-one skill.+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+//+// Meters ANY audio or video file (decoded via ffmpeg, i.e. what a player would hear):+// integrated LUFS ITU-R BS.1770-4 K-weighting, 400 ms blocks at 75 % overlap,+// -70 LUFS absolute and -10 LU relative gates+// LRA EBU Tech 3342 (3 s short-term, -20 LU gate, P95 - P10)+// true peak 4x oversampled (16-tap polyphase windowed sinc), dBTP+// centroid magnitude-weighted spectral centroid over non-silent frames+// Every LUFS number is cross-checked against ffmpeg's own `ebur128`; the two must+// agree within 0.5 LU or the run FAILS (that disagreement means a metering bug).+//+// Usage:+// node audio-check.mjs <file> [more files] [--target film|dense|gentle]+// node audio-check.mjs mix.wav --stems vocals.wav other.wav # vocal-masking check+//+// Targets (see references/audio.md "Measure, don't guess"):+// film (default) mixed film final audio: -14 LUFS integrated (+/-1 LU), true peak <= -1 dBTP+// dense music master, dense styles: -14 LUFS (+/-1 LU), TP <= -1 dBTP+// gentle music master, gentle styles: -16 LUFS (+/-1 LU), TP <= -1 dBTP+// --stems vocals.wav other.wav : the vocal stem must beat the rest by >= 3 dB in+// 500 Hz-4 kHz in >= 80 % of its active seconds, or the dialogue/vocal is likely masked.+//+// Exit code 0 = all checks pass; 1 = a verdict failed; 2 = self-meter vs ffmpeg disagree.++import { execFileSync, spawnSync } from "node:child_process";+import { basename } from "node:path";+import { existsSync } from "node:fs";++const SR = 48000;++// ---------------------------------------------------------------------------+// Decode ANY file through ffmpeg to float stereo 48 kHz: meter what a player decodes.+const decode = (path) => {+ let buf;+ try {+ buf = execFileSync(+ "ffmpeg",+ ["-v", "error", "-i", path, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(SR), "pipe:1"],+ { maxBuffer: 1 << 30, stdio: ["ignore", "pipe", "pipe"] },+ );+ } catch (e) {+ const lines = String(e.stderr || e.message).trim().split("\n");+ console.error(`cannot decode ${path}: ${lines.find((l) => /stream/i.test(l)) || lines[0]} (no audio stream?)`);+ process.exit(1);+ }+ if (buf.length < 8 * SR * 0.4) { console.error(`${path}: no audio stream, or under 400 ms of audio - nothing to meter`); process.exit(1); }+ const f = new Float32Array(buf.buffer, buf.byteOffset, buf.length / 4);+ const n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};++// Independent cross-check: ffmpeg's own ebur128 summary (integrated, LRA, true peak).+const ffmpegEbu = (path) => {+ const r = spawnSync(+ "ffmpeg",+ ["-hide_banner", "-nostats", "-i", path, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"],+ { encoding: "utf8", maxBuffer: 1 << 28 },+ );+ const out = (r.stderr || "") + (r.stdout || "");+ const sum = out.slice(out.lastIndexOf("Summary:"));+ const g = (re) => { const m = re.exec(sum); return m ? Number(m[1]) : NaN; };+ return { I: g(/I:\s+(-?[\d.]+) LUFS/), LRA: g(/LRA:\s+(-?[\d.]+) LU/), TP: g(/Peak:\s+(-?[\d.]+) dBFS/) };+};++// ---------------------------------------------------------------------------+// BS.1770-4 K-weighting: stage 1 high shelf (+4 dB above ~1.7 kHz), stage 2 RLB+// high-pass ~38 Hz (pyloudnorm's closed-form coefficients).+const kWeight = (x, sr) => {+ const out = new Float64Array(x.length);+ {+ const G = 3.999843853973347, Q = 0.7071752369554196, fc = 1681.974450955533;+ const K = Math.tan((Math.PI * fc) / sr), Vh = Math.pow(10, G / 20), Vb = Math.pow(Vh, 0.4996667741545416);+ const a0 = 1 + K / Q + K * K, b0 = (Vh + (Vb * K) / Q + K * K) / a0, b1 = (2 * (K * K - Vh)) / a0,+ b2 = (Vh - (Vb * K) / Q + K * K) / a0, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;+ for (let i = 0; i < x.length; i++) { const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; }+ }+ {+ const fc = 38.13547087602444, Q = 0.5003270373238773, K = Math.tan((Math.PI * fc) / sr);+ const a0 = 1 + K / Q + K * K, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;+ for (let i = 0; i < out.length; i++) { const xi = out[i], y = xi - 2 * x1 + x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = xi; y2 = y1; y1 = y; out[i] = y; }+ }+ return out;+};++const loudness = (chans, sr) => {+ const k = chans.map((c) => kWeight(c, sr)), n = chans[0].length;+ // prefix sums of the channel-summed squared K-weighted signal make every block O(1)+ const ps = new Float64Array(n + 1);+ for (let i = 0; i < n; i++) { let s = 0; for (const c of k) s += c[i] * c[i]; ps[i + 1] = ps[i] + s; }+ const ms = (a, len) => (ps[Math.min(a + len, n)] - ps[a]) / len;+ const lufs = (z) => -0.691 + 10 * Math.log10(Math.max(z, 1e-20));+ // integrated: 400 ms blocks, 75 % overlap (100 ms hop), -70 LUFS absolute + -10 LU relative gates+ const bl = Math.round(0.4 * sr), hop = Math.round(0.1 * sr), blocks = [];+ for (let a = 0; a + bl <= n; a += hop) blocks.push(ms(a, bl));+ const abs = blocks.filter((z) => lufs(z) > -70);+ const rel = lufs(abs.reduce((a, b) => a + b, 0) / Math.max(1, abs.length)) - 10;+ const gated = abs.filter((z) => lufs(z) > rel);+ const integrated = lufs(gated.reduce((a, b) => a + b, 0) / Math.max(1, gated.length));+ // LRA per EBU 3342: 3 s short-term, -70 absolute + -20 LU relative gates, P95 - P10+ const sl = Math.round(3 * sr), st = [];+ for (let a = 0; a + sl <= n; a += hop) st.push(ms(a, sl));+ const stAbs = st.filter((z) => lufs(z) > -70);+ const stRel = lufs(stAbs.reduce((a, b) => a + b, 0) / Math.max(1, stAbs.length)) - 20;+ const stG = stAbs.map(lufs).filter((l) => l > stRel).sort((a, b) => a - b);+ const pct = (p) => (stG.length ? stG[Math.min(stG.length - 1, Math.max(0, Math.round((p / 100) * (stG.length - 1))))] : NaN);+ return { integrated, lra: pct(95) - pct(10), shortMax: st.length ? Math.max(...st.map(lufs)) : NaN };+};++const truePeak = (chans) => {+ // 4x polyphase windowed sinc, 16 taps per phase+ const O = 4, T = 16, h = [];+ for (let ph = 0; ph < O; ph++) {+ const row = [];+ for (let t = 0; t < T; t++) {+ const x = t - T / 2 + 1 - ph / O, w = 0.5 + 0.5 * Math.cos((Math.PI * x) / (T / 2));+ row.push(x === 0 ? 1 : (Math.sin(Math.PI * x) / (Math.PI * x)) * w);+ }+ h.push(row);+ }+ let peak = 0, sample = 0;+ for (const c of chans) for (let i = 0; i < c.length; i++) {+ const a = Math.abs(c[i]); if (a > sample) sample = a;+ if (a < peak * 0.5) continue; // an inter-sample peak cannot exceed ~2x its neighbours here+ for (let ph = 1; ph < O; ph++) {+ let s = 0;+ for (let t = 0; t < T; t++) { const j = i + t - T / 2 + 1; if (j >= 0 && j < c.length) s += c[j] * h[ph][t]; }+ const v = Math.abs(s); if (v > peak) peak = v;+ }+ if (a > peak) peak = a;+ }+ return { dbtp: 20 * Math.log10(Math.max(peak, 1e-12)), samplePeakDb: 20 * Math.log10(Math.max(sample, 1e-12)) };+};++// ---------------------------------------------------------------------------+// Spectral centroid (magnitude-weighted, averaged over non-silent frames).+const fft = (re, im) => {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; } }+ for (let len = 2; len <= n; len <<= 1) {+ const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang);+ for (let i = 0; i < n; i += len) {+ let cr = 1, ci = 0;+ for (let j = 0; j < len / 2; j++) {+ const a = i + j, b = a + len / 2, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr;+ re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi;+ const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;+ }+ }+ }+};+const mono = (chans) => { const n = chans[0].length, m = new Float32Array(n); for (const c of chans) for (let i = 0; i < n; i++) m[i] += c[i] / chans.length; return m; };+const centroid = (chans, sr) => {+ const N = 2048, hop = 512, m = mono(chans);+ const w = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));+ let emax = 0, sum = 0, c = 0, wsum = 0, wtot = 0;+ const frames = [];+ for (let a = 0; a + N <= m.length; a += hop) {+ const re = new Float64Array(N), im = new Float64Array(N);+ for (let i = 0; i < N; i++) re[i] = m[a + i] * w[i];+ fft(re, im);+ const mag = new Float64Array(N / 2 + 1);+ let e = 0;+ for (let k = 0; k <= N / 2; k++) { mag[k] = Math.hypot(re[k], im[k]); e += mag[k] * mag[k]; }+ emax = Math.max(emax, e); frames.push([mag, e]);+ }+ for (const [mag, e] of frames) {+ if (e < emax * 1e-5) continue;+ let num = 0, den = 0;+ for (let k = 1; k < mag.length; k++) { num += ((k * sr) / N) * mag[k]; den += mag[k]; }+ if (den > 0) { sum += num / den; c++; wsum += (num / den) * e; wtot += e; }+ }+ return { mean: c ? sum / c : 0, energyWeighted: wtot ? wsum / wtot : 0 };+};++// ---------------------------------------------------------------------------+// Vocal-masking check (adapted from anidoodle's masking guard): in 500 Hz-4 kHz the+// vocal stem must beat the sum of everything else by >= 3 dB in >= 80 % of the+// seconds where the vocal is active, or the dialogue/vocal is likely masked.+const biquad = (x, b0, b1, b2, a1, a2) => {+ const out = new Float64Array(x.length);+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;+ for (let i = 0; i < x.length; i++) { const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; }+ return out;+};+const bandpass500to4k = (x, sr) => {+ const Q = Math.SQRT1_2;+ const coeffs = (f, hp) => {+ const w0 = (2 * Math.PI * f) / sr, cw = Math.cos(w0), al = Math.sin(w0) / (2 * Q), a0 = 1 + al;+ return hp+ ? [(1 + cw) / 2 / a0, -(1 + cw) / a0, (1 + cw) / 2 / a0, (-2 * cw) / a0, (1 - al) / a0]+ : [(1 - cw) / 2 / a0, (1 - cw) / a0, (1 - cw) / 2 / a0, (-2 * cw) / a0, (1 - al) / a0];+ };+ return biquad(biquad(x, ...coeffs(500, true)), ...coeffs(4000, false));+};+const maskingCheck = (vocalChans, otherChans, sr, { beatDb = 3, activeFloorDb = -50, needShare = 0.8 } = {}) => {+ const v = bandpass500to4k(mono(vocalChans), sr), o = bandpass500to4k(mono(otherChans), sr);+ const n = Math.min(v.length, o.length), secs = Math.floor(n / sr);+ const rmsDb = (x, a, len) => { let s = 0; for (let i = a; i < a + len; i++) s += x[i] * x[i]; return 10 * Math.log10(s / len + 1e-12); };+ let active = 0, clear = 0; const maskedAt = [];+ for (let s = 0; s < secs; s++) {+ const vDb = rmsDb(v, s * sr, sr);+ if (vDb <= activeFloorDb) continue; // vocal not sounding this second+ active++;+ const oDb = rmsDb(o, s * sr, sr);+ if (vDb - oDb >= beatDb) clear++; else maskedAt.push(s);+ }+ const share = active ? clear / active : 1;+ return { active, clear, share, pass: share >= needShare, maskedAt, beatDb, needShare };+};++// ---------------------------------------------------------------------------+const fmt = (x, d = 1) => (Number.isFinite(x) ? x.toFixed(d) : "n/a");+const TARGETS = {+ film: { lufs: -14, tol: 1, tp: -1, label: "mixed film final audio: -14 LUFS +/-1, true peak <= -1 dBTP" },+ dense: { lufs: -14, tol: 1, tp: -1, label: "music master (dense): -14 LUFS +/-1, true peak <= -1 dBTP" },+ gentle: { lufs: -16, tol: 1, tp: -1, label: "music master (gentle): -16 LUFS +/-1, true peak <= -1 dBTP" },+};++const args = process.argv.slice(2);+if (!args.length || args.includes("--help")) {+ console.log("usage: node audio-check.mjs <file...> [--target film|dense|gentle] [--stems vocals.wav other.wav]");+ process.exit(args.length ? 0 : 1);+}+let target = "film"; const files = []; let stems = null;+for (let i = 0; i < args.length; i++) {+ if (args[i] === "--target") target = args[++i];+ else if (args[i] === "--stems") { stems = [args[++i], args[++i]]; }+ else files.push(args[i]);+}+if (!TARGETS[target]) { console.error(`unknown --target "${target}" (film | dense | gentle)`); process.exit(1); }+for (const f of [...files, ...(stems ?? [])]) if (!existsSync(f)) { console.error(`no such file: ${f}`); process.exit(1); }++let anyFail = false, meterBug = false;+for (const file of files) {+ const chans = decode(file), dur = chans[0].length / SR;+ const l = loudness(chans, SR), tp = truePeak(chans), c = centroid(chans, SR), ff = ffmpegEbu(file);+ const t = TARGETS[target];+ const dI = Math.abs(l.integrated - ff.I);+ const agree = Number.isFinite(ff.I) ? dI <= 0.5 : false;+ if (!agree) meterBug = true;++ console.log(`=== ${basename(file)} ===`);+ console.log(`duration ${fmt(dur, 2)} s (decoded to stereo float 48 kHz via ffmpeg)`);+ console.log(`integrated ${fmt(l.integrated)} LUFS ffmpeg ebur128 ${fmt(ff.I)} LUFS delta ${fmt(dI, 2)} LU ${agree ? "AGREE" : "DISAGREE (metering bug, fix before trusting anything)"}`);+ console.log(`LRA ${fmt(l.lra)} LU ffmpeg ${fmt(ff.LRA)} LU`);+ console.log(`true peak ${fmt(tp.dbtp)} dBTP ffmpeg ${fmt(ff.TP)} dBTP sample peak ${fmt(tp.samplePeakDb)} dBFS`);+ console.log(`centroid ${fmt(c.mean, 0)} Hz mean / ${fmt(c.energyWeighted, 0)} Hz energy-weighted`);++ const okL = Math.abs(l.integrated - t.lufs) <= t.tol;+ const okTp = tp.dbtp <= t.tp;+ if (!okL || !okTp) anyFail = true;+ console.log(`--- verdict (${target}: ${t.label}) ---`);+ console.log(`loudness ${okL ? "PASS" : "FAIL"} ${fmt(l.integrated)} LUFS vs ${t.lufs} +/-${t.tol}${okL ? "" : ` -> apply gain ${fmt(t.lufs - l.integrated)} dB (then re-check the peak)`}`);+ console.log(`true peak ${okTp ? "PASS" : "FAIL"} ${fmt(tp.dbtp)} dBTP vs <= ${t.tp} dBTP${okTp ? "" : " -> lower the gain or limit; a hot peak clips on encode"}`);+ console.log("");+}++if (stems) {+ const [vf, of] = stems;+ const mk = maskingCheck(decode(vf), decode(of), SR);+ if (!mk.pass) anyFail = true;+ console.log(`=== vocal masking: ${basename(vf)} vs ${basename(of)} (500 Hz-4 kHz) ===`);+ console.log(`active seconds ${mk.active}, vocal beats the rest by >= ${mk.beatDb} dB in ${mk.clear}/${mk.active} (${fmt(mk.share * 100)} %) ${mk.pass ? "PASS" : "FAIL"} (need >= ${mk.needShare * 100} %)`);+ if (!mk.pass) console.log(`masked at seconds: ${mk.maskedAt.slice(0, 20).join(", ")}${mk.maskedAt.length > 20 ? ", ..." : ""} -> raise the vocal or dip the music 500 Hz-4 kHz under it`);+ console.log("");+}++// Leave through the event loop, never with process.exit() here. On Node 26 an exit taken while one of V8's background threads is+// waiting for a garbage collection deadlocks in shutdown: the numbers are printed, the process never ends, and a shell pipeline+// (or an agent) waits on it for ever. Seen three times in one day on a 74 s file. Setting the exit code and letting a short+// timer run gives the main thread a turn to serve that collection first; the process then ends by itself.+const leave = (code) => { process.exitCode = code; setTimeout(() => {}, 60); };+if (meterBug) { console.log("RESULT: METER DISAGREES WITH FFMPEG (> 0.5 LU) - do not trust these numbers"); leave(2); }+else {+console.log(anyFail ? "RESULT: FAIL" : "RESULT: PASS");+leave(anyFail ? 1 : 0);+}diff --git a/scripts/audit-faces.mjs b/scripts/audit-faces.mjsnew file mode 100644index 0000000..8645d5b--- /dev/null+++ b/scripts/audit-faces.mjs@@ -0,0 +1,22 @@+// Face audit: step through the film and report every overlay that touches the main character's face.+// Contract: after renderFrame(t) the page sets window.__hits (labels of overlays touching the face) and window.__shot.+// See references/pipeline.md (Face audit). Usage: node audit-faces.mjs [portrait 0|1] [step=0.125] env: FILM=film.html+import { chromium } from 'playwright-core';+import { serve } from './serve.mjs';+const portrait = process.argv[2] === '1', step = Number(process.argv[3] || 0.125);+const FILM = process.env.FILM || 'film.html';+const W = portrait ? 1080 : 1920, H = portrait ? 1920 : 1080;+const { srv, url } = await serve('.');+const browser = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=metal', '--ignore-gpu-blocklist'] });+const page = await browser.newPage({ viewport: { width: W, height: H } });+await page.goto(url + '/' + FILM + (portrait ? '?portrait=1' : ''));+await page.waitForFunction(() => typeof window.renderFrame === 'function' && window.READY === true, null, { timeout: 120000 });+const dur = await page.evaluate(() => window.FILM_DURATION);+const res = await page.evaluate(({ dur, step }) => { const out = []; for (let t = 0; t < dur; t += step) { window.renderFrame(t); if (window.__hits.length) out.push([+t.toFixed(3), window.__shot, [...new Set(window.__hits)]]); } return out; }, { dur, step });+await browser.close(); srv.close();+// merge into ranges per shot+element+const ranges = {};+for (const [t, shot, hits] of res) for (const h of hits) { const k = `shot ${String(shot).padStart(2, '0')} · ${h}`; const r = ranges[k] ||= []; const last = r[r.length - 1]; if (last && t - last[1] <= step * 1.5) last[1] = t; else r.push([t, t]); }+const keys = Object.keys(ranges).sort();+console.log(`${portrait ? '9:16' : '16:9'}: ${keys.length ? keys.length + ' face overlaps' : 'no face overlaps'}`);+for (const k of keys) console.log(' ' + k + ' ' + ranges[k].map(([a, b]) => `${a.toFixed(2)}-${b.toFixed(2)}s`).join(', '));diff --git a/scripts/clip.py b/scripts/clip.pynew file mode 100644index 0000000..44fb955--- /dev/null+++ b/scripts/clip.py@@ -0,0 +1,17 @@+#!/usr/bin/env python3+# scripts/clip.py : turn a rendered video clip into frames the film can draw exactly (one picture per film frame, 30 a second).+# Usage (from the film folder): python3 <skill>/scripts/clip.py <clip.mp4> <name> [start seconds=0] [seconds=3] [frame width=1920]+# -> assets/seq/<name>/f000.jpg ... and assets/seq.js (which clips exist and how many frames each has)+import sys, os, subprocess, json, re+if len(sys.argv) < 3: sys.exit('usage (from the film folder): python3 clip.py <clip.mp4> <name> [start seconds=0] [seconds=3] [frame width=1920]')+src, name = sys.argv[1], sys.argv[2]; start = float(sys.argv[3]) if len(sys.argv) > 3 else 0; dur = float(sys.argv[4]) if len(sys.argv) > 4 else 3+WIDE = int(sys.argv[5]) if len(sys.argv) > 5 else 1920 # frame width to keep: more than 1920 when the film crops into the shot (the source must really have it)+d = f'assets/seq/{name}'; os.makedirs(d, exist_ok=True)+for f in os.listdir(d):+ if f.endswith('.jpg'): os.remove(os.path.join(d, f))+# every source frame becomes one film frame (no frame is repeated or dropped), so a 24 fps clip plays a quarter faster and stays perfectly smooth+subprocess.run(['ffmpeg', '-v', 'error', '-y', '-ss', str(start), '-i', src, '-vf', f'scale={WIDE}:{WIDE * 9 // 16}:flags=lanczos', '-fps_mode', 'passthrough', '-frames:v', str(int(round(dur * 30))), '-q:v', '2', '-start_number', '0', f'{d}/f%03d.jpg'], check=True)+n = len([f for f in os.listdir(d) if f.endswith('.jpg')]); mf = 'assets/seq.js'+m = json.loads(re.search(r'window\.SEQ=(\{.*\});', open(mf).read()).group(1)) if os.path.exists(mf) else {}+m[name] = n; open(mf, 'w').write('// written by scripts/clip.py: video clips as frame sequences, name -> number of frames (30 a second)\nwindow.SEQ=' + json.dumps(m) + ';\n')+print(f'{name}: {n} frames -> {d}')diff --git a/scripts/contact-sheet.sh b/scripts/contact-sheet.shnew file mode 100755index 0000000..2d3c77c--- /dev/null+++ b/scripts/contact-sheet.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Reverse-engineer a reference video: a 6x4 contact sheet across its whole length + 3 full frames.+# Usage: contact-sheet.sh <video> [outdir]+v="$1"; o="${2:-./ref-$(basename "${v%.*}")}"; mkdir -p "$o"+d=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$v")+ffmpeg -y -v error -i "$v" -vf "fps=24/$d,scale=480:-1,tile=6x4:padding=4" -frames:v 1 "$o/sheet.png"+for f in 0.15 0.5 0.8; do t=$(python3 -c "print($d*$f)"); ffmpeg -y -v error -ss "$t" -i "$v" -frames:v 1 -vf scale=1280:-1 "$o/frame-$f.png"; done+ffprobe -v error -show_entries stream=width,height,r_frame_rate:format=duration -of default=nw=1 "$v"+echo "wrote $o/sheet.png and 3 frames"diff --git a/scripts/content-box.py b/scripts/content-box.pynew file mode 100644index 0000000..464db6f--- /dev/null+++ b/scripts/content-box.py@@ -0,0 +1,57 @@+#!/usr/bin/env python3+# scripts/content-box.py : where the content of a stretch of footage sits, and the crop that shows all of it with a clear margin.+#+# Use it before cropping any footage that goes inside a frame in the film (a screen recording in a player, a product screen in a+# device, a strip of an earlier film). A crop chosen by eye cuts a card, a panel or a label at the frame's edge sooner or later,+# and a viewer reads that as a mistake. This measures instead.+#+# Usage: python3 <skill>/scripts/content-box.py <video> <start s> <seconds> [options]+# --fit WxH the space the footage must fit in the film, in film pixels (default 1344x598)+# --margin X,Y clear margin to keep round the content, in source pixels (default 60,45)+# --keep Y0-Y1 only look between these source rows (leave out a header row or a caption you will blank) (default: all rows)+# --bg N how bright a pixel must be to count as content, 0 to 255 (default 48: for dark user interfaces;+# for a light ground use --light and it counts pixels darker than 255-N)+# --light the ground is light+# --rest measure only the second half of the stretch (the resting layout), not what flies in+#+# It prints the content box, and one ffmpeg line: pad (when the margin runs past the source's edge), crop and scale. When the+# content is wider than the space, the strip comes out shorter than the space: place it centred, never stretch or cut it.+# A long timeline may run off the edge in a close-up that is moving; a box with a border may not.+import sys, subprocess+import numpy as np++a = sys.argv[1:]+if len(a) < 3: sys.exit('usage: python3 content-box.py <video> <start s> <seconds> [--fit WxH] [--margin X,Y] [--keep Y0-Y1] [--bg N] [--light] [--rest]')+src, ss, ln = a[0], float(a[1]), float(a[2])+def opt(name, default):+ return a[a.index(name) + 1] if name in a else default+FW, FH = (int(v) for v in opt('--fit', '1344x598').lower().split('x'))+MX, MY = (int(v) for v in opt('--margin', '60,45').split(','))+BG = int(opt('--bg', '48')); LIGHT = '--light' in a; REST = '--rest' in a+probe = subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=p=0', src], capture_output=True, text=True).stdout.strip().split(',')+W, H = int(probe[0]), int(probe[1])+K0, K1 = (int(v) for v in opt('--keep', f'0-{H}').split('-'))+raw = subprocess.run(['ffmpeg', '-v', 'error', '-ss', str(ss), '-t', str(ln), '-i', src, '-vf', 'fps=6', '-f', 'rawvideo', '-pix_fmt', 'gray', '-'], capture_output=True).stdout+n = len(raw) // (W * H)+if n == 0: sys.exit('no frames decoded: check the start time and the length')+f = np.frombuffer(raw, dtype=np.uint8).reshape(n, H, W)+if REST: f = f[n // 2:]+m = ((f < 255 - BG) if LIGHT else (f > BG)).any(axis=0); m[:K0] = False; m[K1:] = False+if not m.any(): sys.exit('nothing but ground in that stretch: lower --bg, or check --keep')+ys, xs = np.nonzero(m); x0, x1, y0, y1 = int(xs.min()), int(xs.max()) + 1, int(ys.min()), int(ys.max()) + 1+bw, bh = x1 - x0, y1 - y0+print(f'source {W}x{H}, {len(f)} frames measured{" (resting half)" if REST else ""}')+print(f'content box: x {x0}..{x1} y {y0}..{y1} ({bw} x {bh})')+sw, sh = FW / (bw + 2 * MX), FH / (bh + 2 * MY); s = min(sw, sh) # the scale that fits the content and its margin into the space+if sw <= sh: cw, ch = bw + 2 * MX, bh + 2 * MY # the width decides: the strip comes out shorter than the space+else: ch = bh + 2 * MY; cw = round(FW / s) # the height decides: widen the crop to the space's shape+out_h = min(FH, round(ch * s / 2) * 2)+cx, cy = round((x0 + x1) / 2 - cw / 2), round((y0 + y1) / 2 - ch / 2)+pad_l, pad_r = max(0, -cx), max(0, cx + cw - W); pad_t, pad_b = max(0, -cy), max(0, cy + ch - H)+vf = []+if pad_l or pad_r or pad_t or pad_b: vf.append(f'pad=iw+{pad_l + pad_r}:ih+{pad_t + pad_b}:{pad_l}:{pad_t}:color=black')+vf.append(f'crop={cw}:{ch}:{cx + pad_l}:{cy + pad_t}'); vf.append(f'scale={FW}:{out_h}:flags=lanczos')+print(f'scale {s:.3f}: the content will be {round(bw * s)} x {round(bh * s)} px in a {FW} x {out_h} strip' + (f' (the space is {FW} x {FH}: centre the strip in it)' if out_h < FH else ''))+print('ffmpeg -vf "' + ','.join(vf) + '"')+if cy < K0 or cy + ch > K1: print(f'the crop reaches rows outside --keep ({K0}-{K1}): blank them first, for example drawbox=x=0:y=0:w=iw:h={K0}:color=black:t=fill')+if pad_l or pad_r or pad_t or pad_b: print('the margin runs past the source edge: the pad is black, so draw the strip "lighten" over a dark ground (or pad with the ground colour)')diff --git a/scripts/cutseq.py b/scripts/cutseq.pynew file mode 100644index 0000000..25c42e4--- /dev/null+++ b/scripts/cutseq.py@@ -0,0 +1,24 @@+#!/usr/bin/env python3+# scripts/cutseq.py : a subject cut-out for each of a clip's first frames, so a word can sit BEHIND a person who moves.+# Usage (from the film folder): python3 <skill>/scripts/cutseq.py <name> [frames=15]+# reads assets/seq/<name>/fNNN.jpg (made by scripts/clip.py), writes assets/cut/seq/<name>/fNNN.png (alpha = the subject, scripts/matte.swift; macOS only, compiled on first use)+# and assets/cutseq.js (which clips have cut-outs and for how many frames)+import sys, os, subprocess, json, re+if len(sys.argv) < 2: sys.exit('usage (from the film folder): python3 cutseq.py <name> [frames=15] (macOS only; run clip.py first)')+name = sys.argv[1]; n = int(sys.argv[2]) if len(sys.argv) > 2 else 15+src, dst = f'assets/seq/{name}', f'assets/cut/seq/{name}'; os.makedirs(dst, exist_ok=True)+for f in os.listdir(dst):+ if f.endswith('.png'): os.remove(os.path.join(dst, f))+HERE = os.path.dirname(os.path.abspath(__file__)); MATTE = os.path.join(HERE, 'matte')+if not os.path.exists(MATTE): subprocess.run(['swiftc', '-O', os.path.join(HERE, 'matte.swift'), '-o', MATTE], check=True) # the Mac's own subject cut-out, built once+done = 0+for i in range(n):+ a, b = f'{src}/f{i:03d}.jpg', f'{dst}/f{i:03d}.png'+ if not os.path.exists(a): break+ r = subprocess.run([MATTE, a, b, '1920'], capture_output=True, text=True)+ if r.returncode != 0 or not os.path.exists(b): print('NO CUT-OUT for', a, r.stdout.strip(), r.stderr.strip()[:200]); sys.exit(1)+ done += 1+mf = 'assets/cutseq.js'+m = json.loads(re.search(r'window\.CUTSEQ=(\{.*\});', open(mf).read()).group(1)) if os.path.exists(mf) else {}+m[name] = done; open(mf, 'w').write('// written by scripts/cutseq.py: clips that have a subject cut-out for their first frames, name -> number of frames\nwindow.CUTSEQ=' + json.dumps(m) + ';\n')+print(f'{name}: {done} cut-outs -> {dst}')diff --git a/scripts/doctor.sh b/scripts/doctor.shnew file mode 100755index 0000000..79aae32--- /dev/null+++ b/scripts/doctor.sh@@ -0,0 +1,24 @@+#!/bin/bash+# scripts/doctor.sh : check that this machine has what Take One needs, and say what each missing piece is for.+# Usage: bash <skill>/scripts/doctor.sh exit 0 = ready for the code-only route; 1 = something required is missing+ok() { printf " ok %-18s %s\n" "$1" "$2"; }+miss() { printf " MISSING %-18s %s\n" "$1" "$2"; }+opt() { printf " optional %-18s %s\n" "$1" "$2"; }+need=0+echo "Take One: machine check"+echo "Required (every film):"+if command -v node >/dev/null 2>&1; then v=$(node -p "process.versions.node.split('.')[0]"); if [ "$v" -ge 18 ]; then ok node "$(node -v)"; else miss node "found $(node -v), needs 18 or later"; need=1; fi; else miss node "install Node 18 or later (nodejs.org)"; need=1; fi+command -v npm >/dev/null 2>&1 && ok npm "$(npm -v)" || { miss npm "comes with Node; each film project installs playwright-core with it"; need=1; }+command -v ffmpeg >/dev/null 2>&1 && ok ffmpeg "$(ffmpeg -version 2>/dev/null | head -1 | cut -d' ' -f3)" || { miss ffmpeg "joins the frames and mixes the sound (macOS: brew install ffmpeg)"; need=1; }+command -v ffprobe >/dev/null 2>&1 && ok ffprobe "" || { miss ffprobe "ships with ffmpeg"; need=1; }+if [ -d "/Applications/Google Chrome.app" ] || command -v google-chrome >/dev/null 2>&1 || command -v google-chrome-stable >/dev/null 2>&1 || [ -f "/c/Program Files/Google/Chrome/Application/chrome.exe" ]; then ok "Google Chrome" "draws every frame"; else miss "Google Chrome" "the frames are drawn in Chrome; install it (google.com/chrome)"; need=1; fi+echo "Optional (only some films):"+if command -v python3 >/dev/null 2>&1; then ok python3 "$(python3 -V 2>&1 | cut -d' ' -f2)"+ python3 -c "import numpy, scipy" 2>/dev/null && ok "numpy + scipy" "mapping a music track (songmap.py)" || opt "numpy + scipy" "needed to map a music track you cannot hear: python3 -m pip install numpy scipy"+else opt python3 "needed for music mapping, voice cutting and video clips (songmap.py, vo.py, clip.py)"; fi+command -v whisper-cli >/dev/null 2>&1 && ok whisper-cli "checks that each cut voice line says its text" || opt whisper-cli "checks a recorded voice against the script (whisper.cpp); without it, voice lines are placed unchecked"+if [ "$(uname)" = "Darwin" ]; then command -v swift >/dev/null 2>&1 && ok swift "cut-outs, for type behind a person (matte.swift)" || opt swift "needed for cut-outs (type behind a person); comes with Xcode command line tools"+else opt swift "cut-outs (type behind a person) work on macOS only; other routes are unaffected"; fi+echo "Not checked here: paid services (pictures, video, voice, music). The skill asks before it uses any, and works without them."+[ $need -eq 0 ] && echo "Ready: the code-only route will run on this machine." || echo "Not ready: install what is marked MISSING, then run this again."+exit $needdiff --git a/scripts/export.mjs b/scripts/export.mjsnew file mode 100644index 0000000..b33c5bd--- /dev/null+++ b/scripts/export.mjs@@ -0,0 +1,36 @@+// Export film.html to MP4 frame by frame via window.renderFrame(t).+// Usage: node export.mjs [fps=60] [out=film.mp4] env: FILM=film.html W=1920 H=1080 SLOW=1 (time-stretch)+// START/END (seconds, output time): render only that range, for re-rendering changed shots and splicing (see pipeline.md)+// SUB=N: subframe motion blur. Renders N subframes per output frame (t + k/(fps*N), k=0..N-1) and averages them+// in ffmpeg (tmix). Default off (1). SUB=8 for the final master of smooth-motion styles; never for stepped+// art (pixel, pencil test, crayon boil), where the hold IS the look. Costs N x the render time.+// ALPHA=1: the page draws a transparent overlay (HUD) instead of a full frame; writes ProRes 4444 with alpha (use out=hud.mov)+// then composite: ffmpeg -i footage.mp4 -i hud.mov -filter_complex overlay -c:v libx264 -crf 14 -pix_fmt yuv420p final.mp4+import { chromium } from 'playwright-core';+import { spawn } from 'node:child_process';+import { serve } from './serve.mjs';+const fps = Number(process.argv[2] || 60), out = process.argv[3] || 'film.mp4';+const W = Number(process.env.W || 1920), H = Number(process.env.H || 1080), SLOW = Number(process.env.SLOW || 1);+const SUB = Math.max(1, Math.round(Number(process.env.SUB || 1)));+const FILM = process.env.FILM || 'film.html';+const { srv, url } = await serve('.');+const browser = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=metal', '--ignore-gpu-blocklist'] });+const page = await browser.newPage({ viewport: { width: W, height: H } });+await page.goto(url + '/' + FILM + (H > W ? '?portrait=1' : ''));+await page.waitForFunction(() => typeof window.renderFrame === 'function' && window.READY === true, null, { timeout: 120000 });+const duration = await page.evaluate(() => window.FILM_DURATION || 30);+const T0 = Number(process.env.START || 0), T1 = Number(process.env.END || duration * SLOW);+const f0 = Math.round(T0 * fps), frames = Math.round(T1 * fps);+const enc = process.env.ALPHA ? ['-c:v', 'prores_ks', '-profile:v', '4444', '-pix_fmt', 'yuva444p10le'] : ['-c:v', 'libx264', '-preset', 'slow', '-crf', '14', '-pix_fmt', 'yuv420p', '-movflags', '+faststart'];+// SUB > 1: input runs at fps*SUB; tmix averages each run of SUB, select keeps the last of each group (= one whole group), setpts re-times to fps+const blur = SUB > 1 ? `tmix=frames=${SUB},select='eq(mod(n\\,${SUB})\\,${SUB - 1})',setpts=N/(${fps}*TB),` : '';+const ff = spawn('ffmpeg', ['-y', '-f', 'image2pipe', '-framerate', String(fps * SUB), '-i', '-', '-vf', `${blur}scale=${W}:${H}:flags=lanczos`, '-r', String(fps), ...enc, out], { stdio: ['pipe', 'ignore', 'inherit'] });+for (let i = f0; i < frames; i++) {+ for (let k = 0; k < SUB; k++) {+ const b64 = await page.evaluate(async (t) => { await window.renderFrame(t); const c = [...document.querySelectorAll('canvas')].sort((a, b) => b.width * b.height - a.width * a.height)[0]; return c.toDataURL('image/png').split(',')[1]; }, (i + k / SUB) / fps / SLOW);+ if (!ff.stdin.write(Buffer.from(b64, 'base64'))) await new Promise(r => ff.stdin.once('drain', r));+ }+ if (i % fps === 0) process.stdout.write(`\r${(i / fps).toFixed(0)}s / ${(duration * SLOW).toFixed(1)}s${SUB > 1 ? ` (SUB=${SUB})` : ''}`);+}+ff.stdin.end(); await new Promise(r => ff.on('close', r)); await browser.close(); srv.close();+console.log(`\nwrote ${out}`);diff --git a/scripts/frames.mjs b/scripts/frames.mjsnew file mode 100644index 0000000..52efd11--- /dev/null+++ b/scripts/frames.mjs@@ -0,0 +1,26 @@+// Render review frames of film.html (served over local http) + a contact sheet.+// Usage: node frames.mjs <portrait 0|1> <t1,t2,...> env: FILM=film.html W=1920 H=1080+import { chromium } from 'playwright-core';+import fs from 'node:fs';+import { execFileSync } from 'node:child_process';+import { serve } from './serve.mjs';+const portrait = process.argv[2] === '1';+const times = (process.argv[3] || '0,1,2,3,4,5').split(',').map(Number);+const FILM = process.env.FILM || 'film.html';+const W = Number(process.env.W || (portrait ? 1080 : 1920)), H = Number(process.env.H || (portrait ? 1350 : 1080));+const dir = (FILM === 'film.html' ? 'review/' : 'review-' + FILM.replace('.html', '') + '/') + (portrait ? 'portrait' : 'square');+fs.mkdirSync(dir, { recursive: true });+const { srv, url } = await serve('.');+const browser = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=metal', '--ignore-gpu-blocklist'] });+const page = await browser.newPage({ viewport: { width: W, height: H } });+const errs = []; page.on('pageerror', e => errs.push(e.message)); page.on('console', m => { if (m.type() === 'error') errs.push(m.text()); });+await page.goto(url + '/' + FILM + (portrait ? '?portrait=1' : ''));+await page.waitForFunction(() => typeof window.renderFrame === 'function' && window.READY === true, null, { timeout: 120000 });+for (const t of times) {+ const b64 = await page.evaluate(async (t) => { await window.renderFrame(t); const c = [...document.querySelectorAll('canvas')].sort((a, b) => b.width * b.height - a.width * a.height)[0]; return c.toDataURL('image/png').split(',')[1]; }, t);+ fs.writeFileSync(`${dir}/t${t.toFixed(2).padStart(5, '0')}.png`, Buffer.from(b64, 'base64'));+}+await browser.close(); srv.close();+const cols = 6, rows = Math.max(1, Math.ceil(fs.readdirSync(dir).filter(f => /^t.*\.png$/.test(f)).length / cols)); // grid grows with the frame count (a fixed 6x4 dropped frames past 24)+execFileSync('ffmpeg', ['-y', '-loglevel', 'error', '-pattern_type', 'glob', '-i', `${dir}/t*.png`, '-vf', `scale=360:-1,tile=${cols}x${rows}:padding=6:color=gray`, '-frames:v', '1', `${dir}/sheet.png`]);+console.log(errs.length ? 'CONSOLE ERRORS:\n' + errs.join('\n') : 'no console errors', '\nframes + sheet:', dir);diff --git a/scripts/gate.mjs b/scripts/gate.mjsnew file mode 100644index 0000000..b73cfc8--- /dev/null+++ b/scripts/gate.mjs@@ -0,0 +1,383 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+//+// RENDER QUALITY GATE for take-one films (film.html exposing window.renderFrame(t), a pure+// function of time t in seconds, seeded randomness only). Run it BEFORE showing the user anything.+//+// node gate.mjs <film.html> [--duration S] [--samples 12] [--mp4 out.mp4] [--holds "1.5-3,10-12"] [--cuts "4.5,9"] [--footage "13-18.5@30"]+// node gate.mjs --self-test+//+// 1 DETERMINISM ~12 sampled frames (0, last, evenly spread) drawn forward on one COLD page,+// then in REVERSE on a warmed page. md5 of the pixels must match; PSNR > 45 dB+// is accepted as a fallback (GPU anti-aliasing wobbles a little). On failure it+// runs the poisoning diagnosis: the bad frame is redrawn cold, then after each+// other sample frame in a fresh page, and the frame that changes it is NAMED+// ("ORDER-DEPENDENT: drawing frame X first changes frame Y" = a stale cache or+// state one frame leaves behind for the next).+// 2 CONTRACT a static scan of film.html plus every local <script src> it loads, comments+// stripped: Math.random, Date.now, new Date, performance.now, canvas .filter+// effects, localStorage, and any seed derived from a clock all FAIL. Exemptions,+// because they are part of this skill's own contract: a clock on the same line as+// requestAnimationFrame or navigator.webdriver (the browser preview loop; timing+// belongs to hosts), and `.filter = 'none'` (the per-frame reset from pipeline.md).+// fetch()/new Image/OffscreenCanvas are WARNED with their lines: legal for asset+// setup that finishes before READY, never in the draw path.+// 3 DEAD AIR only with --mp4 (the gate only READS the file): frames decoded small (270 px)+// and grey; a pixel counts as changed above 4/255. Identical consecutive frames+// FAIL, and so does any half-second window whose max changed area is under 0.5%,+// unless inside declared holds (--holds in seconds, or window.HOLDS = [[a,b],...]).+// 4 POPS only with --mp4: the mean frame difference of every frame against the median of its+// 6 neighbours (3 each side). A frame that jumps more than 3x its neighbours (and more+// than 2/255 on average) is a pop: a hard cut, a one-frame flash, a flood that reads as a+// flash, an element that appears with no ease. Each is LISTED with its time. Intentional+// cuts are declared (--cuts "4.5,9" in seconds, or window.CUTS = [4.5, 9]) and pass;+// every undeclared spike FAILS, so it gets explained or fixed.+// Footage that plays inside the film at a lower frame rate than the film (a 30 fps clip in a+// 60 fps film) holds each of its frames for two or more of ours, so every new footage frame+// would read as a pop. Declare it: window.FOOTAGE = [[from, to, fps], ...] (seconds, the clip's+// own frame rate) or --footage "13-18.5@30". Inside those ranges the change is measured once per+// footage frame; cuts inside the footage are still found and still need declaring.+//+// Duration: --duration, else window.FILM_DURATION, else window.DURATION, else 30 s with a note.+// Dependencies: ffmpeg + ffprobe on PATH. playwright-core is resolved from, in order:+// $PLAYWRIGHT_NODE_MODULES (a node_modules dir), a node_modules symlink beside this script+// (scripts/node_modules -> any project's node_modules that has playwright-core),+// ./node_modules of the cwd (the film project's own install), then normal resolution.+// Env: W/H viewport (default 1920x1080; H > W adds ?portrait=1), GATE_TMP for scratch files.+// Exit: 0 pass, 1 fail, 2 could not run.+import { createHash } from 'node:crypto';+import { spawn, spawnSync, execFileSync } from 'node:child_process';+import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';+import fs from 'node:fs';+import http from 'node:http';+import os from 'node:os';+import path from 'node:path';++const SELF = fileURLToPath(import.meta.url);+const VAL = new Set(['duration', 'samples', 'mp4', 'holds', 'cuts', 'footage']);+const pos = [], opt = {};+for (let i = 2; i < process.argv.length; i++) { const a = process.argv[i]; if (a.startsWith('--')) opt[a.slice(2)] = VAL.has(a.slice(2)) ? process.argv[++i] : true; else pos.push(a); }+const W = Number(process.env.W || 1920), H = Number(process.env.H || 1080);+const SAMPLES = Math.max(4, Number(opt.samples ?? 12));+const TMP = path.join(process.env.GATE_TMP || os.tmpdir(), `gate-${process.pid}`);++let fails = 0, checks = 0;+const say = (ok, label, detail = '') => { checks++; if (!ok) fails++; console.log(` ${ok ? 'PASS' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); };+const note = (label, detail = '') => console.log(` ---- ${label}${detail ? ' ' + detail : ''}`);+const head = (n, t) => console.log(`\n${n}. ${t}\n${'-'.repeat(58)}`);+const fmt = (t) => String(+t.toFixed(2));+const md5 = (b) => createHash('md5').update(b).digest('hex');++const loadChromium = () => {+ const roots = [process.env.PLAYWRIGHT_NODE_MODULES, path.join(path.dirname(SELF), 'node_modules'), path.join(process.cwd(), 'node_modules')].filter(Boolean);+ for (const r of roots) { try { return createRequire(path.join(r, 'x.cjs'))('playwright-core').chromium; } catch { /* next */ } }+ try { return createRequire(SELF)('playwright-core').chromium; } catch { /* fall through */ }+ console.error('gate: playwright-core not found. Run the gate from a film project folder (new-canvas-project.sh installs it there), or run "npm install" once in the skill folder, or set PLAYWRIGHT_NODE_MODULES=/path/to/node_modules.');+ process.exit(2);+};++// tiny static server: canvas reading local images needs http, not file:// (taint)+const TYPES = { '.html': 'text/html', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.js': 'text/javascript', '.svg': 'image/svg+xml', '.css': 'text/css', '.json': 'application/json', '.woff2': 'font/woff2' };+const serve = (root) => new Promise((res) => {+ const base = path.resolve(root);+ const srv = http.createServer((req, r) => {+ // only files inside the film folder: a path that climbs out of it with ../ is refused+ let p = ''; try { p = path.join(base, decodeURIComponent(req.url.split('?')[0])); } catch {}+ if (p !== base && !p.startsWith(base + path.sep)) { r.writeHead(403); r.end(); return; }+ fs.readFile(p, (e, d) => { if (e) { r.writeHead(req.url === '/favicon.ico' ? 204 : 404); r.end(); return; } r.writeHead(200, { 'Content-Type': TYPES[path.extname(p).toLowerCase()] || 'application/octet-stream' }); r.end(d); });+ }).listen(0, '127.0.0.1', () => res({ srv, url: `http://127.0.0.1:${srv.address().port}` }));+});++// ---------------------------------------------------------------- browser sessions+const openFilm = async (browser, url) => {+ const errs = [], page = await browser.newPage({ viewport: { width: W, height: H } });+ page.on('pageerror', (e) => errs.push(e.message));+ page.on('console', (m) => { if (m.type() === 'error' && !/favicon/.test(m.location()?.url ?? '')) errs.push(m.text()); }); // a favicon 404 is harmless (pipeline.md)+ await page.goto(url);+ await page.waitForFunction(() => typeof window.renderFrame === 'function' && window.READY === true, null, { timeout: 120000 });+ // stop any preview loop so it cannot race our draws; the gate drives renderFrame itself+ await page.evaluate(() => { window.requestAnimationFrame = () => 0; });+ await page.waitForTimeout(50);+ return { page, errs };+};+const drawPng = async (page, t) => Buffer.from(await page.evaluate(async (t) => {+ await window.renderFrame(t);+ const c = [...document.querySelectorAll('canvas')].sort((a, b) => b.width * b.height - a.width * a.height)[0];+ return c.toDataURL('image/png').split(',')[1];+}, t), 'base64');++const psnr = (a, b) => {+ const r = spawnSync('ffmpeg', ['-v', 'error', '-i', a, '-i', b, '-lavfi', 'psnr=stats_file=-', '-f', 'null', '-'], { encoding: 'utf8' });+ const m = (r.stdout + r.stderr).match(/psnr_avg:([0-9.]+|inf)/);+ return m ? (m[1] === 'inf' ? Infinity : Number(m[1])) : NaN;+};++// ---------------------------------------------------------------- 1. determinism, two ways round+const determinism = async (browser, base, film) => {+ head(1, 'DETERMINISM the same t, drawn two different ways, is the same frame');+ const url = base + '/' + film + (H > W ? '?portrait=1' : '');+ const s1 = await openFilm(browser, url); // COLD: no draws before the forward pass+ let D = opt.duration ? Number(opt.duration) : await s1.page.evaluate(() => window.FILM_DURATION ?? window.DURATION ?? null);+ if (D == null) { D = 30; note('no --duration and no window.FILM_DURATION/DURATION', 'sampling t in [0, 30]'); }+ const pageHolds = await s1.page.evaluate(() => (Array.isArray(window.HOLDS) ? window.HOLDS : null));+ const pageCuts = await s1.page.evaluate(() => (Array.isArray(window.CUTS) ? window.CUTS : null));+ const pageFootage = await s1.page.evaluate(() => (Array.isArray(window.FOOTAGE) ? window.FOOTAGE : null));+ const GRID = 30, lastT = Math.max(0, D - 1 / GRID);+ const times = [...new Set(Array.from({ length: SAMPLES }, (_, i) => Math.round((lastT * i) / (SAMPLES - 1) * GRID) / GRID))];+ const p1 = [], h1 = [];+ for (const t of times) { const png = await drawPng(s1.page, t); p1.push(png); h1.push(md5(png)); } // forward, cold+ await s1.page.close();++ const s2 = await openFilm(browser, url); // WARMED: draw mid + last before the reversed pass+ await drawPng(s2.page, times[times.length >> 1]); await drawPng(s2.page, times[times.length - 1]);+ const p2 = new Array(times.length), h2 = new Array(times.length);+ for (let i = times.length - 1; i >= 0; i--) { const png = await drawPng(s2.page, times[i]); p2[i] = png; h2[i] = md5(png); } // reversed+ await s2.page.close();++ const same = times.filter((_, i) => h1[i] === h2[i]).length;+ if (same === times.length) say(true, `${times.length} sampled frames hash-identical, cold-forward vs warmed-reverse`, `t ${fmt(times[0])}..${fmt(times[times.length - 1])}s`);+ else {+ fs.mkdirSync(TMP, { recursive: true });+ let worst = Infinity;+ for (let i = 0; i < times.length; i++) {+ if (h1[i] === h2[i]) continue;+ const a = path.join(TMP, `a-t${fmt(times[i])}.png`), b = path.join(TMP, `b-t${fmt(times[i])}.png`);+ fs.writeFileSync(a, p1[i]); fs.writeFileSync(b, p2[i]);+ const v = psnr(a, b); worst = Math.min(worst, v);+ console.log(` t=${fmt(times[i])}s: hashes differ, PSNR ${v === Infinity ? 'inf' : v.toFixed(2)} dB (pngs kept in ${TMP})`);+ }+ say(worst > 45, `${times.length - same} differing frame(s) within PSNR tolerance (> 45 dB)`, `min PSNR ${worst === Infinity ? 'inf' : worst.toFixed(2)} dB`);+ // POISONING DIAGNOSIS. A failure is only useful if it says WHERE to look: redraw the bad+ // frame cold, then after each other sample frame in a fresh page, and name the poisoner.+ const bad = times.find((_, i) => h1[i] !== h2[i]);+ const coldHash = async (pre) => { const s = await openFilm(browser, url); if (pre != null) await drawPng(s.page, pre); const h = md5(await drawPng(s.page, bad)); await s.page.close(); return h; };+ const c1 = await coldHash(null), c2 = await coldHash(null);+ if (c1 !== c2) console.log(worst > 45+ ? ` DIAGNOSIS: t=${fmt(bad)}s differs even cold-vs-cold, but far above 45 dB: GPU raster\n wobble (a few anti-aliased pixels), not an ordering bug. Within tolerance.`+ : ` DIAGNOSIS: t=${fmt(bad)}s is NONDETERMINISTIC even cold-vs-cold: unseeded randomness\n (Math.random or a clock) in the draw path, not an ordering bug.`);+ else {+ const culprits = [];+ for (const pre of times.filter((t) => t !== bad)) if ((await coldHash(pre)) !== c1) culprits.push(pre);+ console.log(culprits.length+ ? ` DIAGNOSIS: ORDER-DEPENDENT: drawing frame t=${culprits.map(fmt).join('s, t=')}s first changes frame t=${fmt(bad)}s.\n That is a stale cache (a key that does not name everything the pixels\n depend on) or state one frame leaves behind for the next.${worst > 45 ? '\n (Above 45 dB the difference is invisible: a note, not a failure.)' : ''}`+ : ` DIAGNOSIS: t=${fmt(bad)}s is stable within a session; the difference is between sessions\n (a load-time random, or GPU raster wobble; see the PSNR above).`);+ }+ }+ if (s1.errs.length || s2.errs.length) say(false, 'no console errors while drawing', [...new Set([...s1.errs, ...s2.errs])].slice(0, 3).join(' | '));+ else say(true, 'no console errors while drawing');+ return { D, pageHolds, pageCuts, pageFootage };+};++// ---------------------------------------------------------------- 2. the contract, statically+// preserve line numbers: block/HTML comments become newlines, line comments are cut per line+const strip = (s) => s.replace(/<!--[\s\S]*?-->/g, (m) => m.replace(/[^\n]/g, ' ')).replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/(^|[^:"'`])\/\/.*$/gm, '$1');+const CLOCK_HOST_OK = /requestAnimationFrame|navigator\.webdriver/; // the preview loop; timing belongs to hosts+const RULES = [+ { re: /Math\.random/, label: 'Math.random', fix: 'use a seeded rng(i)' },+ { re: /\bDate\.now\b/, label: 'Date.now', clock: true },+ { re: /\bnew Date\b/, label: 'new Date', clock: true },+ { re: /performance\.now/, label: 'performance.now', clock: true },+ { re: /\.filter\s*=(?!=)(?!\s*['"`]none)/, label: "canvas .filter effect (non-'none' assignment)", fix: "only .filter='none' (the reset) is allowed" },+ { re: /\blocalStorage\b/, label: 'localStorage' },+];+const WARN_RULES = [+ { re: /\bfetch\s*\(/, label: 'fetch()' },+ { re: /\bnew Image\b/, label: 'new Image' },+ { re: /\bOffscreenCanvas\b/, label: 'OffscreenCanvas' },+];+const contractScan = (filmPath) => {+ head(2, 'CONTRACT the draw path cannot reach a clock, chance or storage');+ const html = fs.readFileSync(filmPath, 'utf8');+ const files = [[filmPath, html]];+ for (const m of html.matchAll(/<script[^>]*\bsrc=["']([^"':]+)["']/g)) {+ const p = path.join(path.dirname(filmPath), m[1]);+ if (fs.existsSync(p)) files.push([p, fs.readFileSync(p, 'utf8')]);+ }+ const hits = [], warns = [], hostClocks = []; let rngSites = 0; const badSeeds = [];+ for (const [f, raw] of files) {+ const rel = path.basename(f), lines = strip(raw).split('\n');+ lines.forEach((line, i) => {+ for (const r of RULES) if (r.re.test(line)) {+ if (r.clock && CLOCK_HOST_OK.test(line)) { hostClocks.push(`${rel}:${i + 1} ${r.label}`); continue; }+ hits.push(`${rel}:${i + 1}: ${r.label}${r.fix ? ` (${r.fix})` : ''}`);+ }+ for (const r of WARN_RULES) if (r.re.test(line)) warns.push(`${rel}:${i + 1}: ${r.label}`);+ if (/\b(seed|rng)\w*\s*[=(][^;\n]{0,60}?(Date\.now|performance\.now|new Date)/i.test(line)) badSeeds.push(`${rel}:${i + 1}`);+ rngSites += (line.match(/\b(rng|rnd|rand|hash\d?)\s*\(/g) ?? []).length;+ });+ }+ say(hits.length === 0, `no forbidden call in ${files.length} file(s) (${files.map(([f]) => path.basename(f)).join(', ')})`, hits.slice(0, 8).join(' | '));+ say(badSeeds.length === 0, `randomness is seeded: ${rngSites} rng()/rand()/hash() call sites`, badSeeds.length ? `seed derived from a clock at ${badSeeds.join(', ')}` : 'no seed derived from a clock');+ if (hostClocks.length) note('host clock in the preview loop (allowed)', hostClocks.slice(0, 4).join(' | '));+ if (warns.length) note(`warn: ${warns.length} setup-time load(s): legal only before READY, never in the draw path`, warns.slice(0, 6).join(' | '));+};++// ---------------------------------------------------------------- 3. dead air, on the real MP4+const parseHolds = (s) => (s ? s.split(',').map((r) => r.split('-').map(Number)) : []);+const changedSeries = async (mp4) => {+ const j = JSON.parse(execFileSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height,r_frame_rate', '-of', 'json', mp4], { encoding: 'utf8' })).streams[0];+ const [num, den] = j.r_frame_rate.split('/').map(Number), fps = num / (den || 1);+ const w = 270, h = Math.max(2, Math.round((j.height * w) / j.width / 2) * 2);+ const ff = spawn('ffmpeg', ['-v', 'error', '-i', mp4, '-vf', `scale=${w}:${h}:flags=area,format=gray`, '-f', 'rawvideo', '-']);+ const chunks = []; ff.stdout.on('data', (d) => chunks.push(d));+ await new Promise((res, rej) => { ff.on('close', (c) => (c ? rej(new Error('ffmpeg decode failed')) : res())); });+ const buf = Buffer.concat(chunks), size = w * h, n = Math.floor(buf.length / size);+ const changed = [0], diff = [0]; // changed[f] = fraction of pixels that moved > 4/255 between frame f-1 and f; diff[f] = mean |delta| in 0..255+ for (let f = 1; f < n; f++) {+ let c = 0, sum = 0; const a = (f - 1) * size, b = f * size;+ for (let i = 0; i < size; i++) { const d = Math.abs(buf[a + i] - buf[b + i]); sum += d; if (d > 4) c++; }+ changed.push(c / size); diff.push(sum / size);+ }+ // stillness is judged over a fixed slice of time (1/30 s), not one frame: the same film must get the same answer at 30 and at 60 fps+ const step = Math.max(1, Math.round(fps / 30)), moved = [];+ for (let f = 0; f < n; f++) {+ if (f < step) { moved.push(changed[f] || 0); continue; }+ let c = 0; const a = (f - step) * size, b = f * size;+ for (let i = 0; i < size; i++) if (Math.abs(buf[a + i] - buf[b + i]) > 4) c++;+ moved.push(c / size);+ }+ return { changed, moved, step, diff, fps, n };+};+const deadAir = async (s, holds) => {+ head(3, 'DEAD AIR something visibly moves in every half second');+ const { fps, n } = s, changed = s.moved; // per 1/30 s, see changedSeries+ const inHold = (f) => holds.some(([a, b]) => f / fps >= a - 1e-6 && f / fps <= b + 1e-6);+ if (holds.length) note(`declared holds: ${holds.map(([a, b]) => `${a}-${b}s`).join(', ')}`);+ const still = []; for (let f = s.step; f < n; f++) if (changed[f] === 0 && !(inHold(f) && inHold(f - 1))) still.push(f);+ say(still.length === 0, 'no unexplained identical frames 1/30 s apart', still.length ? `frames ${still.slice(0, 12).join(', ')}${still.length > 12 ? ` +${still.length - 12} more` : ''} (t≈${(still[0] / fps).toFixed(2)}s on)` : `${n} frames at ${fps} fps`);+ const win = Math.max(2, Math.round(fps / 2)), flat = [];+ for (let f = 1; f + win <= n; f++) {+ let m = 0; for (let k = f; k < f + win; k++) m = Math.max(m, changed[k]);+ if (m < 0.005 && !Array.from({ length: win }, (_, k) => f + k).every(inHold)) flat.push(f);+ }+ const merged = []; flat.forEach((f) => { const l = merged[merged.length - 1]; if (l && f <= l[1]) l[1] = f + win; else merged.push([f, f + win]); });+ say(merged.length === 0, `no ${win}-frame (half-second) window under 0.5% changed area`, merged.map(([a, b]) => `${(a / fps).toFixed(2)}-${(b / fps).toFixed(2)}s`).join(', ') || 'none');+ const mv = changed.slice(1).sort((a, b) => a - b);+ note(`${n} frames measured`, `median changed ${((mv[mv.length >> 1] ?? 0) * 100).toFixed(2)}% min ${((mv[0] ?? 0) * 100).toFixed(2)}%`);+};++// ---------------------------------------------------------------- 4. pops, on the real MP4+const popScan = (diff, fps, n) => {+ const spikes = [];+ for (let f = 1; f < n; f++) {+ const nb = []; for (let k = f - 3; k <= f + 3; k++) if (k !== f && k >= 1 && k < n) nb.push(diff[k]);+ nb.sort((a, b) => a - b);+ const ref = Math.max(0.5, nb.length ? (nb[(nb.length - 1) >> 1] + nb[nb.length >> 1]) / 2 : 0);+ if (diff[f] > 2 && diff[f] > 3 * ref) spikes.push({ f, t: f / fps, ratio: diff[f] / ref, d: diff[f] });+ }+ return spikes;+};+// footage at a lower frame rate: each of its frames is held for `hold` of ours, so the change is taken once per footage frame (a sliding max)+const footageDiff = (diff, fps, n, footage) => {+ const out = diff.slice();+ for (const [a, b, ffps] of footage) { const hold = Math.round(fps / ffps); if (!(hold > 1)) continue;+ for (let f = Math.max(1, Math.ceil(a * fps)); f < Math.min(n, Math.floor(b * fps)); f++) { let m = 0; for (let k = f - hold + 1; k <= f; k++) if (k >= 1) m = Math.max(m, diff[k]); out[f] = m; } }+ return out;+};+const pops = (s, cuts, footage = []) => {+ head(4, 'POPS no frame jumps 3x more than its neighbours unless it is a declared cut');+ const { fps, n } = s, diff = footage.length ? footageDiff(s.diff, fps, n, footage) : s.diff, spikes = popScan(diff, fps, n);+ if (footage.length) note(`declared footage: ${footage.map(([a, b, r]) => `${a}-${b}s at ${r} fps`).join(', ')}`);+ if (cuts.length) note(`declared cuts: ${cuts.map((c) => `${c}s`).join(', ')}`);+ const inFoot = (f) => footage.find(([a, b]) => f / fps >= a && f / fps < b);+ const declared = (sp) => { const ft = inFoot(sp.f), tol = ft ? Math.round(fps / ft[2]) + 0.01 : 1.01; return cuts.some((c) => Math.abs(c * fps - sp.f) <= tol); }; // the cut frame, one either side (one footage frame either side inside footage)+ const line = (sp) => `t=${sp.t.toFixed(2)}s (frame ${sp.f}, ${sp.ratio.toFixed(1)}x neighbours, mean diff ${sp.d.toFixed(1)}/255)`;+ const ok = spikes.filter(declared), bad = spikes.filter((sp) => !declared(sp));+ ok.forEach((sp) => note('declared cut', line(sp)));+ bad.forEach((sp) => console.log(` pop ${line(sp)}`));+ say(bad.length === 0, `no undeclared frame-difference spikes (> 3x neighbours)`, bad.length ? `${bad.length} pop(s): explain each as a cut (--cuts / window.CUTS) or fix it (ease it, stretch the flood, carry an element across)` : `${spikes.length} spike(s), all declared cuts`);+};++// ---------------------------------------------------------------- run+const run = async () => {+ const filmPath = path.resolve(pos[0] ?? '');+ if (!pos[0] || !fs.existsSync(filmPath)) { console.error('usage: node gate.mjs <film.html> [--duration S] [--samples 12] [--mp4 out.mp4] [--holds "1-3,10-12"] [--cuts "4.5,9"]\n node gate.mjs --self-test'); process.exit(2); }+ console.log(`QUALITY GATE ${filmPath} viewport ${W}x${H}`);+ const chromium = loadChromium();+ const { srv, url } = await serve(path.dirname(filmPath));+ const browser = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=metal', '--ignore-gpu-blocklist'] });+ try {+ const { pageHolds, pageCuts, pageFootage } = await determinism(browser, url, path.basename(filmPath));+ contractScan(filmPath);+ const mp4 = opt.mp4 && path.resolve(opt.mp4);+ let s = null;+ if (mp4 && !fs.existsSync(mp4)) say(false, 'an MP4 to measure', `${mp4} not found`);+ else if (mp4) { try { s = await changedSeries(mp4); } catch (e) { say(false, 'decode MP4', e.message); } }+ if (s) {+ await deadAir(s, parseHolds(opt.holds).concat(!opt.holds && pageHolds ? pageHolds : []));+ const footage = opt.footage ? String(opt.footage).split(',').map((x) => { const m = x.trim().match(/^([\d.]+)-([\d.]+)@([\d.]+)$/); if (!m) throw new Error(`--footage wants "from-to@fps", got "${x}"`); return [Number(m[1]), Number(m[2]), Number(m[3])]; }) : (pageFootage ?? []);+ pops(s, opt.cuts ? String(opt.cuts).split(',').map(Number) : (pageCuts ?? []), footage);+ } else for (const [k, t] of [[3, 'DEAD AIR something visibly moves in every half second'], [4, 'POPS no frame jumps 3x more than its neighbours unless it is a declared cut']]) { head(k, t); note('skipped: no --mp4 given', 'run again with --mp4 after export'); }+ } finally { await browser.close(); srv.close(); }+ console.log(`\n${'='.repeat(58)}\nGATE: ${fails ? `FAIL ${fails} of ${checks} checks failed` : `PASS ${checks}/${checks} checks`}`);+ process.exit(fails ? 1 : 0);+};++// ---------------------------------------------------------------- --self-test+// Tiny fixture films that MUST fail (math-random, order-dependent-cache, dead-loop, pop) and runs+// that MUST pass (the dead film with its hold declared, the pop declared as a cut), proving the gate catches each.+const FIX = {+ 'math-random.html': `for(let i=0;i<120;i++){g.fillStyle='#fc0';g.fillRect(Math.random()*470,Math.random()*260,6,6)}`,+ 'order-cache.html': `if(window.__warm==null)window.__warm=Math.round(t*2); /* stale: remembers the first t drawn */+ g.fillStyle='hsl('+(window.__warm*47%360)+',60%,35%)';g.fillRect(0,0,480,60);+ g.fillStyle='#fff';g.fillRect(20+t*100,120,40,40);`,+ 'dead.html': `const T=Math.min(t,1);g.fillStyle='#e8b84b';g.beginPath();g.arc(40+T*380,135,24,0,7);g.fill();`,+ 'pop.html': `g.fillStyle='#e8b84b';g.beginPath();g.arc(40+t*130,135,24,0,7);g.fill();+ if(t>=1.5){g.fillStyle='#f4f1ea';g.fillRect(260,10,200,90);} /* a card that appears with no ease: a pop */`,+};+const fixture = (body) => `<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0">+<canvas id="c" width="480" height="270"></canvas><script>+const g=document.getElementById('c').getContext('2d');window.FILM_DURATION=3;+window.renderFrame=t=>{g.setTransform(1,0,0,1,0,0);g.globalAlpha=1;g.fillStyle='#081018';g.fillRect(0,0,480,270);+${body}};+window.READY=true;+</` + `script></body></html>`;++const renderFixtureMp4 = async (chromium, dir, film, mp4, fps, seconds) => {+ const { srv, url } = await serve(dir);+ const browser = await chromium.launch({ channel: 'chrome', headless: true });+ const page = await browser.newPage({ viewport: { width: 480, height: 270 } });+ await page.goto(url + '/' + film);+ await page.waitForFunction(() => typeof window.renderFrame === 'function' && window.READY === true);+ const ff = spawn('ffmpeg', ['-y', '-v', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-i', '-', '-c:v', 'libx264', '-preset', 'fast', '-crf', '14', '-pix_fmt', 'yuv420p', mp4], { stdio: ['pipe', 'ignore', 'inherit'] });+ for (let i = 0; i < fps * seconds; i++) {+ const png = await drawPng(page, i / fps);+ if (!ff.stdin.write(png)) await new Promise((r) => ff.stdin.once('drain', r));+ }+ ff.stdin.end(); await new Promise((r) => ff.on('close', r)); await browser.close(); srv.close();+};++const selfTest = async () => {+ const chromium = loadChromium();+ const dir = fs.mkdtempSync(path.join(process.env.GATE_TMP || os.tmpdir(), 'gate-selftest-'));+ for (const [name, body] of Object.entries(FIX)) fs.writeFileSync(path.join(dir, name), fixture(body));+ const mp4 = path.join(dir, 'dead.mp4'), popMp4 = path.join(dir, 'pop.mp4');+ console.log(`SELF-TEST fixtures in ${dir}`);+ await renderFixtureMp4(chromium, dir, 'dead.html', mp4, 12, 3);+ await renderFixtureMp4(chromium, dir, 'pop.html', popMp4, 12, 3);+ const gate = (args) => spawnSync(process.execPath, [SELF, ...args], { encoding: 'utf8', env: { ...process.env, W: '480', H: '270' } });+ const cases = [+ ['math-random must FAIL (unseeded randomness caught by scan + determinism)', [path.join(dir, 'math-random.html'), '--samples', '6'],+ (r) => r.status !== 0 && /Math\.random/.test(r.stdout) && /NONDETERMINISTIC|min PSNR/.test(r.stdout)],+ ['order-dependent-cache must FAIL and the poisoning frame must be NAMED', [path.join(dir, 'order-cache.html'), '--samples', '6'],+ (r) => r.status !== 0 && /ORDER-DEPENDENT: drawing frame/.test(r.stdout)],+ ['dead-loop mp4 must FAIL dead air', [path.join(dir, 'dead.html'), '--mp4', mp4],+ (r) => r.status !== 0 && /FAIL {2}no unexplained identical frames/.test(r.stdout)],+ ['the same film with its hold declared must PASS', [path.join(dir, 'dead.html'), '--mp4', mp4, '--holds', '1-3'],+ (r) => r.status === 0 && /GATE: PASS/.test(r.stdout)],+ ['an un-eased card appearing at 1.5 s must FAIL pops, listed at its time', [path.join(dir, 'pop.html'), '--mp4', popMp4],+ (r) => r.status !== 0 && /pop {2}t=1\.50s/.test(r.stdout) && /FAIL {2}no undeclared frame-difference spikes/.test(r.stdout)],+ ['the same pop declared as a cut must PASS', [path.join(dir, 'pop.html'), '--mp4', popMp4, '--cuts', '1.5'],+ (r) => r.status === 0 && /declared cut/.test(r.stdout) && /GATE: PASS/.test(r.stdout)],+ ];+ let wrong = 0;+ for (const [name, args, expect] of cases) {+ const r = gate(args), ok = expect(r);+ if (!ok) { wrong++; console.log(r.stdout); }+ console.log(`${ok ? 'PASS' : 'FAIL'} ${name}`);+ }+ console.log(`SELF-TEST: ${wrong ? 'FAIL' : 'PASS'}`);+ process.exit(wrong ? 1 : 0);+};++(opt['self-test'] ? selfTest() : run()).catch((e) => { console.error(`\ngate crashed: ${e.message}`); process.exit(2); });diff --git a/scripts/matte.swift b/scripts/matte.swiftnew file mode 100644index 0000000..4d79c71--- /dev/null+++ b/scripts/matte.swift@@ -0,0 +1,19 @@+// scripts/matte.swift : cut the subject out of a still with the Mac's own subject detection (Vision), free and local.+// Usage: swift <skill>/scripts/matte.swift in.jpg out.png [maxWidth] -> a PNG of the same shape whose alpha is the subject+import Foundation+import Vision+import CoreImage+import AppKit+let a = CommandLine.arguments+let inURL = URL(fileURLWithPath: a[1]), outURL = URL(fileURLWithPath: a[2]); let maxW = a.count > 3 ? Double(a[3])! : 2560+guard let img = CIImage(contentsOf: inURL) else { print("cannot read", a[1]); exit(1) }+let handler = VNImageRequestHandler(ciImage: img, options: [:]); let req = VNGenerateForegroundInstanceMaskRequest()+try handler.perform([req])+guard let obs = req.results?.first else { print("no subject found in", a[1]); exit(2) }+let mask = CIImage(cvPixelBuffer: try obs.generateScaledMaskForImage(forInstances: obs.allInstances, from: handler))+let f = CIFilter(name: "CIBlendWithMask")!+f.setValue(img, forKey: kCIInputImageKey); f.setValue(CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 0)).cropped(to: img.extent), forKey: kCIInputBackgroundImageKey); f.setValue(mask, forKey: kCIInputMaskImageKey)+var out = f.outputImage!.cropped(to: img.extent); let s = min(1.0, maxW / Double(img.extent.width))+if s < 1 { out = out.transformed(by: CGAffineTransform(scaleX: s, y: s)) }+try CIContext().writePNGRepresentation(of: out, to: outURL, format: .RGBA8, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!)+print(a[1], "->", a[2], "subjects:", obs.allInstances.count)diff --git a/scripts/music.mjs b/scripts/music.mjsnew file mode 100644index 0000000..5a20566--- /dev/null+++ b/scripts/music.mjs@@ -0,0 +1,145 @@+#!/usr/bin/env node+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// CODE MUSIC ENGINE CLI. Renders a Piece module to a 48 kHz 32-bit FLOAT WAV (no PCM16 clipping on+// the way) and meters it: integrated LUFS (BS.1770-4), LRA (EBU 3342), true peak (4x), onsets/s+// (spectral flux), spectral centroid, cross-checked against ffmpeg's ebur128.+//+// <piece.mjs> is a module whose default export is a Piece or a function returning one+// (path/to/score.mjs#exportName picks another export). See references/music-engine.md.+//+// node scripts/music.mjs render <piece.mjs> [--seconds N] [--out out.wav] [--flat] [--tempo N] [--loop] [--no-fit]+// node scripts/music.mjs check <piece.mjs> [--seconds N] # bar math, key/mode, LUFS/peak + ffmpeg cross-check, determinism, onsets+// node scripts/music.mjs meter <file.wav|file.mp4> # meter any audio file (decoded through ffmpeg)+import { execFileSync } from "node:child_process";+import { writeFileSync, unlinkSync, mkdtempSync } from "node:fs";+import { resolve, join } from "node:path";+import { tmpdir } from "node:os";+import { pathToFileURL } from "node:url";+import * as M from "./music/index.mjs";++const SR = 48000;++export const writeWavFloat = (path, L, R, sr = SR) => {+ const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(58);+ for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }+ h.write("RIFF", 0); h.writeUInt32LE(50 + data.length, 4); h.write("WAVE", 8);+ h.write("fmt ", 12); h.writeUInt32LE(18, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22); h.writeUInt32LE(sr, 24); h.writeUInt32LE(sr * 8, 28); h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34); h.writeUInt16LE(0, 36);+ h.write("fact", 38); h.writeUInt32LE(4, 42); h.writeUInt32LE(n, 46); h.write("data", 50); h.writeUInt32LE(data.length, 54);+ writeFileSync(path, Buffer.concat([h, data]));+};+/** Decode ANY file through ffmpeg to float stereo 48 kHz: we meter what a player would decode. */+export const decode = (path) => {+ const buf = execFileSync("ffmpeg", ["-v", "error", "-i", path, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(SR), "pipe:1"], { maxBuffer: 1 << 30 });+ const f = new Float32Array(buf.buffer, buf.byteOffset, buf.length / 4), n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};+/** Independent cross-check: ffmpeg's own ebur128 summary (integrated, LRA, true peak). */+const ffmpegEbu = (path) => {+ const out = execFileSync("sh", ["-c", 'ffmpeg -hide_banner -nostats -i "$1" -vn -af ebur128=peak=true -f null - 2>&1', "sh", path], { encoding: "utf8", maxBuffer: 1 << 28 });+ const sum = out.slice(out.lastIndexOf("Summary:"));+ const g = (re) => { const m = re.exec(sum); return m ? Number(m[1]) : NaN; };+ return { I: g(/I:\s+(-?[\d.]+) LUFS/), LRA: g(/LRA:\s+(-?[\d.]+) LU/), TP: g(/Peak:\s+(-?[\d.]+) dBFS/) };+};++const fmt = (x, d = 1) => (Number.isFinite(x) ? x.toFixed(d) : "n/a");++/** Load a piece factory from a .mjs module: default export (or #name), a Piece or () => Piece. */+const getPiece = async (ref) => {+ const [file, exp = "default"] = ref.split("#");+ const mod = await import(pathToFileURL(resolve(file)).href);+ const v = mod[exp];+ if (v === undefined) throw new Error(`${file} has no export "${exp}" (exports: ${Object.keys(mod).join(", ")})`);+ return () => { const x = typeof v === "function" ? v() : v; if (!x || !x.plan || !x.parts) throw new Error(`${ref} is not a Piece (needs plan, parts, harmony)`); return x; };+};++const renderOne = (make, spec) => {+ let piece = make();+ let tempo = spec.tempo ?? piece.plan.tempo, form;+ const loop = spec.loop || piece.plan.loop;+ if (spec.seconds && spec.fit !== false && !loop) {+ const f = M.fitToDuration(piece, spec.seconds); piece = f.piece; tempo = f.tempo;+ form = `${f.form}: ${f.piece.plan.sections.map((x) => x.id).join(", ")}`;+ }+ const opts = { seconds: spec.seconds, tempo };+ if (spec.flat) Object.assign(opts, { expressive: false, piano: M.PIANO_FLAT, flatVelocity: 0.6 });+ const go = () => (loop ? M.renderLoop(piece, SR) : M.renderPiece(piece, SR, opts));+ const t0 = Date.now(), r = go(), ms = Date.now() - t0;+ // determinism: a second render must be bit-identical+ const r2 = go(); let same = r.L.length === r2.L.length;+ if (same) for (let i = 0; i < r.L.length; i++) if (r.L[i] !== r2.L[i] || r.R[i] !== r2.R[i]) { same = false; break; }+ return { r, piece, tempo, ms, deterministic: same, form, loop };+};++const beatsOf = (piece) => piece.plan.sections.reduce((a, s) => a + s.bars * M.beatsPerBar(piece.plan.meter), 0);+const onsetsFromData = (r) => {+ const ts = r.perf.parts.flatMap((p) => p.keys.map((k) => k.t)).sort((a, b) => a - b); let c = 0, last = -1;+ for (const t of ts) if (t - last > 0.03) { c++; last = t; } return c;+};++const printMeters = (L, R, label) => {+ const m = M.measure([L, R], SR);+ console.log(`${label}: ${fmt(m.durationS, 2)} s | ${fmt(m.lufs)} LUFS | LRA ${fmt(m.lra)} LU | ${fmt(m.dbtp, 2)} dBTP | ${m.onsetCount} onsets (${fmt(m.onsetsPerS, 2)}/s) | centroid ${Math.round(m.centroidHz)} Hz`);+ return m;+};++const main = async () => {+ const [cmd, ...args] = process.argv.slice(2);+ const flag = (k) => args.includes(k), val = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };+ const ref = args.find((a) => !a.startsWith("--") && a !== val("--out") && a !== val("--seconds") && a !== val("--tempo"));++ if (cmd === "render") {+ const make = await getPiece(ref);+ const spec = { seconds: val("--seconds") ? Number(val("--seconds")) : undefined, tempo: val("--tempo") ? Number(val("--tempo")) : undefined, flat: flag("--flat"), loop: flag("--loop"), fit: !flag("--no-fit") };+ const { r, piece, tempo, ms, deterministic, form, loop } = renderOne(make, spec);+ const out = val("--out", "out.wav");+ writeWavFloat(out, r.L, r.R, SR);+ console.log(`"${piece.title}" -> ${out}`);+ console.log(`tempo ${fmt(tempo)} bpm${form ? ` | fit: ${form}` : ""}${loop ? ` | seamless loop ${fmt(r.loopS, 3)} s` : ""} | master ${r.masterMode} (gain ${fmt(r.gainDb)} dB) | rendered in ${ms} ms | deterministic: ${deterministic ? "yes (2 renders bit-identical)" : "NO"}`);+ printMeters(r.L, r.R, "meters");+ return;+ }++ if (cmd === "check") {+ // 1. bar math: line() already threw inside make() if any bar was wrong+ let make, piece;+ try { make = await getPiece(ref); piece = make(); } catch (e) { console.log(`FAIL (bar math / load): ${e.message}`); process.exit(1); }+ console.log(`"${piece.title}" | style ${piece.plan.style} | ${piece.plan.meter} at ${piece.plan.tempo} bpm | ${beatsOf(piece)} beats in ${piece.plan.sections.length} section(s)`);+ // 2. plan problems: key/mode histogram, tempo vs style, refused blends, close thirds+ const probs = M.planProblems(piece);+ for (const p of probs) console.log(` PROBLEM: ${p}`);+ if (!probs.length) console.log(" plan: OK (key/mode histogram matches declarations)");+ // 3. render + meters+ const spec = { seconds: val("--seconds") ? Number(val("--seconds")) : undefined };+ const { r, tempo, deterministic, form, loop } = renderOne(make, spec);+ console.log(` render: tempo ${fmt(tempo)} bpm${form ? ` | fit: ${form}` : ""}${loop ? ` | loop ${fmt(r.loopS, 3)} s` : ""} | master ${r.masterMode} | deterministic: ${deterministic ? "yes" : "NO"}`);+ const m = printMeters(r.L, r.R, " meters");+ const target = r.masterMode === "dense" ? -14 : -16;+ const lufsOk = Math.abs(m.lufs - target) < 1 || (r.masterMode === "gentle" && m.lufs < target); // gentle may trade loudness for the peak cap+ console.log(` master: target ${target} LUFS -> ${fmt(m.lufs)} (${lufsOk ? "ok" : "OFF TARGET"}), true peak ${fmt(m.dbtp, 2)} dBTP (${m.dbtp <= -0.9 ? "ok" : "OVER"})`);+ // onsets per beat (ghost-formlessness quick look; the full windowed guard is v2)+ const beats = (m.durationS / 60) * tempo;+ console.log(` motion: ${fmt(m.onsetCount / beats, 2)} onsets/beat over the whole piece (a bed wants >= ~0.5, a groove >= 1)`);+ // 4. ffmpeg ebur128 cross-check on the written file+ const tmp = join(mkdtempSync(join(tmpdir(), "music-")), "check.wav");+ writeWavFloat(tmp, r.L, r.R, SR);+ try {+ const e = ffmpegEbu(tmp);+ const dI = Math.abs(e.I - m.lufs), dT = Math.abs(e.TP - m.dbtp);+ console.log(` ffmpeg ebur128: I ${fmt(e.I)} LUFS (Δ${fmt(dI, 2)}) | LRA ${fmt(e.LRA)} LU | TP ${fmt(e.TP, 2)} dBTP (Δ${fmt(dT, 2)}) ${dI < 1 && dT < 1 ? "-- agrees" : "-- DISAGREES"}`);+ } catch { console.log(" ffmpeg ebur128: skipped (ffmpeg not found)"); }+ unlinkSync(tmp);+ const pass = !probs.length && deterministic && m.dbtp <= -0.9 && lufsOk;+ console.log(pass ? "PASS" : "FAIL");+ process.exit(pass ? 0 : 1);+ }++ if (cmd === "meter") {+ for (const f of args.filter((a) => !a.startsWith("--"))) { const [L, R] = decode(f); printMeters(L, R, f); }+ return;+ }++ console.log("usage: music.mjs render <piece.mjs> [--seconds N] [--out out.wav] [--flat] [--tempo N] [--loop] [--no-fit]\n music.mjs check <piece.mjs> [--seconds N]\n music.mjs meter <file.wav|mp4> ...");+};++main().catch((e) => { console.error(e.message); process.exit(1); });diff --git a/scripts/music/dsp.mjs b/scripts/music/dsp.mjsnew file mode 100644index 0000000..952a824--- /dev/null+++ b/scripts/music/dsp.mjs@@ -0,0 +1,86 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// DSP building blocks. Everything is a pure function of its inputs plus an rng() handed in by+// the caller; stateful filters are legal because a whole buffer renders in one call.+export const TAU = Math.PI * 2;+export const db = (x) => Math.pow(10, x / 20);+export const clamp = (x, a, b) => (x < a ? a : x > b ? b : x);++/** Deterministic seeded uniform rng (mulberry32-style, from anidoodle core.ts). */+export const rng = (seed) => {+ let a = seed >>> 0;+ return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };+};++/** Equal-power pan, p in -1..1 -> [gL, gR]. */+export const pan = (p) => { const a = ((clamp(p, -1, 1) + 1) * Math.PI) / 4; return [Math.cos(a), Math.sin(a)]; };+/** Gaussian from a seeded uniform source. */+export const gauss = (r) => { let u = r(); if (u < 1e-12) u = 1e-12; return Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * r()); };++/** Zavalishin TPT state-variable filter; set() may be called per sample for sweeps. */+export class SVF {+ constructor(sr, f = 1000, q = 0.707) { this.sr = sr; this.ic1 = 0; this.ic2 = 0; this.lp = 0; this.bp = 0; this.hp = 0; this.set(f, q); }+ set(f, q) { this.g = Math.tan((Math.PI * clamp(f, 5, this.sr * 0.49)) / this.sr); this.k = 1 / q; this.a1 = 1 / (1 + this.g * (this.g + this.k)); this.a2 = this.g * this.a1; this.a3 = this.g * this.a2; }+ tick(x) { const v3 = x - this.ic2, v1 = this.a1 * this.ic1 + this.a2 * v3, v2 = this.ic2 + this.a2 * this.ic1 + this.a3 * v3; this.ic1 = 2 * v1 - this.ic1; this.ic2 = 2 * v2 - this.ic2; this.lp = v2; this.bp = v1; this.hp = x - this.k * v1 - v2; return v2; }+}+/** RBJ biquad (direct form I). */+export class Biquad {+ constructor() { this.x1 = 0; this.x2 = 0; this.y1 = 0; this.y2 = 0; this.b0 = 1; this.b1 = 0; this.b2 = 0; this.a1 = 0; this.a2 = 0; }+ static make(sr, type, f, q, gainDb = 0) {+ const bq = new Biquad(), w = (TAU * f) / sr, c = Math.cos(w), s = Math.sin(w), al = s / (2 * q), A = Math.pow(10, gainDb / 40);+ let b0 = 1, b1 = 0, b2 = 0, a0 = 1, a1 = 0, a2 = 0;+ if (type === "lp") { b0 = (1 - c) / 2; b1 = 1 - c; b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "hp") { b0 = (1 + c) / 2; b1 = -(1 + c); b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "bp") { b0 = al; b1 = 0; b2 = -al; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "peak") { b0 = 1 + al * A; b1 = -2 * c; b2 = 1 - al * A; a0 = 1 + al / A; a1 = -2 * c; a2 = 1 - al / A; }+ else { const sq = 2 * Math.sqrt(A) * al, sh = type === "lowshelf" ? 1 : -1;+ b0 = A * ((A + 1) - sh * (A - 1) * c + sq); b1 = sh * 2 * A * ((A - 1) - sh * (A + 1) * c); b2 = A * ((A + 1) - sh * (A - 1) * c - sq);+ a0 = (A + 1) + sh * (A - 1) * c + sq; a1 = -sh * 2 * ((A - 1) + sh * (A + 1) * c); a2 = (A + 1) + sh * (A - 1) * c - sq; }+ bq.b0 = b0 / a0; bq.b1 = b1 / a0; bq.b2 = b2 / a0; bq.a1 = a1 / a0; bq.a2 = a2 / a0; return bq;+ }+ tick(x) { const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2; this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y; return y; }+ run(buf) { for (let i = 0; i < buf.length; i++) buf[i] = this.tick(buf[i]); return buf; }+}+export const onePoleCoef = (sr, f) => 1 - Math.exp((-TAU * f) / sr);++/** PolyBLEP residual for band-limited saw/pulse. */+export const blep = (t, dt) => { if (t < dt) { t /= dt; return t + t - t * t - 1; } if (t > 1 - dt) { t = (t - 1) / dt; return t * t + t + t + 1; } return 0; };++/**+ * A small room: early reflections (decorrelated taps per side, each darker than the last) plus a+ * short 8-line feedback delay network for the diffuse tail. Returns the WET signal only.+ */+export const room = (L, R, sr, o) => {+ const n = L.length, wL = new Float32Array(n), wR = new Float32Array(n), tL = new Float32Array(n), tR = new Float32Array(n), r = o.rng;+ // send filter: high-passed (no mud) and low-passed+ const inL = Float32Array.from(L), inR = Float32Array.from(R);+ Biquad.make(sr, "hp", o.hp, 0.7).run(inL); Biquad.make(sr, "hp", o.hp, 0.7).run(inR);+ Biquad.make(sr, "lp", o.lp, 0.7).run(inL); Biquad.make(sr, "lp", o.lp, 0.7).run(inR);+ // early reflections: 7 taps per side, 6-38 ms, alternating polarity, decreasing gain+ for (const [src, dst, side] of [[inL, wL, 0], [inR, wR, 1], [inR, wL, 2], [inL, wR, 3]]) {+ let acc = 0; const k = onePoleCoef(sr, 5200);+ for (let t = 0; t < 7; t++) {+ const ms = 6 + t * 4.6 + r() * 3 + side * 0.7, d = Math.round((ms / 1000) * sr), g = (o.er * (side < 2 ? 1 : 0.55) * Math.pow(0.8, t) * (t % 2 ? -1 : 1)) / 2.2;+ acc = 0; for (let i = d; i < n; i++) { acc += k * (src[i - d] - acc); dst[i] += acc * g; }+ }+ }+ if (o.late > 0) {+ const N = 8, lens = [1123, 1289, 1447, 1597, 1777, 1913, 2053, 2239].map((x) => Math.round((x * sr) / 48000 * (0.7 + 0.3 * r())));+ const bufs = lens.map((l) => new Float32Array(l)), idx = new Array(N).fill(0), lp = new Array(N).fill(0);+ const gains = lens.map((l) => Math.pow(10, (-3 * l) / (sr * o.rt60))), dampK = onePoleCoef(sr, 3200);+ const pd = Math.round(o.predelay * sr), out = new Float64Array(N), h = new Float64Array(N);+ for (let i = 0; i < n; i++) {+ const xl = i >= pd ? inL[i - pd] : 0, xr = i >= pd ? inR[i - pd] : 0;+ for (let j = 0; j < N; j++) out[j] = bufs[j][idx[j]];+ // Hadamard-ish mix (fast Walsh on 8)+ h.set(out);+ for (let s = 1; s < N; s <<= 1) for (let j = 0; j < N; j += s << 1) for (let q = j; q < j + s; q++) { const a = h[q], b = h[q + s]; h[q] = a + b; h[q + s] = a - b; }+ for (let j = 0; j < N; j++) {+ let v = (h[j] / Math.sqrt(N)) * gains[j];+ lp[j] += dampK * (v - lp[j]); v = lp[j];+ bufs[j][idx[j]] = v + (j % 2 ? xr : xl) * 0.5; idx[j] = (idx[j] + 1) % lens[j];+ }+ tL[i] = (out[0] - out[2] + out[4] - out[6]) * o.late * 0.5; tR[i] = (out[1] - out[3] + out[5] - out[7]) * o.late * 0.5; wL[i] += tL[i]; wR[i] += tR[i];+ }+ }+ return [wL, wR, tL, tR]; // full wet, and the late tail alone+};diff --git a/scripts/music/index.mjs b/scripts/music/index.mjsnew file mode 100644index 0000000..652f397--- /dev/null+++ b/scripts/music/index.mjs@@ -0,0 +1,12 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// CODE MUSIC ENGINE, v1: 100 % procedural, notes as data, synthesized in code. No samples, ever.+export * from "./theory.mjs";+export * from "./tables.mjs";+export * from "./plan.mjs";+export * from "./perform.mjs";+export * from "./piano.mjs";+export * from "./render.mjs";+export * from "./meter.mjs";+export * as instruments from "./instruments.mjs";+export * as lofiKit from "./lofiKit.mjs";+export { rng, db, clamp, pan, SVF, Biquad, room } from "./dsp.mjs";diff --git a/scripts/music/instruments.mjs b/scripts/music/instruments.mjsnew file mode 100644index 0000000..f168a99--- /dev/null+++ b/scripts/music/instruments.mjs@@ -0,0 +1,152 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// The non-piano kit, v1 subset: music box (modal), strings (5 detuned PolyBLEP saws), harp/guitar+// (extended Karplus-Strong), FM electric piano, and the soft drum kit (kick, snare, hat, warm+// saturated bass, vinyl). Each instrument: (keys, sr, n, opts, rng) -> {L, R}. Keys are performed+// presses in seconds. Presets are numbers in one place (the constants at the top of each voice).+import { TAU, clamp, pan, SVF, Biquad, blep, onePoleCoef, gauss } from "./dsp.mjs";++const num = (o, k, d) => (typeof o[k] === "number" ? o[k] : d);+const f0 = (m) => 440 * Math.pow(2, (m - 69) / 12);+const pitchPan = (m, w) => clamp((m - 64) / 30, -1, 1) * w;++/** Sum of decaying sinusoids, the modal core (music box; celesta/mallets/bells in v2). */+const modal = (out, i0, modes, p, sr, maxS, rel, atkMs = 2) => {+ const atk = Math.max(1, Math.round((atkMs / 1000) * sr));+ const [gl, gr] = pan(p), n = out.L.length;+ for (const [f, a, tau] of modes) {+ if (f > sr * 0.45 || a <= 0) continue;+ const w = (TAU * f) / sr, cw = Math.cos(w), sw = Math.sin(w), dec = Math.exp(-1 / (tau * sr));+ const decR = rel ? Math.exp(-(1 / tau + rel.sigma) / sr) : dec;+ const len = Math.min(n - i0, Math.ceil(Math.min(maxS, tau * 11) * sr)), relI = rel ? Math.round(rel.at * sr) : Infinity;+ let c = a, s = 0;+ for (let i = 0; i < len; i++) { const y = i < atk ? (s * i) / atk : s; const j = i0 + i; if (j >= 0) { out.L[j] += y * gl; out.R[j] += y * gr; } const d = i < relI ? dec : decR; const c2 = (c * cw - s * sw) * d; s = (c * sw + s * cw) * d; c = c2; }+ }+};++export const musicBox = (keys, sr, n, o) => {+ // the recipe numbers, verbatim: partials 1, 2, 3 at 1.0/0.35/0.12, a 5.4f ping dying in 60 ms,+ // 2 ms attack, tau = 0.45 sqrt(440/f)+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.5);+ for (const k of keys) {+ const f = f0(k.p), tau = 0.45 * Math.sqrt(440 / f), i0 = Math.round(k.t * sr), g = k.v * 0.3;+ modal(out, i0, [[f, g, tau], [2 * f, 0.35 * g, tau * 0.8], [3 * f, 0.12 * g, tau * 0.6], [5.4 * f, 0.08 * g, 0.06 / 4]], pitchPan(k.p, w), sr, 8);+ }+ return out;+};++/**+ * Extended Karplus-Strong (Jaffe & Smith 1983): a delay line one period long, a two-point loss+ * filter for brightness, an allpass for fine tuning, a pick-position comb on the excitation and a+ * velocity low-pass (a softer pluck is darker). Harp rings long and bright; guitar gets a body.+ */+export const pluck = (keys, sr, n, o, r, kind) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.6);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), P = sr / f, N = Math.floor(P - 0.5), frac = P - N - 0.5;+ const ap = (1 - frac) / (1 + frac); // first-order allpass fractional delay+ const T60 = kind === "harp" ? clamp(4.2 * Math.pow(262 / f, 0.45), 0.8, 8) : clamp(3.2 * Math.pow(262 / f, 0.5), 0.6, 6);+ const S = kind === "harp" ? 0.18 : 0.32; // loss-filter weight (higher = darker)+ const rho = Math.pow(10, -3 / (T60 * f));+ const line = new Float64Array(N + 2);+ // excitation: noise shaped by velocity low-pass and a pick-position comb+ const lp = new SVF(sr, 900 + 6000 * k.v * k.v, 0.6), beta = kind === "harp" ? 0.5 : 0.18, pk = Math.max(1, Math.round(beta * N));+ const exc = new Float64Array(N); for (let i = 0; i < N; i++) exc[i] = lp.tick(gauss(r)); let mean = 0; for (let i = 0; i < N; i++) mean += exc[i] / N;+ for (let i = 0; i < N; i++) line[i] = (exc[i] - mean) - (i >= pk ? exc[i - pk] - mean : 0) * 0.9;+ let peak = 1e-9; for (let i = 0; i < N; i++) peak = Math.max(peak, Math.abs(line[i]));+ const g = (Math.pow(k.v, 1.3) * 0.35) / peak, [gl, gr] = pan(pitchPan(k.p, w));+ const relI = Math.round((k.off - k.t) * sr), len = Math.min(n - i0, Math.ceil(T60 * 1.1 * sr));+ let idx = 0, apx = 0, apy = 0, damp = 1;+ for (let i = 0; i < len; i++) {+ const x = line[idx], nxt = line[(idx + 1) % N];+ const y = ((1 - S) * x + S * nxt) * rho;+ const a = ap * y + apx - ap * apy; apx = y; apy = a; // allpass+ line[idx] = a * damp; idx = (idx + 1) % N;+ if (kind === "guitar" && i > relI) damp = 0.985; // finger damping after release+ const j = i0 + i; if (j < n) { const v = x * g * Math.min(1, i / 24); out.L[j] += v * gl; out.R[j] += v * gr; }+ }+ }+ if (kind === "guitar") for (const [f, q, gdb] of [[110, 2.5, 5], [220, 3, 3], [420, 2, 2], [2800, 1, -3]]) { Biquad.make(sr, "peak", f, q, gdb).run(out.L); Biquad.make(sr, "peak", f, q, gdb).run(out.R); }+ return out;+};++/** Soft string ensemble: 5 detuned PolyBLEP saws per note, slow bow attack, delayed vibrato, low-pass, high-pass 150 Hz. */+export const strings = (keys, sr, n, o, r) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, atk = num(o, "attack", 0.45), rel = num(o, "release", 0.9), w = num(o, "width", 0.8), bright = num(o, "bright", 1);+ const hpL = new SVF(sr, 150, 0.7), hpR = new SVF(sr, 150, 0.7);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + rel * 1.5) * sr));+ const V = 5, dets = [-9, -4.5, 0, 4.2, 8.8], phs = dets.map(() => r()), pans = dets.map((_, i) => pan(((i / (V - 1)) * 2 - 1) * w)), incs = dets.map((d) => (f * Math.pow(2, d / 1200)) / sr);+ const lp = [new SVF(sr, 1000, 0.6), new SVF(sr, 1000, 0.6)], g = Math.pow(k.v, 1.2) * 0.11;+ const vr = 4.8 + r() * 0.8, vph = r() * TAU;+ for (let i = 0; i < len; i++) {+ const t = i / sr;+ const env = t < dur ? 1 - Math.exp(-t / (atk / 3)) : (1 - Math.exp(-dur / (atk / 3))) * Math.exp(-(t - dur) / (rel / 3));+ const vib = 1 + (0.0006 + 0.0022 * clamp((t - 0.35) / 0.6, 0, 1)) * Math.sin(TAU * vr * t + vph);+ let sl = 0, sr_ = 0;+ for (let v = 0; v < V; v++) {+ const inc = incs[v] * vib; let ph = phs[v] + inc; if (ph >= 1) ph -= 1; phs[v] = ph;+ const s = 2 * ph - 1 - blep(ph, inc), pv = pans[v]; sl += s * pv[0]; sr_ += s * pv[1];+ }+ const cut = clamp((500 + 2600 * k.v * bright) * (0.55 + 0.45 * env), 200, 9000);+ if ((i & 31) === 0) { lp[0].set(cut, 0.6); lp[1].set(cut, 0.6); }+ const j = i0 + i; out.L[j] += lp[0].tick(sl) * env * g; out.R[j] += lp[1].tick(sr_) * env * g;+ }+ }+ const bassRole = o.bass === true;+ if (!bassRole) for (let i = 0; i < n; i++) { hpL.tick(out.L[i]); hpR.tick(out.R[i]); out.L[i] = hpL.hp; out.R[i] = hpR.hp; }+ return out;+};++/** FM electric piano: 1:1 body with a decaying index, a 14:1 tine "bark" on the attack, tremolo, a little drive. */+export const ePiano = (keys, sr, n, o) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, w = num(o, "width", 0.35), trem = num(o, "trem", 4.6);+ for (const k of keys) {+ const f = f0(k.p) * (1 + (num(o, "detune", 4) / 1200) * (k.p % 2 ? 1 : -1)), i0 = Math.round(k.t * sr), td = clamp(1.9 * Math.pow(262 / f, 0.5), 0.5, 5), dur = k.off - k.t;+ const I0 = 0.6 + 2.2 * k.v, g = Math.pow(k.v, 1.2) * 0.2, len = Math.min(n - i0, Math.ceil((dur + 0.4) * sr)), [gl, gr] = pan(pitchPan(k.p, w));+ for (let i = 0; i < len; i++) {+ const t = i / sr, rel = t < dur ? 1 : Math.exp(-(t - dur) / 0.07), a = Math.exp(-t / td) * rel * Math.min(1, t * 700);+ const I = I0 * Math.exp(-t / 0.4), bark = 0.9 * k.v * Math.exp(-t / 0.012);+ const y = Math.tanh(1.3 * Math.sin(TAU * f * t + I * Math.sin(TAU * f * t) + bark * Math.sin(TAU * f * 14 * t))) * a * g;+ out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr;+ }+ }+ for (let i = 0; i < n; i++) { const m = 0.25 * Math.sin((TAU * trem * i) / sr); out.L[i] *= 1 - m; out.R[i] *= 1 + m; }+ return out;+};++// ---------------------------------------------------------------- drums and bass (soft kit)+export const kick = (keys, sr, n, o) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, soft = num(o, "soft", 1);+ for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(0.5 * sr)); let ph = 0;+ for (let i = 0; i < len; i++) { const t = i / sr, fq = 48 + (110 + 40 * (1 - soft)) * Math.exp(-t / 0.035); ph += fq / sr;+ const y = Math.tanh(1.6 * Math.sin(TAU * ph) * Math.exp(-t / (0.22 * (0.7 + 0.3 * soft)))) * k.v * 0.5 + Math.sin(TAU * 1300 * t) * Math.exp(-t / 0.004) * 0.04 * k.v; out.L[i0 + i] += y; out.R[i0 + i] += y; } }+ return out;+};+export const snare = (keys, sr, n, o, r) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, rim = o.rim === true;+ for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil(0.35 * sr)), bp = new SVF(sr, rim ? 1800 : 3200, rim ? 3 : 0.8);+ for (let i = 0; i < len; i++) { const t = i / sr, body = (Math.sin(TAU * 185 * t) + 0.5 * Math.sin(TAU * 330 * t)) * Math.exp(-t / 0.045) * (rim ? 0.25 : 0.5);+ bp.tick(gauss(r)); const nz = bp.bp * Math.exp(-t / (rim ? 0.02 : 0.1)) * (rim ? 1.2 : 0.6); const y = (body + nz) * k.v * 0.32; out.L[i0 + i] += y * 0.95; out.R[i0 + i] += y; } }+ return out;+};+export const hat = (keys, sr, n, o, r) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, [gl, gr] = pan(num(o, "pan", 0.3));+ for (const k of keys) { const i0 = Math.round(k.t * sr), dec = k.kind === "o" ? 0.2 : 0.03, len = Math.min(n - i0, Math.ceil(dec * 6 * sr)), hp = new SVF(sr, 7200, 0.7);+ for (let i = 0; i < len; i++) { const t = i / sr; hp.tick(gauss(r)); let y = hp.hp * Math.exp(-t / dec) * k.v * 0.09; if (typeof o.crush === "number") { const q = Math.pow(2, o.crush - 1) * 4; y = Math.round(y * q) / q; } out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr; } }+ return out;+};+/** Warm bass: sine + harmonics, a pluck envelope, and a little saturation so phones hear the line (phone rule). */+export const bass = (keys, sr, n, o) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, drive = num(o, "drive", 1.6);+ for (const k of keys) { const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.1) * sr));+ for (let i = 0; i < len; i++) { const t = i / sr, e = Math.min(1, t * 300) * (0.55 + 0.45 * Math.exp(-t / 0.25)) * (t < dur ? 1 : Math.exp(-(t - dur) / 0.03));+ const y = Math.tanh(drive * (Math.sin(TAU * f * t) + 0.35 * Math.sin(TAU * 2 * f * t) + 0.12 * Math.sin(TAU * 3 * f * t))) / Math.tanh(drive) * e * k.v * 0.3; out.L[i0 + i] += y; out.R[i0 + i] += y; } }+ return out;+};+/** Vinyl: sparse crackle impulses and a low hiss floor. One key spans the texture. */+export const vinyl = (keys, sr, n, _o, r) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, lp = onePoleCoef(sr, 4000);+ for (const k of keys) { const i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil((k.off - k.t) * sr)); let zl = 0, zr = 0;+ for (let i = 0; i < len; i++) { const pop = r() < 7 / sr ? (r() - 0.5) * 0.5 * k.v : 0; const hiss = gauss(r) * 0.004 * k.v; zl += lp * (hiss + pop - zl); zr += lp * (hiss * 0.8 + pop - zr); out.L[i0 + i] += zl; out.R[i0 + i] += zr; } }+ return out;+};diff --git a/scripts/music/lofiKit.mjs b/scripts/music/lofiKit.mjsnew file mode 100644index 0000000..8b68c01--- /dev/null+++ b/scripts/music/lofiKit.mjs@@ -0,0 +1,100 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// LO-FI ELECTRONIC KIT. The voices and the bus moves chill lo-fi electronic music is made of:+// a detuned saw pad low-passed near 2 kHz with a slow attack and chorus, a soft pluck through a+// dotted-eighth ping-pong delay, a sine sub filtered near 120-150 Hz, the kick ducking the pad+// (the pump that makes it breathe), and tape: 5-10 cents of slow wow, a little flutter, and+// saturation. Pure functions of (keys, sr, n, opts, rng): deterministic like the rest.+import { TAU, clamp, pan, SVF, blep } from "./dsp.mjs";++const num = (o, k, d) => (typeof o[k] === "number" ? o[k] : d);+const f0 = (m) => 440 * Math.pow(2, (m - 69) / 12);++/** Warm pad: 7 PolyBLEP saws spread +-14 cents, each drifting on its own slow LFO (the chorus),+ * a 12 dB low-pass that opens a little with the attack, slow attack and long release. */+export const warmPad = (keys, sr, n, o, r) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, atk = num(o, "attack", 0.9), rel = num(o, "release", 1.8), cut = num(o, "cut", 1900), w = num(o, "width", 0.85);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + rel * 2) * sr));+ const spread = num(o, "spread", 1), V = 7, dets = [-14, -9, -4, 0, 4.5, 9.5, 13.5].map((d) => d * spread), phs = dets.map(() => r()), pans = dets.map((_, i) => pan(((i / (V - 1)) * 2 - 1) * w));+ const lfo = dets.map(() => ({ rate: 0.25 + r() * 0.5, ph: r() * TAU })), g = Math.pow(k.v, 1.1) * 0.075, lp = [new SVF(sr, cut, 0.55), new SVF(sr, cut, 0.55)];+ for (let i = 0; i < len; i++) {+ const t = i / sr, env = t < dur ? 1 - Math.exp(-t / (atk / 3)) : (1 - Math.exp(-dur / (atk / 3))) * Math.exp(-(t - dur) / (rel / 3));+ if (env < 1e-5 && t > dur) break;+ let sl = 0, sr_ = 0;+ for (let v = 0; v < V; v++) {+ const cents = dets[v] + 3 * spread * Math.sin(TAU * lfo[v].rate * t + lfo[v].ph), inc = (f * Math.pow(2, cents / 1200)) / sr;+ let ph = phs[v] + inc; if (ph >= 1) ph -= 1; phs[v] = ph;+ const s = 2 * ph - 1 - blep(ph, inc); sl += s * pans[v][0]; sr_ += s * pans[v][1];+ }+ if ((i & 63) === 0) { const c = clamp(cut * (0.7 + 0.3 * env), 200, 8000); lp[0].set(c, 0.55); lp[1].set(c, 0.55); }+ const j = i0 + i; out.L[j] += lp[0].tick(sl) * env * g; out.R[j] += lp[1].tick(sr_) * env * g;+ }+ }+ return out;+};++/** Soft pluck: triangle plus a quiet square an octave down, through a low-pass whose cutoff snaps+ * open and falls back (the pluck), a short amp decay, then a dotted-eighth ping-pong delay. */+export const softPluck = (keys, sr, n, o) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, dec = num(o, "decay", 0.55), bright = num(o, "bright", 3200), p = num(o, "pan", 0);+ const [gl, gr] = pan(p);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), len = Math.min(n - i0, Math.ceil((dec * 6) * sr)), lp = new SVF(sr, bright, 0.9);+ let ph = 0, ph2 = 0;+ for (let i = 0; i < len; i++) {+ const t = i / sr; ph += f / sr; if (ph >= 1) ph -= 1; ph2 += f / 2 / sr; if (ph2 >= 1) ph2 -= 1;+ const tri = 1 - 4 * Math.abs(ph - 0.5), sq = ph2 < 0.5 ? 0.25 : -0.25;+ if ((i & 15) === 0) lp.set(clamp(500 + bright * k.v * Math.exp(-t / 0.09), 200, 9000), 0.9);+ const env = Math.min(1, t * 400) * Math.exp(-t / dec), y = lp.tick(tri + sq) * env * k.v * 0.32;+ out.L[i0 + i] += y * gl; out.R[i0 + i] += y * gr;+ }+ }+ const d = num(o, "delay", 0), fb = num(o, "feedback", 0.32), mix = num(o, "delayMix", 0.3);+ if (d > 0) { // ping-pong: left echoes into right and back, each repeat darker+ const D = Math.round(d * sr), bL = new Float32Array(n), bR = new Float32Array(n), toneL = new SVF(sr, 2600, 0.7), toneR = new SVF(sr, 2600, 0.7);+ for (let i = 0; i < n; i++) {+ const eL = i >= D ? bR[i - D] * fb + (out.L[i - D] + out.R[i - D]) * 0.5 : 0, eR = i >= D ? bL[i - D] : 0;+ bL[i] = toneL.tick(eL); bR[i] = toneR.tick(eR);+ }+ for (let i = 0; i < n; i++) { out.L[i] += bL[i] * mix; out.R[i] += bR[i] * mix; }+ }+ return out;+};++/** Sine sub: the fundamental and a whisper of the 2nd so phones still hear it, low-passed at 150 Hz. */+export const sub = (keys, sr, n, o) => {+ const out = { L: new Float32Array(n), R: new Float32Array(n) }, cut = num(o, "cut", 150);+ for (const k of keys) {+ const f = f0(k.p), i0 = Math.round(k.t * sr), dur = k.off - k.t, len = Math.min(n - i0, Math.ceil((dur + 0.12) * sr)), lp = new SVF(sr, cut, 0.7);+ for (let i = 0; i < len; i++) {+ const t = i / sr, env = Math.min(1, t * 120) * (t < dur ? 0.8 + 0.2 * Math.exp(-t / 0.3) : Math.exp(-(t - dur) / 0.04));+ const y = lp.tick(Math.sin(TAU * f * t) + 0.18 * Math.sin(TAU * 2 * f * t)) * env * k.v * 0.42; out.L[i0 + i] += y; out.R[i0 + i] += y;+ }+ }+ return out;+};++// ---------------------------------------------------------------- bus moves+/** The kick pump: a gain curve that dips by `depth` at every kick and recovers over `release` s. */+export const duckCurve = (kicks, sr, n, depth = 0.4, release = 0.28, attack = 0.008) => {+ const g = new Float32Array(n).fill(1);+ for (const t of kicks) {+ const i0 = Math.round(t * sr), len = Math.min(n - i0, Math.ceil(release * 5 * sr));+ for (let i = 0; i < len; i++) { const s = i / sr, a = s < attack ? s / attack : Math.exp(-(s - attack) / (release / 2.5)); const v = 1 - depth * a; if (v < g[i0 + i]) g[i0 + i] = v; }+ }+ return g;+};+/** Tape: wow (slow pitch drift) and flutter as a modulated fractional delay, then soft saturation. */+export const tape = (L, R, sr, o = {}) => {+ const n = L.length, wc = o.wowCents ?? 7, wf = o.wowHz ?? 0.45, fc = o.flutterCents ?? 1.2, ff = o.flutterHz ?? 6.2, drive = o.drive ?? 1.25;+ // a delay swinging by A seconds at f Hz shifts pitch by 2*pi*f*A: solve A from the cents wanted+ const A1 = (Math.pow(2, wc / 1200) - 1) / (TAU * wf), A2 = (Math.pow(2, fc / 1200) - 1) / (TAU * ff), base = A1 + A2 + 0.002;+ for (const c of [L, R]) {+ const src = Float32Array.from(c);+ for (let i = 0; i < n; i++) {+ const t = i / sr, d = (base + A1 * Math.sin(TAU * wf * t) + A2 * Math.sin(TAU * ff * t)) * sr, x = i - d, j = Math.floor(x), fr = x - j;+ const a = j >= 0 && j < n ? src[j] : 0, b = j + 1 >= 0 && j + 1 < n ? src[j + 1] : 0;+ c[i] = Math.tanh((a + (b - a) * fr) * drive) / drive;+ }+ }+};diff --git a/scripts/music/meter.mjs b/scripts/music/meter.mjsnew file mode 100644index 0000000..561da03--- /dev/null+++ b/scripts/music/meter.mjs@@ -0,0 +1,119 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// The deaf composer's instruments. Pure functions over float buffers:+// loudness ITU-R BS.1770-4 K-weighting, 400 ms blocks at 75 % overlap, -70 LUFS absolute and+// -10 LU relative gates; LRA per EBU Tech 3342 (3 s short-term, -20 LU gate, P95 - P10)+// truePeak 4x oversampled (windowed-sinc polyphase), dBTP+// onsets spectral flux with a max-filtered previous frame (SuperFlux-style), adaptive threshold+// centroid magnitude-weighted spectral centroid, averaged over non-silent frames+export const fft = (re, im) => {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; } }+ for (let len = 2; len <= n; len <<= 1) {+ const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang);+ for (let i = 0; i < n; i += len) { let cr = 1, ci = 0; for (let j = 0; j < len / 2; j++) { const a = i + j, b = a + len / 2, xr = re[b] * cr - im[b] * ci, xi = re[b] * ci + im[b] * cr; re[b] = re[a] - xr; im[b] = im[a] - xi; re[a] += xr; im[a] += xi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } }+ }+};++const kWeight = (x, sr) => {+ // stage 1: high shelf (+4 dB above ~1.7 kHz); stage 2: RLB high-pass ~38 Hz (pyloudnorm's closed form)+ const out = new Float64Array(x.length);+ { const G = 3.999843853973347, Q = 0.7071752369554196, fc = 1681.974450955533, K = Math.tan((Math.PI * fc) / sr), Vh = Math.pow(10, G / 20), Vb = Math.pow(Vh, 0.4996667741545416);+ const a0 = 1 + K / Q + K * K, b0 = (Vh + (Vb * K) / Q + K * K) / a0, b1 = (2 * (K * K - Vh)) / a0, b2 = (Vh - (Vb * K) / Q + K * K) / a0, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < x.length; i++) { const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; } }+ { const fc = 38.13547087602444, Q = 0.5003270373238773, K = Math.tan((Math.PI * fc) / sr), a0 = 1 + K / Q + K * K, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < out.length; i++) { const xi = out[i], y = xi - 2 * x1 + x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = xi; y2 = y1; y1 = y; out[i] = y; } }+ return out;+};++export const loudness = (chans, sr) => {+ const k = chans.map((c) => kWeight(c, sr)), n = chans[0].length;+ const ms = (a, len) => { let s = 0; for (const c of k) { let e = 0; for (let i = a; i < a + len && i < n; i++) e += c[i] * c[i]; s += e / len; } return s; };+ const lufs = (z) => -0.691 + 10 * Math.log10(Math.max(z, 1e-20));+ // integrated+ const bl = Math.round(0.4 * sr), hop = Math.round(0.1 * sr), blocks = [];+ for (let a = 0; a + bl <= n; a += hop) blocks.push(ms(a, bl));+ const abs = blocks.filter((z) => lufs(z) > -70), rel = lufs(abs.reduce((a, b) => a + b, 0) / Math.max(1, abs.length)) - 10;+ const gated = abs.filter((z) => lufs(z) > rel), integrated = lufs(gated.reduce((a, b) => a + b, 0) / Math.max(1, gated.length));+ // short-term (3 s) for LRA and max short-term; momentary max+ const sl = Math.round(3 * sr), st = []; for (let a = 0; a + sl <= n; a += hop) st.push(ms(a, sl));+ const stAbs = st.filter((z) => lufs(z) > -70), stRel = lufs(stAbs.reduce((a, b) => a + b, 0) / Math.max(1, stAbs.length)) - 20;+ const stG = stAbs.map(lufs).filter((l) => l > stRel).sort((a, b) => a - b);+ const pct = (p) => (stG.length ? stG[Math.min(stG.length - 1, Math.max(0, Math.round((p / 100) * (stG.length - 1))))] : NaN);+ const shortTerm = st.map(lufs);+ return { integrated, lra: pct(95) - pct(10), shortMax: Math.max(...shortTerm), momentaryMax: Math.max(...blocks.map(lufs)), shortTerm, hopS: 0.1 };+};++export const truePeak = (chans) => {+ // 4x polyphase windowed sinc, 16 taps per phase+ const O = 4, T = 16, h = [];+ for (let ph = 0; ph < O; ph++) { const row = []; for (let t = 0; t < T; t++) { const x = t - T / 2 + 1 - ph / O, w = 0.5 + 0.5 * Math.cos((Math.PI * x) / (T / 2)); row.push(x === 0 ? 1 : (Math.sin(Math.PI * x) / (Math.PI * x)) * w); } h.push(row); }+ let peak = 0, sample = 0;+ for (const c of chans) for (let i = 0; i < c.length; i++) {+ const a = Math.abs(c[i]); if (a > sample) sample = a;+ if (a < peak * 0.5) continue; // cheap skip: an inter-sample peak cannot exceed ~2x its neighbours here+ for (let ph = 1; ph < O; ph++) { let s = 0; for (let t = 0; t < T; t++) { const j = i + t - T / 2 + 1; if (j >= 0 && j < c.length) s += c[j] * h[ph][t]; } const v = Math.abs(s); if (v > peak) peak = v; }+ if (a > peak) peak = a;+ }+ return { dbtp: 20 * Math.log10(Math.max(peak, 1e-12)), samplePeakDb: 20 * Math.log10(Math.max(sample, 1e-12)) };+};++const hann = (N) => Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));+/** STFT magnitudes of the mono mix. */+const stft = (mono_, N, hop) => {+ const w = hann(N), frames = [];+ for (let a = 0; a + N <= mono_.length; a += hop) { const re = new Float64Array(N), im = new Float64Array(N); for (let i = 0; i < N; i++) re[i] = mono_[a + i] * w[i]; fft(re, im); const m = new Float64Array(N / 2 + 1); for (let k = 0; k <= N / 2; k++) m[k] = Math.hypot(re[k], im[k]); frames.push(m); }+ return frames;+};+export const mono = (chans) => { const n = chans[0].length, m = new Float32Array(n); for (const c of chans) for (let i = 0; i < n; i++) m[i] += c[i] / chans.length; return m; };++/** Onset strength of every accepted peak is returned too (`strength`, on a loudness-normalised scale). */+export const onsetsDetail = (chans, sr, delta = 0.07, absFloor = ONSET_FLOOR) => {+ // loudness-normalise to -23 LUFS first, so the absolute floor means the same thing for every file+ const m = mono(chans), lu = loudness([m], sr).integrated, g = Number.isFinite(lu) ? Math.pow(10, (-23 - lu) / 20) : 1;+ for (let i = 0; i < m.length; i++) m[i] *= g;+ const hop = Math.round(sr / 100), N = sr >= 44100 ? 2048 : 1024, frames = stft(m, N, hop);+ // log-compressed bands on a ~24-per-octave filterbank above 30 Hz+ const bins = frames[0].length, edges = []; for (let f = 30; f < Math.min(16000, sr / 2); f *= Math.pow(2, 1 / 24)) edges.push(Math.round((f / sr) * N));+ const uniq = [...new Set(edges)].filter((b) => b < bins);+ const bands = frames.map((mm) => { const out = new Float64Array(uniq.length - 1); for (let b = 0; b < uniq.length - 1; b++) { let s = 0; for (let k = uniq[b]; k < Math.max(uniq[b] + 1, uniq[b + 1]); k++) s += mm[k]; out[b] = Math.log10(1 + 100 * s); } return out; });+ const raw = new Float64Array(bands.length);+ for (let t = 1; t < bands.length; t++) { let s = 0; const cur = bands[t], prev = bands[t - 1]; for (let b = 0; b < cur.length; b++) { const pm = Math.max(prev[b], b > 0 ? prev[b - 1] : 0, b + 1 < cur.length ? prev[b + 1] : 0); const d = cur[b] - pm; if (d > 0) s += d; } raw[t] = s; }+ let mx = 0; for (const f of raw) mx = Math.max(mx, f); const flux = Array.from(raw, (x) => x / (mx || 1));+ const times = [], strength = []; let last = -1e9;+ for (let t = 3; t < flux.length - 3; t++) {+ let isMax = true; for (let d = -3; d <= 3; d++) if (flux[t + d] > flux[t]) isMax = false; if (!isMax) continue;+ let mean = 0, c = 0; for (let d = -10; d <= 3; d++) { const j = t + d; if (j >= 0 && j < flux.length) { mean += flux[j]; c++; } } mean /= c;+ if (flux[t] >= mean + delta && raw[t] >= absFloor && (t - last) * hop / sr >= 0.05) { times.push((t * hop) / sr); strength.push(raw[t]); last = t; }+ }+ return { times, strength };+};+/** Absolute onset-strength floor (loudness-normalised flux): real note starts sit far above it, a detuned pad's beating sits below. */+export let ONSET_FLOOR = 4;+export const setOnsetFloor = (x) => { ONSET_FLOOR = x; };+export const onsets = (chans, sr, delta = 0.07) => onsetsDetail(chans, sr, delta).times;++export const centroid = (chans, sr) => {+ const N = 2048, frames = stft(mono(chans), N, 512); let emax = 0; const es = frames.map((m) => { let e = 0; for (const x of m) e += x * x; emax = Math.max(emax, e); return e; });+ let sum = 0, c = 0, wsum = 0, wtot = 0;+ frames.forEach((m, i) => { if (es[i] < emax * 1e-5) return; let num = 0, den = 0; for (let k = 1; k < m.length; k++) { num += ((k * sr) / N) * m[k]; den += m[k]; } if (den > 0) { sum += num / den; c++; wsum += (num / den) * es[i]; wtot += es[i]; } });+ return { mean: c ? sum / c : 0, energyWeighted: wtot ? wsum / wtot : 0 };+};++export const measure = (chans, sr) => {+ const l = loudness(chans, sr), tp = truePeak(chans), on = onsets(chans, sr), c = centroid(chans, sr), dur = chans[0].length / sr;+ return { durationS: dur, lufs: l.integrated, lra: l.lra, shortMax: l.shortMax, dbtp: tp.dbtp, samplePeakDb: tp.samplePeakDb, onsetsPerS: on.length / dur, onsetCount: on.length, centroidHz: c.mean, centroidEnergyHz: c.energyWeighted, lastOnsetS: on.length ? on[on.length - 1] : 0, shortTerm: l.shortTerm };+};++/** RMS of a stem over its active samples (|x| > 1e-4), left channel, dBFS: the level a part plays at when it plays. */+export const stemRms = (x, floor = 1e-4) => { let s = 0, c = 0; for (let i = 0; i < x.length; i++) { const v = x[i]; if (Math.abs(v) > floor) { s += v * v; c++; } } return c ? 10 * Math.log10(s / c + 1e-12) : -Infinity; };+/** The lead may sit up to `LEAD_HEADROOM_DB` above its target before it is flagged (the melody must clear masking). */+export const LEAD_HEADROOM_DB = 3;+/**+ * Stem balance: each part's active RMS against its target; a part more than `tolDb` off is flagged.+ * LESSON (anidoodle's launch score): integrated LUFS of the mix looked right while the sub sat+ * 7-10 dB too hot. Loudness says how loud the whole is, never which part is wrong. Meter the stems.+ */+export const stemBalance = (stems, targets, tolDb = 3, headroom = { lead: LEAD_HEADROOM_DB }) => {+ const rows = Object.entries(stems).map(([id, [L]]) => { const rmsDb = stemRms(L), t = targets[id] ?? null, off = t === null ? null : rmsDb - t; return { id, rmsDb, targetDb: t, offDb: off, ok: off === null || (off >= -tolDb && off <= tolDb + (headroom[id] ?? 0)) }; });+ return { rows, pass: rows.every((r) => r.ok), tolDb, headroom };+};diff --git a/scripts/music/perform.mjs b/scripts/music/perform.mjsnew file mode 100644index 0000000..2ad7334--- /dev/null+++ b/scripts/music/perform.mjs@@ -0,0 +1,85 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// Performance: written notes (beats) -> played key presses (seconds). This is where "MIDI" stops.+// Rules from music-performance research (Todd 1992; the KTH rule system, Friberg, Bresin and+// Sundberg 2006; Repp on melody lead and pedalling). All randomness from rng(seed), smoothed so+// deviations correlate across a phrase instead of jittering note to note. Parts with+// opts.grid === true (drum machines, sequenced synths) skip the humanization.+import { beatsPerBar } from "./plan.mjs";+import { clamp, gauss, rng as mkRng } from "./dsp.mjs";++const arch = (x) => Math.sin(Math.PI * Math.pow(clamp(x, 0, 1), 1.45)); // peaks near 0.62 of the phrase++export const perform = (p, tempo, o) => {+ const plan = p.plan, bpb = beatsPerBar(plan.meter), pick = plan.pickupBeats ?? 0, phraseB = (plan.phraseBars ?? 4) * bpb;+ const totalBeats = plan.sections.reduce((a, s) => a + s.bars * bpb, 0);+ // section spans and the dynamic level curve+ const spans = []; { let b = 0; for (const s of plan.sections) { spans.push({ a: b, b: b + s.bars * bpb, dyn: s.dyn }); b += s.bars * bpb; } }+ const level = (b) => { for (const s of spans) if (b < s.b) { const x = clamp((b - s.a) / (s.b - s.a), 0, 1); return s.dyn[0] + (s.dyn[1] - s.dyn[0]) * x; } return spans[spans.length - 1].dyn[1]; };+ // caesura: a breath before a sudden hush (next section starts far quieter than this one ended)+ const breaths = [];+ if (o.expressive) for (let i = 1; i < spans.length; i++) if (spans[i].dyn[0] < 0.6 * spans[i - 1].dyn[1]) breaths.push({ at: spans[i].a, beats: 0.4 });+ // tempo factor per beat (>1 = faster)+ const lastMel = Math.max(...p.parts.flatMap((pt) => pt.notes.map((n) => n.t)));+ const ritBeats = Math.min(2 * bpb, 6, Math.max(1, 0.25 * (totalBeats + pick))), ritFrom = lastMel - ritBeats;+ const factor = (b) => {+ if (!o.expressive) return 1;+ const x = ((b + pick) % phraseB) / phraseB;+ const rub = plan.rubato ?? (plan.style === "nocturne" || plan.style === "cinematic" ? 1 : 0), w = plan.ritard ?? 0.55;+ let f = 1 + rub * (0.05 * arch(x) - 0.025);+ if (b > ritFrom && w < 1) { const u = clamp((b - ritFrom) / ritBeats, 0, 1), q = 2.5; f *= Math.pow(1 + (Math.pow(w, q) - 1) * u, 1 / q); }+ return f;+ };+ const step = 1 / 96, b0 = -pick - 1, b1 = totalBeats + 16, spb = 60 / tempo;+ const tab = new Float64Array(Math.ceil((b1 - b0) / step) + 2); let acc = 0;+ for (let i = 0; i < tab.length; i++) { tab[i] = acc; const b = b0 + i * step; acc += (spb / factor(b)) * step; for (const br of breaths) if (Math.abs(b - br.at) < step / 2) acc += br.beats * spb; }+ const lead = pick > 0 ? 0.25 : 0.0; // a hair of silence before the first note+ const secRaw = (b) => { const f = (b - b0) / step, i = Math.floor(f), u = f - i; const a = tab[clamp(i, 0, tab.length - 1)], c = tab[clamp(i + 1, 0, tab.length - 1)]; return a + (c - a) * u; };+ const start = secRaw(-pick);+ const sec = (b) => secRaw(b) - start + lead;+ const swing = plan.swing ?? 0.5;+ const sw = (b) => { if (swing === 0.5) return b; const fl = Math.floor(b), fr = b - fl; return fl + (fr <= 0.5 ? fr * (swing / 0.5) : swing + (fr - 0.5) * ((1 - swing) / 0.5)); };++ const RoleGain = { melody: 1, inner: 0.55, bass: 0.68, accomp: 0.52, color: 0.7, drum: 1 }; // voicing: melody 6-10 dB over the rest+ let leadSum = 0, leadN = 0;+ const parts = p.parts.map((pt, pi) => {+ const hr = mkRng(p.seed * 131 + pi * 17 + 1), grid = pt.opts?.grid === true, isPiano = pt.inst === "piano";+ let tDev = 0, vDev = 0; // AR(1) states+ const notes = pt.notes.slice().sort((a, b) => a.t - b.t || a.p - b.p);+ const keys = [];+ const melodyNext = (n, i) => { for (let j = i + 1; j < notes.length; j++) if (notes[j].t > n.t + 1e-6) return notes[j].t; return Infinity; };+ let lastT = -1e9, chordIdx = 0;+ notes.forEach((n, i) => {+ if (Math.abs(n.t - lastT) > 1e-6) { chordIdx = 0; lastT = n.t; if (o.expressive && !grid) { tDev = 0.85 * tDev + Math.sqrt(1 - 0.85 * 0.85) * gauss(hr) * 0.007; vDev = 0.7 * vDev + Math.sqrt(1 - 0.49) * gauss(hr) * 0.035; } } else chordIdx++;+ let t = sec(sw(n.t)), end = sec(sw(n.t + n.d));+ let v;+ if (!o.expressive) { v = o.flatVelocity ?? 0.6; }+ else {+ const x = ((n.t + pick) % phraseB) / phraseB, lv = level(n.t);+ const metric = Math.abs(n.t - Math.round(n.t / bpb) * bpb) < 1e-6 ? 1.06 : Math.abs(n.t - Math.round(n.t)) < 1e-6 ? 1 : 0.95;+ const hi = n.role === "melody" ? 1 + 0.06 * ((n.p - 72) / 12) : 1;+ // written v 0.7 = mezzo; section level 0..1 maps to 0.25..0.85 of full velocity+ v = (n.v / 0.7) * (0.25 + 0.6 * lv) * (0.92 + 0.16 * arch(x)) * (grid ? 1 : metric * hi) * (isPiano ? RoleGain[n.role] : 1 / (0.25 + 0.6 * 0.75)) + vDev;+ if (n.t > ritFrom && !plan.loop) v *= 1 - 0.18 * clamp((n.t - ritFrom) / ritBeats, 0, 1); // the cadence relaxes+ t += tDev;+ if (n.role === "melody" && isPiano) { const ld = 0.012 + 0.016 * clamp(v, 0, 1); t -= ld; leadSum += ld; leadN++; }+ if (n.roll !== undefined) t += chordIdx * n.roll; else if (chordIdx > 0 && !grid) t += chordIdx * 0.004;+ // legato: melody keys overlap the next note by ~35 ms; accompaniment keys lift a little early (the pedal holds)+ if (n.role === "melody" && isPiano) { const nx = melodyNext(n, i); if (Number.isFinite(nx) && Math.abs(nx - (n.t + n.d)) < 1e-6) end = sec(sw(nx)) + 0.035; }+ else if (isPiano) end = t + (end - t) * 0.92;+ }+ keys.push({ t: Math.max(0, t), off: Math.max(t + 0.03, end), p: n.p, v: clamp(v, 0.03, 1), role: n.role, kind: n.kind, w: n.v });+ });+ return { id: pt.id, keys };+ });+ // pedal: lift just after each harmony change, catch again ~110 ms later (legato pedalling)+ const pedal = [];+ if (o.expressive && p.harmony.length) {+ const ch = p.harmony.slice().sort((a, b) => a.t - b.t);+ for (let i = 0; i < ch.length; i++) {+ const down = sec(sw(ch[i].t)) + 0.11, up = i + 1 < ch.length ? sec(sw(ch[i + 1].t)) + 0.03 : 1e9;+ pedal.push([down, up]);+ }+ }+ const lastOnset = Math.max(...parts.flatMap((pp) => pp.keys.map((k) => k.t)));+ return { parts, pedal, sec: (b) => sec(sw(b)), lastOnset, meanLeadMs: leadN ? (leadSum / leadN) * 1000 : 0 };+};diff --git a/scripts/music/piano.mjs b/scripts/music/piano.mjsnew file mode 100644index 0000000..a4e86da--- /dev/null+++ b/scripts/music/piano.mjs@@ -0,0 +1,157 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// A modal, physics-shaped piano. No samples: every sound below is a sum of decaying sinusoids and+// filtered seeded noise.+//+// strings f_n = n f0 sqrt(1 + B n^2), B rising from bass to treble (Fletcher 1964 shape)+// unisons 2-3 strings per key detuned 0.3-1.8 cents: a fast "prompt" decay (strings in+// phase, coupled through the bridge) and a slow beating "aftersound" (Weinreich 1977)+// hammer velocity sets loudness AND the spectrum (a faster hammer = shorter contact =+// brighter); the strike point near 1/8 of the string notches partial ~8+// losses every partial decays at its own rate, faster with frequency; sustain by register+// attack a keybed/hammer knock (low thump + short click) and a soundboard modal body+// dampers key-up or pedal-up engages the felt: fast decay plus a breath of felt noise;+// the top keys (MIDI >= 89) have no dampers, as on a real grand+// pedal sustain pedal holds dampers off; undamped strings whose partials coincide with+// the played notes ring sympathetically; a pedal "halo" feeds the room+// stereo bass left, treble right (player's seat)+import { TAU, clamp, pan, onePoleCoef, SVF, gauss, rng as mkRng } from "./dsp.mjs";++export const PIANO_REAL = { inharmonic: true, multiString: true, twoStage: true, hammer: true, knock: true, body: true, sympathetic: true, damperNoise: true, stretch: true, pedal: true, width: 0.4 };+/** The contrast baseline: harmonic partials, one string, one-slope decay, fixed spectrum, no pedal. */+export const PIANO_FLAT = { inharmonic: false, multiString: false, twoStage: false, hammer: false, knock: false, body: false, sympathetic: false, damperNoise: false, stretch: false, pedal: false, width: 0.4 };++const f0Of = (m, stretch) => 440 * Math.pow(2, (m - 69) / 12 + (stretch ? (m > 60 ? 0.012 * Math.pow(m - 60, 1.9) : -0.02 * Math.pow(60 - m, 1.6)) / 1200 : 0));+/** Inharmonicity coefficient by key: ~1e-4 in the wound bass, ~5e-4 at C4, ~4e-3 at C7. */+export const inharmonicityB = (m) => Math.pow(10, m <= 40 ? -3.8 + 0.015 * (40 - m) : -3.8 + 0.0245 * (m - 40));+/** Aftersound T60 of the fundamental by key (s): ~20 s at C4, ~6 s at C6; the prompt sound is 4x faster. */+const t60After = (m) => clamp(20 * Math.pow(2, (-0.9 * (m - 60)) / 12), 1.6, 40);+/** Register trim (dB) so a scale at one velocity reads roughly even. */+const regGain = (m) => Math.pow(10, (m > 60 ? 0.15 * (m - 60) : 0.03 * (60 - m)) / 20);+const stringsPerKey = (m) => (m < 32 ? 1 : m < 44 ? 2 : 3);++export const renderPiano = (keys, pedal, sr, n, o, seed) => {+ const L = new Float32Array(n), R = new Float32Array(n), halo = new Float32Array(n), bodyIn = new Float32Array(n);+ const rnd = mkRng(seed * 31 + 7);+ const pedalAt = (t) => o.pedal && pedal.some(([a, b]) => t >= a && t < b);+ const pedalUpAfter = (t) => { for (const [a, b] of pedal) if (t >= a && t < b) return b; return t; };+ const sorted = keys.slice().sort((a, b) => a.t - b.t);+ const maxLen = Math.min(n, Math.ceil(32 * sr));+ const buf = new Float64Array(maxLen);++ sorted.forEach((k, idx) => {+ const m = k.p, v = clamp(k.v, 0.02, 1), i0 = Math.round(k.t * sr); if (i0 >= n) return;+ const keyR = mkRng(m * 7919 + seed); // per-KEY constants: the same key always has the same strings+ const f0 = f0Of(m, o.stretch), B = o.inharmonic ? inharmonicityB(m) : 0, S = o.multiString ? stringsPerKey(m) : 1;+ const detune = Array.from({ length: S }, (_, s) => (S === 1 ? 0 : (s - (S - 1) / 2) * (0.35 + 1.4 * keyR()) / 1200 * Math.LN2));+ const beta = 0.118 + 0.012 * keyR() + (m > 72 ? -0.02 * (m - 72) / 36 : 0);+ // when does the felt land on the strings?+ let damp = o.pedal ? (pedalAt(k.off) ? pedalUpAfter(k.off) : k.off) : k.off;+ if (m >= 89) damp = Infinity;+ // a restrike of the same key stops this instance's strings+ for (let j = idx + 1; j < sorted.length; j++) if (sorted[j].p === m && sorted[j].t > k.t) { damp = Math.min(damp, sorted[j].t + 0.004); break; }+ const t60a = t60After(m), sigA0 = 6.91 / t60a, sigP0 = sigA0 * 4, sigSingle = sigA0 * 2.4;+ const sigD = 6.91 / (0.1 + 0.28 * clamp((60 - m) / 36, 0, 1));+ const dampI = damp === Infinity ? Infinity : Math.round((damp - k.t) * sr);+ const natural = Math.round(Math.min(t60a * 1.05, 32) * sr);+ const len = Math.min(maxLen, n - i0, dampI === Infinity ? natural : Math.min(natural, dampI + Math.round(0.9 * sr)));+ if (len <= 0) return;+ buf.fill(0, 0, len);+ // hammer: loudness and brightness from velocity; contact time shorter when harder+ // felt hardening: above mf a faster hammer mostly buys brightness, less level (exponent 1.55 -> 0.9)+ const loud = v < 0.6 ? Math.pow(v, 1.55) : Math.pow(0.6, 1.55) * Math.pow(v / 0.6, 0.9);+ const fc = o.hammer ? (330 + 3300 * v * v) * Math.pow(f0 / 262, 0.3) : 1300 * Math.pow(f0 / 262, 0.3);+ const nyq = Math.min(0.45 * sr, 15000);+ let a1 = 0;+ for (let p = 1; p <= 90; p++) {+ const fn = p * f0 * Math.sqrt(1 + B * p * p); if (fn > nyq) break;+ const comb = o.hammer ? 0.1 + 0.9 * Math.abs(Math.sin(Math.PI * p * beta)) : 1;+ const ham = 1 / Math.sqrt(1 + Math.pow(fn / fc, 6)) * (o.hammer ? 1 : 1 / Math.pow(p, 0.35));+ const rad = (fn * fn) / (fn * fn + 105 * 105) / Math.sqrt(1 + Math.pow(fn / 6500, 4));+ const A = (comb * ham * rad) / Math.pow(p, 0.9);+ if (p === 1) a1 = Math.max(A, 1e-6);+ if (A < a1 * 2e-4 && p > 3) continue;+ const fac = 1 + 0.8 * Math.pow(fn / 1500, 2) + fn / 4000;+ const ph = TAU * keyR(); // deterministic per key+ const comps = []; // [freq, amp, sigma]+ if (o.twoStage) {+ const wa = 0.2 / (1 + 0.12 * (p - 1));+ comps.push([fn, A * (1 - wa), sigP0 * fac]);+ if (S > 1) { comps.push([fn * Math.exp(detune[0]), (A * wa) / 2, sigA0 * fac]); comps.push([fn * Math.exp(detune[S - 1]), (A * wa) / 2, sigA0 * fac * 1.07]); }+ else comps.push([fn, A * wa, sigA0 * fac]);+ } else {+ const sig = o.multiString ? sigSingle * fac : sigSingle * (1 + 0.5 * (p - 1));+ if (S > 1) for (let s = 0; s < S; s++) comps.push([fn * Math.exp(detune[s]), A / S, sig]);+ else comps.push([fn, A, sig]);+ }+ comps.forEach(([f, amp, sig], ci) => {+ const w = (TAU * f) / sr, cr = Math.cos(w), ci_ = Math.sin(w);+ let re = amp * Math.cos(ph + ci * 1.3), im = amp * Math.sin(ph + ci * 1.3);+ const dec = Math.exp(-sig / sr), decD = Math.exp(-(sig + sigD) / sr);+ const floor = a1 * 1e-5;+ // how long until this component is inaudible (undamped part)+ const lenC = Math.min(len, Math.ceil((Math.log(amp / floor) / sig) * sr) + 1);+ const dI = Math.min(lenC, dampI === Infinity ? lenC : Math.max(0, dampI));+ for (let i = 0; i < dI; i++) { buf[i] += re; const r2 = (re * cr - im * ci_) * dec; im = (re * ci_ + im * cr) * dec; re = r2; }+ if (dI < lenC) { const lenD = Math.min(lenC, dI + Math.ceil((Math.log(Math.max(Math.hypot(re, im), floor * 1.0001) / floor) / (sig + sigD)) * sr) + 1);+ for (let i = dI; i < lenD; i++) { buf[i] += re; const r2 = (re * cr - im * ci_) * decD; im = (re * ci_ + im * cr) * decD; re = r2; } }+ });+ }+ // hammer contact ramp: 2.2 ms (ff) to 4 ms (pp), raised cosine; this is also a gentle low-pass on the attack+ const ramp = Math.max(2, Math.round((o.hammer ? 4.2 - 2.0 * v : 1.5) / 1000 * sr));+ for (let i = 0; i < ramp && i < len; i++) buf[i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / ramp);+ const REF = 0.37, norm = ((0.22 * loud) / REF) * regGain(m); // fixed scale: register balance comes from the physics, trimmed by regGain+ // knock: a low thump from the action and keybed plus a short click where the hammer lands+ if (o.knock) {+ const kl = Math.min(len, Math.round(0.06 * sr)), sv = new SVF(sr, 2400 + 1600 * v, 0.9);+ for (let i = 0; i < kl; i++) {+ const t = i / sr;+ buf[i] += (0.9 * Math.sin(TAU * 92 * t) * Math.exp(-t / 0.018) + 0.5 * Math.sin(TAU * 205 * t) * Math.exp(-t / 0.011)) * 0.10 * v * REF;+ buf[i] += sv.tick(gauss(rnd)) * Math.exp(-t / 0.0028) * 0.35 * v * v * REF;+ }+ }+ // felt landing on the strings: a breath of low noise at the damp point+ const [gl, gr] = pan(clamp((m - 62) / 34, -1, 1) * o.width);+ if (o.damperNoise && dampI !== Infinity && dampI < len) {+ const sv = new SVF(sr, 500, 0.7), dl = Math.min(len - dampI, Math.round(0.07 * sr));+ for (let i = 0; i < dl; i++) buf[dampI + i] += sv.tick(gauss(rnd)) * Math.sin((Math.PI * i) / dl) * 0.012 * v * REF;+ }+ const inPedal = pedalAt(k.t) || pedalAt(k.t + 0.25);+ for (let i = 0; i < len; i++) {+ const s = buf[i] * norm, j = i0 + i;+ L[j] += s * gl; R[j] += s * gr;+ if (o.body) bodyIn[j] += s * 0.05;+ if (inPedal) halo[j] += s;+ }+ // soundboard excitation: the hammer's force pulse+ if (o.body) { const pl = Math.round((0.0035 - 0.0025 * v) * sr); for (let i = 0; i < pl && i0 + i < n; i++) bodyIn[i0 + i] += Math.sin((Math.PI * i) / pl) * 0.45 * loud * 0.22; }+ // sympathetic strings: open strings whose partials coincide with this note's ring while the pedal is down+ if (o.sympathetic && inPedal) {+ const up = pedalUpAfter(Math.max(k.t, k.t + 0.25));+ const endI = Math.min(n - i0, Math.round((up - k.t) * sr) + Math.round(0.25 * sr), Math.round(10 * sr));+ for (const [off, harmOfGhost, harmOfNote, cpl] of [[-12, 2, 1, 0.07], [-19, 3, 1, 0.05], [-24, 4, 1, 0.035], [12, 1, 2, 0.05], [19, 1, 3, 0.03], [7, 2, 3, 0.03]]) {+ const gm = m + off; if (gm < 21 || gm > 108) continue;+ const gf0 = f0Of(gm, o.stretch), gB = o.inharmonic ? inharmonicityB(gm) : 0;+ const f = harmOfGhost * gf0 * Math.sqrt(1 + gB * harmOfGhost * harmOfGhost);+ const noteP = harmOfNote * f0 * Math.sqrt(1 + B * harmOfNote * harmOfNote);+ const mis = Math.abs(f - noteP) / noteP; if (mis > 0.004) continue;+ const sig = 6.91 / t60After(gm) * (1 + 0.8 * Math.pow(f / 1500, 2)), dec = Math.exp(-sig / sr);+ const [pl, pr] = pan(clamp((gm - 62) / 34, -1, 1) * o.width);+ const amp = 0.22 * loud * cpl * (harmOfNote === 1 ? 1 : 0.5), w = (TAU * f) / sr, rise = Math.exp(-1 / (0.18 * sr));+ let e = 1, env = 0; const dampStart = Math.round((up - k.t) * sr), decD = Math.exp(-(sig + 25) / sr);+ let g = 1, c = Math.cos(gm), sn = Math.sin(gm); const cw = Math.cos(w), sw = Math.sin(w);+ for (let i = 0; i < endI; i++) { env = 1 - (e *= rise); const sOut = sn * amp * env * g; L[i0 + i] += sOut * pl; R[i0 + i] += sOut * pr; halo[i0 + i] += sOut; g *= i < dampStart ? dec : decD; const c2 = c * cw - sn * sw; sn = c * sw + sn * cw; c = c2; }+ }+ }+ });+ // soundboard: a bank of ~40 fixed modes excited by the hammer pulses and a trace of the strings+ if (o.body) {+ const br = mkRng(seed * 13 + 101), out = new Float32Array(n);+ for (let k = 0; k < 40; k++) {+ const f = 70 * Math.pow(3600 / 70, (k + br()) / 40), q = 12 + 26 * br(), g = (0.5 + br()) / Math.sqrt(f / 70) * 0.9;+ const sv = new SVF(sr, f, q); for (let i = 0; i < n; i++) { sv.tick(bodyIn[i]); out[i] += sv.bp * g; }+ }+ const hp = onePoleCoef(sr, 60); let z = 0;+ for (let i = 0; i < n; i++) { z += hp * (out[i] - z); const s = (out[i] - z) * 0.16; L[i] += s * 0.95; R[i] += s * 0.85; }+ }+ return { L, R, halo };+};diff --git a/scripts/music/pieces/first-light.mjs b/scripts/music/pieces/first-light.mjsnew file mode 100644index 0000000..96af764--- /dev/null+++ b/scripts/music/pieces/first-light.mjs@@ -0,0 +1,100 @@+// "First Light", a gentle bed in G for piano and strings. Original composition for the+// take-one code music engine (the engine is adapted from anidoodle, Apache-2.0).+//+// THE HOOK is a slow rise of a third that settles by step: G4 A4 B4, answered a chord later.+// It opens the theme, climbs through Em and C in the build to a B5 over Am (the 9th, the piece's+// one bright ache), and comes home through a borrowed Cm (the Eb) in the coda.+//+// bar 0 intro G left hand alone, p, melody pickup on beat 3+// bars 1-8 theme G D/F# Em C G/B Am D7 G stepwise line, strings join at bar 5+// bars 9-12 build Em C Am D7 eighth-note left hand, melody in the high octave+// bars 13-16 coda C Cm D7 G hush (a breath before it), the Eb ache, home+import { line } from "../plan.mjs";++const BPB = 3;+const mel = (t, s, v = 0.7, pickup) => line(t, s, { role: "melody", v, bpb: BPB, pickup });+const bass = (t, s, v = 0.7) => line(t, s, { role: "bass", v, bpb: BPB, roll: 0.03 });+const lh = (t, s, v = 0.7) => line(t, s, { role: "accomp", v, bpb: BPB, roll: 0.035 });+const str = (t, s, v = 0.45) => line(t, s, { role: "inner", v, bpb: BPB, roll: 0.02 });+const H = (xs) => xs.map(([t, name]) => ({ t, name }));++const firstLight = () => {+ const melody = [+ ...mel(2, "D4:1", 0.64, 1), // the pickup, in the intro bar+ ...mel(3, [+ "G4:1.5 A4:.5 B4:1", // 1 G the hook: a slow rise+ "A4:2 F#4:1", // 2 D/F#+ "B4:1.5 C5:.5 E5:1", // 3 Em the rise again, leaping onto E+ "D5:2 C5:1", // 4 C+ "B4:1.5 A4:.5 G4:1", // 5 G/B falling home (strings enter)+ "A4:1 C5:1 E5:1", // 6 Am climbing+ "D5:1.5 C5:.5 A4:.5 F#4:.5", // 7 D7+ "G4:2 B4:1", // 8 G cadence; B4 lifts into the build+ "B4:1 E5:[email protected] G5:[email protected]", // 9 Em the rise, an octave wide+ "B5:[email protected] A5:.5 G5:.5 F#5:.5", // 11 Am CLIMAX: the 9th over Am, then down by step+ "E5:[email protected] D5:[email protected] C5:1", // 12 D7 falling into the hush+ "B4:2 A4:1", // 13 C coda, pianissimo+ "G4:1 Eb4:1 D4:1", // 14 Cm the borrowed iv: Eb is the ache+ "A4:1.5 G4:.5 F#4:1", // 15 D7+ "G4:3", // 16 G home+ ].join(" | ")),+ ];+ // climax chord: a rolled E5-A5 under the B5 (bar 11 = beat 33), so the loudness holds and the peak drops+ const climaxChord = line(33, "[E5 A5]:1.5 r:1.5", { role: "inner", v: 0.55, bpb: BPB, roll: 0.045 });+ const bassLine = bass(0, [+ "G2:3", // 0 intro+ "G2:3", "F#2:3", "E2:3", "C2:3", "B1:3", "A1:3", "D2:3", "G1:1.5 D2:1.5", // 1-8+ "r:.5 E2:2.5", "r:.5 C2:2.5", "r:.5 A1:2.5", "r:.5 D2:2.5", // 9-12 staggered: the bass answers after each downbeat+ "C2:3", "C2:3", "D2:3", "[G1 D2 G2 D3 G3]:3", // 13-16 rolled home+ ].join(" | "), 0.62);+ const accomp = lh(0, [+ "r:1 D3:1 B3:1", // 0 intro+ "r:1 D3:1 B3:1", "r:1 D3:1 A3:1", "r:1 E3:1 G3:1", "r:1 E3:1 G3:1", // 1-4+ "r:1 D3:1 G3:1", "r:1 E3:1 C4:1", "r:1 F#3:1 C4:1", "r:1 D3:1 B3:1", // 5-8+ "r:.5 E3:.5 G3:.5 B3:.5 G3:.5 E3:.5", // 9 Em the pulse quickens+ "r:.5 E3:.5 G3:.5 C4:.5 G3:.5 E3:.5", // 10 C+ "r:.5 E3:.5 A3:.5 C4:.5 A3:.5 E3:.5", // 11 Am+ "r:.5 F#3:.5 A3:.5 C4:.5 A3:.5 F#3:.5", // 12 D7+ "r:2 G3:1", "r:2 G3:1", "r:2 F#3:1", "r:3", // 13-16 the hush, single notes+ ].join(" | "), 0.62);+ // strings: a quiet sustained choir from bar 5, swelling with the build, thinning in the coda+ const stringsPart = str(15, [+ "[G3 D4]:3", "[A3 E4]:3", "[A3 D4]:3", "[G3 B3]:3", // 5-8+ "[E3 G3 B3]:3", "[E3 G3 C4]:3", "[E3 A3 C4]:3", "[F#3 A3 C4]:3", // 9-12 build+ "[E3 G3 C4]:3", "[Eb3 G3 C4]:3", "[D3 F#3 C4]:3", "[D3 G3 B3]:3", // 13-16 coda (the Eb)+ ].join(" | "), 0.4);+ const harmony = H([[0, "G"], [3, "G"], [6, "D/F#"], [9, "Em"], [12, "C"], [15, "G/B"], [18, "Am"], [21, "D7"], [24, "G"],+ [27, "Em"], [30, "C"], [33, "Am"], [36, "D7"], [39, "C"], [42, "Cm"], [45, "D7"], [48, "G"]]);+ return {+ title: "First Light (bed in G)", seed: 4207, tail: 1.8, harmony, shortForm: firstLightShort,+ plan: {+ style: "nocturne", tempo: 64, meter: "3/4", phraseBars: 4,+ sections: [+ { id: "intro", bars: 1, mood: "tender", key: "G", mode: "major", melody: ["stepwise"], dyn: [0.35, 0.38], optional: true },+ { id: "theme", bars: 8, mood: "tender", key: "G", mode: "major", melody: ["hook", "stepwise"], dyn: [0.4, 0.6], repeatable: true, pickup: 1, variations: ["octaveDouble", "octaveUp"] },+ { id: "build", bars: 4, mood: ["tender", "hopeful", 0.5], key: "G", mode: "major", melody: ["hook", "sequence"], dyn: [0.65, 0.88], repeatable: true, pickup: 1 },+ { id: "coda", bars: 4, mood: ["tender", "melancholy", 0.4], key: "G", mode: "major", melody: ["themeTransformation"], dyn: [0.38, 0.26], ending: "tail" },+ ],+ },+ parts: [+ { id: "rh", inst: "piano", role: "melody", notes: [...melody, ...climaxChord] },+ { id: "lh", inst: "piano", role: "accomp", notes: [...bassLine, ...accomp] },+ { id: "str", inst: "strings", role: "inner", notes: stringsPart, gainDb: -10, opts: { attack: 0.85, release: 1.3, bright: 0.55, width: 0.6 }, send: 1.2 },+ ],+ };+};++/** The short form, for films under ~40 s: intro + theme, closing on the bar-8 cadence (the B4 lift+ * into the build becomes a held G). The theme repeats with its variations when the film needs it. */+const firstLightShort = () => {+ const full = firstLight(), END = 27;+ const parts = full.parts.map((pt) => ({ ...pt, notes: pt.notes.filter((n) => n.t < END && !(n.role === "melody" && n.t >= 24)) }));+ parts[0].notes.push(...line(24, "G4:3", { role: "melody", v: 0.66, bpb: BPB }));+ parts[1].notes = parts[1].notes.filter((n) => !(n.role === "bass" && n.t >= 24)).concat(bass(24, "[G1 D2 G2 D3 G3]:3", 0.62));+ const sections = full.plan.sections.slice(0, 2).map((x) => (x.id === "theme" ? { ...x, dyn: [0.4, 0.5], ending: "tail" } : x));+ return { ...full, title: "First Light (short form)", shortForm: undefined, parts, harmony: full.harmony.filter((c) => c.t < END), plan: { ...full.plan, ritard: 0.7, sections } };+};++export default firstLight;+export { firstLightShort };diff --git a/scripts/music/pieces/night-drive.mjs b/scripts/music/pieces/night-drive.mjsnew file mode 100644index 0000000..5c4edbc--- /dev/null+++ b/scripts/music/pieces/night-drive.mjs@@ -0,0 +1,69 @@+// "Night Drive", a 120 bpm half-time lofi groove loop, 8 bars of 4/4 = exactly 16.000 s.+// Original composition for the take-one code music engine (engine adapted from anidoodle,+// Apache-2.0). A seamless loop: plan.loop is set, so renderLoop folds the reverb/delay tail back+// onto bar 1 and the CLI renders it loop-ready. The last bar ends on E (the v), not a cadence,+// so the loop pulls back to Am forever.+//+// chords, one per bar, twice around: Am9 Fmaj9 Cmaj9 Em7+// drums: half-time (snare on 3), swung eighth hats, kick ducks the pad and keys (the pump)+// voices: warm detuned-saw pad (rootless voicings), soft pluck lead through a dotted-eighth+// ping-pong delay, FM e-piano offbeat stabs, sine sub on the roots, vinyl crackle+import { line } from "../plan.mjs";++const BPB = 4;+const L = (t, s, role, v = 0.7, extra = {}) => line(t, s, { role, v, bpb: BPB, ...extra });+const BPM = 120, BARS = 8, DOTTED_EIGHTH = (60 / BPM) * 0.75;++// one part written a bar at a time: fn(bar, chord index 0..3) -> notation or null+const byBar = (role, v, fn, extra = {}) => {+ const out = [];+ for (let b = 0; b < BARS; b++) { const s = fn(b, b % 4); if (s) out.push(...L(b * 4, s, role, v, extra)); }+ return out;+};++const PAD = ["[E3 A3 C4 E4]", "[A3 C4 E4 G4]", "[E3 G3 B3 D4]", "[G3 B3 D4 E4]"]; // Am, Fmaj9 (rootless), Cmaj9, Em7+const SUB = ["A1:3 r:.5 E2:.5", "F1:3 r:.5 C2:.5", "C2:3 r:.5 G1:.5", "E2:3 r:.5 E1:.5"];+const STAB = ["r:1.5 [C4 E4 A4]:1 r:1.5", "r:2.5 [C4 E4 G4]:1 r:.5", "r:1.5 [D4 E4 G4]:1 r:1.5", "r:2.5 [B3 D4 G4]:1 r:.5"];+const LEAD = [+ null, // 1 the pad establishes+ "r:2.5 E5:.5 G5:.5 A5:.5", // 2 pickup run+ "B5:1.5 A5:.5 G5:.5 E5:1 r:.5", // 3 the hook, high+ "G5:.5 E5:.5 D5:1 E5:1.5 r:.5", // 4+ "r:.5 A4:.5 C5:.5 E5:1 D5:.5 C5:1", // 5 the answer, low+ "A4:1 C5:.5 A4:.5 G4:2", // 6+ "r:.5 E5:.5 G5:.5 B5:1 A5:.5 G5:1", // 7 hook variant+ "E5:1 D5:.5 B4:.5 D5:1 A4:1", // 8 ends hanging on the 11th: the loop pulls home+];++export default () => {+ const pad = byBar("accomp", 0.6, (b, c) => `${PAD[c]}:4`, { roll: 0.025 });+ const keys = byBar("inner", 0.62, (b, c) => (b === 0 ? null : STAB[c]), { roll: 0.02 });+ const lead = byBar("melody", 0.72, (b) => LEAD[b]);+ const subL = byBar("bass", 0.8, (b, c) => (b === 7 ? "E2:2 D2:1 E2:1" : SUB[c]));+ const kick = byBar("drum", 0.85, (b) => (b % 2 ? "C4:1 r:1.5 C4:[email protected] r:.5 C4:[email protected]" : "C4:1 r:1.75 C4:[email protected]"));+ const snare = byBar("drum", 0.7, () => "r:2 C4:2");+ const ghost = byBar("drum", 0.5, (b) => (b % 2 ? "r:3.75 C4:[email protected]" : null));+ const hats = byBar("drum", 0.5, () => "C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected] C4:[email protected]");+ const crackle = [{ t: 0, d: BARS * 4, p: 60, v: 0.5, role: "color" }];+ const harmony = Array.from({ length: BARS }, (_, b) => ({ t: b * 4, name: ["Am9", "Fmaj9", "Cmaj9", "Em7"][b % 4] }));+ return {+ title: "Night Drive (lofi loop, 120)", seed: 3117, tail: 2.4, harmony,+ plan: {+ style: "lofi", tempo: BPM, meter: "4/4", swing: 0.57, loop: true, phraseBars: 4,+ sections: [{ id: "loop", bars: BARS, mood: "nostalgic", key: "A", mode: "aeolian", melody: ["hook"], dyn: [0.6, 0.66], repeatable: true }],+ },+ parts: [+ { id: "pad", inst: "warmPad", role: "accomp", notes: pad, gainDb: -4, opts: { cut: 2100, attack: 0.4, release: 1.2, spread: 0.7 }, send: 0.35 },+ { id: "keys", inst: "ePiano", role: "inner", notes: keys, gainDb: 0, opts: { width: 0.4 }, send: 0.3 },+ { id: "lead", inst: "softPluck", role: "melody", notes: lead, gainDb: 4, opts: { decay: 0.45, bright: 5400, delay: DOTTED_EIGHTH, feedback: 0.28, delayMix: 0.26 }, send: 0.25 },+ { id: "sub", inst: "sub", role: "bass", notes: subL, gainDb: -7, opts: { cut: 150 } },+ { id: "kick", inst: "kick", role: "drum", notes: kick, gainDb: 0.5, send: 0.08 },+ { id: "snare", inst: "snare", role: "drum", notes: snare, gainDb: 6, send: 0.3 },+ { id: "ghost", inst: "snare", role: "drum", notes: ghost, opts: { rim: true }, gainDb: 3, send: 0.2 },+ { id: "hat", inst: "hat", role: "drum", notes: hats, opts: { pan: 0.25 }, gainDb: 18, send: 0.1 },+ { id: "vinyl", inst: "vinyl", role: "color", notes: crackle, gainDb: -10 },+ ],+ fx: { duck: { by: "kick", parts: ["pad", "keys"], depth: 0.35, release: 0.24 }, tape: { wowCents: 5, wowHz: 0.375, flutterCents: 1.2, flutterHz: 6, drive: 1.15 } },+ stemTargets: { kick: -14, snare: -21, hat: -28, sub: -18, pad: -21, lead: -17, keys: -23 },+ };+};diff --git a/scripts/music/plan.mjs b/scripts/music/plan.mjsnew file mode 100644index 0000000..b0a30b3--- /dev/null+++ b/scripts/music/plan.mjs@@ -0,0 +1,112 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// The Piece/Section/Part model, the bar-checked line() text notation, the plan validator, and+// resequence() (repeat/drop sections so a piece fits any film duration).+//+// A Note is { t, d, p, v, role, roll?, kind? }: t, d in beats from the piece start; p = MIDI;+// v = written velocity 0..1 (performance shapes it). Roles: melody | inner | bass | accomp | color | drum.+import { midi, MODES, detectMode, pcOf, modeFit } from "./theory.mjs";+import { MOODS, STYLES, REFUSED_BLENDS } from "./tables.mjs";++export const beatsPerBar = (m) => (m === "3/4" ? 3 : m === "4/4" ? 4 : m === "6/8" ? 2 : 4);++// ---------------------------------------------------------------- notation+// "Eb4:1 | C5:2 Bb4:.5 Ab4:.5 | [Ab2 Eb3]:1 r:2 | G5:1/[email protected] ..." ; a token is NOTE:DUR[@VEL] or+// [CHORD]:DUR[@VEL] or r:DUR. Every bar must sum to the meter, the last one too (a line that ends+// mid-bar writes its rest: "C2:3 r:1"): a wrong bar throws, so a gap is always written, never+// silent. The first bar may instead be a declared `pickup`, or, when the line starts off the+// barline, exactly the beats left to the next barline. A `hit` (a ping, a sting placed on any beat)+// is one bar no longer than the meter, said out loud with `hit: true`.+const dur = (s) => { if (s.includes("/")) { const [a, b] = s.split("/").map(Number); return a / b; } return Number(s); };+export const line = (start, src, o) => {+ const out = []; let t = start; const bars = src.split("|").map((b) => b.trim()).filter((b, i, a) => b.length || (i > 0 && i < a.length - 1));+ if (o.hit && bars.length !== 1) throw new Error(`a hit is one bar, got ${bars.length}: "${src}"`);+ bars.forEach((bar, bi) => {+ let sum = 0;+ for (const tok of bar.split(/\s+(?![^\[]*\])/).filter(Boolean)) {+ const m = /^(\[[^\]]+\]|[^:]+):([0-9./]+)(?:@([0-9.]+))?$/.exec(tok); if (!m) throw new Error(`bad token "${tok}" in "${bar}"`);+ const d = dur(m[2]), vel = (o.v ?? 0.7) * (m[3] ? Number(m[3]) : 1);+ if (m[1] !== "r") {+ const names = m[1].startsWith("[") ? m[1].slice(1, -1).trim().split(/\s+/) : [m[1]];+ for (const nm of names) out.push({ t, d, p: midi(nm), v: vel, role: o.role, roll: names.length > 1 ? o.roll ?? 0.012 : undefined, kind: o.kind });+ }+ t += d; sum += d;+ }+ const first = bi === 0, toBarline = o.bpb - (((start % o.bpb) + o.bpb) % o.bpb);+ const ok = Math.abs(sum - o.bpb) < 1e-6 || (first && o.pickup !== undefined && Math.abs(sum - o.pickup) < 1e-6) || (first && toBarline < o.bpb - 1e-6 && Math.abs(sum - toBarline) < 1e-6) || (o.hit === true && sum <= o.bpb + 1e-6);+ if (!ok) throw new Error(`bar ${bi} sums to ${+sum.toFixed(4)} beats, meter wants ${o.bpb}: "${bar}"${sum < o.bpb && bi === bars.length - 1 ? ` (a line that ends mid-bar writes its rest: "${bar} r:${+(o.bpb - sum).toFixed(4)}")` : ""}`);+ });+ return out;+};++// ---------------------------------------------------------------- validation+export const planProblems = (p) => {+ const probs = [], plan = p.plan, st = STYLES[plan.style], bpb = beatsPerBar(plan.meter);+ if (!st) probs.push(`unknown style ${plan.style}`);+ else if (plan.tempo < st.tempo[0] * 0.85 || plan.tempo > st.tempo[1] * 1.15) probs.push(`tempo ${plan.tempo} far outside style ${st.id} ${st.tempo.join("-")}`);+ let b0 = -(plan.pickupBeats ?? 0);+ for (const s of plan.sections) {+ const ids = Array.isArray(s.mood) ? [s.mood[0], s.mood[1]] : [s.mood];+ for (const id of ids) if (!MOODS[id]) probs.push(`${s.id}: unknown mood ${id}`);+ if (Array.isArray(s.mood) && REFUSED_BLENDS.some(([a, b]) => (a === s.mood[0] && b === s.mood[1]) || (a === s.mood[1] && b === s.mood[0]))) probs.push(`${s.id}: refused blend ${s.mood[0]}+${s.mood[1]}`);+ if (!MODES[s.mode]) probs.push(`${s.id}: unknown mode ${s.mode}`);+ const lo = b0, hi = b0 + s.bars * bpb + (b0 < 0 ? plan.pickupBeats ?? 0 : 0);+ const notes = p.parts.flatMap((pt) => pt.notes).filter((n) => n.t >= lo && n.t < hi && n.role !== "drum");+ if (notes.length) {+ const top = detectMode(notes, [s.mode, "major", "aeolian", "dorian", "mixolydian", "lydian"]);+ const want = pcOf(s.key.replace(/m$/, ""));+ const hit = top.slice(0, 2).some((c) => pcOf(c.tonic) === want && c.mode === s.mode);+ // a mode shares its notes with its relatives (D dorian = C major): accept the declared tonic when its scale explains the notes+ // as well as the winner does and the tonic is heard (>= 8 % of note time). Otherwise the tonic is not dominant enough.+ const fit = modeFit(notes, want, s.mode), best = modeFit(notes, pcOf(top[0].tonic), top[0].mode);+ if (!hit && !(fit.inScale >= best.inScale - 0.02 && fit.tonicShare >= 0.08)) probs.push(`${s.id}: declared ${s.key} ${s.mode}, notes measure ${top.map((c) => `${c.tonic} ${c.mode}`).join(" / ")} (tonic ${s.key} is ${Math.round(fit.tonicShare * 100)} % of note time, ${Math.round(fit.inScale * 100)} % in scale): make the tonic heard (bass on it at section starts and cadences) and state the mode's colour note`);+ }+ b0 = hi;+ }+ // voice guard: no close thirds below C3 in piano parts (nocturne style guard)+ for (const pt of p.parts) if (pt.inst === "piano") {+ const by = new Map(); for (const n of pt.notes) { const k = Math.round(n.t * 96); by.set(k, [...(by.get(k) ?? []), n.p]); }+ for (const [k, ps] of by) { ps.sort((a, b) => a - b); for (let i = 1; i < ps.length; i++) if (ps[i] < 48 && ps[i] - ps[i - 1] <= 4) probs.push(`close third below C3 at beat ${k / 96}`); }+ }+ return probs;+};++// ---------------------------------------------------------------- fit to any duration+/** Section beat spans [start, end) in piece beats (pickup lives before 0 and belongs to section 0). */+export const sectionSpans = (plan) => { const bpb = beatsPerBar(plan.meter); let b = 0; return plan.sections.map((s, i) => { const a = i === 0 ? -(plan.pickupBeats ?? 0) : b; b += s.bars * bpb; return { s, a, b: b }; }); };++/** Apply a repeat variation ("same" | "octaveDouble" | "octaveUp" | "thin") to one section's notes. */+const vary = (notes, v) => {+ if (v === "octaveDouble") return [...notes, ...notes.filter((n) => n.role === "melody").map((n) => ({ ...n, p: n.p - 12, role: "inner", v: n.v * 0.8 }))];+ if (v === "octaveUp") return notes.map((n) => (n.role === "melody" ? { ...n, p: n.p + 12, v: n.v * 0.9 } : n));+ if (v === "thin") return notes.filter((n) => n.role !== "accomp" || Math.abs(n.t - Math.round(n.t)) < 1e-6);+ return notes;+};++/**+ * Rebuild a piece from a list of section indices (repeat/drop), shifting notes and chords.+ * A section's `pickup` (melody beats before its downbeat) travels with it. Repeats cycle through+ * the section's `variations` so a returning theme is never a photocopy.+ */+export const resequence = (p, order) => {+ const spans = sectionSpans(p.plan); const parts = p.parts.map((pt) => ({ ...pt, notes: [] })); const harmony = []; const sections = [];+ let cursor = 0; const bpb = beatsPerBar(p.plan.meter), seen = new Map();+ order.forEach((si, k) => {+ const sec = p.plan.sections[si], sp = spans[si], start = si === 0 ? 0 : sp.a, len = sec.bars * bpb, shift = cursor - start;+ const rep = seen.get(si) ?? 0; seen.set(si, rep + 1);+ const vr = rep > 0 && sec.variations?.length ? sec.variations[(rep - 1) % sec.variations.length] : "same";+ const pk = si === 0 ? p.plan.pickupBeats ?? 0 : sec.pickup ?? 0;+ p.parts.forEach((pt, j) => {+ const body = pt.notes.filter((n) => n.t >= start && n.t < sp.b).map((n) => ({ ...n, t: n.t + shift }));+ if (pk > 0) {+ if (k > 0) parts[j].notes = parts[j].notes.filter((n) => !(n.role === "melody" && n.t >= cursor - pk - 1e-9));+ parts[j].notes.push(...vary(pt.notes.filter((n) => n.role === "melody" && n.t >= start - pk && n.t < start).map((n) => ({ ...n, t: n.t + shift })), vr));+ }+ parts[j].notes.push(...vary(body, vr));+ });+ for (const c of p.harmony) if (c.t >= (si === 0 ? -1e9 : start) && c.t < sp.b) harmony.push({ ...c, t: c.t + shift });+ sections.push({ ...sec, id: rep ? `${sec.id}#${rep}${vr === "same" ? "" : `(${vr})`}` : sec.id });+ cursor += len;+ });+ const pickupBeats = order[0] === 0 ? p.plan.pickupBeats : p.plan.sections[order[0]].pickup ?? 0;+ return { ...p, parts, harmony, plan: { ...p.plan, sections, pickupBeats } };+};diff --git a/scripts/music/render.mjs b/scripts/music/render.mjsnew file mode 100644index 0000000..3517977--- /dev/null+++ b/scripts/music/render.mjs@@ -0,0 +1,170 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// Piece -> performance -> one stem per part -> room -> master. Pure in (piece, sampleRate, opts).+// Gentle styles: one static gain to -16 LUFS, true peak <= -1 dBTP, never a compressor (if the+// ceiling can't be met by gain alone the loudness goes down). Dense styles: -14 LUFS through a+// look-ahead limiter.+import { resequence, beatsPerBar } from "./plan.mjs";+import { perform } from "./perform.mjs";+import { renderPiano, PIANO_REAL } from "./piano.mjs";+import * as I from "./instruments.mjs";+import { room, Biquad, db, rng as mkRng } from "./dsp.mjs";+import { warmPad, softPluck, sub, duckCurve, tape } from "./lofiKit.mjs";+import { loudness, truePeak, stemBalance } from "./meter.mjs";+import { STYLES } from "./tables.mjs";++const voice = (pt, keys, sr, n, seed) => {+ const o = pt.opts ?? {}, r = mkRng(seed);+ switch (pt.inst) {+ case "musicBox": return I.musicBox(keys, sr, n, o);+ case "harp": return I.pluck(keys, sr, n, o, r, "harp");+ case "guitar": return I.pluck(keys, sr, n, o, r, "guitar");+ case "strings": return I.strings(keys, sr, n, o, r);+ case "ePiano": return I.ePiano(keys, sr, n, o);+ case "kick": return I.kick(keys, sr, n, o);+ case "snare": return I.snare(keys, sr, n, o, r);+ case "hat": return I.hat(keys, sr, n, o, r);+ case "bass": return I.bass(keys, sr, n, o);+ case "vinyl": return I.vinyl(keys, sr, n, o, r);+ case "warmPad": return warmPad(keys, sr, n, o, r);+ case "softPluck": return softPluck(keys, sr, n, o);+ case "sub": return sub(keys, sr, n, o);+ default: throw new Error(`no instrument ${pt.inst} in the v1 engine (have: piano, musicBox, harp, guitar, strings, ePiano, kick, snare, hat, bass, vinyl, warmPad, softPluck, sub)`);+ }+};++export const renderPiece = (piece, sr, o = {}) => {+ const expressive = o.expressive ?? true, tempo = o.tempo ?? piece.plan.tempo, style = STYLES[piece.plan.style];+ const perf = perform(piece, tempo, { expressive, flatVelocity: o.flatVelocity });+ const n = o.seconds ? Math.round(o.seconds * sr) : Math.ceil((perf.lastOnset + piece.tail) * sr);+ const L = new Float32Array(n), R = new Float32Array(n), haloL = new Float32Array(n), stems = {};+ const sends = [];+ // the pump: one gain curve from the ducking part's onsets, applied to every ducked part before the mix+ const dk = piece.fx?.duck, byIdx = dk ? piece.parts.findIndex((p) => p.id === dk.by) : -1;+ const pump = dk && byIdx >= 0 ? duckCurve(perf.parts[byIdx].keys.map((k) => k.t), sr, n, dk.depth ?? 0.4, dk.release ?? 0.28) : null;+ piece.parts.forEach((pt, pi) => {+ if (o.only && !o.only(pt)) return;+ const keys = perf.parts[pi].keys; if (!keys.length) return;+ let sL, sR;+ if (pt.inst === "piano") { const r = renderPiano(keys, perf.pedal, sr, n, o.piano ?? PIANO_REAL, piece.seed + pi); sL = r.L; sR = r.R; if ((o.piano ?? PIANO_REAL).pedal) for (let i = 0; i < n; i++) haloL[i] += r.halo[i] * db(pt.gainDb ?? 0); }+ else { const r = voice(pt, keys, sr, n, piece.seed * 101 + pi); sL = r.L; sR = r.R; }+ if (pump && dk.parts.includes(pt.id)) for (let i = 0; i < n; i++) { sL[i] *= pump[i]; sR[i] *= pump[i]; }+ const g = db(pt.gainDb ?? 0);+ if (pt.pan) { const a = Math.max(0, pt.pan), b = Math.max(0, -pt.pan); for (let i = 0; i < n; i++) { sL[i] *= 1 - a * 0.6; sR[i] *= 1 - b * 0.6; } }+ for (let i = 0; i < n; i++) { sL[i] *= g; sR[i] *= g; L[i] += sL[i]; R[i] += sR[i]; }+ if (o.stems) stems[pt.id] = [sL, sR];+ sends.push([sL, sR, pt.send ?? 1]);+ });+ // ---- space+ const rng = mkRng(piece.seed * 7 + 5), dry = [Float32Array.from(L), Float32Array.from(R)];+ let wet = [new Float32Array(n), new Float32Array(n)];+ const sp = piece.plan.space;+ if (style.id === "musicBox" && !sp) { // the recipe: ONE early reflection, 30 ms late, 14 dB down, no tail+ const d = Math.round(0.03 * sr), g = db(-14); for (let i = d; i < n; i++) { wet[0][i] = dry[0][i - d] * g; wet[1][i] = dry[1][i - d] * g * 0.9; L[i] += wet[0][i]; R[i] += wet[1][i]; }+ } else if (style.reverb !== "none" || sp) {+ const sL = new Float32Array(n), sR = new Float32Array(n);+ for (const [a, b, s] of sends) for (let i = 0; i < n; i++) { sL[i] += a[i] * s; sR[i] += b[i] * s; }+ const hall = style.reverb === "hall";+ for (let i = 0; i < n; i++) { sL[i] += haloL[i] * 0.35; sR[i] += haloL[i] * 0.35; } // pedal halo: undamped strings ring into the room+ const [wL, wR, tL, tR] = room(sL, sR, sr, { er: sp?.er ?? (hall ? 0.35 : 0.45), late: sp?.late ?? (hall ? 0.3 : 0.2), rt60: sp?.rt60 ?? (hall ? 2.3 : 1.5), predelay: hall ? 0.035 : 0.022, hp: sp?.hp ?? 300, lp: hall ? 7000 : 6000, seed: piece.seed, rng });+ for (let i = 0; i < n; i++) { L[i] += wL[i]; R[i] += wR[i]; }+ wet = [tL, tR]; // early reflections (< 40 ms) fuse with the direct sound (precedence effect)+ }+ // ---- master: DC/rumble high-pass (4th-order Butterworth at 30 Hz), lo-fi tone, end fade+ for (const q of [0.5412, 1.3066]) { Biquad.make(sr, "hp", 30, q).run(L); Biquad.make(sr, "hp", 30, q).run(R); }+ if (style.id === "lofi" && !piece.fx?.clean) { for (const c of [L, R]) { Biquad.make(sr, "lp", 8500, 0.6).run(c); Biquad.make(sr, "highshelf", 5000, 0.7, -3).run(c); for (let i = 0; i < n; i++) c[i] = Math.tanh(c[i] * 1.2) / 1.2; } }+ if (piece.fx?.tape) tape(L, R, sr, piece.fx.tape);+ const fade = Math.min(n, Math.round(0.25 * sr)); for (let i = 0; i < fade; i++) { const g = 0.5 - 0.5 * Math.cos((Math.PI * i) / fade); L[n - 1 - i] *= g; R[n - 1 - i] *= g; }+ let masterMode = o.master ?? "auto";+ if (masterMode === "auto") masterMode = style.master;+ const gainDb = masterMode === "none" ? 0 : master(L, R, sr, masterMode);+ return { L, R, perf, tempo, gainDb, masterMode, stems, piece, dry, wet };+};++/** The master stage, in place. Gentle: one static gain to -16 LUFS, pulled down if the true peak passes -1 dBTP. Dense: -14 LUFS through the look-ahead limiter. Returns the gain in dB. */+export const master = (L, R, sr, masterMode) => {+ const n = L.length, target = masterMode === "dense" ? -14 : -16;+ let gainDb = target - loudness([L, R], sr).integrated;+ for (let i = 0; i < n; i++) { L[i] *= db(gainDb); R[i] *= db(gainDb); }+ const tp = truePeak([L, R]).dbtp;+ if (tp > -1) {+ if (masterMode === "gentle") { const cut = tp + 1.05; gainDb -= cut; for (let i = 0; i < n; i++) { L[i] *= db(-cut); R[i] *= db(-cut); } }+ else {+ limiter(L, R, sr, db(-1.3)); const again = target - loudness([L, R], sr).integrated; if (again > 0) { const g = db(Math.min(again, 1)); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } limiter(L, R, sr, db(-1.3)); }+ }+ }+ return gainDb;+};++/**+ * A seamless loop of a `plan.loop` piece: rendered unmastered with its tail, the tail (reverb, delay+ * repeats, pad release) folded back onto the start, then mastered once. Tape wow and flutter are+ * snapped to a whole number of cycles per loop so the pitch drift meets itself at the seam.+ */+export const renderLoop = (piece, sr) => {+ const beats = piece.plan.sections.reduce((a, s) => a + s.bars * beatsPerBar(piece.plan.meter), 0), loopS = (beats * 60) / piece.plan.tempo;+ const snap = (hz) => Math.max(1, Math.round(hz * loopS)) / loopS, tp = piece.fx?.tape;+ const p = { ...piece, plan: { ...piece.plan, loop: true, ritard: 1 }, fx: piece.fx && { ...piece.fx, tape: tp && { ...tp, wowHz: snap(tp.wowHz ?? 0.45), flutterHz: snap(tp.flutterHz ?? 6.2) } } };+ const r = renderPiece(p, sr, { seconds: loopS + piece.tail, master: "none" }), n = Math.round(loopS * sr), L = r.L.slice(0, n), R = r.R.slice(0, n);+ for (let i = n; i < r.L.length; i++) { L[i - n] += r.L[i]; R[i - n] += r.R[i]; }+ const mode = STYLES[piece.plan.style].master, gainDb = master(L, R, sr, mode);+ return { ...r, L, R, gainDb, masterMode: mode, loopS };+};++/** Each part's stem level against the piece's targets (unmastered, pre-room: the mix as the parts were set). */+export const measureStems = (piece, sr, o = {}, tolDb = 3) => {+ const r = renderPiece(piece, sr, { ...o, stems: true, master: "none" });+ return stemBalance(r.stems, piece.stemTargets ?? {}, tolDb);+};++/** Look-ahead peak limiter (1.5 ms look-ahead, 120 ms release), used by dense styles only; `ceil` is linear. */+export const limiter = (L, R, sr, ceil) => {+ const n = L.length, la = Math.round(0.0015 * sr), rel = Math.exp(-1 / (0.12 * sr)), need = new Float32Array(n);+ for (let i = 0; i < n; i++) { const a = Math.max(Math.abs(L[i]), Math.abs(R[i])) * 1.12; need[i] = a > ceil ? ceil / a : 1; } // 1.12: inter-sample margin+ const g = new Float32Array(n); let cur = 1;+ for (let i = n - 1; i >= 0; i--) { let m = 1; for (let j = i; j < Math.min(n, i + la); j++) m = Math.min(m, need[j]); g[i] = m; }+ for (let i = 0; i < n; i++) { cur = g[i] < cur ? g[i] : 1 - (1 - cur) * rel; if (cur > g[i]) cur = g[i]; L[i] *= cur; R[i] *= cur; }+};++/**+ * Fit a piece to ANY duration. Candidate forms = every subset of `optional` sections dropped x the+ * `repeatable` group (contiguous repeatable sections, with their variations) repeated 0..n times.+ * For each, the tempo that lands the last onset at (seconds - tail) is solved; the form whose tempo+ * sits inside the style's range and closest to the written tempo wins. If no full form fits and the+ * piece has a `shortForm`, that is fitted instead. The tail absorbs the rest. Nothing in a piece+ * hard-codes the film's length.+ */+export const fitToDuration = (piece, seconds) => {+ const st = STYLES[piece.plan.style], T0 = piece.plan.tempo, lo = Math.max(st.tempo[0] * 0.9, T0 * 0.82), hi = Math.min(st.tempo[1] * 1.1, T0 * 1.18);+ const secs = piece.plan.sections, want = seconds - piece.tail;+ const solve = (p) => { let tempo = T0; for (let k = 0; k < 5; k++) tempo *= perform(p, tempo, { expressive: true }).lastOnset / want; return tempo; };+ const opt = secs.map((s, i) => (s.optional ? i : -1)).filter((i) => i >= 0);+ const grp = secs.map((s, i) => (s.repeatable ? i : -1)).filter((i) => i >= 0);+ let best = null, anyTooShort = false;+ for (let mask = 0; mask < 1 << opt.length; mask++) {+ const dropped = opt.filter((_, j) => mask & (1 << j));+ // ra = extra statements of the first repeatable section in place (A A B), rg = repeats of the whole group (A B A B)+ for (let ra = 0; ra <= (grp.length > 1 ? 2 : 0); ra++) for (let rg = 0; rg <= (grp.length ? 64 : 0); rg++) {+ let order = secs.map((_, i) => i);+ for (let k = 0; k < rg; k++) { const at = order.lastIndexOf(grp[grp.length - 1]); order = [...order.slice(0, at + 1), ...grp, ...order.slice(at + 1)]; }+ for (let k = 0; k < ra; k++) { const at = order.indexOf(grp[0]); order = [...order.slice(0, at + 1), grp[0], ...order.slice(at + 1)]; }+ order = order.filter((i) => !dropped.includes(i));+ if (!order.length) break;+ const p = mask === 0 && ra === 0 && rg === 0 ? piece : resequence(piece, order), tempo = solve(p);+ if (tempo > hi) break; // more repeats only make it longer+ if (tempo < lo) { anyTooShort = true; continue; }+ // dropping music costs more than a tempo nudge; back-to-back restatements cost a little+ const cost = Math.abs(Math.log(tempo / T0)) + 0.06 * dropped.length + 0.01 * rg + 0.025 * ra;+ if (!best || cost < best.cost) best = { p, tempo, order, cost };+ }+ }+ if (best) return { piece: { ...best.p, plan: { ...best.p.plan, tempo: best.tempo } }, tempo: best.tempo, order: best.order, form: "full" };+ if (!anyTooShort && piece.shortForm) { const f = fitToDuration(piece.shortForm(), seconds); return { ...f, form: `short form (${f.form})` }; }+ const tempo = anyTooShort ? lo : hi;+ return { piece: { ...piece, plan: { ...piece.plan, tempo } }, tempo, order: secs.map((_, i) => i), form: anyTooShort ? "full, tail extended" : "full, tail cut" };+};++/** A film's audio slot: (sr) => [L, R] at exactly the film's length. */+export const filmAudio = (piece, seconds) => (sr) => {+ const fit = fitToDuration(piece, seconds), r = renderPiece(fit.piece, sr, { seconds, tempo: fit.tempo });+ return [r.L, r.R];+};diff --git a/scripts/music/tables.mjs b/scripts/music/tables.mjsnew file mode 100644index 0000000..a638c63--- /dev/null+++ b/scripts/music/tables.mjs@@ -0,0 +1,53 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// The mood/style/melody tables as DATA. A piece names rows; it never writes adjectives.+// v1 port note: only the instruments listed in render.mjs are synthesized here; other family+// names in these rows are kept as data for v2.++// centroid null = report only (piano brightness is never gated).+export const MOODS = {+ joy: { id: "joy", modes: ["major", "mixolydian", "majorPentatonic"], tempo: [110, 150], meters: ["4/4", "12/8"], harmonicRhythmBars: [1, 1], register: [72, 96], onsetsPerBeat: [2, 4], attackMs: [2, 10], lra: [4, 8], centroidHz: [1800, 6000], families: ["musicBox", "mallets", "pluck", "piano"], melody: ["arpeggio", "hook"], master: "gentle" },+ playful: { id: "playful", modes: ["major", "blues", "majorPentatonic"], tempo: [120, 160], meters: ["4/4"], harmonicRhythmBars: [0.25, 0.5], register: [60, 90], onsetsPerBeat: [2, 4], attackMs: [2, 5], lra: [6, 10], centroidHz: [1500, 6000], families: ["pluck", "mallets", "fmBell", "bass", "chip"], melody: ["hook", "callResponse"], master: "dense" },+ tender: { id: "tender", modes: ["major", "lydian"], tempo: [60, 80], meters: ["3/4", "6/8"], harmonicRhythmBars: [1, 2], register: [64, 84], onsetsPerBeat: [1, 2], attackMs: [5, 30], lra: [6, 12], centroidHz: null, families: ["piano", "harp", "strings", "organ"], melody: ["stepwise", "counterMelody"], master: "gentle" },+ wistful: { id: "wistful", modes: ["dorian", "major"], tempo: [70, 95], meters: ["6/8", "4/4"], harmonicRhythmBars: [1, 1], register: [64, 86], onsetsPerBeat: [1.5, 3], attackMs: [5, 20], lra: [6, 10], centroidHz: [1000, 2000], families: ["piano", "musicBox", "strings"], melody: ["stepwise", "themeTransformation"], master: "gentle" },+ melancholy: { id: "melancholy", modes: ["aeolian", "harmonicMinor"], tempo: [50, 72], meters: ["3/4", "4/4"], harmonicRhythmBars: [1, 2], register: [55, 80], onsetsPerBeat: [0.75, 1.5], attackMs: [20, 80], lra: [8, 14], centroidHz: null, families: ["piano", "strings"], melody: ["stepwise", "drone"], master: "gentle" },+ hopeful: { id: "hopeful", modes: ["melodicMinor", "major"], tempo: [80, 110], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 88], onsetsPerBeat: [1.5, 3], attackMs: [10, 40], lra: [8, 12], centroidHz: null, families: ["piano", "strings", "fmBell"], melody: ["sequence", "stepwise"], master: "gentle" },+ curious: { id: "curious", modes: ["dorian", "lydian", "wholeTone"], tempo: [80, 110], meters: ["4/4", "6/8"], harmonicRhythmBars: [1, 2], register: [60, 84], onsetsPerBeat: [1, 2], attackMs: [2, 10], lra: [6, 10], centroidHz: [1000, 2000], families: ["pluck", "celesta", "fmBell"], melody: ["ostinato", "hook"], master: "gentle" },+ tension: { id: "tension", modes: ["harmonicMinor", "phrygian"], tempo: [90, 130], meters: ["4/4"], harmonicRhythmBars: [2, 4], register: [48, 72], onsetsPerBeat: [2, 4], attackMs: [2, 10], lra: [10, 16], centroidHz: [800, 1500], families: ["strings", "drums", "bass"], melody: ["ostinato", "drone"], master: "dense" },+ dread: { id: "dread", modes: ["phrygian", "aeolian", "locrian"], tempo: [50, 80], meters: ["4/4"], harmonicRhythmBars: [4, 4], register: [36, 60], onsetsPerBeat: [0.5, 1.5], attackMs: [50, 200], lra: [12, 18], centroidHz: [0, 1000], families: ["bass", "piano", "strings"], melody: ["drone"], master: "gentle" },+ awe: { id: "awe", modes: ["lydian", "major"], tempo: [60, 90], meters: ["4/4", "3/4"], harmonicRhythmBars: [2, 2], register: [72, 100], onsetsPerBeat: [1, 3], attackMs: [5, 400], lra: [10, 16], centroidHz: null, families: ["fmBell", "strings", "harp", "organ", "piano"], melody: ["arpeggio", "drone", "themeTransformation"], master: "gentle" },+ triumph: { id: "triumph", modes: ["major", "aeolian"], tempo: [100, 140], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 90], onsetsPerBeat: [3, 6], attackMs: [2, 10], lra: [6, 10], centroidHz: [1500, 6000], families: ["drums", "strings", "organ"], melody: ["hook", "themeTransformation"], master: "dense" },+ drive: { id: "drive", modes: ["aeolian", "dorian", "mixolydian"], tempo: [110, 140], meters: ["4/4"], harmonicRhythmBars: [1, 1], register: [60, 86], onsetsPerBeat: [4, 8], attackMs: [1, 5], lra: [4, 8], centroidHz: null, families: ["drums", "bass", "pluck"], melody: ["hook", "arpeggio", "ostinato"], master: "dense" },+ calm: { id: "calm", modes: ["mixolydian", "majorPentatonic", "major"], tempo: [60, 90], meters: ["6/8", "3/4"], harmonicRhythmBars: [2, 2], register: [60, 84], onsetsPerBeat: [1, 2], attackMs: [5, 30], lra: [4, 8], centroidHz: [1000, 2000], families: ["guitar", "fmBell"], melody: ["stepwise", "drone"], master: "gentle" },+ nostalgic: { id: "nostalgic", modes: ["major"], tempo: [70, 95], meters: ["4/4"], harmonicRhythmBars: [0.5, 1], register: [60, 84], onsetsPerBeat: [1.5, 3], attackMs: [5, 20], lra: [6, 10], centroidHz: [900, 1600], families: ["ePiano", "drums", "bass"], melody: ["stepwise", "hook"], master: "dense" },+ romantic: { id: "romantic", modes: ["major", "aeolian"], tempo: [60, 85], meters: ["3/4", "4/4"], harmonicRhythmBars: [1, 1], register: [60, 88], onsetsPerBeat: [1, 2.5], attackMs: [10, 60], lra: [8, 14], centroidHz: [1000, 2000], families: ["piano", "strings"], melody: ["stepwise", "counterMelody"], master: "gentle" },+};++/** Blends the gate refuses: use consecutive sections instead. */+export const REFUSED_BLENDS = [["joy", "dread"], ["playful", "melancholy"], ["calm", "tension"]];+export const ARCS = { rise: ["melancholy", "hopeful", "triumph"], turn: ["joy", "tension", "joy"], fallAndReturn: ["tender", "melancholy", "tender"], wonder: ["curious", "awe"], comic: ["playful", "tension", "playful"] };++export const STYLES = {+ musicBox: { id: "musicBox", tempo: [110, 130], meters: ["12/8"], families: ["musicBox", "fmBell"], moods: ["joy", "curious", "tender", "playful", "wistful"], master: "gentle", reverb: "room", arrangement: "melody -> +bass -> +arp -> +octave sparkle -> bell", guards: ["pluck-only instruments", "more notes, never longer notes"] },+ nocturne: { id: "nocturne", tempo: [50, 72], meters: ["3/4", "6/8"], families: ["piano", "strings"], moods: ["tender", "melancholy", "wistful", "romantic"], master: "gentle", reverb: "room", arrangement: "left-hand broken chords spanning a tenth, right-hand stepwise theme", guards: ["rubato <= 8% of a beat", "no close thirds below C3"] },+ drive: { id: "drive", tempo: [110, 140], meters: ["4/4"], families: ["drums", "bass", "pluck", "strings"], moods: ["drive", "triumph", "tension", "awe"], master: "dense", reverb: "hall", arrangement: "riser, breath, drop", guards: ["phone rule: every low part has content above 500 Hz"] },+ cinematic: { id: "cinematic", tempo: [60, 120], meters: ["4/4", "3/4"], families: ["strings", "piano", "harp", "fmBell", "drums"], moods: ["awe", "triumph", "melancholy", "tension", "hopeful"], master: "gentle", reverb: "hall", arrangement: "layered by register slot; crescendos over 4-8 bars", guards: ["max 4 families at once outside climaxes"] },+ // lofi tempo widened from anidoodle's [70, 90]: half-time grooves are commonly notated 100-125 bpm+ lofi: { id: "lofi", tempo: [70, 124], meters: ["4/4"], families: ["ePiano", "drums", "bass"], moods: ["nostalgic", "calm", "wistful"], master: "dense", reverb: "room", swing: [0.54, 0.62], arrangement: "4 or 8 bar loop with small variations", guards: ["no 2 consecutive identical 8-bar blocks", "master low-pass <= 9 kHz allowed"] },+ folk: { id: "folk", tempo: [80, 120], meters: ["6/8", "3/4", "4/4"], families: ["guitar", "harp", "fmBell"], moods: ["calm", "wistful", "joy", "nostalgic"], master: "gentle", reverb: "room", arrangement: "fingerpicked pattern + lead", guards: ["strum spread 10-30 ms low to high"] },+ minimalist: { id: "minimalist", tempo: [100, 140], meters: ["4/4", "12/8"], families: ["mallets", "piano"], moods: ["curious", "tension", "awe"], master: "gentle", reverb: "room", arrangement: "interlocking ostinatos; one change every 8-16 bars", guards: ["a change at least every 16 bars"] },+ jazz: { id: "jazz", tempo: [90, 180], meters: ["4/4"], families: ["piano", "bass", "drums"], moods: ["playful", "nostalgic", "romantic", "curious"], master: "gentle", reverb: "room", swing: [0.6, 0.67], arrangement: "walking bass on quarters, comping off the beat", guards: ["7th chords required"] },+ lullaby: { id: "lullaby", tempo: [60, 75], meters: ["3/4", "6/8"], families: ["musicBox", "celesta", "piano", "harp"], moods: ["tender", "calm"], master: "gentle", reverb: "room", arrangement: "melody + gentle arp, nothing percussive", guards: ["minor lullaby flagged for the human check"] },+ ambient: { id: "ambient", tempo: [50, 80], meters: ["4/4"], families: ["strings", "fmBell", "organ"], moods: ["awe", "calm", "dread"], master: "gentle", reverb: "hall", arrangement: "slow evolution", guards: ["melodic motif at least every 8 bars", "composite ghost check"] },+};++export const MELODY_TYPES = {+ arpeggio: { construction: "chord tones in a fixed pattern, one per subdivision", guards: "follows every chord change; range <= 17" },+ stepwise: { construction: "step ratio >= 0.7; leaps onto chord tones, stepped back", guards: "range <= 12 per phrase; one high point, in the second half" },+ hook: { construction: "a 2-5 note cell with a distinctive rhythm, repeated and varied", guards: "repetition index 0.4-0.75; returns in the final section" },+ ostinato: { construction: "a fixed 1-2 bar pattern bent to chord tones", guards: "something above it changes every 8 bars" },+ drone: { construction: "tonic or fifth held or re-struck under moving harmony", guards: "re-articulated every 4 bars" },+ callResponse: { construction: "question off the tonic answered on it, new register or instrument", guards: "answer within 1 bar" },+ counterMelody: { construction: "moves when the main line holds, mostly contrary", guards: "shared onsets <= 50%" },+ sequence: { construction: "a 1-2 bar cell repeated a step up or down", guards: "max 3 repeats, then break" },+ themeTransformation: { construction: "the main theme re-cut for a new mood", guards: "contour correlation >= 0.8" },+};diff --git a/scripts/music/theory.mjs b/scripts/music/theory.mjsnew file mode 100644index 0000000..e01f127--- /dev/null+++ b/scripts/music/theory.mjs@@ -0,0 +1,62 @@+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+// Pitch maths and the MODES table. Pure data and pure functions.++// Intervals are semitones above the tonic. `color` is the degree that makes the mode read as itself.+export const MODES = {+ major: { id: "major", intervals: [0, 2, 4, 5, 7, 9, 11], color: "3, 7", use: "joy, arrival, sunlight; the music-box default", guard: "" },+ aeolian: { id: "aeolian", intervals: [0, 2, 3, 5, 7, 8, 10], color: "b3, b6", use: "sadness, longing, gravity, night", guard: "tonic clarity" },+ harmonicMinor: { id: "harmonicMinor", intervals: [0, 2, 3, 5, 7, 8, 11], color: "raised 7 over V", use: "drama, fate, cadences inside minor", guard: "augmented step b6-7 only as a passing figure, max 2 per phrase" },+ melodicMinor: { id: "melodicMinor", intervals: [0, 2, 3, 5, 7, 9, 11], color: "raised 6 and 7", use: "hopeful minor, yearning lines that climb", guard: "rising lines only; falling lines revert to aeolian" },+ dorian: { id: "dorian", intervals: [0, 2, 3, 5, 7, 9, 10], color: "natural 6", use: "bittersweet, sad but moving forward, folk", guard: "natural 6 in the first 4 bars" },+ phrygian: { id: "phrygian", intervals: [0, 1, 3, 5, 7, 8, 10], color: "b2", use: "menace, heat, the villain's shadow", guard: "b2 resolves to 1 within 2 beats; max 8 bars unless dread" },+ lydian: { id: "lydian", intervals: [0, 2, 4, 6, 7, 9, 11], color: "#4", use: "wonder, flight, magic", guard: "#4 in the first 4 bars; never rest on #4" },+ mixolydian: { id: "mixolydian", intervals: [0, 2, 4, 5, 7, 9, 10], color: "b7", use: "pastoral, easygoing, sunny rock", guard: "b7 in the first 4 bars" },+ majorPentatonic: { id: "majorPentatonic", intervals: [0, 2, 4, 7, 9], color: "no half steps", use: "innocence, lullaby, chiptune melodies", guard: "one non-pentatonic harmony change per 16 bars" },+ minorPentatonic: { id: "minorPentatonic", intervals: [0, 3, 5, 7, 10], color: "b3, b7", use: "cool, soulful, sad without pain", guard: "same 16-bar rule" },+ blues: { id: "blues", intervals: [0, 3, 5, 6, 7, 10], color: "b5", use: "swagger, comedy, jazz and lo-fi colour", guard: "b5 passing only, <= 1/8 note" },+ wholeTone: { id: "wholeTone", intervals: [0, 2, 4, 6, 8, 10], color: "no tonic pull", use: "dream, confusion, magic transition", guard: "max 4 bars, then a real tonic" },+ locrian: { id: "locrian", intervals: [0, 1, 3, 5, 6, 8, 10], color: "b5 over the tonic", use: "never a section mode", guard: "one-bar colour only" },+};++const PC = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };++/** "Ab4" -> 68, "C#6" -> 85, "Fb3" -> 52 (spelling kept for readable scores, value is what sounds). */+export const midi = (name) => {+ const m = /^([A-G])(bb|b|#|x)?(-?\d)$/.exec(name.trim());+ if (!m) throw new Error(`bad note name "${name}"`);+ const acc = m[2] === "b" ? -1 : m[2] === "bb" ? -2 : m[2] === "#" ? 1 : m[2] === "x" ? 2 : 0;+ return 12 * (Number(m[3]) + 1) + PC[m[1]] + acc;+};+export const pcOf = (name) => { const m = /^([A-G])(bb|b|#|x)?$/.exec(name); if (!m) throw new Error(`bad pitch class "${name}"`); return (PC[m[1]] + (m[2] === "b" ? -1 : m[2] === "#" ? 1 : m[2] === "bb" ? -2 : m[2] === "x" ? 2 : 0) + 12) % 12; };+export const hz = (m) => 440 * Math.pow(2, (m - 69) / 12);+const NAMES = ["C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];+const SHARPS = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];+export const nameOf = (m, sharp = false) => `${(sharp ? SHARPS : NAMES)[((m % 12) + 12) % 12]}${Math.floor(m / 12) - 1}`;++/** Scale degree (1-based, may exceed the mode length: wraps into higher octaves) to MIDI. */+export const degree = (tonicMidi, mode, deg) => {+ const iv = MODES[mode].intervals, k = deg - 1, oct = Math.floor(k / iv.length), i = ((k % iv.length) + iv.length) % iv.length;+ return tonicMidi + 12 * oct + iv[i];+};++/** Detect the best-matching key and mode from a duration-weighted pitch-class histogram. */+export const detectMode = (notes, modes = ["major", "aeolian", "dorian", "mixolydian", "lydian", "phrygian"]) => {+ const h = new Array(12).fill(0); for (const n of notes) h[((n.p % 12) + 12) % 12] += n.d;+ const tot = h.reduce((a, b) => a + b, 0) || 1;+ const res = [];+ for (let t = 0; t < 12; t++) for (const md of modes) {+ const iv = new Set(MODES[md].intervals.map((x) => (x + t) % 12));+ let inS = 0; for (let k = 0; k < 12; k++) if (iv.has(k)) inS += h[k];+ // in-scale share, plus a tonic and fifth weight so relative modes separate+ res.push({ tonic: NAMES[t], mode: md, score: inS / tot + 0.35 * (h[t] / tot) + 0.12 * (h[(t + 7) % 12] / tot) });+ }+ return res.sort((a, b) => b.score - a.score).slice(0, 3);+};++/** How well a declared tonic + mode explains some notes: share of note time inside the scale, and the tonic's own share. */+export const modeFit = (notes, tonicPc, mode) => {+ const h = new Array(12).fill(0); for (const n of notes) h[((n.p % 12) + 12) % 12] += n.d;+ const tot = h.reduce((a, b) => a + b, 0) || 1, iv = new Set(MODES[mode].intervals.map((x) => (x + tonicPc) % 12));+ let inS = 0; for (let k = 0; k < 12; k++) if (iv.has(k)) inS += h[k];+ return { inScale: inS / tot, tonicShare: h[((tonicPc % 12) + 12) % 12] / tot };+};diff --git a/scripts/mux-audio.sh b/scripts/mux-audio.shnew file mode 100755index 0000000..d64a349--- /dev/null+++ b/scripts/mux-audio.sh@@ -0,0 +1,4 @@+#!/bin/bash+# Mux an audio track (already cut to length) into a video without re-encoding the picture.+# Usage: mux-audio.sh <video.mp4> <audio.wav|mp3> <out.mp4>+ffmpeg -y -v error -i "$1" -i "$2" -map 0:v -map 1:a -c:v copy -c:a aac -b:a 256k -shortest -movflags +faststart "$3" && echo "wrote $3"diff --git a/scripts/new-canvas-project.sh b/scripts/new-canvas-project.shnew file mode 100755index 0000000..6f96d3a--- /dev/null+++ b/scripts/new-canvas-project.sh@@ -0,0 +1,24 @@+#!/bin/bash+# Scaffold a canvas film project. Usage: new-canvas-project.sh <dir>+set -e; d="$1"; S="$(cd "$(dirname "$0")" && pwd)"+mkdir -p "$d/assets"; cp "$S/serve.mjs" "$S/frames.mjs" "$S/export.mjs" "$S/springs.js" "$d/"+cd "$d"; [ -f package.json ] || echo '{"name":"film","private":true,"type":"module"}' > package.json+npm install --silent playwright-core >/dev/null 2>&1+[ -f film.html ] || cat > film.html <<'HTML'+<!doctype html><html><head><meta charset="utf-8"><title>film</title>+<style>html,body{margin:0;background:#111}canvas{display:block;width:100vw;height:auto;max-height:100vh;object-fit:contain}</style>+<script src="springs.js"></script></head>+<body><canvas id="c"></canvas><script>+const P=new URLSearchParams(location.search).has('portrait');const W=P?1080:1920,H=P?1350:1080;+const c=document.getElementById('c');c.width=W;c.height=H;const g=c.getContext('2d');+window.FILM_DURATION=10;+// motion = springs (Spring.to: one spring per target change, closed form, any t in any order). Linear motion = never.+const CARD_X=[[0,-400],[0.4,W/2-300],[3,W/2-100],[6,W+100]];+window.renderFrame=t=>{g.setTransform(1,0,0,1,0,0);g.globalAlpha=1;g.globalCompositeOperation='source-over';g.filter='none';+ g.fillStyle='#fafaf8';g.fillRect(0,0,W,H);+ const x=Spring.to(t,CARD_X,'camera'),s=0.6+0.4*Spring.unit(t-0.4,'playful');+ g.save();g.translate(x+300,H/2);g.scale(s,s);g.fillStyle='#111';g.font='700 120px system-ui';g.textAlign='center';g.fillText('t = '+t.toFixed(2),0,40);g.restore();};+document.fonts.ready.then(()=>{window.READY=true;if(navigator.webdriver)return;let s=performance.now();const loop=n=>{window.renderFrame(((n-s)/1000)%window.FILM_DURATION);requestAnimationFrame(loop)};requestAnimationFrame(loop);});+</script></body></html>+HTML+echo "project ready at $d (edit film.html; springs in springs.js; review with: node frames.mjs 0 0,1,2)"diff --git a/scripts/plate.py b/scripts/plate.pynew file mode 100644index 0000000..965d883--- /dev/null+++ b/scripts/plate.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+# scripts/plate.py : a still's background with the subject taken out, so the subject can move in front of it.+#+# One photograph becomes a shot with depth: cut the subject out (matte.swift), fill its place in the picture (this script),+# then draw three layers that move apart as the camera pushes in or slides: the plate, anything that belongs between (a word),+# the cut-out. The subject only ever moves a little off its own place, so only a thin rim of the fill is seen; it is filled+# with the colours round the hole, blurred more the deeper into it. This is not a clean plate for a subject that leaves.+#+# Usage: python3 <skill>/scripts/plate.py <photo> <cut-out.png> <out.jpg> [--grow 16] [--quality 92]+# <cut-out.png> the same size as the photo, its alpha the subject (from: swift <skill>/scripts/matte.swift photo.jpg cut.png)+# --grow N how far past the cut-out's edge the hole reaches, in pixels (default 16: past its soft edge, so none of the+# subject's colour is sampled into the fill). Raise it when a rim of the subject's colour shows in the plate.+# Needs numpy, scipy, Pillow. See references/real-shots.md, "A still as a shot with depth".+import sys+import numpy as np+from PIL import Image+from scipy.ndimage import gaussian_filter, binary_dilation++a = sys.argv[1:]+if len(a) < 3: sys.exit('usage: python3 plate.py <photo> <cut-out.png> <out.jpg> [--grow 16] [--quality 92]')+def opt(name, default): return a[a.index(name) + 1] if name in a else default+GROW, Q = int(opt('--grow', '16')), int(opt('--quality', '92'))+img = np.asarray(Image.open(a[0]).convert('RGB')).astype(np.float32)+cut = Image.open(a[1]).convert('RGBA')+if cut.size != (img.shape[1], img.shape[0]): sys.exit(f'the cut-out is {cut.size[0]}x{cut.size[1]} and the photo is {img.shape[1]}x{img.shape[0]}: they must be the same size')+hole = binary_dilation(np.asarray(cut)[:, :, 3] > 6, iterations=GROW)+if not hole.any(): sys.exit('the cut-out is empty: nothing to take out')+valid = (~hole).astype(np.float32)+out = None+s = max(img.shape[:2]) / 6.0+sig = []+while s >= 5: sig.append(s); s /= 2 # coarse first, then finer fills laid over it where they are sure+for s in sig:+ den = gaussian_filter(valid, s)+ num = np.stack([gaussian_filter(img[:, :, c] * valid, s) for c in range(3)], axis=2)+ f = num / np.maximum(den, 1e-4)[:, :, None]+ w = np.clip(den / 0.28, 0, 1)[:, :, None]+ out = f if out is None else w * f + (1 - w) * out+edge = gaussian_filter(hole.astype(np.float32), 3)[:, :, None] # a soft seam between the photograph and the fill+res = img * (1 - edge) + out * edge+Image.fromarray(np.clip(res, 0, 255).astype(np.uint8)).save(a[2], quality=Q)+print(f'wrote {a[2]}: {res.shape[1]}x{res.shape[0]}, the hole is {hole.mean() * 100:.1f}% of the frame')+print('the fill is only good for a rim: keep the subject within about 3% of the frame of its own place (scale and slide together)')diff --git a/scripts/render-parallel.sh b/scripts/render-parallel.shnew file mode 100755index 0000000..18dbfb6--- /dev/null+++ b/scripts/render-parallel.sh@@ -0,0 +1,39 @@+#!/bin/bash+# Render a long film in parallel pieces and join them (picture only; add sound with mux-audio.sh).+# Run it from the project folder (the one with film.html, export.mjs and node_modules).+#+# render-parallel.sh <fps> <duration_s> <out.mp4> [workers=3] [piece_s=12]+# SUB=4 render-parallel.sh 60 78 master.mp4 # subframe motion blur on every piece+#+# Why: one browser renders about 4 to 8 frames a second at 1080p, so a 75 s film at 60 fps is ten minutes+# or more in a single process. Pieces are whole seconds long so each one prints progress at once, and a+# piece whose browser never starts (an empty log after 60 s) is started again. Three workers is a safe+# default on a laptop: every worker is a full Chrome, and six of them have run a 16 GB machine out of memory.+set -u+fps=${1:?fps}; dur=${2:?duration in seconds}; out=${3:?output mp4}; workers=${4:-3}; piece=${5:-12}+work="$(dirname "$out")/.pieces-$(basename "$out" .mp4)"; rm -rf "$work"; mkdir -p "$work"+starts=(); t=0; while [ "$(echo "$t < $dur" | bc)" = 1 ]; do starts+=("$t"); t=$((t + piece)); done+n=${#starts[@]}+run_piece() { local i=$1 s=${starts[$1]} e; e=$(echo "if (${starts[$1]} + $piece < $dur) ${starts[$1]} + $piece else $dur" | bc)+ START=$s END=$e node export.mjs "$fps" "$work/p$i.mp4" > "$work/p$i.log" 2>&1 & echo $! > "$work/p$i.pid"; }+next=0; running=()+while [ $next -lt $n ] || [ ${#running[@]} -gt 0 ]; do+ while [ ${#running[@]} -lt "$workers" ] && [ $next -lt $n ]; do : > "$work/p$next.log"; date +%s > "$work/p$next.t0"; run_piece $next; running+=("$next"); next=$((next + 1)); done+ sleep 4; still=()+ for i in "${running[@]}"; do p=$(cat "$work/p$i.pid")+ if kill -0 "$p" 2>/dev/null; then+ if [ ! -s "$work/p$i.log" ] && [ $(( $(date +%s) - $(cat "$work/p$i.t0") )) -gt 60 ]; then kill "$p" 2>/dev/null; sleep 1; date +%s > "$work/p$i.t0"; run_piece "$i"; echo "piece $i restarted (its browser never started)"; fi+ still+=("$i")+ fi+ done+ running=("${still[@]:-}"); [ -z "${running[0]:-}" ] && running=()+done+: > "$work/list.txt"+for i in $(seq 0 $((n - 1))); do+ if ! ffprobe -v error -show_entries format=duration -of csv=p=0 "$work/p$i.mp4" > /dev/null 2>&1; then echo "piece $i failed: last lines of its log:"; tail -c 600 "$work/p$i.log" | tr '\r' '\n' | grep -v '^frame=' | tail -8; exit 1; fi+ echo "file 'p$i.mp4'" >> "$work/list.txt"+done+ffmpeg -v error -y -f concat -safe 0 -i "$work/list.txt" -c copy "$out" || exit 1+got=$(ffprobe -v error -count_packets -select_streams v -show_entries stream=nb_read_packets -of csv=p=0 "$out"); want=$(echo "$dur * $fps / 1" | bc)+echo "wrote $out: $got frames (expected about $want)"; [ "$got" -ge $((want - 2)) ] || { echo "frame count is short: a piece stopped early, read its log in $work"; exit 1; }+rm -rf "$work"diff --git a/scripts/review-pack.sh b/scripts/review-pack.shnew file mode 100755index 0000000..16e636f--- /dev/null+++ b/scripts/review-pack.sh@@ -0,0 +1,45 @@+#!/bin/bash+# Build the pack a fresh reviewer reads: what a stranger would see, and nothing about how it was made.+#+# review-pack.sh <cut.mp4> <pack_dir> [--beats "0,1.5,4.8,..."] [--strips "9.2-11.6,66.0-67.2"] [--text "4.8,9.6,..."]+#+# Writes into <pack_dir>:+# sheet_1fps_partN.png one frame per second of the whole film, 40 per sheet+# beats_gridN.png frames at the story beats, 9 per grid (default: 36 evenly spaced)+# full_t<time>.png every 5th beat at full size+# strip_<a>-<b>.png 12 consecutive frames across each fast move or key transition you list+# phone_360px.png the frames that carry words, at phone width (default: the beats)+# WORDS-AND-SOUND.md a form to fill in: who it is for, the words with times, the sound report+# Then hand the folder to a new agent with references/reviewer-brief.md.+set -u+V=${1:?cut.mp4}; P=${2:?pack dir}; shift 2; beats=""; strips=""; text=""+while [ $# -gt 0 ]; do case "$1" in --beats) beats=$2; shift 2;; --strips) strips=$2; shift 2;; --text) text=$2; shift 2;; *) echo "unknown option $1"; exit 2;; esac; done+rm -rf "$P"; mkdir -p "$P"; T=$(mktemp -d)+dur=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$V"); D=${dur%.*}+k=0; s=0; while [ $s -lt "$D" ]; do k=$((k + 1)); ffmpeg -v error -y -ss $s -t 39.9 -i "$V" -vf "fps=1,scale=400:-1,tile=8x5:padding=4:color=gray" -frames:v 1 "$P/sheet_1fps_part$k.png"; s=$((s + 40)); done+if [ -z "$beats" ]; then beats=$(python3 -c "d=$dur; print(','.join(f'{d*i/35.5:.1f}' for i in range(36)))"); fi+IFS=',' read -ra B <<< "$beats"; i=0+for t in "${B[@]}"; do ffmpeg -v error -y -ss "$t" -i "$V" -frames:v 1 -vf scale=640:-1 "$T/b$(printf %03d $i).png"; [ $((i % 5)) -eq 0 ] && ffmpeg -v error -y -ss "$t" -i "$V" -frames:v 1 "$P/full_t$t.png"; i=$((i + 1)); done+g=0; j=0; while [ $j -lt ${#B[@]} ]; do g=$((g + 1)); ffmpeg -v error -y -start_number $j -i "$T/b%03d.png" -frames:v 9 -vf "tile=3x3" -frames:v 1 "$P/beats_grid$g.png" 2>/dev/null; j=$((j + 9)); done+IFS=',' read -ra S <<< "$strips"+for r in "${S[@]:-}"; do [ -z "$r" ] && continue; a=${r%-*}; b=${r#*-}; len=$(python3 -c "print($b-$a)"); ffmpeg -v error -y -ss "$a" -t "$len" -i "$V" -vf "fps=12/$len,scale=480:-1,tile=4x3:padding=3:color=gray" -frames:v 1 "$P/strip_$a-$b.png"; done+[ -z "$text" ] && text=$beats; IFS=',' read -ra X <<< "$text"; i=0+for t in "${X[@]}"; do [ $i -ge 20 ] && break; ffmpeg -v error -y -ss "$t" -i "$V" -frames:v 1 -vf scale=360:-1 "$T/p$(printf %03d $i).png"; i=$((i + 1)); done+ffmpeg -v error -y -i "$T/p%03d.png" -vf "tile=5x$(( (i + 4) / 5 ))" -frames:v 1 "$P/phone_360px.png" 2>/dev/null+cat > "$P/WORDS-AND-SOUND.md" <<FORM+# The film: ${dur%.*} s. FILL IN: format, where it posts.+Audience: FILL IN (who it is for). It will often be seen muted, on a phone, once.++## Words spoken or sung, with film times+FILL IN, one line per phrase: <time> <words>++## Sound report (the reviewer cannot hear it)+FILL IN from scripts/audio-check.mjs and scripts/songmap.py: loudness and true peak; where the music is quiet, where it hits hardest; any sound effects and where they land.++## Beat times in beats_grid*.png, in order+$beats++## Files+sheet_1fps_part*.png (one frame per second), beats_grid*.png (9 per grid, times above), full_t*.png (full size), strip_*.png (12 frames across a fast move, range in the name), phone_360px.png (frames with words at phone width). The film itself: $(basename "$V").+FORM+rm -rf "$T"; echo "pack in $P: $(ls "$P" | wc -l | tr -d ' ') files. Fill in WORDS-AND-SOUND.md before handing it over."diff --git a/scripts/review-room/index.html b/scripts/review-room/index.htmlnew file mode 100644index 0000000..4f53bfd--- /dev/null+++ b/scripts/review-room/index.html@@ -0,0 +1,79 @@+<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Take One · Review room</title><link rel="icon" type="image/svg+xml" href="/logo/take-one-mark.svg">+<style>+:root{--bg:#0c0c0d;--panel:#151516;--line:#2c2b29;--ink:#ecebe8;--dim:#8b8a86;--accent:#d97757;--ok:#5fb97a}+*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);font:16px/1.45 -apple-system,BlinkMacSystemFont,"Helvetica Neue",Arial,sans-serif}+header{display:flex;gap:14px;align-items:center;padding:14px 20px;border-bottom:1px solid var(--line)}+header .brand{display:flex;align-items:center;gap:14px;margin-right:10px}header .brand img{height:38px;display:block}header h1{font-size:15px;margin:0;font-weight:600;color:var(--dim);letter-spacing:.02em;padding-left:14px;border-left:1px solid var(--line)}header label{color:var(--dim);font-size:14px}+select,button,textarea{font:inherit;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:10px}+select{padding:8px 10px}button{padding:9px 14px;cursor:pointer}button:hover{border-color:#55544f}button.go{background:var(--accent);border-color:var(--accent);color:#17110e;font-weight:650}+main{display:grid;grid-template-columns:minmax(0,1fr) 400px;height:calc(100% - 62px)}+#left{padding:18px 20px;overflow:auto}#stage{display:grid;gap:12px;grid-template-columns:1fr}#stage.two{grid-template-columns:1fr 1fr}+.vid{position:relative;background:#000;border-radius:12px;overflow:hidden;aspect-ratio:16/9}.vid video{width:100%;height:100%;display:block}+.vid .tag{position:absolute;left:10px;top:10px;background:rgba(12,12,13,.72);padding:3px 9px;border-radius:8px;font-size:13px;color:var(--dim)}+#hit{position:absolute;inset:0;cursor:crosshair}+.pin{position:absolute;width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;border:3px solid #fff;background:var(--accent);box-shadow:0 0 0 2px rgba(0,0,0,.55);pointer-events:none}+#bar{display:flex;gap:10px;align-items:center;margin-top:12px}#time{font-variant-numeric:tabular-nums;color:var(--dim);min-width:190px;font-size:14px}+#seekwrap{position:relative;flex:1;height:28px}#seek{position:absolute;inset:0;width:100%;margin:0;accent-color:var(--accent)}+#marks{position:absolute;left:0;right:0;top:-5px;height:8px;pointer-events:none}#marks i{position:absolute;width:8px;height:8px;margin-left:-4px;border-radius:50%;background:var(--accent)}#marks i.done{background:var(--ok)}+#hint{color:var(--dim);font-size:14px;margin-top:10px}+#right{border-left:1px solid var(--line);display:flex;flex-direction:column;min-height:0}+#compose{padding:16px;border-bottom:1px solid var(--line)}#where{font-size:14px;color:var(--accent);margin-bottom:8px;min-height:20px}+textarea{width:100%;min-height:92px;padding:10px 12px;resize:vertical}#compose .row{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}+#list{overflow:auto;padding:8px 16px 20px;flex:1}.note{display:grid;grid-template-columns:112px 1fr;gap:10px;padding:12px 0;border-bottom:1px solid var(--line)}+.note img{width:112px;border-radius:6px;cursor:pointer;display:block;background:#000}.note .t{font-size:13px;color:var(--accent);cursor:pointer}.note .x{font-size:13px;color:var(--dim);cursor:pointer;margin-left:10px}+.note p{margin:4px 0 0;white-space:pre-wrap}.note.done p{color:var(--dim);text-decoration:line-through}.empty{color:var(--dim);padding:18px 0}+#toast{position:fixed;left:50%;bottom:26px;transform:translateX(-50%);background:var(--ok);color:#0c1a10;padding:10px 16px;border-radius:10px;font-weight:650;display:none}+</style></head><body>+<header><span class="brand"><img src="/logo/take-one-logo.svg" alt="Take One"><h1>Review room</h1></span><label>Cut <select id="cut"></select></label><label>Compare with <select id="cmp"><option value="">nothing</option></select></label><span style="flex:1"></span><button class="go" id="send">Send notes to Claude</button></header>+<main><section id="left">+ <div id="stage"><div class="vid"><video id="v" playsinline preload="auto"></video><div id="hit"></div><div class="tag" id="tagA"></div></div>+ <div class="vid" id="boxB" style="display:none"><video id="w" playsinline muted preload="auto"></video><div class="tag" id="tagB"></div></div></div>+ <div id="bar"><button id="play">Play</button><button id="back" title="one frame back">◀ frame</button><button id="fwd" title="one frame forward">frame ▶</button>+ <div id="seekwrap"><div id="marks"></div><input id="seek" type="range" min="0" max="1" step="0.001" value="0"></div><span id="time"></span></div>+ <div id="hint">Click anywhere on the picture to pin a note to that spot on that frame. Space plays and pauses. The arrow keys move one frame.</div>+</section>+<aside id="right"><div id="compose"><div id="where">Click on the picture, or write a note about the whole film.</div>+ <textarea id="text" placeholder="What should change here?"></textarea>+ <div class="row"><button class="go" id="add">Save note</button><button id="nopin">Note on this frame, no pin</button><button id="whole">Note on the whole film</button></div></div>+ <div id="list"></div></aside></main><div id="toast"></div>+<script>+const $=(id)=>document.getElementById(id),v=$('v'),w=$('w'),FPS=30;let cuts=[],notes=[],pin=null,mode='pin';+const fmt=(t)=>{const m=Math.floor(t/60),s=t-m*60;return m+':'+s.toFixed(2).padStart(5,'0');};+const api=(p,o)=>fetch(p,o).then((r)=>r.json());+const toast=(s)=>{const t=$('toast');t.textContent=s;t.style.display='block';clearTimeout(toast.k);toast.k=setTimeout(()=>t.style.display='none',2600);};+async function boot(){cuts=await api('/api/cuts');for(const c of cuts){$('cut').add(new Option(c.name.replace('.mp4',''),c.name));$('cmp').add(new Option(c.name.replace('.mp4',''),c.name));}+ const want=localStorage.getItem('rr-cut');if(want&&cuts.some((c)=>c.name===want))$('cut').value=want;setCut();await refresh();}+function setCut(){v.src='/video/'+encodeURIComponent($('cut').value);$('tagA').textContent=$('cut').value.replace('.mp4','');localStorage.setItem('rr-cut',$('cut').value);clearPin();draw();}+function setCmp(){const n=$('cmp').value;$('boxB').style.display=n?'':'none';$('stage').className=n?'two':'';if(n){w.src='/video/'+encodeURIComponent(n);$('tagB').textContent=n.replace('.mp4','')+' (compare)';w.currentTime=v.currentTime;}else w.removeAttribute('src');}+async function refresh(){notes=(await api('/api/notes')).notes;draw();}+function mine(){return notes.filter((n)=>n.cut===$('cut').value).sort((a,b)=>(a.t??-1)-(b.t??-1));}+function draw(){const L=$('list');L.innerHTML='';const ns=mine();if(!ns.length)L.innerHTML='<div class="empty">No notes on this cut yet.</div>';+ for(const n of ns){const d=document.createElement('div');d.className='note'+(n.done?' done':'');+ const im=n.shot?`<img src="/${n.shot}?${n.id}">`:'<div></div>',when=n.t===null?'whole film':fmt(n.t)+(n.x===null?'':' · pinned');+ d.innerHTML=`${im}<div><span class="t">${when}</span><span class="x" data-a="done">${n.done?'reopen':'mark done'}</span><span class="x" data-a="del">delete</span><p></p></div>`;d.querySelector('p').textContent=n.text;+ const jump=()=>{if(n.t!==null){v.pause();v.currentTime=n.t;showPin(n.x,n.y);}};d.querySelector('.t').onclick=jump;if(n.shot)d.querySelector('img').onclick=jump;+ d.querySelector('[data-a=del]').onclick=async()=>{await fetch('/api/notes/'+n.id,{method:'DELETE'});refresh();};+ d.querySelector('[data-a=done]').onclick=async()=>{await api('/api/notes/'+n.id,{method:'POST',body:JSON.stringify({done:!n.done})});refresh();};L.appendChild(d);}+ const M=$('marks');M.innerHTML='';if(v.duration)for(const n of ns)if(n.t!==null){const i=document.createElement('i');i.style.left=(n.t/v.duration*100)+'%';if(n.done)i.className='done';M.appendChild(i);}}+function showPin(x,y){document.querySelectorAll('.pin').forEach((p)=>p.remove());if(x===null||x===undefined)return;const p=document.createElement('div');p.className='pin';p.style.left=x*100+'%';p.style.top=y*100+'%';$('hit').appendChild(p);}+function clearPin(){pin=null;mode='pin';showPin(null);$('where').textContent='Click on the picture, or write a note about the whole film.';}+$('hit').onclick=(e)=>{const r=$('hit').getBoundingClientRect();v.pause();pin={x:(e.clientX-r.left)/r.width,y:(e.clientY-r.top)/r.height};mode='pin';showPin(pin.x,pin.y);$('where').textContent='Note pinned at '+fmt(v.currentTime);$('text').focus();};+$('nopin').onclick=()=>{v.pause();pin=null;mode='frame';showPin(null);$('where').textContent='Note on the frame at '+fmt(v.currentTime);$('text').focus();};+$('whole').onclick=()=>{pin=null;mode='whole';showPin(null);$('where').textContent='Note on the whole film';$('text').focus();};+function shot(){const c=document.createElement('canvas');c.width=960;c.height=540;const g=c.getContext('2d');g.drawImage(v,0,0,960,540);+ if(pin){g.lineWidth=5;g.strokeStyle='#fff';g.fillStyle='#d97757';g.beginPath();g.arc(pin.x*960,pin.y*540,16,0,7);g.fill();g.stroke();}return c.toDataURL('image/jpeg',0.85);}+async function add(){const text=$('text').value.trim();if(!text){$('text').focus();return;}if(mode==='pin'&&!pin)mode=v.paused&&v.currentTime>0?'frame':'whole';+ const b={cut:$('cut').value,text};if(mode!=='whole'){b.t=v.currentTime;b.shot=shot();if(pin){b.x=pin.x;b.y=pin.y;}}+ await api('/api/notes',{method:'POST',body:JSON.stringify(b)});$('text').value='';clearPin();await refresh();toast('Note saved');}+$('add').onclick=add;$('text').addEventListener('keydown',(e)=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();add();}});+$('send').onclick=async()=>{await api('/api/send',{method:'POST',body:JSON.stringify({cut:$('cut').value})});toast('Sent. Claude can read your notes now.');};+const step=(d)=>{v.pause();v.currentTime=Math.max(0,Math.min(v.duration||0,Math.round(v.currentTime*FPS+d)/FPS));};+$('play').onclick=()=>v.paused?v.play():v.pause();$('back').onclick=()=>step(-1);$('fwd').onclick=()=>step(1);+$('seek').oninput=()=>{v.currentTime=$('seek').value*(v.duration||0);};+v.onplay=()=>{$('play').textContent='Pause';showPin(null);if(w.src){w.currentTime=v.currentTime;w.play();}};v.onpause=()=>{$('play').textContent='Play';if(w.src){w.pause();w.currentTime=v.currentTime;}};+v.onseeked=()=>{if(w.src&&v.paused)w.currentTime=v.currentTime;};v.onloadedmetadata=draw;+v.ontimeupdate=()=>{$('seek').value=v.duration?v.currentTime/v.duration:0;$('time').textContent=fmt(v.currentTime)+' / '+fmt(v.duration||0)+' · frame '+Math.round(v.currentTime*FPS);};+$('cut').onchange=()=>{setCut();};$('cmp').onchange=setCmp;+document.addEventListener('keydown',(e)=>{if(e.target.tagName==='TEXTAREA'||e.target.tagName==='SELECT')return;if(e.code==='Space'){e.preventDefault();$('play').onclick();}if(e.key==='ArrowLeft'){e.preventDefault();step(e.shiftKey?-FPS:-1);}if(e.key==='ArrowRight'){e.preventDefault();step(e.shiftKey?FPS:1);}});+boot();+</script></body></html>diff --git a/scripts/review-room/server.mjs b/scripts/review-room/server.mjsnew file mode 100644index 0000000..60eac97--- /dev/null+++ b/scripts/review-room/server.mjs@@ -0,0 +1,50 @@+// review-room/server.mjs : a local review room for the cuts of a film. Watch a cut, click on the picture, leave a note on that exact frame.+// Nothing leaves this computer: it only listens on 127.0.0.1.+// Usage: node server.mjs <folder with the exported .mp4 cuts> [port=4400] then open http://localhost:4400+// Notes go to <folder>/review-notes/notes.json, a snapshot of each noted frame (pin drawn in) to <folder>/review-notes/shots/,+// and every press of "Send notes" adds a line starting SENT to <folder>/review-notes/sent.log (watch that file to be told).+import http from 'node:http';+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+if (!process.argv[2]) { console.error('usage: node server.mjs <folder with the exported .mp4 cuts> [port]'); process.exit(1); }+const HERE = path.dirname(fileURLToPath(import.meta.url)), OUT = path.resolve(process.argv[2]), DIR = path.join(OUT, 'review-notes'), NOTES = path.join(DIR, 'notes.json'), SHOTS = path.join(DIR, 'shots'), LOG = path.join(DIR, 'sent.log'), PORT = Number(process.argv[3] || 4400);+fs.mkdirSync(SHOTS, { recursive: true });+const load = () => { try { return JSON.parse(fs.readFileSync(NOTES, 'utf8')); } catch { return { notes: [], sent: [] }; } };+const save = (d) => fs.writeFileSync(NOTES, JSON.stringify(d, null, 1));+const cuts = () => fs.readdirSync(OUT).filter((f) => /\.mp4$/i.test(f) && !/silent|small|draft-frames/.test(f))+ .map((f) => ({ name: f, mtime: fs.statSync(path.join(OUT, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime); // newest first+const body = (req) => new Promise((res) => { const c = []; req.on('data', (d) => c.push(d)); req.on('end', () => { try { res(JSON.parse(Buffer.concat(c).toString() || '{}')); } catch { res({}); } }); });+const json = (res, code, o) => { res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(o)); };+function file(req, res, p, type) {+ if (!fs.existsSync(p)) { res.writeHead(404); return res.end('not found'); }+ const size = fs.statSync(p).size, r = /bytes=(\d*)-(\d*)/.exec(req.headers.range || '');+ if (r) { const a = r[1] ? Number(r[1]) : 0, b = r[2] ? Math.min(Number(r[2]), size - 1) : size - 1;+ res.writeHead(206, { 'content-type': type, 'accept-ranges': 'bytes', 'content-range': `bytes ${a}-${b}/${size}`, 'content-length': b - a + 1 }); return fs.createReadStream(p, { start: a, end: b }).pipe(res); }+ res.writeHead(200, { 'content-type': type, 'accept-ranges': 'bytes', 'content-length': size, 'cache-control': 'no-store' }); fs.createReadStream(p).pipe(res);+}+http.createServer(async (req, res) => {+ // the room answers only its own page: another website open in the same browser cannot read the notes or plant one+ const host = String(req.headers.host || ''), origin = req.headers.origin;+ if (!/^(localhost|127\.0\.0\.1):\d+$/.test(host) || (origin && origin !== 'http://' + host)) { res.writeHead(403); return res.end('forbidden'); }+ const u = new URL(req.url, 'http://x'), p = decodeURIComponent(u.pathname);+ if (p === '/') return file(req, res, path.join(HERE, 'index.html'), 'text/html; charset=utf-8');+ const LOGO = path.join(HERE, '..', '..', 'assets', 'logo'); // the Take One mark and wordmark+ if (p === '/favicon.ico') return file(req, res, path.join(LOGO, 'take-one-mark.svg'), 'image/svg+xml');+ if (p.startsWith('/logo/') && /^[a-z0-9-]+\.svg$/.test(path.basename(p))) return file(req, res, path.join(LOGO, path.basename(p)), 'image/svg+xml');+ if (p === '/api/cuts') return json(res, 200, cuts());+ if (p.startsWith('/video/')) { const n = path.basename(p); return cuts().some((c) => c.name === n) ? file(req, res, path.join(OUT, n), 'video/mp4') : json(res, 404, {}); }+ if (p.startsWith('/shots/')) return file(req, res, path.join(SHOTS, path.basename(p)), 'image/jpeg');+ if (p === '/api/notes' && req.method === 'GET') return json(res, 200, load());+ if (p === '/api/notes' && req.method === 'POST') { const b = await body(req), d = load(), id = Date.now().toString(36);+ const n = { id, cut: String(b.cut || ''), t: typeof b.t === 'number' ? Math.round(b.t * 1000) / 1000 : null, frame: typeof b.t === 'number' ? Math.round(b.t * 30) : null,+ x: typeof b.x === 'number' ? Math.round(b.x * 1000) / 1000 : null, y: typeof b.y === 'number' ? Math.round(b.y * 1000) / 1000 : null, text: String(b.text || '').slice(0, 4000), at: new Date().toISOString(), done: false };+ if (typeof b.shot === 'string' && b.shot.startsWith('data:image/jpeg;base64,')) { fs.writeFileSync(path.join(SHOTS, id + '.jpg'), Buffer.from(b.shot.slice(23), 'base64')); n.shot = 'shots/' + id + '.jpg'; }+ d.notes.push(n); save(d); console.log(`NOTE ${n.cut} ${n.t ?? 'whole film'} ${n.text.slice(0, 80)}`); return json(res, 200, n); }+ const m = /^\/api\/notes\/([a-z0-9]+)$/.exec(p);+ if (m && req.method === 'POST') { const b = await body(req), d = load(), n = d.notes.find((x) => x.id === m[1]); if (!n) return json(res, 404, {}); if (typeof b.text === 'string') n.text = b.text.slice(0, 4000); if (typeof b.done === 'boolean') n.done = b.done; save(d); return json(res, 200, n); }+ if (m && req.method === 'DELETE') { const d = load(); d.notes = d.notes.filter((x) => x.id !== m[1]); save(d); const sf = path.join(SHOTS, m[1] + '.jpg'); if (fs.existsSync(sf)) fs.unlinkSync(sf); return json(res, 200, { ok: true }); }+ if (p === '/api/send' && req.method === 'POST') { const b = await body(req), d = load(); d.sent.push({ at: new Date().toISOString(), cut: String(b.cut || ''), open: d.notes.filter((n) => !n.done).length }); save(d);+ const line = `SENT ${d.notes.filter((n) => !n.done).length} open notes on ${b.cut || ''}`; console.log(line); fs.appendFileSync(LOG, line + '\n'); return json(res, 200, { ok: true }); }+ res.writeHead(404); res.end('not found');+}).listen(PORT, '127.0.0.1', () => console.log(`Take One review room on http://localhost:${PORT}`));diff --git a/scripts/serve.mjs b/scripts/serve.mjsnew file mode 100644index 0000000..f5487bd--- /dev/null+++ b/scripts/serve.mjs@@ -0,0 +1,17 @@+// Tiny static server so canvas can read local images (file:// taints the canvas).+import http from 'node:http'; import fs from 'node:fs'; import path from 'node:path';+const types = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif',+ '.svg': 'image/svg+xml', // without this an SVG logo used as an <img> never loads, silently+ '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav' };+export function serve(root = '.') {+ return new Promise(res => {+ const base = path.resolve(root);+ const srv = http.createServer((req, r) => {+ // only files inside the film folder: a path that climbs out of it with ../ is refused+ let p = ''; try { p = path.join(base, decodeURIComponent(req.url.split('?')[0])); } catch {}+ if (p !== base && !p.startsWith(base + path.sep)) { r.writeHead(403); r.end(); return; }+ fs.readFile(p, (e, d) => { if (e) { r.writeHead(404); r.end(); return; } r.writeHead(200, { 'Content-Type': types[path.extname(p)] || 'application/octet-stream' }); r.end(d); });+ // 127.0.0.1: this computer only. Without a host the server answers the whole network.+ }).listen(0, '127.0.0.1', () => res({ srv, url: `http://127.0.0.1:${srv.address().port}` }));+ });+}diff --git a/scripts/sfx.mjs b/scripts/sfx.mjsnew file mode 100644index 0000000..fb3cc23--- /dev/null+++ b/scripts/sfx.mjs@@ -0,0 +1,819 @@+#!/usr/bin/env node+// Adapted from anidoodle (github.com/alexgreensh/anidoodle), Apache License 2.0, Copyright 2026 Alex Greenshpun+//+// Procedural SFX kit for take-one films: every effect synthesized in code (no samples,+// no ElevenLabs), deterministic per seed, placed on exact film frames over a music bed.+//+// node sfx.mjs list # kinds, variants, levels, uses+// node sfx.mjs one <kind> [variant] [seed] <out.wav> # one sound (KEY=C BPM=90 env for tuned kinds)+// node sfx.mjs kit <outdir> # every kind x variant + metrics check (exit 1 on fail)+// node sfx.mjs mix <plan.json> <bed-audio> <out.wav> # place a cue plan over a music bed+//+// plan.json: { fps, frames?, bpm?, beatZeroS?, beatsPerBar?, key?, seed, snap?, minDb?, ceilingDb?,+// cues: [{ kind, frame, variant?, snap?, seed?, pitch?, lengthS?, beats?, key?, bpm?,+// dir?, gainDb?, duckDb?, minDb?, label? }] }+// frames defaults to the bed's length. Cues are addressed by INTEGER film frame (fractional throws).+// The frame is the sound's sync point: the hit; the PASS-BY of a whoosh; the END of a riser.+// The bed ducks under cues (raised-cosine 40 ms attack, 280 ms release, 1.2 s after an impact,+// capped at 9 dB), the final mix goes through a look-ahead -1 dBTP ceiling, and every cue must sit+// within 6 dB of the ducked bed over its speaking window or the mix throws "buried cue".+// Taste rules (warnings): one riser + one impact per film; at most 2 cues in any 100 ms.+import { execFileSync } from "node:child_process";+import { writeFileSync, mkdirSync, realpathSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { readFile } from "node:fs/promises";+import { join, resolve } from "node:path";++const SR = 48000;+const TAU = Math.PI * 2;+const db = (x) => Math.pow(10, x / 20);+const dB = (x) => 20 * Math.log10(Math.max(x, 1e-12));+const clamp = (x, a, b) => (x < a ? a : x > b ? b : x);+const panGains = (p) => { const a = ((clamp(p, -1, 1) + 1) * Math.PI) / 4; return [Math.cos(a), Math.sin(a)]; };+const mkRng = (seed) => {+ let a = seed >>> 0;+ return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };+};++// ---------------------------------------------------------------- filters+/** Zavalishin TPT state-variable filter; set() may be called per sample for sweeps. */+class SVF {+ constructor(sr, f = 1000, q = 0.707) { this.sr = sr; this.ic1 = 0; this.ic2 = 0; this.lp = 0; this.bp = 0; this.hp = 0; this.set(f, q); }+ set(f, q) { this.g = Math.tan((Math.PI * clamp(f, 5, this.sr * 0.49)) / this.sr); this.k = 1 / q; this.a1 = 1 / (1 + this.g * (this.g + this.k)); this.a2 = this.g * this.a1; this.a3 = this.g * this.a2; }+ tick(x) { const v3 = x - this.ic2, v1 = this.a1 * this.ic1 + this.a2 * v3, v2 = this.ic2 + this.a2 * this.ic1 + this.a3 * v3; this.ic1 = 2 * v1 - this.ic1; this.ic2 = 2 * v2 - this.ic2; this.lp = v2; this.bp = v1; this.hp = x - this.k * v1 - v2; return v2; }+}+/** RBJ biquad (direct form I). */+class Biquad {+ constructor() { this.x1 = 0; this.x2 = 0; this.y1 = 0; this.y2 = 0; this.b0 = 1; this.b1 = 0; this.b2 = 0; this.a1 = 0; this.a2 = 0; }+ static make(sr, type, f, q) {+ const bq = new Biquad(), w = (TAU * f) / sr, c = Math.cos(w), s = Math.sin(w), al = s / (2 * q);+ let b0 = 1, b1 = 0, b2 = 0, a0 = 1, a1 = 0, a2 = 0;+ if (type === "lp") { b0 = (1 - c) / 2; b1 = 1 - c; b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else if (type === "hp") { b0 = (1 + c) / 2; b1 = -(1 + c); b2 = b0; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; }+ else { b0 = al; b1 = 0; b2 = -al; a0 = 1 + al; a1 = -2 * c; a2 = 1 - al; } // bp+ bq.b0 = b0 / a0; bq.b1 = b1 / a0; bq.b2 = b2 / a0; bq.a1 = a1 / a0; bq.a2 = a2 / a0; return bq;+ }+ tick(x) { const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2; this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y; return y; }+ run(buf) { for (let i = 0; i < buf.length; i++) buf[i] = this.tick(buf[i]); return buf; }+}+const onePoleCoef = (sr, f) => 1 - Math.exp((-TAU * f) / sr);++/** A small room: early reflections plus a short 8-line FDN tail. Returns the WET signal only. */+const room = (L, R, sr, o) => {+ const n = L.length, wL = new Float32Array(n), wR = new Float32Array(n), r = o.rng;+ const inL = Float32Array.from(L), inR = Float32Array.from(R);+ Biquad.make(sr, "hp", o.hp, 0.7).run(inL); Biquad.make(sr, "hp", o.hp, 0.7).run(inR);+ Biquad.make(sr, "lp", o.lp, 0.7).run(inL); Biquad.make(sr, "lp", o.lp, 0.7).run(inR);+ for (const [src, dst, side] of [[inL, wL, 0], [inR, wR, 1], [inR, wL, 2], [inL, wR, 3]]) {+ let acc = 0; const k = onePoleCoef(sr, 5200);+ for (let t = 0; t < 7; t++) {+ const ms = 6 + t * 4.6 + r() * 3 + side * 0.7, d = Math.round((ms / 1000) * sr), g = (o.er * (side < 2 ? 1 : 0.55) * Math.pow(0.8, t) * (t % 2 ? -1 : 1)) / 2.2;+ acc = 0; for (let i = d; i < n; i++) { acc += k * (src[i - d] - acc); dst[i] += acc * g; }+ }+ }+ if (o.late > 0) {+ const N = 8, lens = [1123, 1289, 1447, 1597, 1777, 1913, 2053, 2239].map((x) => Math.round(((x * sr) / 48000) * (0.7 + 0.3 * r())));+ const bufs = lens.map((l) => new Float32Array(l)), idx = new Array(N).fill(0), lp = new Array(N).fill(0);+ const gains = lens.map((l) => Math.pow(10, (-3 * l) / (sr * o.rt60))), dampK = onePoleCoef(sr, 3200);+ const pd = Math.round(o.predelay * sr), out = new Float64Array(N), h = new Float64Array(N);+ for (let i = 0; i < n; i++) {+ const xl = i >= pd ? inL[i - pd] : 0, xr = i >= pd ? inR[i - pd] : 0;+ for (let j = 0; j < N; j++) out[j] = bufs[j][idx[j]];+ h.set(out);+ for (let s = 1; s < N; s <<= 1) for (let j = 0; j < N; j += s << 1) for (let q = j; q < j + s; q++) { const a = h[q], b = h[q + s]; h[q] = a + b; h[q + s] = a - b; }+ for (let j = 0; j < N; j++) {+ let v = (h[j] / Math.sqrt(N)) * gains[j];+ lp[j] += dampK * (v - lp[j]); v = lp[j];+ bufs[j][idx[j]] = v + (j % 2 ? xr : xl) * 0.5; idx[j] = (idx[j] + 1) % lens[j];+ }+ wL[i] += (out[0] - out[2] + out[4] - out[6]) * o.late * 0.5; wR[i] += (out[1] - out[3] + out[5] - out[7]) * o.late * 0.5;+ }+ }+ return [wL, wR];+};++// ---------------------------------------------------------------- sfx building blocks+const buf = (n) => new Float64Array(Math.max(0, Math.round(n)));+const secs = (sr, s) => Math.max(0, Math.round(s * sr));+/** 32-bit integer hash of two values: per-cue seeds that stay put when other cues move. */+const mixSeed = (a, b) => {+ let h = (Math.imul(a | 0, 0x9e3779b1) ^ Math.imul(b | 0, 0x85ebca6b)) >>> 0;+ h = Math.imul(h ^ (h >>> 16), 0x7feb352d) >>> 0; h = Math.imul(h ^ (h >>> 15), 0x846ca68b) >>> 0;+ return (h ^ (h >>> 16)) >>> 0;+};+const strSeed = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; };++/** A stereo bus. Mono layers are placed with a pan (constant, or per sample) and an optional Haas offset. */+class Bus {+ constructor(sr, n) { this.sr = sr; this.n = n; this.L = buf(n); this.R = buf(n); }+ add(sig, at = 0, g = 1, p = 0, haasMs = 0) {+ const d = Math.round((Math.abs(haasMs) * this.sr) / 1000), dL = haasMs < 0 ? d : 0, dR = haasMs > 0 ? d : 0;+ const fixed = typeof p === "number" ? panGains(p) : null;+ for (let i = 0; i < sig.length; i++) {+ const v = sig[i] * g; if (v === 0) continue;+ const [gl, gr] = fixed ?? panGains(p(i));+ const a = at + i + dL, b = at + i + dR;+ if (a >= 0 && a < this.n) this.L[a] += v * gl;+ if (b >= 0 && b < this.n) this.R[b] += v * gr;+ }+ }+ add2(l, r, at = 0, g = 1) { for (let i = 0; i < l.length; i++) { const k = at + i; if (k < 0 || k >= this.n) continue; this.L[k] += l[i] * g; this.R[k] += r[i] * g; } }+}++const white = (r, n) => { const o = buf(n); for (let i = 0; i < o.length; i++) o[i] = r() * 2 - 1; return o; };+/** Pink noise (Paul Kellet's refined filter). */+const pink = (r, n) => {+ const o = buf(n); let b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0;+ for (let i = 0; i < o.length; i++) {+ const w = r() * 2 - 1;+ b0 = 0.99886 * b0 + w * 0.0555179; b1 = 0.99332 * b1 + w * 0.0750759; b2 = 0.969 * b2 + w * 0.153852;+ b3 = 0.8665 * b3 + w * 0.3104856; b4 = 0.55 * b4 + w * 0.5329522; b5 = -0.7616 * b5 - w * 0.016898;+ o[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362) * 0.11; b6 = w * 0.115926;+ }+ return o;+};+/** Modal synthesis: sum of damped sinusoids (bubbles rise, bodies drop); no aliasing, stops at -100 dB. */+const modal = (sr, n, modes) => {+ const o = buf(n), ny = 0.45 * sr;+ for (const m of modes) {+ if (!(m.f > 0) || m.f > ny) continue;+ const i0 = secs(sr, m.t0 ?? 0), att = m.att ?? 0.00006, end = Math.min(o.length, i0 + Math.ceil(m.tau * 11.5 * sr)), riseEnd = m.tau * 6.9;+ let ph = m.ph ?? 0;+ for (let i = i0; i < end; i++) {+ const t = (i - i0) / sr, f = m.f * (1 + (m.glide ?? 0) * (1 - Math.exp(-t / (m.glideTau ?? 0.01)))) * (1 + (m.rise ?? 0) * Math.min(t, riseEnd));+ o[i] += Math.sin(ph) * m.a * (1 - Math.exp(-t / att)) * Math.exp(-t / m.tau);+ ph += (TAU * Math.min(f, ny)) / sr;+ }+ }+ return o;+};+const endFade = (o, sr, s = 0.008) => { const f = Math.min(o.length, secs(sr, s)); for (let i = 0; i < f; i++) o[o.length - 1 - i] *= 0.5 - 0.5 * Math.cos((Math.PI * i) / f); return o; };+/** A sine whose frequency and amplitude are functions of time (phase-accumulated, so glides never click). */+const chirp = (sr, n, f, env, ph0 = 0) => {+ const o = buf(n); let ph = ph0;+ for (let i = 0; i < o.length; i++) { const t = i / sr; o[i] = Math.sin(ph) * env(t); ph += (TAU * Math.min(f(t), sr * 0.45)) / sr; }+ return endFade(o, sr, 0.03);+};+/** Enveloped noise burst, optionally band-limited: the contact transient of almost every hit. */+const burst = (sr, r, len, tau, o = {}) => {+ const n = secs(sr, len), s = o.pink ? pink(r, n) : white(r, n);+ for (let i = 0; i < n; i++) s[i] *= Math.exp(-i / sr / tau) * Math.min(1, i / (sr * 0.00008) + 0.35);+ filt(s, sr, o); return endFade(s, sr, 0.008);+};+const filt = (s, sr, o) => {+ const run = (bq) => { for (let i = 0; i < s.length; i++) s[i] = bq.tick(s[i]); };+ if (o.hp) run(Biquad.make(sr, "hp", o.hp, 0.707));+ if (o.lp) run(Biquad.make(sr, "lp", o.lp, 0.707));+ if (o.bp) run(Biquad.make(sr, "bp", o.bp, o.q ?? 1));+ return s;+};+/** Time-varying state-variable filter (a sweep): f(t) in Hz. */+const sweep = (s, sr, f, q, mode) => {+ const sv = new SVF(sr, f(0), typeof q === "number" ? q : q(0));+ for (let i = 0; i < s.length; i++) {+ if ((i & 15) === 0) { const t = i / sr; sv.set(clamp(f(t), 20, sr * 0.45), typeof q === "number" ? q : q(t)); }+ sv.tick(s[i]); s[i] = mode === "lp" ? sv.lp : mode === "bp" ? sv.bp : sv.hp;+ }+ return s;+};+const shape = (s, sr, env) => { for (let i = 0; i < s.length; i++) s[i] *= env(i / sr); return s; };+/** Attack-decay envelope: raised-cosine attack of `a` seconds, exponential decay of time constant `tau`. */+const ad = (a, tau) => (t) => (t < a ? 0.5 - 0.5 * Math.cos((Math.PI * t) / a) : Math.exp(-(t - a) / tau));+const smooth = (u) => { const x = clamp(u, 0, 1); return x * x * (3 - 2 * x); };++/** Put the bus in a small space: room's wet signal, mixed in. Stereo width comes from here. */+const space = (b, r, o) => {+ const L = Float32Array.from(b.L), R = Float32Array.from(b.R);+ const [wL, wR] = room(L, R, b.sr, { er: o.er ?? 0.5, late: 0.6, rt60: o.rt60, predelay: o.predelay ?? 0.012, hp: o.hp ?? 250, lp: o.lp ?? 7000, rng: r });+ for (let i = 0; i < b.n; i++) { b.L[i] += wL[i] * o.mix; b.R[i] += wR[i] * o.mix; }+};++/** DC block (22 Hz HP), air roll-off (16.5 kHz), NaN guard, trailing silence trimmed, end fade. */+const finish = (b, keep) => {+ const sr = b.sr, top = Math.min(16500, sr * 0.4);+ for (const c of [b.L, b.R]) {+ const h = Biquad.make(sr, "hp", 22, 0.707), l1 = Biquad.make(sr, "lp", top, 0.5412), l2 = Biquad.make(sr, "lp", top, 1.3066);+ for (let i = 0; i < c.length; i++) { const v = l2.tick(l1.tick(h.tick(c[i]))); c[i] = Number.isFinite(v) ? v : 0; }+ }+ let peak = 0; for (let i = 0; i < b.n; i++) peak = Math.max(peak, Math.abs(b.L[i]), Math.abs(b.R[i]));+ let end = b.n; const floor = peak * 1e-4;+ while (end > keep + 1 && Math.abs(b.L[end - 1]) < floor && Math.abs(b.R[end - 1]) < floor) end--;+ const rang = end === b.n;+ end = Math.min(b.n, end + secs(sr, 0.004));+ const L = new Float32Array(end), R = new Float32Array(end), fade = Math.min(end, rang ? Math.min(secs(sr, 0.4), Math.round(end * 0.2)) : secs(sr, 0.004));+ for (let i = 0; i < end; i++) { const g = i >= end - fade ? 0.5 - 0.5 * Math.cos((Math.PI * (end - 1 - i)) / fade) : 1; L[i] = b.L[i] * g; R[i] = b.R[i] * g; }+ return [L, R];+};++// ---- measurement: K-weighted (BS.1770) power, the same yardstick for levels and audibility+const kWeight = (x, sr) => {+ const out = new Float64Array(x.length);+ { const G = 3.999843853973347, Q = 0.7071752369554196, fc = 1681.974450955533, K = Math.tan((Math.PI * fc) / sr), Vh = Math.pow(10, G / 20), Vb = Math.pow(Vh, 0.4996667741545416);+ const a0 = 1 + K / Q + K * K, b0 = (Vh + (Vb * K) / Q + K * K) / a0, b1 = (2 * (K * K - Vh)) / a0, b2 = (Vh - (Vb * K) / Q + K * K) / a0, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < x.length; i++) { const y = b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = x[i]; y2 = y1; y1 = y; out[i] = y; } }+ { const fc = 38.13547087602444, Q = 0.5003270373238773, K = Math.tan((Math.PI * fc) / sr), a0 = 1 + K / Q + K * K, a1 = (2 * (K * K - 1)) / a0, a2 = (1 - K / Q + K * K) / a0;+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0; for (let i = 0; i < out.length; i++) { const xi = out[i], y = xi - 2 * x1 + x2 - a1 * y1 - a2 * y2; x2 = x1; x1 = xi; y2 = y1; y1 = y; out[i] = y; } }+ return out;+};+/** Loudness (LUFS-scaled, ungated) of K-weighted channels over samples [a, b). */+const winLufs = (kL, kR, a, b) => {+ let s = 0; const lo = Math.max(0, a), hi = Math.min(kL.length, b), len = Math.max(1, hi - lo);+ for (let i = lo; i < hi; i++) s += kL[i] * kL[i] + kR[i] * kR[i];+ return -0.691 + 10 * Math.log10(Math.max(s / len, 1e-20));+};+/** The window where a sound actually speaks: 10 ms frames within 10 dB of its loudest, 15-500 ms. */+const speakingWindow = (kL, kR, sr) => {+ const hop = Math.max(1, secs(sr, 0.01)), nf = Math.ceil(kL.length / hop), e = new Float64Array(nf);+ for (let f = 0; f < nf; f++) { let s = 0; for (let i = f * hop; i < Math.min(kL.length, (f + 1) * hop); i++) s += kL[i] * kL[i] + kR[i] * kR[i]; e[f] = s; }+ let mx = 0, at = 0; for (let f = 0; f < nf; f++) if (e[f] > mx) { mx = e[f]; at = f; }+ let a = at, b = at; const th = mx * 0.1;+ while (a > 0 && e[a - 1] >= th) a--;+ while (b < nf - 1 && e[b + 1] >= th) b++;+ let s0 = a * hop, s1 = Math.min(kL.length, (b + 1) * hop);+ const min = secs(sr, 0.015), max = secs(sr, 0.5);+ if (s1 - s0 > max) { const c = at * hop + hop / 2; s0 = Math.max(s0, Math.round(c - max / 2)); s1 = Math.min(s1, s0 + max); }+ if (s1 - s0 < min) s1 = Math.min(kL.length, s0 + min);+ return [s0, s1];+};+/** Integrated LUFS (BS.1770-4 gating), for the mix report. */+const integratedLufs = (L, R, sr) => {+ const kL = kWeight(L, sr), kR = kWeight(R, sr), n = L.length, bl = Math.round(0.4 * sr), hop = Math.round(0.1 * sr);+ const lufs = (z) => -0.691 + 10 * Math.log10(Math.max(z, 1e-20)), blocks = [];+ for (let a = 0; a + bl <= n; a += hop) { let s = 0; for (let i = a; i < a + bl; i++) s += kL[i] * kL[i] + kR[i] * kR[i]; blocks.push(s / bl); }+ const abs = blocks.filter((z) => lufs(z) > -70), rel = lufs(abs.reduce((a, b) => a + b, 0) / Math.max(1, abs.length)) - 10;+ const gated = abs.filter((z) => lufs(z) > rel);+ return lufs(gated.reduce((a, b) => a + b, 0) / Math.max(1, gated.length));+};+/** True peak, 4x oversampled (windowed-sinc polyphase), dBTP. */+const truePeak = (chans) => {+ const O = 4, T = 16, h = [];+ for (let ph = 0; ph < O; ph++) { const row = []; for (let t = 0; t < T; t++) { const x = t - T / 2 + 1 - ph / O, w = 0.5 + 0.5 * Math.cos((Math.PI * x) / (T / 2)); row.push(x === 0 ? 1 : (Math.sin(Math.PI * x) / (Math.PI * x)) * w); } h.push(row); }+ let peak = 0;+ for (const c of chans) for (let i = 0; i < c.length; i++) {+ const a = Math.abs(c[i]);+ if (a < peak * 0.5) continue;+ for (let ph = 1; ph < O; ph++) { let s = 0; for (let t = 0; t < T; t++) { const j = i + t - T / 2 + 1; if (j >= 0 && j < c.length) s += c[j] * h[ph][t]; } const v = Math.abs(s); if (v > peak) peak = v; }+ if (a > peak) peak = a;+ }+ return dB(peak);+};++// ---------------------------------------------------------------- the kit: 10 kinds, each layered (transient + body + tail)+const PC = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };+const parseKey = (key) => {+ const m = /^([A-G])(#|b)?(m|min|minor)?$/.exec(String(key).trim());+ if (!m) throw new Error(`sfx: bad key "${key}" (use e.g. "C", "Eb", "F#m")`);+ return { pc: (PC[m[1]] + (m[2] === "b" ? -1 : m[2] === "#" ? 1 : 0) + 12) % 12, minor: !!m[3] };+};+const keyHz = (c, octave, semis = 0) => 440 * Math.pow(2, (c.key.pc + semis + 12 * (octave + 1) - 69) / 12);+const PENTA = { major: [0, 2, 4, 7, 9], minor: [0, 3, 5, 7, 10] };+/** Glockenspiel-bar partials: a bright tuned strike that sits above a mix. */+const glock = (f, tau, a, t0 = 0) => [+ { f, tau, a, t0 }, { f: f * 2.756, tau: tau * 0.42, a: a * 0.32, t0 }, { f: f * 5.404, tau: tau * 0.18, a: a * 0.14, t0 }, { f: f * 8.933, tau: tau * 0.09, a: a * 0.06, t0 },+];++const tick = {+ variants: ["key", "soft", "ui", "space"], level: -20.5, duckDb: 0,+ use: "typing (one per character: key), a laptop key (soft), an interface tick (ui), the space bar (space)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 0.22), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.5;+ if (v === "ui") {+ const f = c.j(4300, 0.05) * P;+ b.add(modal(sr, n, [{ f, tau: 0.0017, a: 1 }, { f: f * 2.03, tau: 0.0009, a: 0.3 }, { f: f * 0.51, tau: 0.004, a: 0.25 }]), 0, 0.8, p0);+ b.add(burst(sr, r, 0.002, 0.00028, { hp: 5500 }), 0, 0.45, p0);+ space(b, r, { rt60: 0.18, mix: 0.05, hp: 1500 });+ return { bus: b, hit: 0 };+ }+ const soft = v === "soft", spc = v === "space";+ const f1 = c.j(soft ? 1550 : spc ? 1900 : 3150, 0.07) * P;+ // 1 the key's plastic click (three stiff modes), 2 the contact transient, 3 bottom-out into the plate+ b.add(burst(sr, r, 0.0016, 0.00035, { hp: soft ? 1200 : 2800 }), 0, soft ? 0.3 : 0.55, p0);+ b.add(modal(sr, n, [{ f: f1, tau: soft ? 0.0024 : 0.0031, a: 1 }, { f: f1 * c.j(1.63, 0.03), tau: 0.002, a: 0.5 }, { f: f1 * c.j(2.41, 0.03), tau: 0.0014, a: 0.3 }]), 0, soft ? 0.45 : 0.65, p0, 0.12);+ b.add(modal(sr, n, [{ f: c.j(spc ? 145 : soft ? 205 : 265, 0.1) * P, tau: spc ? 0.02 : 0.009, a: 1, t0: c.j(0.0028, 0.3), att: 0.0004 }, { f: c.j(spc ? 520 : 780, 0.1) * P, tau: 0.004, a: 0.35, t0: 0.003 }]), 0, spc ? 0.9 : 0.55, p0);+ if (spc) b.add(modal(sr, n, [{ f: c.j(2500, 0.1) * P, tau: 0.004, a: 1 }, { f: c.j(4100, 0.1) * P, tau: 0.002, a: 0.5 }]), secs(sr, c.j(0.0065, 0.25)), 0.28, p0 + 0.15); // stabiliser wire+ if (!soft) { // the upstroke, a quieter higher click as the key returns+ const up = secs(sr, c.j(spc ? 0.12 : 0.085, 0.25));+ b.add(modal(sr, n, [{ f: f1 * 1.18, tau: 0.0017, a: 1 }, { f: f1 * 1.9, tau: 0.001, a: 0.4 }]), up, 0.17, p0);+ b.add(burst(sr, r, 0.001, 0.00025, { hp: 4000 }), up, 0.1, p0);+ }+ if (soft) for (const ch of [b.L, b.R]) filt(ch, sr, { lp: 6000 });+ space(b, r, { rt60: 0.22, mix: 0.06, hp: 600 });+ return { bus: b, hit: 0 };+ },+};++const press = {+ variants: ["thock", "soft", "confirm"], level: -13, duckDb: 2,+ use: "a button press, the Generate thock (thock), a gentle toggle (soft), a press that succeeds, tuned to the key (confirm)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, v === "confirm" ? 2.8 : 1.2), b = new Bus(sr, n), soft = v === "soft";+ // body: a pitch-dropping sine, the "th" of thock+ const lo = c.j(soft ? 70 : 84, 0.05) * P, drop = c.j(soft ? 105 : 150, 0.1) * P, tau = c.j(soft ? 0.065 : 0.052, 0.1);+ const body = chirp(sr, secs(sr, 0.5), (t) => lo + drop * Math.exp(-t / 0.017), ad(0.0006, tau));+ b.add(body.map((x) => Math.tanh(x * 1.5) / Math.tanh(1.5)), 0, 1, 0);+ b.add(burst(sr, r, 0.004, soft ? 0.001 : 0.0006, { lp: soft ? 2500 : 7000, hp: 500 }), 0, soft ? 0.3 : 0.5, 0);+ if (!soft) {+ // the plastic cap: three modes, a hair to the side+ b.add(modal(sr, n, [{ f: c.j(1060, 0.05) * P, tau: 0.007, a: 1 }, { f: c.j(1790, 0.05) * P, tau: 0.005, a: 0.6 }, { f: c.j(2870, 0.05) * P, tau: 0.0035, a: 0.4 }]), 0, 0.42, 0.08, 0.3);+ const up = secs(sr, c.j(0.14, 0.2)); // release: the button coming back up+ b.add(modal(sr, n, [{ f: c.j(1420, 0.05) * P, tau: 0.003, a: 1 }, { f: c.j(2330, 0.05) * P, tau: 0.002, a: 0.5 }]), up, 0.13, 0.05);+ b.add(chirp(sr, secs(sr, 0.1), () => lo * 1.6, ad(0.0005, 0.012)), up, 0.12, 0);+ }+ if (v === "confirm") { // a glassy tuned answer 12 ms after the press+ const f = keyHz(c, 6);+ b.add(modal(sr, n, glock(f, 0.35, 1, 0.012)), 0, 0.18, -0.25);+ b.add(modal(sr, n, glock(f * 1.5, 0.28, 1, 0.07)), 0, 0.12, 0.3);+ }+ space(b, r, { rt60: v === "confirm" ? 0.9 : 0.4, mix: v === "confirm" ? 0.16 : 0.1, hp: 220 });+ return { bus: b, hit: 0 };+ },+};++const pop = {+ variants: ["pop", "cork", "tiny"], level: -16, duckDb: 1,+ use: "something appears (pop), a cap coming off / a card landing (cork), a small dot or badge appearing (tiny)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 0.5), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.3;+ const [f0, rise, tau, nz] = v === "cork" ? [260, 0.9, 0.032, 0.7] : v === "tiny" ? [920, 1.1, 0.012, 0.3] : [420, 1.6, 0.022, 0.45];+ const f = c.j(f0, 0.1) * P, tt = c.j(tau, 0.15);+ b.add(chirp(sr, n, (t) => f * (1 + rise * (1 - Math.exp(-t / 0.005))), ad(0.0004, tt)), 0, 1, p0);+ b.add(burst(sr, r, 0.005, v === "cork" ? 0.0014 : 0.0008, { bp: v === "tiny" ? 3200 : v === "cork" ? 900 : 1400, q: 1.4 }), 0, nz * 2.2, p0);+ if (v !== "tiny") b.add(modal(sr, n, [{ f: c.j(v === "cork" ? 110 : 140, 0.1) * P, tau: 0.01, a: 1, att: 0.0005 }]), 0, 0.3, 0);+ if (v === "cork") b.add(shape(filt(pink(r, secs(sr, 0.12)), sr, { hp: 1800 }), sr, ad(0.004, 0.025)), secs(sr, 0.004), 0.25, p0); // the rush of air+ space(b, r, { rt60: 0.35, mix: 0.1 });+ return { bus: b, hit: 0 };+ },+};++const dropAt = (c, b, at, f0, tau, g, p) => {+ const { sr, r } = c;+ b.add(burst(sr, r, 0.001, 0.00025, { hp: 2500 }), at, 0.35 * g, p); // the surface tick+ // the plink: a bubble of air trapped by the drop rings with a RISING pitch (van den Doel)+ b.add(modal(sr, b.n, [{ f: f0, tau, a: 1, t0: 0.0015, att: 0.0012, rise: 0.4 / tau }, { f: f0 * 2.01, tau: tau * 0.3, a: 0.08, t0: 0.0015, att: 0.0012, rise: 0.4 / tau }]), at, g, p);+};+const ink = {+ variants: ["plip", "double", "bloom"], level: -15, duckDb: 2,+ use: "an ink drop landing (plip), a drop and its smaller echo (double), the drop that opens an ink bloom (bloom)",+ make(c, v) {+ const { sr, r, P } = c, n = secs(sr, 3), b = new Bus(sr, n), p0 = (r() - 0.5) * 0.3, f0 = c.j(1150, 0.12) * P, tau = c.j(0.04, 0.15);+ dropAt(c, b, 0, f0, tau, 1, p0);+ if (v === "double") dropAt(c, b, secs(sr, c.j(0.085, 0.2)), f0 * c.j(1.35, 0.06), tau * 0.7, 0.42, p0 + 0.25);+ if (v === "bloom") { // the ink spreads: a soft wet swell and a low round note under it+ const sw = shape(filt(pink(r, secs(sr, 1.5)), sr, { lp: 750, hp: 120 }), sr, ad(0.09, 0.45));+ const sw2 = shape(filt(pink(r, secs(sr, 1.5)), sr, { lp: 750, hp: 120 }), sr, ad(0.11, 0.45));+ b.add2(sw, sw2, secs(sr, 0.02), 0.5);+ b.add(chirp(sr, secs(sr, 2.2), (t) => c.j(98, 0.04) * P * (1 - 0.06 * smooth(t / 0.6)), ad(0.05, 0.34)), secs(sr, 0.01), 0.22, 0);+ }+ space(b, r, { rt60: v === "bloom" ? 1.1 : 0.6, mix: v === "bloom" ? 0.22 : 0.14, hp: 300 });+ return { bus: b, hit: 0 };+ },+};++const paper = {+ variants: ["slide", "flip", "rustle"], level: -18, duckDb: 1.5,+ use: "a sheet sliding in and landing (slide, hit = the landing), a page turn (flip, hit = the snap), handling paper (rustle)",+ make(c, v) {+ const { sr, r, P } = c;+ if (v === "flip") {+ const len = c.o.lengthS ?? c.j(0.32, 0.1), N = secs(sr, len), b = new Bus(sr, N + secs(sr, 0.6));+ let ph = 0; const am = buf(N); for (let i = 0; i < N; i++) { const u = i / N; ph += (2 * Math.PI * (55 - 30 * u)) / sr; am[i] = 1 - 0.55 * (0.5 + 0.5 * Math.sin(ph)); }+ const env = (t) => { const u = t / len; return smooth(u / 0.55) * (u < 0.55 ? 1 : 1 - smooth((u - 0.55) / 0.45) * 0.85); };+ for (const [side, amt] of [[0, 1], [1, 1]]) {+ const s = white(r, N); sweep(s, sr, (t) => (1500 + 2700 * Math.sin(Math.PI * Math.min(1, t / len))) * P, 0.9, "bp");+ for (let i = 0; i < N; i++) s[i] *= am[i] * env(i / sr);+ b.add(s, 0, 1.1 * amt, side ? 0.2 * c.dir : -0.2 * c.dir);+ }+ const snap = N - secs(sr, 0.01);+ b.add(burst(sr, r, 0.006, 0.0009, { hp: 1500 }), snap, 0.55, 0.25 * c.dir);+ b.add(modal(sr, b.n, [{ f: c.j(880, 0.1) * P, tau: 0.005, a: 1 }, { f: c.j(190, 0.1) * P, tau: 0.012, a: 0.6, att: 0.0005 }]), snap, 0.3, 0.2 * c.dir);+ space(b, r, { rt60: 0.4, mix: 0.1 });+ return { bus: b, hit: snap };+ }+ if (v === "rustle") {+ const len = c.o.lengthS ?? c.j(0.5, 0.15), N = secs(sr, len), b = new Bus(sr, N + secs(sr, 0.5)), k = 28 + Math.floor(r() * 24);+ for (let g = 0; g < k; g++) {+ const t = len * Math.pow(r(), 1.3), gl = c.j(0.008, 0.6), f = (1500 + 4500 * r()) * P;+ b.add(burst(sr, r, gl, gl * 0.35, { bp: f, q: 1.3 }), secs(sr, t), (0.4 + r()) * 1.2 * Math.sin(Math.PI * Math.min(1, t / len + 0.05)), (r() - 0.5) * 0.8);+ }+ const bed = shape(filt(pink(r, N), sr, { lp: 3200, hp: 500 }), sr, (t) => Math.sin(Math.PI * Math.min(1, t / len)));+ b.add(bed, 0, 0.35, 0);+ space(b, r, { rt60: 0.35, mix: 0.08 });+ return { bus: b, hit: 0 };+ }+ // slide: the sheet travels, speeding then braking, then lands+ const len = c.o.lengthS ?? c.j(0.45, 0.12), N = secs(sr, len), land = secs(sr, len * 0.86), b = new Bus(sr, N + secs(sr, 0.6));+ const sp = (t) => { const u = t / (len * 0.86); return u < 1 ? smooth(u / 0.3) * (1 - 0.4 * u) : 0.15 * Math.exp(-(t - len * 0.86) / 0.02); };+ const pan = (i) => c.dir * (-0.3 + 0.55 * Math.min(1, i / land));+ for (const side of [0, 1]) {+ const s = pink(r, N); sweep(s, sr, (t) => (1000 + 1700 * sp(t)) * P, 0.8, "bp"); for (let i = 0; i < N; i++) s[i] *= sp(i / sr);+ b.add(s, 0, 1.3, (i) => pan(i) + (side ? 0.15 : -0.15));+ }+ const fib = buf(N); for (let i = 0; i < N; i++) if (r() < (180 * sp(i / sr)) / sr) fib[i] = (r() - 0.5) * 2;+ b.add(filt(fib, sr, { hp: 3000 }), 0, 0.35, pan);+ b.add(modal(sr, b.n, [{ f: c.j(150, 0.1) * P, tau: 0.02, a: 1, att: 0.0008 }, { f: c.j(620, 0.1) * P, tau: 0.006, a: 0.3 }]), land, 0.45, pan(land));+ b.add(burst(sr, r, 0.008, 0.0015, { lp: 3000, pink: true }), land, 0.5, pan(land));+ space(b, r, { rt60: 0.4, mix: 0.1 });+ return { bus: b, hit: land };+ },+};++/**+ * A pass-by: the source moves along a line past the listener. Distance sets level and air+ * absorption, the radial velocity sets the doppler glide (high approaching, low leaving) and the+ * angle sets the pan. hit = the closest point.+ */+const passBy = (c, b, len, o) => {+ const { sr, r, P } = c, N = secs(sr, len), tc = len * 0.56, w = len * 0.2;+ const geo = (t) => { const x = (t - tc) / w, d = Math.sqrt(1 + x * x); return { x, d, D: 1 / (1 + o.dop * (x / d)) }; };+ const edge = (t) => Math.min(1, t / 0.03, (len - t) / 0.03);+ const amp = (t) => { const { d } = geo(t); return Math.pow(d, -1.7) * Math.max(0, edge(t)); };+ const panAt = (i) => { const { x, d } = geo(i / sr); return clamp(c.dir * o.spread * (x / d), -1, 1); };+ const air = [pink(r, N), pink(r, N)];+ for (const s of air) { sweep(s, sr, (t) => { const g = geo(t); return o.air * P * g.D * (0.55 + 0.45 / g.d); }, 0.7, "bp"); for (let i = 0; i < N; i++) s[i] *= amp(i / sr); }+ // mostly panned (the source moves), partly decorrelated (the air around it)+ const mono = air[0].map((x, i) => x * 0.75 + air[1][i] * 0.25);+ b.add(mono, 0, 3.2, panAt);+ b.add2(air[1], air[0], 0, 0.9);+ if (o.toneAmt > 0) { const t = white(r, N); sweep(t, sr, (tt) => o.tone * P * geo(tt).D, o.toneQ, "bp"); for (let i = 0; i < N; i++) t[i] *= amp(i / sr); b.add(t, 0, o.toneAmt, panAt); }+ if (o.bodyAmt > 0) { const s = pink(r, N); sweep(s, sr, (t) => o.body * geo(t).D, 0.8, "lp"); for (let i = 0; i < N; i++) s[i] *= amp(i / sr); b.add(s, 0, o.bodyAmt, (i) => panAt(i) * 0.4); }+ return secs(sr, tc);+};+const whoosh = {+ variants: ["soft", "air", "fast", "deep"], level: -16, duckDb: 2,+ use: "something travels past camera: a gentle transition (soft, the default), a card flying (air), a quick flick (fast), a big heavy move (deep). hit = the pass-by",+ make(c, v) {+ const cfg = { soft: { len: 0.9, air: 620, tone: 1050, toneQ: 5, body: 180, toneAmt: 0.35, bodyAmt: 0.25, dop: 0.14, spread: 0.6 },+ air: { len: 0.7, air: 950, tone: 1750, toneQ: 7, body: 220, toneAmt: 0.5, bodyAmt: 0.3, dop: 0.22, spread: 0.8 },+ fast: { len: 0.38, air: 1400, tone: 2600, toneQ: 8, body: 260, toneAmt: 0.55, bodyAmt: 0.15, dop: 0.32, spread: 0.85 },+ deep: { len: 1.05, air: 460, tone: 780, toneQ: 5, body: 150, toneAmt: 0.3, bodyAmt: 0.9, dop: 0.2, spread: 0.7 } }[v];+ const len = c.o.lengthS ?? c.j(cfg.len, 0.08), b = new Bus(c.sr, secs(c.sr, len + 0.8));+ const hit = passBy(c, b, len, { ...cfg, air: c.j(cfg.air, 0.1), tone: c.j(cfg.tone, 0.1) });+ space(b, c.r, { rt60: v === "deep" ? 1.2 : 0.7, mix: 0.12, hp: 300 });+ return { bus: b, hit };+ },+};++const swish = {+ variants: ["in", "out", "soft"], level: -17, duckDb: 1,+ use: "a UI panel or card sliding (in = rising, out = falling), a subtle nudge (soft). Short, never sharp",+ make(c, v) {+ const { sr, r, P } = c, len = c.o.lengthS ?? c.j(v === "soft" ? 0.28 : 0.2, 0.1), N = secs(sr, len), b = new Bus(sr, secs(sr, len + 0.5));+ const [f1, f2] = v === "out" ? [3400, 1300] : v === "soft" ? [900, 1900] : [1300, 3400], pk = 0.35;+ const f = (t) => f1 * Math.pow(f2 / f1, smooth(t / len)) * P;+ const env = (t) => { const u = t / len; return u < pk ? 0.5 - 0.5 * Math.cos((Math.PI * u) / pk) : Math.exp(-(u - pk) * 4.5) * (1 - smooth((u - 0.85) / 0.15)); };+ const pan = (i) => c.dir * (-0.35 + (0.7 * i) / N);+ for (const side of [0, 1]) { const s = pink(r, N); sweep(s, sr, f, v === "soft" ? 0.9 : 1.3, "bp"); sweep(s, sr, f, 0.8, "bp"); shape(s, sr, env); b.add(s, 0, 1.4, (i) => pan(i) + (side ? 0.2 : -0.2)); }+ const t = white(r, N); sweep(t, sr, f, 6, "bp"); shape(t, sr, env); b.add(t, 0, v === "soft" ? 0.1 : 0.2, pan);+ space(b, r, { rt60: 0.35, mix: 0.08 });+ return { bus: b, hit: secs(sr, len * pk) };+ },+};++const riser = {+ variants: ["soft", "air", "tonal"], level: -15, duckDb: 2,+ use: "the ONE build into the big reveal: soft (the signature: air + a tuned chord), air (noise only), tonal (more chord). Tempo-synced: beats + bpm; hit = its end, on the downbeat",+ make(c, v) {+ const { sr, r } = c, len = c.o.lengthS ?? ((c.o.beats ?? 4) * 60) / c.bpm, N = secs(sr, len), b = new Bus(sr, N + secs(sr, 0.03));+ const [nz, tn] = v === "air" ? [1, 0] : v === "tonal" ? [0.45, 1] : [0.8, 0.55];+ const cut = (t) => Math.min(1, (len - t) / 0.02); // it stops ON the downbeat+ // 1 air: noise through a resonant low-pass opening 250 Hz -> 10 kHz, growing wider+ for (const side of [0, 1]) {+ const s = pink(r, N); sweep(s, sr, (t) => 250 * Math.pow(40, Math.pow(t / len, 1.4)), (t) => 1.2 + 1.6 * (t / len), "lp"); filt(s, sr, { hp: 160 });+ shape(s, sr, (t) => Math.pow(t / len, 2.2) * cut(t));+ b.add(s, 0, nz * 1.6, (i) => (side ? 1 : -1) * (0.15 + 0.6 * (i / N)));+ }+ // 2 a tuned chord (root, fifth, octave, the octave above fading in) pulsing in tempo: 8ths -> 16ths -> 32nds+ if (tn > 0) {+ const beat = c.bpm / 60, voices = [[keyHz(c, 3), -0.5, 0], [keyHz(c, 3, 7), 0.5, 0.5], [keyHz(c, 4), 0, 0.25], [keyHz(c, 5), 0, 0.75]];+ voices.forEach(([f, p, phase], vi) => {+ const s = buf(N); let ph = 0, tp = phase;+ for (let i = 0; i < N; i++) {+ const t = i / sr, u = t / len, rate = beat * (u < 0.5 ? 2 : u < 0.8 ? 4 : 8), I = 0.2 + 1.6 * u;+ tp += rate / sr; ph += (2 * Math.PI * f * c.P) / sr;+ const trem = 1 - (0.25 + 0.45 * u) * (0.5 + 0.5 * Math.cos(2 * Math.PI * tp));+ const fadeIn = vi === 3 ? smooth((u - 0.55) / 0.35) : 1;+ s[i] = Math.sin(ph + I * Math.sin(2 * ph)) * trem * Math.pow(u, 1.8) * fadeIn * cut(t);+ }+ b.add(s, 0, tn * 0.22, p);+ });+ }+ for (const ch of [b.L, b.R]) for (let i = 0; i < ch.length; i++) ch[i] = Math.tanh(ch[i] * 1.3) / 1.3;+ return { bus: b, hit: N };+ },+};++const impact = {+ variants: ["boom", "soft", "bloom"], level: -9, duckDb: 6,+ use: "the ONE big reveal (boom), a smaller landing (soft), the reveal with a tuned shimmer and a breath in before it (bloom)",+ make(c, v) {+ const { sr, r, P } = c, soft = v === "soft", pre = v === "bloom" ? secs(sr, 0.28) : 0, n = pre + secs(sr, soft ? 3.5 : 5.5), b = new Bus(sr, n);+ // 1 sub drop, saturated so small speakers still hear its harmonics+ const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.32 : 0.6, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));+ b.add(sub.map((x) => Math.tanh(x * 1.8) / Math.tanh(1.8)), pre, 1, 0);+ // 2 punch: dark noise + two chest modes, a hair wide+ b.add(burst(sr, r, 0.35, soft ? 0.05 : 0.07, { lp: soft ? 500 : 950, pink: true }), pre, soft ? 0.9 : 1.3, -0.1, 0.4);+ b.add(burst(sr, r, 0.35, soft ? 0.05 : 0.07, { lp: soft ? 500 : 950, pink: true }), pre, soft ? 0.9 : 1.3, 0.1, -0.4);+ b.add(modal(sr, n, [{ f: c.j(170, 0.06) * P, tau: 0.09, a: 1, att: 0.001 }, { f: c.j(96, 0.06) * P, tau: 0.15, a: 0.8, att: 0.001 }]), pre, soft ? 0.25 : 0.4, 0);+ if (!soft) b.add(burst(sr, r, 0.004, 0.0007, { hp: 1500 }), pre, 0.35, 0); // 3 the crack on top+ if (v === "bloom") {+ // a breath in before it: a reversed swell that stops on the hit+ for (const side of [0, 1]) { const s = pink(r, pre); sweep(s, sr, (t) => 400 * Math.pow(8, t / 0.28), 1, "lp"); shape(s, sr, (t) => Math.pow(t / 0.28, 3)); b.add(s, 0, 0.8, side ? 0.4 : -0.4); }+ // and a tuned shimmer on the key: root, 3rd, 5th, 9th in the upper octaves, spread across the field+ const third = c.key.minor ? 3 : 4;+ [[keyHz(c, 5), -0.6], [keyHz(c, 5, third), 0.6], [keyHz(c, 5, 7), -0.3], [keyHz(c, 6, 2), 0.3], [keyHz(c, 6), 0]].forEach(([f, p], k) => {+ const ms = glock(f * c.P, 1.5, 1, 0.02 + k * 0.012).map((m) => ({ ...m, att: 0.03 }));+ b.add(modal(sr, n, ms), pre, 0.09, p);+ });+ }+ space(b, r, { rt60: soft ? 1.2 : 2.4, mix: soft ? 0.2 : 0.34, hp: 120, lp: 3500, predelay: 0.02, er: 0.35 });+ return { bus: b, hit: pre };+ },+};++const chime = {+ variants: ["sparkle", "bell", "glint"], level: -17, duckDb: 1.5,+ use: "magic / success, tuned to the film's key: a rising pentatonic sparkle (sparkle), one bell (bell), a tiny glint on a highlight (glint)",+ make(c, v) {+ const { sr, r } = c, n = secs(sr, v === "bell" ? 6 : v === "glint" ? 2 : 4), b = new Bus(sr, n), scale = PENTA[c.key.minor ? "minor" : "major"];+ if (v === "bell") {+ b.add(modal(sr, n, glock(keyHz(c, 5) * c.P, 1.4, 1)), 0, 1, -0.1);+ b.add(modal(sr, n, glock(keyHz(c, 6, 7) * c.P, 0.9, 1, 0.004)), 0, 0.3, 0.3);+ b.add(burst(sr, r, 0.003, 0.0005, { hp: 5000 }), 0, 0.2, 0);+ space(b, r, { rt60: 1.6, mix: 0.25, hp: 400 });+ return { bus: b, hit: 0 };+ }+ const count = v === "glint" ? 2 : 4 + Math.floor(r() * 3), oct = v === "glint" ? 7 : 6, start = Math.floor(r() * 3);+ let t = 0;+ for (let k = 0; k < count; k++) {+ const d = start + k, f = keyHz(c, oct + Math.floor(d / 5), scale[d % 5]) * c.P, g = 0.6 + (0.4 * k) / count;+ const p = c.dir * (-0.55 + (1.1 * k) / Math.max(1, count - 1)) * (k % 2 ? 1 : 0.8);+ b.add(modal(sr, n, glock(f, v === "glint" ? 0.14 : c.j(0.5, 0.15), 1)), secs(sr, t), g, p);+ t += c.j(v === "glint" ? 0.04 : 0.055, 0.15);+ }+ if (v === "sparkle") { const s = [white(r, secs(sr, 1)), white(r, secs(sr, 1))]; for (const x of s) { filt(x, sr, { hp: 7500 }); shape(x, sr, ad(0.06, 0.3)); } b.add2(s[0], s[1], 0, 0.035); }+ space(b, r, { rt60: v === "glint" ? 0.8 : 1.8, mix: v === "glint" ? 0.15 : 0.3, hp: 400, predelay: 0.015 });+ return { bus: b, hit: 0 };+ },+};++export const SFX = { tick, press, pop, whoosh, swish, riser, impact, chime, paper, ink };+export const SFX_KINDS = Object.keys(SFX);+export const sfxInfo = (k) => ({ variants: SFX[k].variants, levelLufs: SFX[k].level, duckDb: SFX[k].duckDb, use: SFX[k].use });++const checkSeed = (seed) => { if (!Number.isSafeInteger(seed) || seed < 0 || seed > 0xffffffff) throw new Error(`sfx: seed must be an integer 0..4294967295, got ${String(seed)}`); };+const checkRange = (name, x, lo, hi) => { if (x !== undefined && (typeof x !== "number" || !Number.isFinite(x) || x < lo || x > hi)) throw new Error(`sfx: ${name} must be a number ${lo}..${hi}, got ${String(x)}`); };+export const validateSfx = (kind, o = {}) => {+ if (!(kind in SFX)) throw new Error(`sfx: unknown kind "${kind}" (kinds: ${SFX_KINDS.join(", ")})`);+ const d = SFX[kind];+ if (o.variant !== undefined && !d.variants.includes(o.variant)) throw new Error(`sfx: ${kind} has no variant "${o.variant}" (variants: ${d.variants.join(", ")})`);+ if (o.seed !== undefined) checkSeed(o.seed);+ checkRange("pitch", o.pitch, -24, 24); checkRange("lengthS", o.lengthS, 0.05, 30); checkRange("beats", o.beats, 0.25, 64); checkRange("bpm", o.bpm, 20, 300); checkRange("gainDb", o.gainDb, -60, 24);+ if (o.dir !== undefined && o.dir !== 1 && o.dir !== -1) throw new Error(`sfx: dir must be 1 or -1, got ${String(o.dir)}`);+ if (o.key !== undefined) parseKey(o.key);+};+/**+ * What a sound needs from the film: a key (tuned kinds) and a bpm (tempo-synced kinds). Never+ * defaulted: an effect tuned to a key the score isn't in, or pulsing at a tempo it isn't at, is wrong.+ */+export const sfxNeeds = (kind, variant, o = {}) => ({+ key: kind === "chime" || (kind === "riser" && variant !== "air") || (kind === "press" && variant === "confirm") || (kind === "impact" && variant === "bloom"),+ bpm: kind === "riser" && !(variant === "air" && o.lengthS !== undefined),+});+/**+ * Render one sound. Pure in (kind, opts, sr). The level is calibrated: the kind's target loudness+ * (K-weighted over its speaking window), +-1 dB per-seed variation, + opts.gainDb; peak capped at -1 dBFS.+ */+export const renderSfx = (kind, o = {}, sr = SR) => {+ validateSfx(kind, o);+ const d = SFX[kind], variant = o.variant ?? d.variants[0], seed = o.seed ?? 1, r = mkRng((seed ^ 0x5f3759df) >>> 0);+ const need = sfxNeeds(kind, variant, o);+ if (need.key && o.key === undefined) throw new Error(`sfx: ${kind}:${variant} is tuned and needs a key (opts.key or plan.key); there is no default key`);+ if (need.bpm && o.bpm === undefined) throw new Error(`sfx: ${kind}:${variant} is tempo-synced and needs a bpm (opts.bpm or plan.bpm); there is no default tempo`);+ const c = { sr, r, P: Math.pow(2, (o.pitch ?? 0) / 12), o, dir: o.dir ?? 1, key: o.key === undefined ? null : parseKey(o.key), bpm: o.bpm ?? NaN, j: (x, amt) => x * (1 + (r() * 2 - 1) * amt) };+ const made = d.make(c, variant), [L, R] = finish(made.bus, made.hit);+ const kL = kWeight(L, sr), kR = kWeight(R, sr), window = speakingWindow(kL, kR, sr), now = winLufs(kL, kR, window[0], window[1]);+ let g = d.level + (r() * 2 - 1) + (o.gainDb ?? 0) - now;+ let peak = 0; for (let i = 0; i < L.length; i++) peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));+ g = Math.min(g, -1 - dB(peak));+ const G = db(g); for (let i = 0; i < L.length; i++) { L[i] *= G; R[i] *= G; }+ return { L, R, sr, kind, variant, seed, hit: Math.min(made.hit, L.length - 1), window, lufs: now + g };+};++// ---------------------------------------------------------------- placement: cues by film frame over a music bed+const GRID = { bar: 0, beat: 1, "8th": 0.5, "16th": 0.25 };+const cueName = (c, i) => `cue #${i} (${c.kind}${c.variant ? ":" + c.variant : ""}${c.label ? ` "${c.label}"` : ""} @ frame ${c.frame})`;+const optsOf = (p, c, seed) => ({ seed: c.seed ?? seed, variant: c.variant, pitch: c.pitch, lengthS: c.lengthS, beats: c.beats, bpm: c.bpm ?? p.bpm, key: c.key ?? p.key, dir: c.dir, gainDb: c.gainDb });++export const validateSfxPlan = (p) => {+ if (!Number.isSafeInteger(p.fps) || p.fps <= 0) throw new Error(`sfx plan: fps must be a positive integer, got ${String(p.fps)}`);+ if (!Number.isSafeInteger(p.frames) || p.frames <= 0) throw new Error(`sfx plan: frames must be a positive integer, got ${String(p.frames)}`);+ if (p.seed !== undefined) checkSeed(p.seed);+ if (p.bpm !== undefined && (!Number.isFinite(p.bpm) || p.bpm < 20 || p.bpm > 300)) throw new Error(`sfx plan: bpm must be 20..300, got ${String(p.bpm)}`);+ if (!Array.isArray(p.cues)) throw new Error("sfx plan: cues must be an array");+ p.cues.forEach((c, i) => {+ if (!c || typeof c !== "object") throw new Error(`sfx plan: cue #${i} is not an object`);+ if (!(c.kind in SFX)) throw new Error(`sfx plan: cue #${i} has unknown kind "${String(c.kind)}" (kinds: ${SFX_KINDS.join(", ")})`);+ if (typeof c.frame !== "number" || !Number.isFinite(c.frame) || c.frame < 0 || c.frame >= p.frames) throw new Error(`sfx plan: ${cueName(c, i)}: frame must be 0..${p.frames - 1}`);+ if (!Number.isInteger(c.frame)) throw new Error(`sfx plan: ${cueName(c, i)}: frame must be a whole frame (cues are addressed by the frame the picture shows; for a hit between frames, snap it to the beat grid)`);+ const snap = c.snap ?? p.snap ?? "none";+ if (!(snap === "none" || snap in GRID)) throw new Error(`sfx plan: ${cueName(c, i)}: snap must be none|bar|beat|8th|16th`);+ if ((snap !== "none" || c.beats !== undefined) && p.bpm === undefined && c.bpm === undefined) throw new Error(`sfx plan: ${cueName(c, i)}: snap/beats need a bpm (plan.bpm)`);+ if (c.duckDb !== undefined && (!Number.isFinite(c.duckDb) || c.duckDb < 0 || c.duckDb > 18)) throw new Error(`sfx plan: ${cueName(c, i)}: duckDb must be 0..18`);+ try { validateSfx(c.kind, optsOf(p, c, 0)); } catch (e) { throw new Error(`sfx plan: ${cueName(c, i)}: ${e.message}`); }+ const o = optsOf(p, c, 0), need = sfxNeeds(c.kind, c.variant ?? SFX[c.kind].variants[0], o);+ if (need.key && o.key === undefined) throw new Error(`sfx plan: ${cueName(c, i)} is tuned: set plan.key or cue.key; there is no default key`);+ if (need.bpm && o.bpm === undefined) throw new Error(`sfx plan: ${cueName(c, i)} is tempo-synced: set plan.bpm or cue.bpm; there is no default tempo`);+ });+};++/** Taste rules, as warnings: one riser + one impact per film; at most 2 cues in any 100 ms. */+export const tasteWarnings = (p, placed) => {+ const warn = [];+ for (const kind of ["riser", "impact"]) {+ const of = p.cues.filter((c) => c.kind === kind);+ if (of.length > 1) warn.push(`taste: ${of.length} ${kind}s (frames ${of.map((c) => c.frame).join(", ")}); one ${kind} per film marks THE reveal, a second halves both`);+ }+ const times = placed.map((pc) => ({ t: pc.hitS, i: pc.i })).sort((a, b) => a.t - b.t);+ for (let i = 0; i + 2 < times.length; i++) if (times[i + 2].t - times[i].t <= 0.1)+ warn.push(`taste: 3+ cues within 100 ms around ${times[i].t.toFixed(2)} s (cues #${times[i].i}, #${times[i + 1].i}, #${times[i + 2].i}); at most 2 cues per 100 ms`);+ return warn;+};++/** Render and place every cue. Per-cue seed depends on (kind, frame, occurrence), never on list order. */+export const placeSfx = (p, sr = SR) => {+ validateSfxPlan(p);+ const seen = new Map(), filmS = p.frames / p.fps;+ return p.cues.map((cue, i) => {+ const k = `${cue.kind}@${cue.frame}`, occ = seen.get(k) ?? 0; seen.set(k, occ + 1);+ const seed = mixSeed(p.seed ?? 0, (strSeed(cue.kind) ^ Math.round(cue.frame * 1000) ^ (occ * 7919)) >>> 0);+ const t0 = cue.frame / p.fps, snap = cue.snap ?? p.snap ?? "none";+ let hitS = t0;+ if (snap !== "none") {+ const bpm = cue.bpm ?? p.bpm, beat = 60 / bpm, g = snap === "bar" ? beat * (p.beatsPerBar ?? 4) : beat * GRID[snap], z = p.beatZeroS ?? 0;+ hitS = z + Math.round((t0 - z) / g) * g;+ if (hitS >= filmS) hitS -= g;+ if (hitS < 0) hitS += g;+ }+ const sound = renderSfx(cue.kind, optsOf(p, cue, seed), sr), start = Math.round(hitS * sr) - sound.hit;+ if (start < 0) {+ const pre = sound.hit / sr, need = Math.ceil(pre * p.fps);+ throw new Error(`sfx plan: ${cueName(cue, i)}: its ${pre.toFixed(2)} s pre-roll starts before frame 0; move it to frame >= ${need} or shorten it (lengthS/beats)`);+ }+ return { i, cue, sound, hitS, snappedFromS: t0, start, window: [start + sound.window[0], start + sound.window[1]] };+ });+};++/** The bed's gain under the cues: raised-cosine dip (40 ms attack), held, released (280 ms; 1.2 s after an impact), capped at 9 dB. */+export const sfxDuck = (placed, n, sr, o = {}) => {+ const g = new Float32Array(n).fill(1), att = secs(sr, o.attackS ?? 0.04), maxDb = o.maxDb ?? 9;+ for (const pc of placed) {+ const depth = Math.min(maxDb, pc.cue.duckDb ?? SFX[pc.cue.kind].duckDb); if (depth <= 0) continue;+ const rel = secs(sr, pc.cue.kind === "impact" ? 1.2 : o.releaseS ?? 0.28), lo = db(-depth), [a, b] = pc.window;+ for (let i = Math.max(0, a - att); i < Math.min(n, b + rel); i++) {+ const s = i < a ? 0.5 - 0.5 * Math.cos((Math.PI * (i - (a - att))) / att) : i < b ? 1 : 0.5 + 0.5 * Math.cos((Math.PI * (i - b)) / rel);+ const v = 1 - (1 - lo) * s; if (v < g[i]) g[i] = v;+ }+ }+ return g;+};++/** Look-ahead true-peak ceiling (2 ms look-ahead, 80 ms release, 1.12 inter-sample margin). Returns deepest GR in dB. */+const ceiling = (L, R, sr, ceil) => {+ const n = L.length, la = secs(sr, 0.002), rel = Math.exp(-1 / (0.08 * sr)), need = new Float32Array(n), g = new Float32Array(n);+ for (let i = 0; i < n; i++) { const a = Math.max(Math.abs(L[i]), Math.abs(R[i])) * 1.12; need[i] = a > ceil ? ceil / a : 1; }+ for (let i = n - 1; i >= 0; i--) { let m = 1; for (let j = i; j < Math.min(n, i + la); j++) if (need[j] < m) m = need[j]; g[i] = m; }+ let cur = 1, deepest = 1;+ for (let i = 0; i < n; i++) { cur = g[i] < cur ? g[i] : 1 - (1 - cur) * rel; if (cur > g[i]) cur = g[i]; L[i] *= cur; R[i] *= cur; if (cur < deepest) deepest = cur; }+ return 20 * Math.log10(deepest);+};++/** Audibility of each cue vs the ducked bed over the cue's speaking window (the bed's window at least 100 ms). */+export const sfxAudibility = (placed, music, sr, p) => {+ const mL = kWeight(music[0], sr), mR = kWeight(music[1], sr), minWin = secs(sr, 0.1);+ return placed.map((pc) => {+ const s = pc.sound, kL = kWeight(s.L, sr), kR = kWeight(s.R, sr), [wa, wb] = s.window, cueLufs = winLufs(kL, kR, wa, wb);+ let [a, b] = pc.window; if (b - a < minWin) { const c = (a + b) >> 1; a = c - (minWin >> 1); b = a + minWin; }+ const musicLufs = winLufs(mL, mR, a, b);+ const silent = musicLufs < -70, marginDb = silent ? 99 : cueLufs - musicLufs;+ const minDb = pc.cue.minDb ?? p.minDb ?? -6;+ return { i: pc.i, kind: pc.cue.kind, variant: s.variant, label: pc.cue.label ?? "", atS: pc.hitS, cueLufs, musicLufs, marginDb, minDb, ok: marginDb >= minDb };+ });+};++/**+ * The whole film's sound: bed (padded or cut to the film) ducked under the cues, effects added,+ * one look-ahead true-peak ceiling at -1 dBTP. music = [L, R] Float32Arrays at `sr`, or null.+ */+export const mixSfx = (music, p, sr = SR) => {+ const n = Math.round((p.frames / p.fps) * sr), placed = placeSfx(p, sr);+ const warnings = tasteWarnings(p, placed);+ const fxL = new Float32Array(n), fxR = new Float32Array(n);+ for (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }+ const duck = sfxDuck(placed, n, sr, p.duck), mL = new Float32Array(n), mR = new Float32Array(n);+ if (music) { const m = Math.min(n, music[0].length); for (let i = 0; i < m; i++) { mL[i] = music[0][i] * duck[i]; mR[i] = music[1][i] * duck[i]; } }+ const L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = mL[i] + fxL[i]; R[i] = mR[i] + fxR[i]; }+ const limiterDb = ceiling(L, R, sr, db((p.ceilingDb ?? -1) - 0.3));+ const fade = Math.min(n, secs(sr, 0.015)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }+ const audibility = sfxAudibility(placed, [mL, mR], sr, p);+ return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, warnings, ok: audibility.every((a) => a.ok), lufs: integratedLufs(L, R, sr), dbtp: truePeak([L, R]) };+};++/** A cue nobody hears is a bug, not a subtle choice. */+export const assertSfxAudible = (m) => {+ const bad = m.audibility.filter((a) => !a.ok);+ if (bad.length) throw new Error(`buried cue: ${bad.length} cue(s) under the bed:\n` + bad.map((a) => ` #${a.i} ${a.kind}:${a.variant}${a.label ? ` "${a.label}"` : ""} @ ${a.atS.toFixed(2)} s is ${a.marginDb.toFixed(1)} dB vs the bed (floor ${a.minDb} dB): raise its gainDb or its duckDb`).join("\n"));+ return m;+};++// ---------------------------------------------------------------- io+/** 32-bit float stereo WAV (no clipping on the way to the encoder). */+export const writeWavFloat = (path, L, R, sr = SR) => {+ const n = L.length, data = Buffer.alloc(n * 8), h = Buffer.alloc(44);+ for (let i = 0; i < n; i++) { data.writeFloatLE(L[i], i * 8); data.writeFloatLE(R[i], i * 8 + 4); }+ h.write("RIFF", 0); h.writeUInt32LE(36 + data.length, 4); h.write("WAVEfmt ", 8); h.writeUInt32LE(16, 16); h.writeUInt16LE(3, 20); h.writeUInt16LE(2, 22);+ h.writeUInt32LE(sr, 24); h.writeUInt32LE(sr * 8, 28); h.writeUInt16LE(8, 32); h.writeUInt16LE(32, 34); h.write("data", 36); h.writeUInt32LE(data.length, 40);+ writeFileSync(path, Buffer.concat([h, data]));+};+const writeAudio = (path, L, R) => {+ if (/\.(mp3|m4a|aac|flac|ogg)$/i.test(path)) { // ffmpeg only for the final encode+ const w = path + ".tmp.wav"; writeWavFloat(w, L, R, SR);+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", w, path]); execFileSync("rm", [w]);+ } else writeWavFloat(path, L, R, SR);+};+/** Decode any audio file to 48 kHz stereo float via ffmpeg. */+export const readBed = (path) => {+ const raw = execFileSync("ffmpeg", ["-v", "error", "-i", path, "-ac", "2", "-ar", String(SR), "-f", "f32le", "-"], { maxBuffer: 1 << 30 });+ const n = Math.floor(raw.length / 8), L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = raw.readFloatLE(i * 8); R[i] = raw.readFloatLE(i * 8 + 4); }+ return [L, R];+};++// ---------------------------------------------------------------- cli+const peakOf = (L, R) => { let p = 0; for (let i = 0; i < L.length; i++) p = Math.max(p, Math.abs(L[i]), Math.abs(R[i])); return p; };+const envOpts = () => ({ key: process.env.KEY, bpm: process.env.BPM ? Number(process.env.BPM) : undefined, lengthS: process.env.LEN ? Number(process.env.LEN) : undefined });++const cmdList = () => {+ for (const k of SFX_KINDS) { const i = sfxInfo(k); console.log(`${k.padEnd(8)} [${i.variants.join(", ")}] level ${i.levelLufs} LUFS(win), duck ${i.duckDb} dB\n ${i.use}`); }+};+const cmdOne = (args) => {+ const out = args.pop(), [kind, variant, seed] = args;+ const s = renderSfx(kind, { variant, seed: seed ? Number(seed) : undefined, ...envOpts() }, SR);+ writeAudio(out, s.L, s.R);+ console.log(`${kind}:${s.variant} seed ${s.seed}: ${(s.L.length / SR).toFixed(2)} s, hit @ ${(s.hit / SR).toFixed(3)} s, ${s.lufs.toFixed(1)} LUFS(win), peak ${dB(peakOf(s.L, s.R)).toFixed(1)} dBFS`);+};+/** Every kind x variant, 3 seeds each: WAV out + metrics vs target (exit 1 if any fails). */+const cmdKit = (outdir) => {+ const dir = resolve(outdir); mkdirSync(dir, { recursive: true });+ let fail = 0; const meters = {};+ console.log("kind:variant len(s) hit(s) LUFS(win) x3 target worst-off peak dBFS ok");+ for (const kind of SFX_KINDS) {+ const info = sfxInfo(kind);+ for (const variant of info.variants) {+ const hits = [1, 2, 3].map((seed) => renderSfx(kind, { variant, seed, key: "C", bpm: 90 }, SR));+ // one listen-file per variant: the 3 varied hits back to back+ const gap = secs(SR, 0.35), lead = secs(SR, 0.15), n = lead + hits.reduce((a, h) => a + h.L.length + gap, 0);+ const L = new Float32Array(n), Rr = new Float32Array(n); let at = lead;+ for (const h of hits) { L.set(h.L, at); Rr.set(h.R, at); at += h.L.length + gap; }+ writeWavFloat(join(dir, `${kind}-${variant}.wav`), L, Rr, SR);+ const lens = hits.map((h) => h.L.length / SR), lufs = hits.map((h) => h.lufs), peak = dB(peakOf(L, Rr));+ const worstOff = Math.max(...lufs.map((l) => Math.abs(l - info.levelLufs)));+ const durOk = lens.every((l) => l >= 0.05 && l <= 12), clipOk = peak <= -0.99, lvlOk = worstOff <= 2;+ const finiteOk = hits.every((h) => { for (let i = 0; i < h.L.length; i++) if (!Number.isFinite(h.L[i]) || !Number.isFinite(h.R[i])) return false; return true; });+ const ok = durOk && clipOk && lvlOk && finiteOk; if (!ok) fail++;+ meters[`${kind}:${variant}`] = { lens, lufs, target: info.levelLufs, peak, ok };+ console.log(`${(kind + ":" + variant).padEnd(18)} ${lens.map((l) => l.toFixed(2)).join("/").padEnd(15)} ${(hits[0].hit / SR).toFixed(3).padStart(6)} ${lufs.map((l) => l.toFixed(1)).join(" / ").padEnd(20)} ${String(info.levelLufs).padStart(5)} ${worstOff.toFixed(2).padStart(8)} ${peak.toFixed(1).padStart(8)} ${ok ? "ok" : "FAIL" + (durOk ? "" : " dur") + (clipOk ? "" : " clip") + (lvlOk ? "" : " level")}`);+ }+ }+ writeFileSync(join(dir, "meters.json"), JSON.stringify(meters, null, 1));+ console.log(fail ? `\n${fail} variant(s) FAILED` : `\nall variants ok -> ${dir}`);+ process.exit(fail ? 1 : 0);+};+const cmdMix = async (planPath, bedPath, outPath) => {+ const plan = JSON.parse(await readFile(planPath, "utf8"));+ const bed = readBed(bedPath);+ if (plan.frames === undefined) plan.frames = Math.floor((bed[0].length / SR) * plan.fps);+ const m = mixSfx(bed, plan, SR);+ for (const w of m.warnings) console.error(w);+ console.log(`# kind:variant frame hit(s) cue LUFS bed LUFS margin floor ok`);+ for (const a of m.audibility) {+ const pc = m.placed[a.i];+ console.log(`${String(a.i).padEnd(3)} ${(a.kind + ":" + a.variant).padEnd(17)} ${String(pc.cue.frame).padStart(5)} ${a.atS.toFixed(3).padStart(6)} ${a.cueLufs.toFixed(1).padStart(8)} ${a.musicLufs.toFixed(1).padStart(8)} ${a.marginDb.toFixed(1).padStart(6)} ${String(a.minDb).padStart(5)} ${a.ok ? "ok" : "BURIED"}${a.label ? " " + a.label : ""}`);+ }+ assertSfxAudible(m); // throws "buried cue: ..." naming each one+ writeAudio(outPath, m.L, m.R);+ let duckMin = 1; for (let i = 0; i < m.duck.length; i++) if (m.duck[i] < duckMin) duckMin = m.duck[i];+ console.log(`\n${outPath}: ${(m.L.length / SR).toFixed(2)} s, ${plan.cues.length} cues, ${m.lufs.toFixed(1)} LUFS, ${m.dbtp.toFixed(2)} dBTP, deepest duck ${dB(duckMin).toFixed(1)} dB, all cues audible: ${m.ok}`);+};++// compare real paths: the skill is often installed as a symlink, and a plain URL compare then says "not main" and the script exits without a word+const realOf = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };+const isMain = !!process.argv[1] && realOf(fileURLToPath(import.meta.url)) === realOf(process.argv[1]);+if (isMain) {+ const [cmd, ...args] = process.argv.slice(2);+ if (cmd === "list") cmdList();+ else if (cmd === "one" && args.length >= 2) cmdOne(args);+ else if (cmd === "kit" && args[0]) cmdKit(args[0]);+ else if (cmd === "mix" && args.length === 3) await cmdMix(args[0], args[1], args[2]);+ else { console.log("usage: node sfx.mjs list | one <kind> [variant] [seed] <out.wav> | kit <outdir> | mix <plan.json> <bed> <out.wav>"); process.exit(cmd ? 1 : 0); }+}diff --git a/scripts/songmap.py b/scripts/songmap.pynew file mode 100644index 0000000..1718ed4--- /dev/null+++ b/scripts/songmap.py@@ -0,0 +1,55 @@+#!/usr/bin/env python3+# scripts/songmap.py : a map of a music track without hearing it: tempo, where the beats fall, how loud each half second is+# (all / bass / top), where it goes silent, and its last hit. Usage: python3 <skill>/scripts/songmap.py <track.wav> [bpm guess=120]+import sys, subprocess+if len(sys.argv) < 2: sys.exit('usage: python3 songmap.py <track.wav|mp3> [bpm guess=120]')+try:+ import numpy as np+ from scipy.signal import butter, sosfilt+except ImportError: sys.exit('songmap.py needs numpy and scipy: python3 -m pip install numpy scipy')+src = sys.argv[1]; guess = float(sys.argv[2]) if len(sys.argv) > 2 else 120.0+SR = 22050+x = np.frombuffer(subprocess.run(['ffmpeg', '-v', 'error', '-i', src, '-ac', '1', '-ar', str(SR), '-f', 'f32le', '-'], capture_output=True, check=True).stdout, dtype=np.float32).astype(np.float64)+dur = len(x) / SR+if dur < 5: sys.exit(f'{src}: {dur:.1f} s is too short to map (it needs at least 5 s of music)')+# onset strength: positive spectral flux at a 10 ms hop+hop, win = 220, 1024; nfr = (len(x) - win) // hop+S = np.abs(np.fft.rfft(np.stack([x[i * hop:i * hop + win] for i in range(nfr)]) * np.hanning(win), axis=1))+flux = np.maximum(0, np.diff(np.log1p(20 * S), axis=0)).sum(axis=1); flux = np.concatenate([[0], flux]); fps = SR / hop+o = flux - np.convolve(flux, np.ones(41) / 41, mode='same'); o = np.maximum(o, 0)+# tempo: the beat period whose comb picks up the most onset energy, searched finely around the guess+best = None+for bpm in np.arange(guess - 12, guess + 12.001, 0.05):+ per = 60 / bpm * fps; ph_best = None+ for ph in np.linspace(0, per, 40, endpoint=False):+ idx = np.round(ph + per * np.arange(int((len(o) - ph) / per))).astype(int); idx = idx[idx < len(o)]+ s = (o[idx] + 0.5 * o[np.minimum(idx + 1, len(o) - 1)] + 0.5 * o[np.maximum(idx - 1, 0)]).sum() / len(idx)+ if ph_best is None or s > ph_best[0]: ph_best = (s, ph)+ if best is None or ph_best[0] > best[0]: best = (ph_best[0], bpm, ph_best[1] / fps)+_, bpm, phase = best+print(f'{src}: {dur:.2f} s tempo {bpm:.2f} bpm first beat at {phase:.3f} s (beats every {60/bpm:.4f} s)')+# loudness per half second: all, bass (<150 Hz), top (>6 kHz), in dB relative to the track's loudest half second+def band(lo, hi):+ sos = butter(4, [lo, hi], btype='band', fs=SR, output='sos') if lo and hi else butter(4, hi or lo, btype='low' if hi and not lo else 'high', fs=SR, output='sos')+ return sosfilt(sos, x)+def rms(y, t0, t1): a = y[int(t0 * SR):int(t1 * SR)]; return np.sqrt((a * a).mean() + 1e-12)+lowx, topx = band(None, 150), band(6000, None)+step = 0.5; rows = []+for i in range(int(dur / step)):+ rows.append((rms(x, i * step, (i + 1) * step), rms(lowx, i * step, (i + 1) * step), rms(topx, i * step, (i + 1) * step)))+rows = np.array(rows); ref = rows[:, 0].max()+def bar(v, r): d = 20 * np.log10(v / r + 1e-9); return ' ' if d < -40 else '.' if d < -24 else ':' if d < -15 else '+' if d < -8 else '#'+for name, c, r in (('all ', 0, ref), ('bass', 1, rows[:, 1].max()), ('top ', 2, rows[:, 2].max())):+ print(name, ''.join(bar(v, r) for v in rows[:, c]))+print(' ' + ''.join(str((i // 20) % 10) if i % 20 == 0 else ('|' if i % 4 == 0 else ' ') for i in range(len(rows))), ' (one character = 0.5 s, | every 2 s, digit every 10 s)')+# silences (all below -40 dB for 0.25 s or more) and the last hit+fr = 0.05; e = np.array([rms(x, i * fr, (i + 1) * fr) for i in range(int(dur / fr))]); q = 20 * np.log10(e / ref + 1e-9) < -40+gaps, s = [], None+for i, v in enumerate(list(q) + [False]):+ if v and s is None: s = i+ if not v and s is not None:+ if (i - s) * fr >= 0.25: gaps.append((round(s * fr, 2), round(i * fr, 2)))+ s = None+print('silences:', gaps)+strong = np.where(o > 0.45 * o.max())[0]+print('last strong hit at %.2f s; strongest hits at' % (strong[-1] / fps), [round(i / fps, 2) for i in np.argsort(o)[-8:][::-1]])diff --git a/scripts/springs.js b/scripts/springs.jsnew file mode 100644index 0000000..5cf3ccb--- /dev/null+++ b/scripts/springs.js@@ -0,0 +1,60 @@+// Closed-form damped springs for film.html. Deterministic: the value at any t is computed directly,+// with no frame history, so frames still render in any order (the gate's determinism check holds).+// Idea credit: Raphael Aubry's claude-motion-design (MIT); this implementation is our own.+//+// <script src="springs.js"></script> (new-canvas-project.sh copies it in)+// Spring.unit(t, 'snappy') 0 -> 1 step response, t in seconds since the move began (0 before)+// Spring.to(t, [[0, 0], [1.2, 400], [3, 150]], 'camera')+// a value that starts at 0, springs to 400 from t=1.2, then to 150 from t=3.+// Multi-target = a SUM of one spring per target change, so a retarget mid-flight keeps its momentum+// and nothing ever snaps.+// Spring.to2(t, [[0, [x, y]], [1, [x2, y2]]], 'ui') same for points ([x, y] or any-length arrays)+// Spring.presets / Spring.make(stiffness, damping) custom: { k, c } with mass 1+//+// Presets (stiffness/damping, mass 1): snappy UI 320/30 (a hair of overshoot) camera/containers 170/26 (settles clean)+// heavy type/logos 120/24 (no overshoot, weight) playful mascots 180/12 (bounces)+(function (root) {+ const presets = {+ snappy: { k: 320, c: 30 }, ui: { k: 320, c: 30 },+ camera: { k: 170, c: 26 }, container: { k: 170, c: 26 },+ heavy: { k: 120, c: 24 }, type: { k: 120, c: 24 }, logo: { k: 120, c: 24 },+ playful: { k: 180, c: 12 }, mascot: { k: 180, c: 12 },+ };+ const pick = (p) => (typeof p === 'string' ? presets[p] : p) || presets.snappy;++ // step response of x'' + c x' + k x = k (x(0)=0, x'(0)=0): underdamped, critical and overdamped in closed form+ function unit(t, p) {+ if (!(t > 0)) return 0;+ const { k, c } = pick(p), w0 = Math.sqrt(k), z = c / (2 * w0);+ if (Math.abs(z - 1) < 1e-4) return 1 - Math.exp(-w0 * t) * (1 + w0 * t);+ if (z < 1) {+ const wd = w0 * Math.sqrt(1 - z * z);+ return 1 - Math.exp(-z * w0 * t) * (Math.cos(wd * t) + (z * w0 / wd) * Math.sin(wd * t));+ }+ const s = Math.sqrt(z * z - 1), r1 = -w0 * (z - s), r2 = -w0 * (z + s);+ return 1 - (r2 * Math.exp(r1 * t) - r1 * Math.exp(r2 * t)) / (r2 - r1);+ }++ // time until the spring stays within eps of its target (for planning holds; scans analytically sampled t)+ function settle(p, eps = 0.005) {+ let last = 0;+ for (let t = 0; t < 10; t += 1 / 240) if (Math.abs(1 - unit(t, p)) > eps) last = t;+ return last;+ }++ // keys: [[t0, v0], [t1, v1], ...] sorted by time. Before t0 the value is v0.+ function to(t, keys, p) {+ let v = keys[0][1];+ for (let i = 1; i < keys.length; i++) {+ if (t <= keys[i][0]) break;+ v += (keys[i][1] - keys[i - 1][1]) * unit(t - keys[i][0], p);+ }+ return v;+ }+ function to2(t, keys, p) {+ return keys[0][1].map((_, j) => to(t, keys.map(([kt, kv]) => [kt, kv[j]]), p));+ }++ const Spring = { unit, to, to2, settle, presets, make: (k, c) => ({ k, c }) };+ if (typeof module === 'object' && module.exports) module.exports = Spring; else root.Spring = Spring;+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/scripts/storyboard-sheet.sh b/scripts/storyboard-sheet.shnew file mode 100755index 0000000..1b8fcf3--- /dev/null+++ b/scripts/storyboard-sheet.sh@@ -0,0 +1,9 @@+#!/bin/bash+# The storyboard, drawn: tile one rough frame per shot into a single sheet the person can read at a glance.+# storyboard-sheet.sh <folder of frames, named in shot order> <out.png> [columns=4]+# Frames are pencil sketches from an image model (pictures route) or blockout frames rendered from the page (code route).+set -u+dir=${1:?folder of frames}; out=${2:?out.png}; cols=${3:-4}; T=$(mktemp -d); i=0+for f in $(ls "$dir" | grep -i -E '\.(png|jpg|jpeg|webp)$' | sort); do ffmpeg -v error -y -i "$dir/$f" -vf "scale=480:270:force_original_aspect_ratio=decrease,pad=480:270:(ow-iw)/2:(oh-ih)/2:color=0x101010" "$T/s$(printf %03d $i).png"; i=$((i + 1)); done+[ $i -eq 0 ] && { echo "no frames in $dir"; exit 1; }+ffmpeg -v error -y -i "$T/s%03d.png" -vf "tile=${cols}x$(( (i + cols - 1) / cols )):padding=6:margin=6:color=0x202020" -frames:v 1 "$out" && echo "storyboard sheet: $out ($i shots, read left to right, top to bottom)"; rm -rf "$T"diff --git a/scripts/text-audit.mjs b/scripts/text-audit.mjsnew file mode 100644index 0000000..04dc62f--- /dev/null+++ b/scripts/text-audit.mjs@@ -0,0 +1,136 @@+#!/usr/bin/env node+// scripts/text-audit.mjs : measure every word a canvas film puts on screen, instead of eyeballing it.+//+// node <skill>/scripts/text-audit.mjs [film.html] [--step 0.1] [--ignore "regex"] [--json out.json]+//+// Run it from the film's folder, on the stills gate and again before the reviewer. It loads the film in headless Chrome,+// records every fillText / strokeText the page makes while it draws each sampled frame (text, size on screen, where, how+// opaque), joins the samples into "this text was on screen from A to B", and checks what a phone viewer can actually take in:+//+// SMALL text held 0.6 s or more that is too small at phone width. FAIL under about 6.7 px on a 360 px wide phone (3.3 %+// of the height of a 16:9 frame), WARN under about 8.7 px (4.3 %). Measured on the phone, so a tall 9:16 frame is+// judged by the same eye. Captions pass easily; chips, tags, counters and menus fail.+// FLASH a caption or card (3.5 % of the height or more) that is not up long enough to read: it needs 0.4 s + 0.2 s a+// word. A payoff that lands just before a cut.+// A line typed letter by letter in one place (a prompt) counts as one piece, from its first letter.+// A film shown inside the film (a small player replaying earlier scenes) is not text to read: the page sets+// window.TEXT_AUDIT_SKIP = true while it draws that inner picture, and the audit leaves those draws out.+// EDGE text that sits partly out of the frame for 0.8 s or more (unless it is huge type, 20 % of the height or more,+// cropped on purpose). Text flying in or out does not count.+// PINNED small text parked in a corner zone for 6 s or more in total: a label, a counter, a name. A film is not a page.+// LONG one big line (5 % of the height or more) held more than 6 s: the frame may have become a slide.+// FACE text over a face, when the film exposes window.FACES = (t) => [[x, y, w, h], ...] in canvas pixels.+//+// Exit 1 when there is a FAIL. WARN lines are leads: look at each one and either fix it or say why it stays.+// Limits: it sees text drawn with fillText/strokeText only (not words inside pictures or SVGs), it does not know about clip+// regions or about something painted over the text later, and it reads size, not contrast. Text meant as texture can be+// skipped with --ignore.+import fs from 'node:fs';+import http from 'node:http';+import path from 'node:path';+import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';++const args = process.argv.slice(2);+const opt = (name, def) => { const i = args.indexOf('--' + name); if (i < 0) return def; const v = args[i + 1]; args.splice(i, 2); return v; };+const STEP = Number(opt('step', 0.1)), IGNORE = opt('ignore', null), JSON_OUT = opt('json', null);+const film = path.resolve(args[0] || 'film.html');+if (!fs.existsSync(film)) { console.error(`text-audit: no film at ${film}\nusage: node text-audit.mjs [film.html] [--step 0.1] [--ignore "regex"] [--json out.json]`); process.exit(2); }+const SELF = fileURLToPath(import.meta.url);+const loadChromium = () => {+ for (const r of [process.env.PLAYWRIGHT_NODE_MODULES, path.join(path.dirname(film), 'node_modules'), path.join(process.cwd(), 'node_modules'), path.join(path.dirname(SELF), 'node_modules')].filter(Boolean)) {+ try { return createRequire(path.join(r, 'x.cjs'))('playwright-core').chromium; } catch { /* next */ } }+ try { return createRequire(SELF)('playwright-core').chromium; } catch { /* fall through */ }+ console.error('text-audit: playwright-core not found. Run it from the film project folder (new-canvas-project.sh installs it there), or set PLAYWRIGHT_NODE_MODULES.'); process.exit(2);+};+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.mp4': 'video/mp4', '.wav': 'audio/wav', '.mp3': 'audio/mpeg' };+const serve = (root) => new Promise((res) => { const srv = http.createServer((req, rs) => {+ // only files inside the film folder: a neighbour folder whose name starts the same way is refused too+ let p = ''; try { p = path.join(root, decodeURIComponent(new URL(req.url, 'http://x').pathname)); } catch {}+ if ((p !== root && !p.startsWith(root + path.sep)) || !fs.existsSync(p) || fs.statSync(p).isDirectory()) { rs.writeHead(404); return rs.end(); }+ rs.writeHead(200, { 'content-type': TYPES[path.extname(p).toLowerCase()] || 'application/octet-stream' }); fs.createReadStream(p).pipe(rs); });+ srv.listen(0, '127.0.0.1', () => res({ srv, url: `http://127.0.0.1:${srv.address().port}` })); });++const { srv, url } = await serve(path.dirname(film));+const browser = await loadChromium().launch({ channel: 'chrome', headless: true });+const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } });+// record every text draw: what, how big on screen, where, how opaque+await page.addInitScript(() => {+ window.__TXT = [];+ for (const fn of ['fillText', 'strokeText']) {+ const orig = CanvasRenderingContext2D.prototype[fn];+ CanvasRenderingContext2D.prototype[fn] = function (text, x, y, ...rest) {+ try {+ const s = String(text); if (s.trim() && window.__TXT_ON && !window.TEXT_AUDIT_SKIP) {+ const m = this.measureText(s), tr = this.getTransform(), px = parseFloat((/(\d+(?:\.\d+)?)px/.exec(this.font) || [0, 0])[1]);+ const cs = [[x - m.actualBoundingBoxLeft, y - m.actualBoundingBoxAscent], [x + m.actualBoundingBoxRight, y - m.actualBoundingBoxAscent], [x + m.actualBoundingBoxRight, y + m.actualBoundingBoxDescent], [x - m.actualBoundingBoxLeft, y + m.actualBoundingBoxDescent]]+ .map(([a, b]) => [tr.a * a + tr.c * b + tr.e, tr.b * a + tr.d * b + tr.f]);+ const xs = cs.map((c) => c[0]), ys = cs.map((c) => c[1]);+ window.__TXT.push({ s, px: px * Math.hypot(tr.c, tr.d), a: this.globalAlpha, x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) });+ }+ } catch { /* never break the film's own drawing */ }+ return orig.call(this, text, x, y, ...rest);+ };+ }+});+const errs = []; page.on('pageerror', (e) => errs.push(e.message));+await page.goto(url + '/' + path.basename(film));+await page.waitForFunction(() => typeof window.renderFrame === 'function' && window.READY === true, null, { timeout: 120000 });+const info = await page.evaluate(() => { const c = [...document.querySelectorAll('canvas')].sort((a, b) => b.width * b.height - a.width * a.height)[0]; return { W: c.width, H: c.height, D: window.FILM_DURATION, cuts: window.CUTS || [], faces: typeof window.FACES === 'function' }; });+const { W, H, D } = info, n = Math.floor(D / STEP);+const samples = await page.evaluate(async ({ n, STEP }) => { const out = [];+ for (let i = 0; i <= n; i++) { const t = Math.min(i * STEP, window.FILM_DURATION - 1e-3); window.__TXT = []; window.__TXT_ON = true; await window.renderFrame(t); window.__TXT_ON = false;+ out.push({ t, txt: window.__TXT, faces: typeof window.FACES === 'function' ? window.FACES(t) : null }); }+ return out; }, { n, STEP });+await browser.close(); srv.close();++// join samples into intervals per text (a gap of more than two steps starts a new one)+const ign = IGNORE ? new RegExp(IGNORE, 'i') : null, runs = new Map(), done = [];+for (const smp of samples) {+ const seen = new Map();+ for (const d of smp.txt) { if (d.a < 0.5 || d.px < 1 || (ign && ign.test(d.s))) continue; if (d.x1 < 0 || d.x0 > W || d.y1 < 0 || d.y0 > H) continue;+ const k = d.s.replace(/\d+/g, '#').replace(/[.\u2026\s]+$/, ''); /* "3 of 8" and "4 of 8", "Working." and "Working..." are one piece of text */ const cur = seen.get(k); if (!cur || d.px > cur.px) seen.set(k, d); }+ for (const [k, d] of seen) { let r = runs.get(k);+ if (r && smp.t - r.t1 > STEP * 2.5) { done.push(r); r = null; }+ if (!r) { r = { s: d.s, t0: smp.t, t1: smp.t, minPx: d.px, maxPx: d.px, box: d, faceHit: false, edge: 0, corner: 0, sizes: [] }; runs.set(k, r); }+ r.t1 = smp.t; r.s = d.s; r.sizes.push(d.px); r.minPx = Math.min(r.minPx, d.px); r.maxPx = Math.max(r.maxPx, d.px); r.box = d;+ const out = Math.max(0, -d.x0) + Math.max(0, d.x1 - W) + Math.max(0, -d.y0) + Math.max(0, d.y1 - H); if (out > 0.02 * W) r.edge += STEP;+ const cx = (d.x0 + d.x1) / 2 / W, cy = (d.y0 + d.y1) / 2 / H; if ((cx < 0.2 || cx > 0.8) && (cy < 0.14 || cy > 0.86)) r.corner += STEP;+ if (smp.faces) for (const [fx, fy, fw, fh] of smp.faces) if (d.x0 < fx + fw && d.x1 > fx && d.y0 < fy + fh && d.y1 > fy) r.faceHit = true;+ }+}+done.push(...runs.values());+// typed text: a line that grows letter by letter in one place (a prompt being typed) is one piece of text, read from its first letter+done.sort((a, b) => a.t0 - b.t0);+for (let i = 0; i < done.length; i++) { const a = done[i]; if (!a) continue;+ for (let j = i + 1; j < done.length; j++) { const b = done[j]; if (!b) continue; if (b.t0 - a.t1 > STEP * 2.5) break;+ if (b.s.length > a.s.length && b.s.startsWith(a.s.trimEnd()) && Math.abs(b.box.x0 - a.box.x0) < 0.01 * W && Math.abs(b.box.y0 - a.box.y0) < 0.02 * H) {+ b.t0 = a.t0; b.sizes.push(...a.sizes); b.edge += a.edge; b.corner += a.corner; b.faceHit = b.faceHit || a.faceHit; done[i] = null; break; } } }+done.splice(0, done.length, ...done.filter(Boolean));+const words = (s) => s.trim().split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w)).length;+const pct = (px) => (px / H * 100).toFixed(1) + '% H', phone = (px) => (px * 360 / W).toFixed(1) + ' px on a phone';+const f = (t) => t.toFixed(1), q = (s) => '"' + (s.length > 48 ? s.slice(0, 45) + '...' : s) + '"';+const finds = [], add = (sev, rule, r, why) => finds.push({ sev, rule, t0: r.t0, t1: r.t1, text: r.s, why });+const pinned = new Map();+for (const r of done) { const held = r.t1 - r.t0 + STEP, w = words(r.s); if (!w) continue;+ r.sizes.sort((a, b) => a - b); r.minPx = r.sizes[Math.floor(r.sizes.length / 2)]; // its size once it has settled (the middle one), not while it flies in+ const nearEnd = r.t1 >= D - STEP * 1.5; // still up on the last frame: not a flash+ // judged by its size on a phone 360 px wide, whatever the frame's shape. The two lines are what 3.3 % and 4.3 % of the height+ // come to in a 16:9 frame (6.7 and 8.7 px), so a wide film is judged exactly as before; a tall film is no longer failed for+ // text that is 22 px on the phone (the old rule measured against a frame height of 1920)+ if (held >= 0.6) { const ph = r.minPx * 360 / W; if (ph < 6.6825) add('FAIL', 'SMALL', r, `${pct(r.minPx)}, ${phone(r.minPx)}`); else if (ph < 8.7075) add('WARN', 'SMALL', r, `${pct(r.minPx)}, ${phone(r.minPx)}`); }+ const need = 0.4 + 0.2 * w; if (held < need && !nearEnd && r.minPx / H >= 0.035) add(held < need * 0.6 ? 'FAIL' : 'WARN', 'FLASH', r, `${w} word${w > 1 ? 's' : ''} up for ${f(held)} s, needs about ${f(need)} s`);+ if (r.edge >= 0.8 && r.maxPx / H < 0.2) add('WARN', 'EDGE', r, `partly out of the frame for ${f(r.edge)} s`);+ if (r.faceHit) add('FAIL', 'FACE', r, 'sits on a face');+ if (r.maxPx / H < 0.05 && r.corner > 0) pinned.set(r.s, (pinned.get(r.s) || 0) + r.corner);+ if (held > 6 && w >= 2 && r.minPx / H >= 0.05) add('WARN', 'LONG', r, `held ${f(held)} s: the same frame for too long?`);+}+for (const [s, sec] of pinned) if (sec >= 6) finds.push({ sev: 'WARN', rule: 'PINNED', t0: 0, t1: D, text: s, why: `small text in a corner for ${f(sec)} s in all` });+finds.sort((a, b) => (a.sev === b.sev ? a.t0 - b.t0 : a.sev === 'FAIL' ? -1 : 1));+const fails = finds.filter((x) => x.sev === 'FAIL').length, warns = finds.length - fails;+console.log(`TEXT AUDIT ${path.basename(film)} ${W}x${H}, ${f(D)} s, a sample every ${STEP} s, ${done.length} pieces of text${info.faces ? '' : ' (no window.FACES: the face check did not run)'}`);+if (errs.length) console.log(' page errors while drawing: ' + errs.slice(0, 3).join(' | '));+for (const x of finds) console.log(` ${x.sev} ${x.rule.padEnd(6)} ${(f(x.t0) + '-' + f(x.t1) + ' s').padEnd(15)} ${q(x.text).padEnd(52)} ${x.why}`);+console.log(fails ? `TEXT AUDIT: FAIL ${fails} to fix, ${warns} to look at` : warns ? `TEXT AUDIT: PASS with ${warns} to look at` : 'TEXT AUDIT: PASS');+if (JSON_OUT) fs.writeFileSync(JSON_OUT, JSON.stringify({ film: path.basename(film), W, H, D, step: STEP, finds, texts: done.map((r) => ({ text: r.s, t0: r.t0, t1: r.t1, minPx: r.minPx, maxPx: r.maxPx })) }, null, 1));+process.exit(fails ? 1 : 0);diff --git a/scripts/unbundle.py b/scripts/unbundle.pynew file mode 100644index 0000000..e9369b3--- /dev/null+++ b/scripts/unbundle.py@@ -0,0 +1,13 @@+# Unpack bundle-*.bin from ~/Downloads into assets/real/<name>.png+# A name inside a bundle may only land inside assets/real: an absolute path, or one that climbs out with ../, is skipped.+import sys,struct,os,glob+out=os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),'assets','real'))+for f in (sys.argv[1:] or sorted(glob.glob(os.path.expanduser('~/Downloads/bundle-*.bin')))):+ b=open(f,'rb').read(); i=0; n=0; bad=0+ while i<len(b):+ L=struct.unpack('>I',b[i:i+4])[0]; name=b[i+4:i+4+L].decode(); i+=4+L+ D=struct.unpack('>I',b[i:i+4])[0]; d=b[i+4:i+4+D]; i+=4+D+ p=os.path.realpath(os.path.join(out,name if os.path.splitext(name)[1] else name+'.png'))+ if not p.startswith(out+os.sep): bad+=1; continue+ os.makedirs(os.path.dirname(p),exist_ok=True); open(p,'wb').write(d); n+=1+ print(os.path.basename(f),n,'frames'+(f', {bad} skipped (names that point outside assets/real)' if bad else '')); os.remove(f)diff --git a/scripts/vo.py b/scripts/vo.pynew file mode 100644index 0000000..5b8289e--- /dev/null+++ b/scripts/vo.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+# scripts/vo.py : lay a recorded narration on the film, and prove that every cut line says what the script says.+# Usage (from the film folder): python3 <skill>/scripts/vo.py vo.json (VO_FORCE=1 writes the track even when a line is cut wrong)+# vo.json: {"seconds": 45, "takes": [{"file": "audio/vo/narrator.mp3", "lines": [{"id": "hook", "text": "The line as spoken.", "at": 0.4}, ...]}]}+# one entry in "takes" per recorded file (a second voice is a second take). "lines" lists every line in the take, in the order spoken.+# line fields: id; text; at = when it starts in the film, in seconds (leave out a line that is in the take but not used);+# chain + gap = start no earlier than the end of the line before plus gap; marks = {"name": word index} for a sentence that starts inside the line.+# optional: "wav" (default audio/vo.wav), "js" (default assets/vo.js)+# How a take is cut:+# 1. it is split into islands of speech by its own silences;+# 2. whisper gives rough word times, used only to say which silence sits between two lines (the longest one there);+# 3. each line is cut silence to silence, so a cut can never land inside a word;+# 4. every cut line is transcribed ON ITS OWN and compared with its text. A line with extra or lost words stops the build.+# out: the voice track (film length, 48 kHz mono) and a small file of when each line starts, so the words on screen can follow the voice.+# needs: ffmpeg, numpy, whisper-cli with a model (VO_MODEL=<path>, default ./ggml-large-v3-turbo.bin). VO_LANG sets the language (default en).+import sys, subprocess, json, re, os, hashlib, difflib, struct, numpy as np+if len(sys.argv) < 2: sys.exit('usage (from the film folder): python3 vo.py vo.json (the format is at the top of this file)')+CFG = json.load(open(sys.argv[1])); SR = 48000; DUR = float(CFG['seconds'])+MODEL = os.path.expanduser(os.environ.get('VO_MODEL', './ggml-large-v3-turbo.bin')); LANG = os.environ.get('VO_LANG', 'en')+if not os.path.exists(MODEL): sys.exit(f'no whisper model at {MODEL}: set VO_MODEL to a ggml model file')+NUM = {'40': 'forty', '4': 'four', '1': 'one'}+def norm(w):+ w = re.sub(r"[^a-z0-9']", '', w.lower().replace('’', "'")); return NUM.get(w, w)+def words_of(s): return [w for w in (norm(x) for x in s.split()) if w]+def whisper_words(take):+ base = os.path.splitext(take)[0]; wav16 = base + '-16k.wav'; out = base + '-words.json'+ if not os.path.exists(out) or os.path.getmtime(out) < os.path.getmtime(take):+ subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', take, '-ar', '16000', '-ac', '1', wav16], check=True)+ subprocess.run(['whisper-cli', '-m', MODEL, '-f', wav16, '-l', LANG, '-ml', '1', '-sow', '-oj', '-of', base + '-words', '-np'], capture_output=True, check=True)+ ws = [(norm(s['text']), s['offsets']['from'] / 1000, s['offsets']['to'] / 1000) for s in json.load(open(out))['transcription']]+ return [w for w in ws if w[0] and not w[0].startswith('[')]+def islands(y):+ hop = int(0.005 * SR); n = len(y) // hop; edb = 20 * np.log10(np.sqrt(np.mean(y[:n * hop].reshape(n, hop) ** 2, axis=1)) + 1e-9)+ ref = float(np.percentile(edb[edb > -60], 95)); loud = edb > ref - 34; runs = []; s = None+ for i in range(n + 1):+ v = i < n and loud[i]+ if v and s is None: s = i+ if not v and s is not None: runs.append([s, i]); s = None+ merged = []+ for r in runs: # a stop consonant is not a pause: close gaps under 70 ms+ if merged and r[0] - merged[-1][1] < 14: merged[-1][1] = r[1]+ else: merged.append(r)+ return [(a * hop / SR, b * hop / SR) for a, b in merged if b - a >= 6], ref+def hear(clips): # transcribe each clip on its own; cached by its samples+ d = 'audio/vo/.check'; os.makedirs(d, exist_ok=True); cf = d + '/cache.json'; cache = json.load(open(cf)) if os.path.exists(cf) else {}; need = []+ keys = []+ for c in clips:+ m = len(c) // 3 * 3; x = np.concatenate([np.zeros(6400), c[:m].reshape(-1, 3).mean(axis=1), np.zeros(6400)]); pcm = (np.clip(x * 3, -1, 1) * 32767).astype('<i2').tobytes()+ k = hashlib.sha1(pcm).hexdigest()[:16]; keys.append(k)+ if k not in cache:+ p = f'{d}/{k}.wav'; open(p, 'wb').write(b'RIFF' + struct.pack('<I', 36 + len(pcm)) + b'WAVEfmt ' + struct.pack('<IHHIIHH', 16, 1, 1, 16000, 32000, 2, 16) + b'data' + struct.pack('<I', len(pcm)) + pcm); need.append((k, p))+ if need:+ subprocess.run(['whisper-cli', '-m', MODEL, '-l', LANG, '-np', '-nt', '-otxt', *[p for _, p in need]], capture_output=True, check=True)+ for k, p in need:+ cache[k] = open(p + '.txt').read().strip() if os.path.exists(p + '.txt') else ''+ for f in (p, p + '.txt'):+ if os.path.exists(f): os.remove(f)+ json.dump(cache, open(cf, 'w'), indent=0)+ return [cache[k] for k in keys]+def lay(take, LINES, track, VO):+ words = whisper_words(take); n = len(LINES)+ want = [(w, li) for li, ln in enumerate(LINES) for w in words_of(ln['text'])]+ j = 0; hit = {}+ for i, (w, li) in enumerate(want):+ for k in range(j, min(j + 4, len(words))):+ a = words[k][0]+ if a == w or a.startswith(w) or w.startswith(a) or (len(w) > 3 and a[:4] == w[:4]): hit[i] = k; j = k + 1; break+ miss = [want[i][0] for i in range(len(want)) if i not in hit]+ if len(miss) > max(2, len(want) * 0.15): sys.exit(f'{take} does not match its lines: {len(miss)} of {len(want)} words not found: {miss[:12]}')+ y = np.frombuffer(subprocess.run(['ffmpeg', '-v', 'error', '-i', take, '-ac', '1', '-ar', str(SR), '-f', 'f32le', '-'], capture_output=True, check=True).stdout, dtype=np.float32).astype(np.float64)+ isl, ref = islands(y); gaps = [(isl[i][1], isl[i + 1][0]) for i in range(len(isl) - 1)]; mid = lambda g: (g[0] + g[1]) / 2+ spans = []+ for li, ln in enumerate(LINES):+ idx = [hit[i] for i, (w, l) in enumerate(want) if l == li and i in hit]+ if not idx: sys.exit(f"line not found in {take}: {ln['text']}")+ spans.append(idx)+ warn = []; B = [] # between two lines: the longest silence around the last word of one and the first word of the next+ for a, b in zip(spans, spans[1:]):+ ta, tb = words[a[-1]][1], words[b[0]][2]; am, bm = (ta + words[a[-1]][2]) / 2, (words[b[0]][1] + tb) / 2; floor = (B[-1][1] if B else 0) + 0.08+ cand = [g for g in gaps if g[0] >= ta - 0.05 and g[1] <= tb + 0.05 and g[0] > floor] or [g for g in gaps if g[1] > am - 0.2 and g[0] < bm + 0.4 and g[0] > floor]+ gs = max(floor, (words[a[-1]][2] + words[b[0]][1]) / 2); B.append(max(cand, key=lambda g: g[1] - g[0]) if cand else (gs, gs))+ first = next(i for i in isl if i[1] > words[spans[0][0]][1])+ def span(i, B): return (first[0] if i == 0 else B[i - 1][1]), (isl[-1][1] if i == n - 1 else B[i][0])+ def cut(i, B):+ on, off = span(i, B); nxt = B[i][1] if i < n - 1 else off + 1; c = y[max(0, int((on - 0.03) * SR)):int(max(on + 0.1, min(off + 0.12, max(off, nxt - 0.01))) * SR)].copy()+ f1, f2 = int(0.006 * SR), int(0.06 * SR); c[:f1] *= np.linspace(0, 1, f1); c[-f2:] *= np.linspace(1, 0, f2); return c+ def sim(i, h):+ W, Hh = words_of(LINES[i]['text']), words_of(h); return 1.0 if W == Hh else 0.98 * difflib.SequenceMatcher(None, W, Hh).ratio()+ def wrong(i, h): # extra or lost words. One word spelled another way is not a wrong cut, but the first and last sounds must be there.+ W, Hh = words_of(LINES[i]['text']), words_of(h); a, b = ''.join(W), ''.join(Hh); r = lambda x, z: difflib.SequenceMatcher(None, x, z).ratio()+ if a == b or (len(W) == 1 and len(Hh) <= 1): return False+ return not (r(a, b) >= 0.85 and r(a[:5], b[:5]) >= 0.6 and r(a[-5:], b[-5:]) >= 0.6)+ heard = hear([cut(i, B) for i in range(n)]); moved = 0+ for _ in range(3): # a wrong cut is repaired by trying the silences next to it and keeping the one both lines are heard right with+ fixed = False+ for b in range(n - 1):+ guess = B[b][1] - B[b][0] < 0.03+ if not (guess or wrong(b, heard[b]) or wrong(b + 1, heard[b + 1])): continue+ lo, hi = span(b, B)[0], span(b + 1, B)[1]; cands = [g for g in gaps if g[0] > lo + 0.1 and g[1] < hi - 0.1 and abs(mid(g) - mid(B[b])) < 2.0 and g != B[b]]+ if not cands: continue+ best, pick, ph = sim(b, heard[b]) + sim(b + 1, heard[b + 1]) - (1e-3 if guess else -1e-6), None, None # a real silence beats a guess when both are heard the same+ hs = hear([c for g in cands for c in (cut(b, B[:b] + [g] + B[b + 1:]), cut(b + 1, B[:b] + [g] + B[b + 1:]))])+ for k, g in sorted(enumerate(cands), key=lambda kg: kg[1][0] - kg[1][1]): # longest silence first+ sc = sim(b, hs[2 * k]) + sim(b + 1, hs[2 * k + 1])+ if sc > best: best, pick, ph = sc, g, (hs[2 * k], hs[2 * k + 1])+ if pick: B[b] = pick; heard[b], heard[b + 1] = ph; fixed = True; moved += 1+ if not fixed: break+ for b in range(n - 1):+ if B[b][1] - B[b][0] < 0.03: warn.append(f" NO PAUSE between '{LINES[b]['text']}' and the next line: cut at the quietest point, check by ear")+ clips = []; bad = 0; soft = []+ for i, ln in enumerate(LINES):+ on, off = span(i, B); c = cut(i, B); act = np.abs(c) > 10 ** ((ref - 30) / 20); clips.append((ln, on, off, c, spans[i], 20 * np.log10(np.sqrt(np.mean(c[act] ** 2)))))+ if wrong(i, heard[i]): bad += 1; warn.append(f" WRONG CUT: '{ln['text']}' was heard alone as '{heard[i]}'")+ elif words_of(ln['text']) != words_of(heard[i]): soft.append(f" one word heard differently (check by ear): '{ln['text']}' -> '{heard[i]}'")+ med = float(np.median([c[5] for c in clips])); prev_end = 0; rows = []+ for ln, on, off, c, sp, r in clips:+ if ln['at'] is None: continue+ g = float(np.clip(med - r, -4, 5)); t0 = ln['at']+ if ln.get('chain'): t0 = max(t0, prev_end + ln.get('gap', 0.25))+ if t0 < prev_end + 0.05: warn.append(f" TIGHT: '{ln['text']}' starts {t0:.2f} but the line before ends {prev_end:.2f}")+ s = int((t0 - 0.03) * SR); c = c[:max(0, len(track) - s)]; track[s:s + len(c)] += c * 10 ** (g / 20); prev_end = t0 + (off - on)+ if prev_end > DUR - 0.15: warn.append(f" LATE: '{ln['text']}' ends {prev_end:.2f}, the film ends {DUR:.2f}")+ VO[ln['id']] = round(t0, 3)+ for name, wi in (ln.get('marks') or {}).items(): # a sentence that starts inside the line: the longest silence near where its first word should fall (by share of letters); whisper's word times are too loose for this+ cw = [len(w) for w in words_of(ln['text'])]; exp = on + sum(cw[:wi]) / sum(cw) * (off - on); inner = [g for g in gaps if g[0] > on and g[1] < off and abs(g[1] - exp) < 0.7]+ VO[name] = round(t0 + (max(inner, key=lambda g: g[1] - g[0])[1] if inner else exp) - on, 3)+ rows.append(f"{t0:6.2f} {off - on:5.2f} {g:+5.1f} {ln['text']}")+ print(os.path.basename(take)); print('\n'.join(rows))+ print(f" CHECKED: {len(clips) - bad} of {len(clips)} lines, each heard alone, match their text" + (f' ({moved} cut(s) moved to the right silence)' if moved else '') + ('' if not soft else '\n' + '\n'.join(soft)))+ print('\n'.join(warn) if warn else ' no line runs into the next')+ if miss: print(' words the transcript did not give back (check by ear):', miss)+ return bad+track = np.zeros(int(DUR * SR) + SR); VO = {}; bad = 0+for take in CFG['takes']:+ bad += lay(take['file'], [dict(at=None, **l) if 'at' not in l else l for l in take['lines']], track, VO)+if bad and not os.environ.get('VO_FORCE'): sys.exit(f'{bad} line(s) are cut wrong: not writing the voice track')+WAV, JS = CFG.get('wav', 'audio/vo.wav'), CFG.get('js', 'assets/vo.js')+for p in (WAV, JS): os.makedirs(os.path.dirname(p) or '.', exist_ok=True)+subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'f64le', '-ar', str(SR), '-ac', '1', '-i', '-', '-af',+ 'highpass=f=85,equalizer=f=3200:t=q:w=1.1:g=2,equalizer=f=230:t=q:w=1.0:g=-1.5,acompressor=threshold=-24dB:ratio=3:attack=6:release=110:makeup=2',+ '-c:a', 'pcm_s24le', WAV], input=track[:int(DUR * SR)].tobytes(), check=True)+open(JS, 'w').write('// written by scripts/vo.py: when each spoken line starts (seconds)\nwindow.VO=' + json.dumps(VO) + ';\n')+print('wrote', WAV, 'and', JS)