@vibecook/ice 0.10.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/README.md +79 -50
  2. package/dist/chunk-BA7XJC27.js +2429 -0
  3. package/dist/chunk-BA7XJC27.js.map +1 -0
  4. package/dist/chunk-BKV4ZEU3.js +1 -0
  5. package/dist/chunk-BKV4ZEU3.js.map +1 -0
  6. package/dist/{chunk-5FQS7V2C.js → chunk-DYK6KNLG.js} +13303 -7485
  7. package/dist/chunk-DYK6KNLG.js.map +1 -0
  8. package/dist/chunk-ENIFIUEP.js +155 -0
  9. package/dist/chunk-ENIFIUEP.js.map +1 -0
  10. package/dist/chunk-IBWWLA6D.js +634 -0
  11. package/dist/chunk-IBWWLA6D.js.map +1 -0
  12. package/dist/{chunk-OR5FNVUE.js → chunk-JS6PG6YD.js} +398 -167
  13. package/dist/chunk-JS6PG6YD.js.map +1 -0
  14. package/dist/chunk-QXOCF56A.js +148 -0
  15. package/dist/chunk-QXOCF56A.js.map +1 -0
  16. package/dist/chunk-ZPUPBULB.js +7399 -0
  17. package/dist/chunk-ZPUPBULB.js.map +1 -0
  18. package/dist/desk-engine.js +36 -0
  19. package/dist/desk-engine.js.map +1 -0
  20. package/dist/desk-kit.js +244 -0
  21. package/dist/desk-kit.js.map +1 -0
  22. package/dist/desk-objects.js +12728 -0
  23. package/dist/desk-objects.js.map +1 -0
  24. package/dist/desk.js +469 -0
  25. package/dist/desk.js.map +1 -0
  26. package/dist/devtools.js +233 -189
  27. package/dist/devtools.js.map +1 -1
  28. package/dist/dom.js +7 -19
  29. package/dist/index.js +232 -20
  30. package/dist/kernel.js +53 -25
  31. package/dist/react.js +1045 -38
  32. package/dist/react.js.map +1 -1
  33. package/dist/types/packages/core/src/behavior/define-behavior.d.ts +11 -0
  34. package/dist/types/packages/core/src/behavior/runtime.d.ts +4 -0
  35. package/dist/types/packages/core/src/canvas/define-canvas-type.d.ts +86 -0
  36. package/dist/types/packages/core/src/canvas/define-container.d.ts +17 -0
  37. package/dist/types/packages/core/src/canvas/diagnostics.d.ts +27 -0
  38. package/dist/types/packages/core/src/canvas/engine-catalog.d.ts +70 -0
  39. package/dist/types/packages/core/src/canvas/extensions.d.ts +125 -0
  40. package/dist/types/packages/core/src/canvas/frame-behavior-host.d.ts +16 -0
  41. package/dist/types/packages/core/src/canvas/frame-preview.d.ts +79 -0
  42. package/dist/types/packages/core/src/canvas/frame-projection.d.ts +38 -0
  43. package/dist/types/packages/core/src/canvas/frame-view.d.ts +36 -0
  44. package/dist/types/packages/core/src/canvas/migrate.d.ts +14 -0
  45. package/dist/types/packages/core/src/canvas/placement.d.ts +30 -0
  46. package/dist/types/packages/core/src/canvas/presentation-transition.d.ts +100 -0
  47. package/dist/types/packages/core/src/canvas/runtime-extension-host.d.ts +16 -0
  48. package/dist/types/packages/core/src/canvas/session.d.ts +47 -0
  49. package/dist/types/packages/core/src/catalog/camera-derived.d.ts +16 -27
  50. package/dist/types/packages/core/src/catalog/desk.d.ts +326 -0
  51. package/dist/types/packages/core/src/catalog/gesture.d.ts +51 -0
  52. package/dist/types/packages/core/src/catalog/graph.d.ts +2 -2
  53. package/dist/types/packages/core/src/catalog/index.d.ts +2 -0
  54. package/dist/types/packages/core/src/catalog/pointer.d.ts +42 -0
  55. package/dist/types/packages/core/src/catalog/selection-presence.d.ts +7 -0
  56. package/dist/types/packages/core/src/catalog/settings-resources.d.ts +28 -2
  57. package/dist/types/packages/core/src/catalog/surface.d.ts +1 -0
  58. package/dist/types/packages/core/src/doc/doc-commit-sink.d.ts +18 -2
  59. package/dist/types/packages/core/src/doc/doc-kit.d.ts +21 -2
  60. package/dist/types/packages/core/src/doc/envelope.d.ts +5 -2
  61. package/dist/types/packages/core/src/doc/schema-migrate.d.ts +1 -1
  62. package/dist/types/packages/core/src/doc/version-gate.d.ts +21 -3
  63. package/dist/types/packages/core/src/engine/commit-sink.d.ts +10 -1
  64. package/dist/types/packages/core/src/engine/engine.d.ts +6 -0
  65. package/dist/types/packages/core/src/engine/frame-control.d.ts +74 -0
  66. package/dist/types/packages/core/src/engine/guests.d.ts +4 -1
  67. package/dist/types/packages/core/src/engine/world-doors.d.ts +12 -0
  68. package/dist/types/packages/core/src/facade/create-canvas-engine.d.ts +146 -13
  69. package/dist/types/packages/core/src/index.d.ts +34 -13
  70. package/dist/types/packages/core/src/input/queue.d.ts +3 -1
  71. package/dist/types/packages/core/src/interaction/install.d.ts +30 -0
  72. package/dist/types/packages/core/src/interaction/wakes.d.ts +24 -0
  73. package/dist/types/packages/core/src/nav/nav-geometry.d.ts +100 -0
  74. package/dist/types/packages/core/src/nav/nested-canvas.d.ts +47 -4
  75. package/dist/types/packages/core/src/ops/cascade.d.ts +2 -1
  76. package/dist/types/packages/core/src/ops/claims.d.ts +6 -0
  77. package/dist/types/packages/core/src/ops/insert.d.ts +4 -0
  78. package/dist/types/packages/core/src/ops/point-pick.d.ts +4 -1
  79. package/dist/types/packages/core/src/ops/sibling-order.d.ts +14 -4
  80. package/dist/types/packages/core/src/ops/tray.d.ts +48 -0
  81. package/dist/types/packages/core/src/presence/presence-kit.d.ts +5 -0
  82. package/dist/types/packages/core/src/schema/meta.d.ts +10 -0
  83. package/dist/types/packages/core/src/schema/prefab.d.ts +8 -0
  84. package/dist/types/packages/core/src/settings/defaults.d.ts +25 -6
  85. package/dist/types/packages/core/src/surface/gpu-device.d.ts +55 -0
  86. package/dist/types/packages/core/src/systems/camera-sim.d.ts +29 -0
  87. package/dist/types/packages/core/src/systems/chrome.d.ts +15 -23
  88. package/dist/types/packages/core/src/systems/drag-mods.d.ts +34 -0
  89. package/dist/types/packages/core/src/systems/held.d.ts +71 -0
  90. package/dist/types/packages/core/src/systems/insert-ghost.d.ts +2 -0
  91. package/dist/types/packages/core/src/systems/l0-input.d.ts +14 -0
  92. package/dist/types/packages/core/src/systems/l1-pick.d.ts +37 -1
  93. package/dist/types/packages/core/src/systems/l2-arbitrate.d.ts +18 -4
  94. package/dist/types/packages/core/src/systems/l3-behave.d.ts +4 -1
  95. package/dist/types/packages/core/src/systems/l3-claim.d.ts +7 -0
  96. package/dist/types/packages/core/src/systems/l3-connect.d.ts +1 -1
  97. package/dist/types/packages/core/src/systems/l3-drop.d.ts +30 -1
  98. package/dist/types/packages/core/src/systems/l3-marquee.d.ts +2 -1
  99. package/dist/types/packages/core/src/systems/l3-ports.d.ts +1 -1
  100. package/dist/types/packages/core/src/systems/l4-cursor.d.ts +5 -0
  101. package/dist/types/packages/core/src/systems/nav-flight.d.ts +85 -3
  102. package/dist/types/packages/core/src/systems/nav-tap.d.ts +44 -0
  103. package/dist/types/packages/core/src/systems/press-wheel.d.ts +11 -0
  104. package/dist/types/packages/core/src/systems/tray.d.ts +108 -0
  105. package/dist/types/packages/core/src/systems/zoom-through.d.ts +30 -0
  106. package/dist/types/packages/core/src/tools/define-tool.d.ts +10 -0
  107. package/dist/types/packages/core/src/widget/define-widget.d.ts +166 -63
  108. package/dist/types/packages/core/src/widget/equip.d.ts +14 -2
  109. package/dist/types/packages/core/src/widget/held-tools.d.ts +83 -0
  110. package/dist/types/packages/core/src/widget/menu-actions.d.ts +44 -0
  111. package/dist/types/packages/core/src/widget/mount-store.d.ts +21 -46
  112. package/dist/types/packages/core/src/widget/spawn.d.ts +1 -1
  113. package/dist/types/packages/desk/src/assets/blue-noise.gen.d.ts +10 -0
  114. package/dist/types/packages/desk/src/card/card.d.ts +103 -0
  115. package/dist/types/packages/desk/src/compose/ambient.d.ts +59 -0
  116. package/dist/types/packages/desk/src/compose/builder.d.ts +285 -0
  117. package/dist/types/packages/desk/src/compose/children.d.ts +3 -0
  118. package/dist/types/packages/desk/src/compose/index.d.ts +14 -0
  119. package/dist/types/packages/desk/src/compose/marks.d.ts +126 -0
  120. package/dist/types/packages/desk/src/compose/pick.d.ts +5 -0
  121. package/dist/types/packages/desk/src/compose/reflector.d.ts +111 -0
  122. package/dist/types/packages/desk/src/compose/tap.d.ts +5 -0
  123. package/dist/types/packages/desk/src/docs.d.ts +23 -0
  124. package/dist/types/packages/desk/src/engine/budget.d.ts +38 -0
  125. package/dist/types/packages/desk/src/engine/device.d.ts +54 -0
  126. package/dist/types/packages/desk/src/engine/index.d.ts +5 -0
  127. package/dist/types/packages/desk/src/engine/pipeline.d.ts +36 -0
  128. package/dist/types/packages/desk/src/engine/rasters.d.ts +66 -0
  129. package/dist/types/packages/desk/src/engine/records.d.ts +56 -0
  130. package/dist/types/packages/desk/src/engine/shader.d.ts +22 -0
  131. package/dist/types/packages/desk/src/engine/struct.d.ts +39 -0
  132. package/dist/types/packages/desk/src/engine/target.d.ts +26 -0
  133. package/dist/types/packages/desk/src/gpu-ablation.d.ts +61 -0
  134. package/dist/types/packages/desk/src/gpu-memory.d.ts +54 -0
  135. package/dist/types/packages/desk/src/gpu-profiler.d.ts +141 -0
  136. package/dist/types/packages/desk/src/gpu-wrap.d.ts +8 -0
  137. package/dist/types/packages/desk/src/ground.d.ts +388 -0
  138. package/dist/types/packages/desk/src/hold/focus.d.ts +53 -0
  139. package/dist/types/packages/desk/src/hold/pose.d.ts +132 -0
  140. package/dist/types/packages/desk/src/hold/shaders.d.ts +9 -0
  141. package/dist/types/packages/desk/src/host/editor.d.ts +18 -0
  142. package/dist/types/packages/desk/src/host/index.d.ts +9 -0
  143. package/dist/types/packages/desk/src/host/ink.d.ts +18 -0
  144. package/dist/types/packages/desk/src/host/layer.d.ts +430 -0
  145. package/dist/types/packages/desk/src/host/picture.d.ts +2 -0
  146. package/dist/types/packages/desk/src/host/surface.d.ts +5 -0
  147. package/dist/types/packages/desk/src/index.d.ts +13 -0
  148. package/dist/types/packages/desk/src/kind.d.ts +187 -0
  149. package/dist/types/packages/desk/src/kinds/world.d.ts +429 -0
  150. package/dist/types/packages/desk/src/kit/arrays.d.ts +88 -0
  151. package/dist/types/packages/desk/src/kit/blobs.d.ts +40 -0
  152. package/dist/types/packages/desk/src/kit/book.d.ts +2 -0
  153. package/dist/types/packages/desk/src/kit/editor.d.ts +103 -0
  154. package/dist/types/packages/desk/src/kit/eye.d.ts +37 -0
  155. package/dist/types/packages/desk/src/kit/hold.d.ts +1 -0
  156. package/dist/types/packages/desk/src/kit/index.d.ts +26 -0
  157. package/dist/types/packages/desk/src/kit/inside.d.ts +116 -0
  158. package/dist/types/packages/desk/src/kit/layer.d.ts +159 -0
  159. package/dist/types/packages/desk/src/kit/light.d.ts +3 -0
  160. package/dist/types/packages/desk/src/kit/mesh.d.ts +29 -0
  161. package/dist/types/packages/desk/src/kit/mips.d.ts +2 -0
  162. package/dist/types/packages/desk/src/kit/nav.d.ts +2 -0
  163. package/dist/types/packages/desk/src/kit/paper-tex.d.ts +5 -0
  164. package/dist/types/packages/desk/src/kit/physics.d.ts +44 -0
  165. package/dist/types/packages/desk/src/kit/place.d.ts +44 -0
  166. package/dist/types/packages/desk/src/kit/print.d.ts +30 -0
  167. package/dist/types/packages/desk/src/kit/raster.d.ts +34 -0
  168. package/dist/types/packages/desk/src/kit/sdf.d.ts +1 -0
  169. package/dist/types/packages/desk/src/kit/seeds.d.ts +11 -0
  170. package/dist/types/packages/desk/src/kit/services.d.ts +34 -0
  171. package/dist/types/packages/desk/src/kit/springs.d.ts +12 -0
  172. package/dist/types/packages/desk/src/kit/strokes.d.ts +93 -0
  173. package/dist/types/packages/desk/src/kit/text.d.ts +142 -0
  174. package/dist/types/packages/desk/src/kit/uniform.d.ts +8 -0
  175. package/dist/types/packages/desk/src/kit/view.d.ts +39 -0
  176. package/dist/types/packages/desk/src/kit/wgsl.d.ts +15 -0
  177. package/dist/types/packages/desk/src/lattice/line.d.ts +15 -0
  178. package/dist/types/packages/desk/src/lattice/lod.d.ts +52 -0
  179. package/dist/types/packages/desk/src/lattice/ruler.d.ts +88 -0
  180. package/dist/types/packages/desk/src/marks/assemble.d.ts +65 -0
  181. package/dist/types/packages/desk/src/marks/ease.d.ts +4 -0
  182. package/dist/types/packages/desk/src/marks/laser.d.ts +41 -0
  183. package/dist/types/packages/desk/src/marks/layout.d.ts +167 -0
  184. package/dist/types/packages/desk/src/marks/pass.d.ts +59 -0
  185. package/dist/types/packages/desk/src/marks/shaders.d.ts +12 -0
  186. package/dist/types/packages/desk/src/mat/grid.d.ts +50 -0
  187. package/dist/types/packages/desk/src/mat/lamp.d.ts +14 -0
  188. package/dist/types/packages/desk/src/mat/layout.d.ts +144 -0
  189. package/dist/types/packages/desk/src/mat/mat-pass.d.ts +83 -0
  190. package/dist/types/packages/desk/src/mat/night.d.ts +95 -0
  191. package/dist/types/packages/desk/src/mat/projector.d.ts +39 -0
  192. package/dist/types/packages/desk/src/mat/shaders.d.ts +17 -0
  193. package/dist/types/packages/desk/src/mat/tilt.d.ts +14 -0
  194. package/dist/types/packages/desk/src/nav/flight.d.ts +186 -0
  195. package/dist/types/packages/desk/src/nav/portal.d.ts +95 -0
  196. package/dist/types/packages/desk/src/object.d.ts +46 -0
  197. package/dist/types/packages/desk/src/pass-instrument.d.ts +89 -0
  198. package/dist/types/packages/desk/src/shaders.d.ts +12 -0
  199. package/dist/types/packages/desk/src/shaders.gen.d.ts +16 -0
  200. package/dist/types/packages/desk/src/submit-instrument.d.ts +36 -0
  201. package/dist/types/packages/desk/src/theme.d.ts +475 -0
  202. package/dist/types/packages/desk/src/tray/carry.d.ts +99 -0
  203. package/dist/types/packages/desk/src/tray/drawer.d.ts +113 -0
  204. package/dist/types/packages/desk/src/tray/flux.d.ts +46 -0
  205. package/dist/types/packages/desk/src/tray/index.d.ts +4 -0
  206. package/dist/types/packages/desk/src/tray/lattice.d.ts +71 -0
  207. package/dist/types/packages/desk/src/tray/layout.d.ts +7 -0
  208. package/dist/types/packages/desk/src/tray/look.d.ts +29 -0
  209. package/dist/types/packages/desk/src/tray/pass.d.ts +96 -0
  210. package/dist/types/packages/desk/src/tray/shaders.d.ts +10 -0
  211. package/dist/types/packages/desk/src/tray/specimens.d.ts +199 -0
  212. package/dist/types/packages/devtools/src/attach.d.ts +22 -8
  213. package/dist/types/packages/devtools/src/dock.d.ts +18 -14
  214. package/dist/types/packages/devtools/src/gpu-panel.d.ts +105 -0
  215. package/dist/types/packages/devtools/src/index.d.ts +5 -4
  216. package/dist/types/packages/dom/src/desk-host.d.ts +91 -0
  217. package/dist/types/packages/dom/src/host.d.ts +13 -14
  218. package/dist/types/packages/dom/src/index.d.ts +12 -10
  219. package/dist/types/packages/dom/src/loop.d.ts +18 -1
  220. package/dist/types/packages/dom/src/pointer-adapter.d.ts +5 -29
  221. package/dist/types/packages/dom/src/widget-focus.d.ts +17 -13
  222. package/dist/types/packages/ice/src/desk-engine.d.ts +2 -0
  223. package/dist/types/packages/ice/src/desk-kit.d.ts +6 -0
  224. package/dist/types/packages/ice/src/desk-objects.d.ts +5 -0
  225. package/dist/types/packages/ice/src/desk.d.ts +5 -0
  226. package/dist/types/packages/kernel/src/atlas-pack.d.ts +157 -0
  227. package/dist/types/packages/kernel/src/bezier.d.ts +0 -15
  228. package/dist/types/packages/kernel/src/coords.d.ts +0 -39
  229. package/dist/types/packages/kernel/src/index.d.ts +2 -2
  230. package/dist/types/packages/kernel/src/nav-flight.d.ts +6 -0
  231. package/dist/types/packages/kernel/src/tray.d.ts +155 -0
  232. package/dist/types/packages/objects/src/board/board-pass.d.ts +180 -0
  233. package/dist/types/packages/objects/src/board/board-pen.d.ts +36 -0
  234. package/dist/types/packages/objects/src/board/board.d.ts +104 -0
  235. package/dist/types/packages/objects/src/board/data.d.ts +31 -0
  236. package/dist/types/packages/objects/src/board/history.d.ts +33 -0
  237. package/dist/types/packages/objects/src/board/kind.d.ts +208 -0
  238. package/dist/types/packages/objects/src/board/layout.d.ts +102 -0
  239. package/dist/types/packages/objects/src/board/object.d.ts +7 -0
  240. package/dist/types/packages/objects/src/board/pen.d.ts +71 -0
  241. package/dist/types/packages/objects/src/board/shaders.d.ts +36 -0
  242. package/dist/types/packages/objects/src/board/stroke.d.ts +99 -0
  243. package/dist/types/packages/objects/src/board/theme.d.ts +150 -0
  244. package/dist/types/packages/objects/src/calendar/data.d.ts +97 -0
  245. package/dist/types/packages/objects/src/calendar/events.d.ts +58 -0
  246. package/dist/types/packages/objects/src/calendar/hand.d.ts +53 -0
  247. package/dist/types/packages/objects/src/calendar/host/input.d.ts +67 -0
  248. package/dist/types/packages/objects/src/calendar/host/print.d.ts +9 -0
  249. package/dist/types/packages/objects/src/calendar/kind.d.ts +297 -0
  250. package/dist/types/packages/objects/src/calendar/law.d.ts +151 -0
  251. package/dist/types/packages/objects/src/calendar/layout.d.ts +47 -0
  252. package/dist/types/packages/objects/src/calendar/month.d.ts +75 -0
  253. package/dist/types/packages/objects/src/calendar/object.d.ts +45 -0
  254. package/dist/types/packages/objects/src/calendar/pad.d.ts +42 -0
  255. package/dist/types/packages/objects/src/calendar/pass.d.ts +229 -0
  256. package/dist/types/packages/objects/src/calendar/print.d.ts +87 -0
  257. package/dist/types/packages/objects/src/calendar/printing.d.ts +80 -0
  258. package/dist/types/packages/objects/src/calendar/roll.d.ts +45 -0
  259. package/dist/types/packages/objects/src/calendar/shaders.d.ts +12 -0
  260. package/dist/types/packages/objects/src/calendar/sheet.d.ts +43 -0
  261. package/dist/types/packages/objects/src/calendar/tiles.d.ts +67 -0
  262. package/dist/types/packages/objects/src/calendar/turn.d.ts +73 -0
  263. package/dist/types/packages/objects/src/calendar/writing.d.ts +42 -0
  264. package/dist/types/packages/objects/src/index.d.ts +22 -0
  265. package/dist/types/packages/objects/src/kinds.d.ts +24 -0
  266. package/dist/types/packages/objects/src/minimat/inside.d.ts +17 -0
  267. package/dist/types/packages/objects/src/minimat/kind.d.ts +51 -0
  268. package/dist/types/packages/objects/src/minimat/layout.d.ts +83 -0
  269. package/dist/types/packages/objects/src/minimat/minimat.d.ts +179 -0
  270. package/dist/types/packages/objects/src/minimat/object.d.ts +8 -0
  271. package/dist/types/packages/objects/src/minimat/pass.d.ts +61 -0
  272. package/dist/types/packages/objects/src/minimat/shaders.d.ts +10 -0
  273. package/dist/types/packages/objects/src/minimat/theme.d.ts +98 -0
  274. package/dist/types/packages/objects/src/notebook/ink.d.ts +70 -0
  275. package/dist/types/packages/objects/src/notebook/kind.d.ts +236 -0
  276. package/dist/types/packages/objects/src/notebook/law.d.ts +129 -0
  277. package/dist/types/packages/objects/src/notebook/layout.d.ts +46 -0
  278. package/dist/types/packages/objects/src/notebook/leaf.d.ts +44 -0
  279. package/dist/types/packages/objects/src/notebook/mesh.d.ts +20 -0
  280. package/dist/types/packages/objects/src/notebook/motion.d.ts +107 -0
  281. package/dist/types/packages/objects/src/notebook/object.d.ts +8 -0
  282. package/dist/types/packages/objects/src/notebook/pages.d.ts +56 -0
  283. package/dist/types/packages/objects/src/notebook/pass.d.ts +197 -0
  284. package/dist/types/packages/objects/src/notebook/pick.d.ts +30 -0
  285. package/dist/types/packages/objects/src/notebook/raster.d.ts +28 -0
  286. package/dist/types/packages/objects/src/notebook/shaders.d.ts +11 -0
  287. package/dist/types/packages/objects/src/notebook/shape.d.ts +155 -0
  288. package/dist/types/packages/objects/src/notebook/theme.d.ts +76 -0
  289. package/dist/types/packages/objects/src/palette.d.ts +577 -0
  290. package/dist/types/packages/objects/src/paper/host/body.d.ts +30 -0
  291. package/dist/types/packages/objects/src/paper/kind.d.ts +81 -0
  292. package/dist/types/packages/objects/src/paper/layout.d.ts +73 -0
  293. package/dist/types/packages/objects/src/paper/object.d.ts +31 -0
  294. package/dist/types/packages/objects/src/paper/pages.d.ts +43 -0
  295. package/dist/types/packages/objects/src/paper/paper-pass.d.ts +86 -0
  296. package/dist/types/packages/objects/src/paper/paper.d.ts +117 -0
  297. package/dist/types/packages/objects/src/paper/shaders.d.ts +18 -0
  298. package/dist/types/packages/objects/src/paper/theme.d.ts +58 -0
  299. package/dist/types/packages/objects/src/paper/typing.d.ts +51 -0
  300. package/dist/types/packages/objects/src/paper/writing.d.ts +161 -0
  301. package/dist/types/packages/objects/src/photo/carry.d.ts +33 -0
  302. package/dist/types/packages/objects/src/photo/kind.d.ts +136 -0
  303. package/dist/types/packages/objects/src/photo/layout.d.ts +39 -0
  304. package/dist/types/packages/objects/src/photo/object.d.ts +5 -0
  305. package/dist/types/packages/objects/src/photo/photo-pass.d.ts +104 -0
  306. package/dist/types/packages/objects/src/photo/photo.d.ts +262 -0
  307. package/dist/types/packages/objects/src/photo/pictures.d.ts +152 -0
  308. package/dist/types/packages/objects/src/photo/sample.d.ts +9 -0
  309. package/dist/types/packages/objects/src/photo/shaders.d.ts +18 -0
  310. package/dist/types/packages/objects/src/preset.d.ts +44 -0
  311. package/dist/types/packages/objects/src/shaders.d.ts +3 -0
  312. package/dist/types/packages/objects/src/shaders.gen.d.ts +21 -0
  313. package/dist/types/packages/react/src/canvas-hooks.d.ts +12 -0
  314. package/dist/types/packages/react/src/desk.d.ts +56 -0
  315. package/dist/types/packages/react/src/engine-context.d.ts +2 -2
  316. package/dist/types/packages/react/src/frame-preview-boundary.d.ts +19 -0
  317. package/dist/types/packages/react/src/hooks.d.ts +9 -14
  318. package/dist/types/packages/react/src/index.d.ts +16 -9
  319. package/dist/types/packages/react/src/keymap.d.ts +21 -2
  320. package/dist/types/packages/react/src/selection-menu.d.ts +171 -0
  321. package/dist/types/packages/react/src/tray-bar.d.ts +124 -0
  322. package/package.json +64 -31
  323. package/dist/chunk-5FQS7V2C.js.map +0 -1
  324. package/dist/chunk-JWRHAM7L.js +0 -1163
  325. package/dist/chunk-JWRHAM7L.js.map +0 -1
  326. package/dist/chunk-MFTMPJUF.js +0 -681
  327. package/dist/chunk-MFTMPJUF.js.map +0 -1
  328. package/dist/chunk-OR5FNVUE.js.map +0 -1
  329. package/dist/ground.js +0 -1213
  330. package/dist/ground.js.map +0 -1
  331. package/dist/r3f.js +0 -1644
  332. package/dist/r3f.js.map +0 -1
  333. package/dist/types/packages/core/src/input/measure-queue.d.ts +0 -30
  334. package/dist/types/packages/core/src/settings/ground-config.d.ts +0 -103
  335. package/dist/types/packages/core/src/systems/measure-ingest.d.ts +0 -26
  336. package/dist/types/packages/devtools/src/gl-panel.d.ts +0 -69
  337. package/dist/types/packages/dom/src/measure-adapter.d.ts +0 -31
  338. package/dist/types/packages/dom/src/measure-wiring.d.ts +0 -49
  339. package/dist/types/packages/dom/src/planes.d.ts +0 -33
  340. package/dist/types/packages/dom/src/reflectors/chrome.d.ts +0 -33
  341. package/dist/types/packages/dom/src/reflectors/dom-widgets.d.ts +0 -59
  342. package/dist/types/packages/dom/src/reflectors/graybox.d.ts +0 -31
  343. package/dist/types/packages/dom/src/reflectors/plane-transform.d.ts +0 -38
  344. package/dist/types/packages/ground/src/index.d.ts +0 -69
  345. package/dist/types/packages/ground/src/layer.d.ts +0 -40
  346. package/dist/types/packages/ground/src/pass.d.ts +0 -41
  347. package/dist/types/packages/ground/src/passes/grid-classic.d.ts +0 -30
  348. package/dist/types/packages/ground/src/passes/grid-magnet.d.ts +0 -31
  349. package/dist/types/packages/ground/src/passes/grid.d.ts +0 -28
  350. package/dist/types/packages/ground/src/passes/guides-collect.d.ts +0 -14
  351. package/dist/types/packages/ground/src/passes/guides.d.ts +0 -3
  352. package/dist/types/packages/ground/src/passes/magnet-collect.d.ts +0 -63
  353. package/dist/types/packages/ground/src/passes/soup-collect.d.ts +0 -35
  354. package/dist/types/packages/ground/src/passes/soup-mesh.d.ts +0 -8
  355. package/dist/types/packages/ground/src/passes/wires-collect.d.ts +0 -35
  356. package/dist/types/packages/ground/src/passes/wires.d.ts +0 -10
  357. package/dist/types/packages/ground/src/poles.d.ts +0 -47
  358. package/dist/types/packages/ground/src/renderer.d.ts +0 -15
  359. package/dist/types/packages/ice/src/ground.d.ts +0 -1
  360. package/dist/types/packages/ice/src/r3f.d.ts +0 -1
  361. package/dist/types/packages/kernel/src/eviction.d.ts +0 -23
  362. package/dist/types/packages/kernel/src/zoom-bands.d.ts +0 -19
  363. package/dist/types/packages/r3f/src/bridge.d.ts +0 -129
  364. package/dist/types/packages/r3f/src/composite-material.d.ts +0 -26
  365. package/dist/types/packages/r3f/src/compositor-pass.d.ts +0 -105
  366. package/dist/types/packages/r3f/src/dev-write-trap.d.ts +0 -30
  367. package/dist/types/packages/r3f/src/gl-root.d.ts +0 -96
  368. package/dist/types/packages/r3f/src/gl-router.d.ts +0 -70
  369. package/dist/types/packages/r3f/src/index.d.ts +0 -17
  370. package/dist/types/packages/r3f/src/island-state.d.ts +0 -112
  371. package/dist/types/packages/r3f/src/island.d.ts +0 -13
  372. package/dist/types/packages/r3f/src/pool.d.ts +0 -56
  373. package/dist/types/packages/r3f/src/preview-capture.d.ts +0 -19
  374. package/dist/types/packages/r3f/src/resource-registry.d.ts +0 -30
  375. package/dist/types/packages/r3f/src/self-sustain.d.ts +0 -39
  376. package/dist/types/packages/r3f/src/use-island-frame.d.ts +0 -39
  377. package/dist/types/packages/react/src/infinite-canvas.d.ts +0 -140
  378. package/dist/types/packages/react/src/preview-snapshots.d.ts +0 -17
  379. package/dist/types/packages/react/src/widget-preview.d.ts +0 -14
  380. package/dist/types/packages/react/src/widget-root.d.ts +0 -33
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../objects/src/minimat/theme.ts","../../objects/src/minimat/minimat.ts","../../objects/src/minimat/inside.ts","../../objects/src/minimat/layout.ts","../../objects/src/minimat/pass.ts","../../objects/src/minimat/shaders.ts","../../objects/src/shaders.gen.ts","../../objects/src/shaders.ts","../../objects/src/minimat/kind.ts","../../objects/src/minimat/object.ts","../../objects/src/paper/theme.ts","../../objects/src/paper/paper.ts","../../objects/src/paper/layout.ts","../../objects/src/paper/pages.ts","../../objects/src/paper/paper-pass.ts","../../objects/src/paper/shaders.ts","../../objects/src/paper/writing.ts","../../objects/src/paper/kind.ts","../../objects/src/paper/typing.ts","../../objects/src/paper/host/body.ts","../../objects/src/paper/object.ts","../../objects/src/board/theme.ts","../../objects/src/board/stroke.ts","../../objects/src/board/history.ts","../../objects/src/board/data.ts","../../objects/src/board/board.ts","../../objects/src/board/layout.ts","../../objects/src/board/board-pass.ts","../../objects/src/board/pen.ts","../../objects/src/board/shaders.ts","../../objects/src/board/kind.ts","../../objects/src/board/board-pen.ts","../../objects/src/board/object.ts","../../objects/src/calendar/law.ts","../../objects/src/calendar/month.ts","../../objects/src/calendar/roll.ts","../../objects/src/calendar/pad.ts","../../objects/src/calendar/sheet.ts","../../objects/src/calendar/data.ts","../../objects/src/calendar/tiles.ts","../../objects/src/calendar/layout.ts","../../objects/src/calendar/pass.ts","../../objects/src/calendar/events.ts","../../objects/src/calendar/print.ts","../../objects/src/calendar/printing.ts","../../objects/src/calendar/turn.ts","../../objects/src/calendar/shaders.ts","../../objects/src/calendar/kind.ts","../../objects/src/calendar/hand.ts","../../objects/src/calendar/writing.ts","../../objects/src/calendar/host/input.ts","../../objects/src/calendar/host/print.ts","../../objects/src/calendar/object.ts","../../objects/src/notebook/law.ts","../../objects/src/notebook/layout.ts","../../objects/src/notebook/shape.ts","../../objects/src/notebook/mesh.ts","../../objects/src/notebook/ink.ts","../../objects/src/notebook/motion.ts","../../objects/src/notebook/raster.ts","../../objects/src/notebook/pages.ts","../../objects/src/notebook/pass.ts","../../objects/src/notebook/pick.ts","../../objects/src/notebook/shaders.ts","../../objects/src/notebook/kind.ts","../../objects/src/notebook/leaf.ts","../../objects/src/notebook/object.ts","../../objects/src/photo/sample.ts","../../objects/src/photo/photo.ts","../../objects/src/photo/layout.ts","../../objects/src/photo/pictures.ts","../../objects/src/photo/photo-pass.ts","../../objects/src/photo/shaders.ts","../../objects/src/photo/kind.ts","../../objects/src/photo/carry.ts","../../objects/src/photo/object.ts","../../objects/src/preset.ts","../../objects/src/palette.ts","../../objects/src/notebook/theme.ts","../../objects/src/kinds.ts"],"sourcesContent":["// The MINI MAT's own theme — the container's law as numbers (moved out of the engine's src/theme.ts at K4a, design-016\n// §5). Its shadow and ring are the kit's ONE PHYSICS (kit/physics.ts); its gate is the portal's (theme.ts `PORTAL`), by name.\n\nimport { PHYSICS } from \"@ice/desk/kit\";\nimport { PORTAL } from \"@ice/desk\";\n\n/**\n * The MINI MAT (MINIMAT.md) — the desk's CONTAINER: a smaller self-healing cutting mat lying on\n * the big one, and inside it another desk (a nested canvas: double-click it, or zoom into it, and\n * it becomes the desk). Its sheet is the mat's own vinyl — the sage and the cream print (`MAT`),\n * the mat's chain by day and the Moon by night — so it is told from the desk by what a real small\n * mat has: its cut edge and its shadow, the printed BORDER round its cutting area (a frame line,\n * a ruler along the top and left edges — its ticks on the very lattice the face shows, numbered\n * in the inside's own units — and its NAME in the foot, as a mat's maker prints its own), and the\n * finer grid of the miniature desk inside. It is thin, so it lies flat and lifts as little as a\n * sheet does, casting the desk's one shadow (`BOOK.shadow`: the note's penumbra with a contact\n * term at the base). World units (CSS px at zoom 1).\n */\nexport const MINIMAT = {\n /** A new mini mat: 8 × 6 of the tree-shadow design's 80-unit modules (mat.css `--module`). */\n size: { w: 640, h: 480 },\n /** The die-cut corner; the printed border's width (the FACE is the sheet inset by it); the vinyl's thickness. */\n radius: 10, margin: 32, thick: 3,\n /** Held it rises and reads a touch larger — a thin sheet lifts less than a note (PAPER.lift 12 · 1.03); hovered it rises a fifth of that (Marks on the Mat: hover is a rise, never an outline). */\n lift: { height: 10, scale: 1.02 }, hover: 0.2,\n /** The shadow: the desk's one law. */\n shadow: PHYSICS.slab,\n /** The cut edge: a bevel this wide, catching the lamp on its near side (× 1 + light) and falling away on the far (× 1 − dark). */\n edge: { width: 1.5, light: 0.1, dark: 0.18 },\n /**\n * The print, in the mat's cream at the tree-shadow design's print-strong (55 %): the frame round the\n * face, the ruler's ticks, its numerals and the name. Its lines this wide (world units: a print\n * scales with the sheet — but never under a device px, the ink thinning instead); the ticks' lengths\n * — minor, medium, major, for the lattice's fine, mid and coarse rungs. The NUMERALS: the rulers' own\n * mono digits (RULER.md), this tall (cap, world units), after their tick by `gap`, their cap's top\n * `top` in from the sheet's edge; a rung is numbered once its sites are `labelsFrom` CSS px apart on\n * screen (its every tenth site, the next rung's, stays numbered). The NAME: the design's print label\n * (mono capitals, tracked 0.16 em) this tall, in the foot of the border from the face's left edge.\n * Text fades in as its cap grows from 4 to 6 CSS px (smaller is a smudge, never a word).\n */\n print: {\n frame: 0.55, tick: 0.55, width: 1, ticks: [5, 9, 14] as const,\n digits: { cap: 6, gap: 2.5, top: 4 }, labelsFrom: [48, 64] as const,\n name: { cap: 8, tracking: 0.16 }, legible: [4, 6] as const,\n },\n /** The sole-selection ring (DESIGN.md §7), CSS px, in `--vf-select`. */\n ring: PHYSICS.ring,\n /**\n * The face's far LOD (MINIMAT.md §5): its children drawn as CHIPS — at most this many (ICE's preview\n * record keeps 128), none smaller than this many CSS px; a note's writing GREEKED as lines of ink once\n * its chip is this tall (CSS px), at this presence, its lines this thick (× the line pitch).\n */\n chips: { max: 64, minPx: 1, greekPx: 18, greekAlpha: 0.42, greekWeight: 0.3 },\n /**\n * The face's corner (MINIMAT.md §5; D2b): the inside is clipped SQUARE — the live inside, the far LOD and a flight through it\n * (`faceClip`; its `faceLaw.radius`, K8a — the mini mat's own number, which the kit held as `FACE_RADIUS` until then).\n */\n faceRadius: 0,\n /** The live inside's GATE (CSS px of the face's short side): the portal's law (theme.ts `PORTAL`), by name. */\n gate: PORTAL.gate,\n} as const;\n","// The MINI MAT's law — pure: no GPU (MINIMAT.md). A mini mat on the desk is an\n// axis-aligned rect of the mat's own vinyl; `resolveMiniMat` turns it and its\n// motion (held · hovered · selected · fading) into the GEOMETRY the pass draws\n// and the hit test reads. Its FACE is the cutting area inside the printed\n// border — the rect its inside shows through (the portal, MINIMAT.md §3), and\n// what a flight into it is built on. `chipOf` lays one of its children out on\n// the face as the far LOD draws it (§5): the child's footprint mapped through\n// the inside's embedding, in the host's world. The lamp is the desk's one lamp\n// (paper.ts `lampOf`): the shadow falls away from it, the cut edge catches it.\n\nimport { type FadeIn, lod, dressScale, type LineLaw, lineWeight, GLYPHS, type CameraState, type PortalAffine, type Rect, clipOf, type PortalClip, type Lamp, sdRoundBox, type ChildShape, type ChipFinish, PAPER_FINISH, VINYL_FINISH } from \"@ice/desk/kit\";\nimport type { RGB } from \"@ice/desk\";\nimport { MINIMAT } from \"./theme\";\n\n/** The mini mat's numbers (theme.ts `MINIMAT`) — the engine's unless a host tweaks them. */\nexport interface MiniMatLaw {\n readonly size: { readonly w: number; readonly h: number };\n readonly radius: number;\n readonly margin: number;\n readonly thick: number;\n readonly lift: { readonly height: number; readonly scale: number };\n readonly hover: number;\n readonly shadow: {\n readonly penumbra: { readonly sigma0: number; readonly sigmaPerHeight: number; readonly alpha: number };\n readonly contact: { readonly sigma: number; readonly alpha: number; readonly reach: number };\n readonly slopeMax: number;\n };\n readonly edge: { readonly width: number; readonly light: number; readonly dark: number };\n readonly print: {\n readonly frame: number; readonly tick: number; readonly width: number; readonly ticks: readonly [number, number, number];\n readonly digits: { readonly cap: number; readonly gap: number; readonly top: number };\n readonly labelsFrom: readonly [number, number];\n readonly name: { readonly cap: number; readonly tracking: number };\n readonly legible: readonly [number, number];\n };\n readonly ring: number;\n readonly chips: { readonly max: number; readonly minPx: number; readonly greekPx: number; readonly greekAlpha: number; readonly greekWeight: number };\n readonly gate: readonly [number, number];\n}\nexport const DEFAULT_MINIMAT_LAW: MiniMatLaw = MINIMAT;\n\nexport interface MiniMatRect {\n /** World centre, in the frame of the desk it lies on. */\n readonly cx: number; readonly cy: number;\n /** The sheet, world units. */\n readonly w: number; readonly h: number;\n}\n\n/** What moves: the hold's lift (0..1), the hover's rise (0..1), the selection ring's presence (0..1), the presence itself (1 … 0 gone). */\nexport interface MiniMatMotion { readonly held: number; readonly hover: number; readonly ring: number; readonly fade: number }\nexport const MINIMAT_REST: MiniMatMotion = { held: 0, hover: 0, ring: 0, fade: 1 };\n\nexport interface MiniMatGeometry {\n readonly centre: readonly [number, number];\n /** Half extents as drawn (the hold's scale applied). */\n readonly half: readonly [number, number];\n /** The die-cut corner and the printed border, as drawn. */\n readonly radius: number;\n readonly margin: number;\n /** The sheet's underside off the desk (the hold's and the hover's rise) and its thickness, world units. */\n readonly lift: number;\n readonly thick: number;\n readonly scale: number;\n /** The shadow's ground offset per unit of height, world axes — away from the lamp, capped. */\n readonly slope: readonly [number, number];\n /** The unit direction to the lamp, world axes (x right, y down the screen, z off the desk). */\n readonly lamp: readonly [number, number, number];\n readonly ring: number;\n readonly alpha: number;\n}\n\nexport function resolveMiniMat(r: MiniMatRect, m: MiniMatMotion, law: MiniMatLaw, lamp: Lamp): MiniMatGeometry {\n const scale = 1 + (law.lift.scale - 1) * m.held;\n const dx = lamp.x - r.cx;\n const dy = lamp.y - r.cy;\n const h = Math.max(lamp.h, 1e-6);\n const len = Math.hypot(dx, dy, h);\n let sx = -dx / h;\n let sy = -dy / h;\n const s = Math.hypot(sx, sy);\n const cap = law.shadow.slopeMax;\n if (s > cap) { sx *= cap / s; sy *= cap / s; }\n return {\n centre: [r.cx, r.cy], half: [(r.w / 2) * scale, (r.h / 2) * scale],\n radius: law.radius * scale, margin: law.margin * scale,\n lift: law.lift.height * Math.max(m.held, law.hover * m.hover), thick: law.thick, scale,\n slope: [sx, sy], lamp: [dx / len, dy / len, h / len],\n ring: m.ring, alpha: m.fade,\n };\n}\n\n/** The sheet's signed distance at a world point. */\nexport const sdMiniMat = (G: MiniMatGeometry, wx: number, wy: number): number => sdRoundBox(wx - G.centre[0], wy - G.centre[1], G.half[0], G.half[1], G.radius);\n\n/** The FACE — the cutting area inside the printed border, world units: what the inside shows through. */\nexport function faceOf(G: MiniMatGeometry): Rect {\n const hx = Math.max(G.half[0] - G.margin, 1e-3);\n const hy = Math.max(G.half[1] - G.margin, 1e-3);\n return { x: G.centre[0] - hx, y: G.centre[1] - hy, width: 2 * hx, height: 2 * hy };\n}\n\nexport type MiniMatHit = \"face\" | \"border\" | \"outside\";\n/** What is under a world point: the face (the inside's window), the border (the sheet round it), or nothing. */\nexport function pickMiniMat(G: MiniMatGeometry, wx: number, wy: number): MiniMatHit {\n if (sdMiniMat(G, wx, wy) >= 0) return \"outside\";\n const F = faceOf(G);\n return wx >= F.x && wx <= F.x + F.width && wy >= F.y && wy <= F.y + F.height ? \"face\" : \"border\";\n}\n\n/** How far the shadow can reach past the sheet, world units — the vertex quad's pad (the slab's sweep and its penumbra). */\nexport function shadowReach(G: MiniMatGeometry, law: MiniMatLaw = DEFAULT_MINIMAT_LAW): number {\n const top = G.lift + G.thick;\n const p = law.shadow.penumbra;\n return Math.hypot(G.slope[0], G.slope[1]) * top + 2.5 * (p.sigma0 + p.sigmaPerHeight * top) + 2.5 * law.shadow.contact.sigma;\n}\n\n/** The face on screen under a camera — the portal's clip. */\nexport const faceClip = (G: MiniMatGeometry, cam: CameraState): PortalClip => clipOf(faceOf(G), MINIMAT.faceRadius, cam);\n\n// ---------------------------------------------------------------- the far LOD (MINIMAT.md §5)\n\n/** The lattice a face shows at the far LOD — the inside's three rungs, their presences and half-widths. */\nexport interface FaceLattice {\n /** Fine, mid, coarse spacing, inside units. */\n readonly rungs: readonly [number, number, number];\n /** Each rung's line presence. */\n readonly weights: readonly [number, number, number];\n /** Each rung's line half-width, DEVICE px. */\n readonly widths: readonly [number, number, number];\n}\n\n/**\n * The lattice a face draws at the far LOD: the inside's three rungs at the zoom it is seen at\n * (`insideZoom` — M.s × the host camera's zoom: the live inside's own camera zoom), each rung's\n * line weight by the mat's line law under the fade-in window DRESSED for the inside's arrival\n * (`lodZoom`, floored — mat/grid.ts `dressScale`), exactly as the live inside dresses its mat —\n * so the face and the live inside draw the same lines, and the one fades into the other unseen.\n */\nexport function faceLattice(insideZoom: number, fadeIn: FadeIn, law: LineLaw, lodZoom?: number): FaceLattice {\n const s = dressScale(insideZoom, lodZoom);\n const win: FadeIn = s === 1 ? fadeIn : [fadeIn[0] * s, fadeIn[1] * s];\n const l = lod({ camX: 0, camY: 0, zoom: insideZoom, width: 1, height: 1 });\n const w = [l.fine, l.mid, l.coarse].map((sp) => lineWeight(sp * insideZoom, win, law));\n const at = (i: number) => w[i] as { readonly halfWidth: number; readonly alpha: number };\n return { rungs: [l.fine, l.mid, l.coarse], weights: [at(0).alpha, at(1).alpha, at(2).alpha], widths: [at(0).halfWidth, at(1).halfWidth, at(2).halfWidth] };\n}\n\n/**\n * The finishes a mini mat's face draws its chips in (K8a — its `faceLaw`, the kit's shared vocabulary: never the children's kind\n * names): `paper` — a sheet in the chip's colour, its writing greeked; `vinyl` — grained vinyl with its frame line at the chip's margin.\n */\nexport const MINIMAT_FINISHES: readonly ChipFinish[] = [PAPER_FINISH, VINYL_FINISH];\n\n/** The most lines of a note's writing a chip greeks. */\nexport const CHIP_LINES = 6;\n\n/** A chip as the pass takes it: the child mapped into the HOST's world through the inside's embedding `M` (host = o + child · s). */\nexport interface Chip {\n /** The finish it is drawn in — one of the mini mat's own (`MINIMAT_FINISHES`), the builder's pick among the child's. */\n readonly finish: ChipFinish;\n readonly centre: readonly [number, number];\n readonly half: readonly [number, number];\n readonly cos: number; readonly sin: number;\n readonly radius: number;\n readonly colour: RGB;\n readonly height: number;\n /** Greeked lines in the chip's own frame, host units: x from, x to, the stroke's centre y — at most CHIP_LINES. */\n readonly lines: readonly (readonly [number, number, number])[];\n /** The lines' stroke half-thickness, host units, and their ink. */\n readonly stroke: number;\n readonly ink: RGB;\n /** A mini mat chip's border, host units. */\n readonly margin: number;\n}\n\n/** A child through the embedding: its footprint scaled by `M.s` about the host's origin; a note's lines greeked at `weight` × the line pitch (MINIMAT.chips). */\nexport function chipOf(c: ChildShape, M: PortalAffine, weight: number = MINIMAT.chips.greekWeight): Chip {\n const s = M.s;\n const w = c.writing;\n const hx = c.hx * s;\n const hy = c.hy * s;\n const lines: [number, number, number][] = [];\n let stroke = 0;\n if (w?.lines.length) {\n // the note's frame is its top-left in note units; the chip's is its centre in host units. A line's\n // stroke sits on the x-height's middle (0.32 em over the baseline — a hand's x-height is ~0.45 em).\n stroke = 0.5 * weight * w.em * s;\n for (const L of w.lines.slice(0, CHIP_LINES)) {\n if (!(L.width > 0.5)) continue;\n lines.push([(w.x0 - c.hx) * s, (w.x0 + L.width - c.hx) * s, (L.y - 0.32 * w.em - c.hy) * s]);\n }\n }\n return {\n finish: typeof c.finish === \"string\" ? c.finish : (c.finish[0] ?? PAPER_FINISH), centre: [M.ox + c.cx * s, M.oy + c.cy * s], half: [hx, hy], cos: Math.cos(c.angle), sin: Math.sin(c.angle),\n radius: c.radius * s, colour: c.colour, height: c.height * s, lines, stroke, ink: w?.ink ?? c.colour, margin: (c.margin ?? 0) * s,\n };\n}\n\n// ---------------------------------------------------------------- the print's words (MINIMAT.md §2)\n\n/** The most characters of a NAME the border prints. */\nexport const NAME_CHARS = 32;\n\n/** A name as the atlas's glyph indices (mat/layout.ts `GLYPHS`): capitals, a letter it lacks printed as a space; at most NAME_CHARS. */\nexport function nameGlyphs(name: string, glyphs: string = GLYPHS): number[] {\n const space = glyphs.indexOf(\" \");\n return [...name.toUpperCase()].slice(0, NAME_CHARS).map((ch) => { const i = glyphs.indexOf(ch); return i >= 0 ? i : space; });\n}\n\n/**\n * Glyph indices packed four to a float (6 bits each, base 64 — an integer under 2²⁴, exact in\n * an f32), NAME_CHARS / 4 floats: what the record's `name` carries. The shader unpacks slot k\n * as `(u32(f[k / 4]) >> (6 · (k % 4))) & 63`.\n */\nexport function packGlyphs(indices: readonly number[]): number[] {\n const out = new Array<number>(NAME_CHARS / 4).fill(0);\n indices.slice(0, NAME_CHARS).forEach((g, k) => { out[k >> 2] = (out[k >> 2] as number) + (g & 63) * 64 ** (k & 3); });\n return out;\n}\n\n/** Which rung of the face's lattice the ruler numbers, and how: its spacing (inside units), the label's `mult · 10^exp` per site index, and the presence of the sites it numbers that the next rung does not. */\nexport interface Numerals { readonly spacing: number; readonly mult: number; readonly exp: number; readonly fade: number }\n\n/**\n * The ruler's numerals at the zoom the inside is seen at (`insideZoom`): the finest of the face's rungs\n * whose sites are `from[0]` CSS px apart on screen, its own sites fading in by `from` and every tenth\n * (the next rung's) at full — the rulers' law (RULER.md), on three rungs. A spacing is 2·10^k (lod.ts),\n * so a site's value is `index · 2 · 10^k`. Null = no rung is far enough apart to number.\n */\nexport function numeralsOf(L: FaceLattice, insideZoom: number, from: readonly [number, number]): Numerals | null {\n for (const spacing of L.rungs) {\n const pitch = spacing * insideZoom;\n if (pitch < from[0]) continue;\n const exp = Math.round(Math.log10(spacing / 2));\n const t = Math.min(Math.max((pitch - from[0]) / Math.max(from[1] - from[0], 1e-6), 0), 1);\n return { spacing, mult: 2, exp, fade: t * t * (3 - 2 * t) };\n }\n return null;\n}\n\n/** Is a chip worth drawing at a zoom — its short side at least `minPx` CSS px? */\nexport const chipVisible = (ch: Chip, zoom: number, minPx: number = MINIMAT.chips.minPx): boolean => 2 * Math.min(ch.half[0], ch.half[1]) * zoom >= minPx;\n","// A mini mat's INSIDE as a host sees it (MINIMAT.md §3–§5) — pure: no GPU. The\n// lab and the Node oracle both build their frames through these, so the two\n// hosts agree on every number a still is made of.\n//\n// insideView the embedding (the flight's own: the inside's arrival fitted\n// to the face — `portalAffine`), the camera the inside renders\n// under at the host's camera (`outgoingCamera`), its face on\n// screen, and the gate's answer — ALWAYS, past the gate or not:\n// the far LOD draws the face on the same embedding.\n// miniMatInstance what the mini mat pass takes: the geometry, the vinyl, the\n// embedding with the lattice the live inside would draw, the chips.\n//\n// The view through ANY container's face — `insideViewOfFace` — the live inside's presentation, a flight's presentations and\n// the lamps it hands between the two desks are the kit's since K4b (kit/inside.ts): the builder nests every container by them.\n\nimport { type GridConfig, type CameraState, FIT, type FitBand, PORTAL_GATE, type Rect, type Viewport, type InsideView, insideViewOfFace } from \"@ice/desk/kit\";\nimport type { MiniMatInstance } from \"./layout\";\nimport { type Chip, DEFAULT_MINIMAT_LAW, faceLattice, faceOf, type MiniMatGeometry, type MiniMatLaw, numeralsOf } from \"./minimat\";\nimport { MINIMAT } from \"./theme\";\n\n\n/**\n * A mini mat's inside under the host camera `cam`: `content` the bounds of the inside (null = empty\n * — it arrives on its origin at zoom 1). The arrival and the embedding are the flight's own\n * (`arrivalCamera`, `portalAffine` on the same inputs), so a live inside rendered under `cam` IS the\n * flight's first frame. Null only for a face with no area.\n */\nexport function insideView(G: MiniMatGeometry, content: Rect | null, cam: CameraState, vp: Viewport, fit: FitBand = FIT, gate: readonly [number, number] = PORTAL_GATE): InsideView | null {\n return insideViewOfFace(faceOf(G), MINIMAT.faceRadius, content, cam, vp, fit, gate);\n}\n\n/**\n * What the pass takes for one mini mat: `grid` is the INSIDE's (its fade-in and its line law — the\n * face's far-LOD lattice is the live inside's, dressed for its arrival when `dress`; its vinyl — the\n * inside's mat is the same vinyl, `grid.mat.ground`), `name` what its foot prints; the ruler numbers\n * the rung the law says at the inside's zoom.\n */\nexport function miniMatInstance(G: MiniMatGeometry, view: InsideView, grid: GridConfig, chips: readonly Chip[], name?: string, dress = true, law: MiniMatLaw = DEFAULT_MINIMAT_LAW): MiniMatInstance {\n const lattice = faceLattice(view.cam.zoom, grid.fadeIn, grid.mat.line, dress ? view.arrival.zoom : undefined);\n return { geometry: G, ground: grid.mat.ground, grain: grid.mat.grain, inside: { M: view.M, lattice }, chips, numerals: numeralsOf(lattice, view.cam.zoom, law.print.labelsFrom), ...(name ? { name } : {}) };\n}\n","// The mini mat pass's GPU records, declared once (MINIMAT.md §6). `MiniMat` is\n// one mini mat as drawn — what `resolveMiniMat` returns, its vinyl, the inside's\n// embedding and the lattice its face shows at the far LOD, the live inside's\n// presence and its range of chips; `Chip` is one child as the face draws it\n// small; `MiniMatUniforms` the pass's own knobs. The camera, the light, the gobo\n// and the portal chain arrive through the mat's block (`MatUniforms`), which the\n// pass fills for itself so a mini mat is lit exactly as the desk it lies on.\n\nimport { defineStruct } from \"@ice/desk/engine\";\nimport { type PortalAffine, type GlyphAtlasMeta, VINYL_FINISH } from \"@ice/desk/kit\";\nimport type { RGB } from \"@ice/desk\";\nimport { CHIP_LINES, type Chip, type FaceLattice, type MiniMatGeometry, type MiniMatLaw, NAME_CHARS, nameGlyphs, type Numerals, packGlyphs } from \"./minimat\";\n\n// vec2s first, then scalars, then vec4s: tight under the alignment rules.\nexport const MiniMat = defineStruct(\"MiniMat\", [\n [\"centre\", \"vec2f\"], [\"half\", \"vec2f\"],\n [\"slope\", \"vec2f\"], // the shadow's ground offset per unit of height, world axes\n [\"lamp\", \"vec2f\"], // the lamp's ground direction (unit), world axes — what the cut edge catches\n [\"radius\", \"f32\"], [\"margin\", \"f32\"], [\"lift\", \"f32\"], [\"thick\", \"f32\"],\n [\"alpha\", \"f32\"], [\"ring\", \"f32\"],\n [\"live\", \"f32\"], // the live inside over the face: −1 none (the face draws its far LOD), else its objects' presence — the chips fade over it by 1 − that\n [\"lampZ\", \"f32\"], // the lamp's elevation (the unit direction's z)\n [\"chipFirst\", \"u32\"], [\"chipCount\", \"u32\"],\n [\"nameLen\", \"f32\"], [\"pad0\", \"f32\"],\n [\"ground\", \"vec4f\"], // the vinyl's colour (sRGB), the grain's amplitude\n [\"inside\", \"vec4f\"], // the inside's embedding M (host = o + inside · s): s, ox, oy; unused\n [\"rungs\", \"vec4f\"], // the inside's lattice at this zoom: fine, mid, coarse spacing (inside units); unused\n [\"weights\", \"vec4f\"], // each rung's line presence (fine, mid, coarse), dressed as the live inside dresses it; unused\n [\"widths\", \"vec4f\"], // each rung's line half-width, DEVICE px; unused\n [\"numerals\", \"vec4f\"], // the ruler's numbered rung (minimat.ts `numeralsOf`): spacing (inside units), mult, exp, the fade of its own sites — spacing 0 = none\n [\"name\", `array<vec4f, ${NAME_CHARS / 16}>`], // the NAME's glyph indices, four to a float (minimat.ts `packGlyphs`)\n] as const);\n\nexport const ChipRecord = defineStruct(\"Chip\", [\n [\"centre\", \"vec2f\"], [\"half\", \"vec2f\"],\n [\"rot\", \"vec2f\"], // cos, sin of the tilt\n [\"radius\", \"f32\"], [\"kind\", \"f32\"], // the corner; 0 a sheet of paper, 1 a mini mat\n [\"colour\", \"vec4f\"], // the chip's colour (sRGB), its height off the face (host units)\n [\"ink\", \"vec4f\"], // the writing's ink (sRGB), the greeked stroke's half-thickness (host units)\n [\"frame\", \"vec4f\"], // a mini mat chip's border (host units), the line count, unused ×2\n [\"lines\", `array<vec4f, ${CHIP_LINES}>`], // per greeked line, in the chip's frame (host units): x from, x to, the stroke's y, unused\n] as const);\n\nexport const MiniMatUniforms = defineStruct(\"MiniMatUniforms\", [\n [\"print\", \"vec4f\"], // presences: the frame round the face, the ticks and the words; unused; the print's line width (world units)\n [\"ticks\", \"vec4f\"], // the ticks' lengths — minor, medium, major (world units); unused\n [\"edge\", \"vec4f\"], // the cut edge's bevel: width (world units), light, dark; the ring's width (CSS px)\n [\"shadow\", \"vec4f\"], // the penumbra: σ at contact, σ per unit of height, alpha; the contact term's alpha\n [\"shadow2\", \"vec4f\"], // the contact term's σ and the gap it fades over (world); the greeked lines' presence; the chips' least size (CSS px)\n [\"cream\", \"vec4f\"], // the print's ink (MAT.line, sRGB); the greeking's onset (CSS px of chip height)\n [\"castTint\", \"vec4f\"], // what a shadow is made of by day (MAT.cast, sRGB), unused — `cast` is a WGSL reserved word\n [\"select\", \"vec4f\"], // --vf-select (the ring), unused\n [\"digits\", \"vec4f\"], // the numerals: cap (world units), gap after the tick, the cap's top in from the sheet's edge; unused\n [\"text\", \"vec4f\"], // the name's cap, its tracking (em), legible from · to (CSS px of cap)\n [\"atlas\", \"vec4f\"], // the glyph atlas (RULER.md): cell width, cell height, advance, baseline (texels)\n [\"atlas2\", \"vec4f\"], // its cap (texels), width, height (texels), glyph count\n] as const);\n\nexport const MAX_MINIMATS = 256;\nexport const MAX_CHIPS = 4096;\n\n/** One mini mat for the pass: its geometry, its vinyl, its inside's embedding and lattice, the live inside's presence, its chips. */\nexport interface MiniMatInstance {\n readonly geometry: MiniMatGeometry;\n /** The vinyl (sRGB) — the mat's own sage unless the host says. */\n readonly ground: RGB;\n /** The grain's amplitude on the vinyl (theme.ts `MAT_GRID.grain`). */\n readonly grain: number;\n /** The inside's embedding (host = o + inside · s) and the lattice the face shows on it. */\n readonly inside: { readonly M: PortalAffine; readonly lattice: FaceLattice };\n /** The live inside over the face: absent or −1 = none (the face is the mini mat's own drawing), else its objects' presence 0..1. */\n readonly live?: number | undefined;\n /** The children as the face draws them small (the far LOD), in the host's world. */\n readonly chips?: readonly Chip[] | undefined;\n /** The name printed in the foot of the border (capitals; minimat.ts `nameGlyphs`). */\n readonly name?: string | undefined;\n /** The rung the ruler numbers (minimat.ts `numeralsOf`); absent = none. */\n readonly numerals?: Numerals | null | undefined;\n}\n\nexport function miniMatValues(m: MiniMatInstance, chipFirst: number, chipCount: number) {\n const G = m.geometry;\n const M = m.inside.M;\n const L = m.inside.lattice;\n const lz = G.lamp[2];\n const lxy = Math.hypot(G.lamp[0], G.lamp[1]);\n return {\n centre: G.centre, half: G.half, slope: G.slope,\n lamp: lxy > 1e-9 ? [G.lamp[0] / lxy, G.lamp[1] / lxy] : [0, 0],\n radius: G.radius, margin: G.margin, lift: G.lift, thick: G.thick,\n alpha: G.alpha, ring: G.ring, live: m.live === undefined || m.live < 0 ? -1 : Math.min(m.live, 1), lampZ: lz,\n chipFirst, chipCount,\n ground: [m.ground[0], m.ground[1], m.ground[2], m.grain],\n inside: [M.s, M.ox, M.oy, 0],\n rungs: [...L.rungs, 0], weights: [...L.weights, 0], widths: [...L.widths, 0],\n numerals: m.numerals ? [m.numerals.spacing, m.numerals.mult, m.numerals.exp, m.numerals.fade] : [0, 0, 0, 0],\n nameLen: m.name ? Math.min([...m.name].length, NAME_CHARS) : 0,\n name: m.name ? packGlyphs(nameGlyphs(m.name)) : new Array<number>(NAME_CHARS / 4).fill(0),\n };\n}\n\nexport function chipValues(c: Chip) {\n const lines = new Array<number>(4 * CHIP_LINES).fill(0);\n c.lines.slice(0, CHIP_LINES).forEach((l, i) => { lines[4 * i] = l[0]; lines[4 * i + 1] = l[1]; lines[4 * i + 2] = l[2]; });\n return {\n centre: c.centre, half: c.half, rot: [c.cos, c.sin], radius: c.radius, kind: c.finish === VINYL_FINISH ? 1 : 0,\n colour: [c.colour[0], c.colour[1], c.colour[2], c.height],\n ink: [c.ink[0], c.ink[1], c.ink[2], c.stroke],\n frame: [c.margin, Math.min(c.lines.length, CHIP_LINES), 0, 0],\n lines,\n };\n}\n\n/** The knobs from the law, the colours the pass is handed and the glyph atlas it prints with. */\nexport function miniMatUniformValues(law: MiniMatLaw, colours: { readonly cream: RGB; readonly cast: RGB; readonly select: RGB }, glyphs: GlyphAtlasMeta) {\n const p = law.print;\n const sh = law.shadow;\n return {\n print: [p.frame, p.tick, 0, p.width],\n ticks: [p.ticks[0], p.ticks[1], p.ticks[2], 0],\n edge: [law.edge.width, law.edge.light, law.edge.dark, law.ring],\n shadow: [sh.penumbra.sigma0, sh.penumbra.sigmaPerHeight, sh.penumbra.alpha, sh.contact.alpha],\n shadow2: [sh.contact.sigma, sh.contact.reach, law.chips.greekAlpha, law.chips.minPx],\n cream: [colours.cream[0], colours.cream[1], colours.cream[2], law.chips.greekPx],\n castTint: [colours.cast[0], colours.cast[1], colours.cast[2], 0],\n select: [colours.select[0], colours.select[1], colours.select[2], 0],\n digits: [p.digits.cap, p.digits.gap, p.digits.top, 0],\n text: [p.name.cap, p.name.tracking, p.legible[0], p.legible[1]],\n atlas: [glyphs.cellW, glyphs.cellH, glyphs.advance, glyphs.baseline],\n atlas2: [glyphs.cap, glyphs.width, glyphs.height, glyphs.count],\n };\n}\n","// The mini mat pass (MINIMAT.md §6) — the desk's containers, instanced, drawn in\n// paint order in ranges (a live inside is drawn between them, right after its\n// mini mat — ground.ts `drawSlot`). Owns its copy of the mat's uniform block\n// (filled for the slot's camera and light every frame, so a mini mat takes the\n// dapple of the desk it lies on), its knobs, the per-mini-mat records and the\n// chips — every mini mat's children drawn small on its face at the far LOD,\n// packed back to back, each mini mat naming its range. Shares, with every slot\n// spawned from the first, the pipeline and the samplers; reads its OWN slot's\n// animated silhouette (the wind target), as every object pass does.\n\nimport { bindGroup, bindLayout, renderPipeline, uniformBuffer, compile, compose } from \"@ice/desk/engine\";\nimport { createRecordStore, type RecordStore, MAT_COLORS, type RGB } from \"@ice/desk\";\nimport { type FadeIn, type View, type MatConfig, type MatFrame, type SlotLight, type MatPass, type Presentation, DAY_LIGHT, type MatLight, sentBytes, writeChanged } from \"@ice/desk/kit\";\nimport { ChipRecord, chipValues, MAX_CHIPS, MAX_MINIMATS, MiniMat, type MiniMatInstance, MiniMatUniforms, miniMatUniformValues, miniMatValues } from \"./layout\";\nimport { DEFAULT_MINIMAT_LAW, type MiniMatLaw } from \"./minimat\";\nimport type { MiniMatShaders } from \"./shaders\";\n\n/** Premultiplied \"source over\" — every desk object's blend. */\nconst BLEND_PREMUL: GPUBlendState = {\n color: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n alpha: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n};\n\ninterface MiniMatShared {\n readonly layout: GPUBindGroupLayout;\n /** The mini mats (`fs`) — and their chips again, over a live inside that is fading in (`fs_chips`). */\n readonly pipeline: GPURenderPipeline;\n readonly chipsPipeline: GPURenderPipeline;\n readonly goboSampler: GPUSampler;\n readonly noiseSampler: GPUSampler;\n slots: number;\n}\n\n/** Chips a mini mat's record may name — its BLOCK in the chips buffer (engine/records.ts; the law's `chips.max` caps within it). */\nexport const CHIPS_PER_MAT = MAX_CHIPS / MAX_MINIMATS;\n/** Mini mat slots a pass starts with (a desk seldom shows more; the store doubles past it). */\nconst SLOTS_AT_START = 64;\n\nexport class MiniMatPass {\n readonly name = \"minimat/mats\";\n private readonly knobs = MiniMatUniforms.alloc(1);\n /** The mini mats' PERSISTENT records and their chips (engine/records.ts, design-015 §4.3; D6): a slot per mini mat while drawn, its chips a fixed block, written when it changed. */\n private readonly store: RecordStore<MiniMatInstance>;\n /** The records the last prepare turned away at the pass's cap — not drawn; the ground reports them (`GroundStats.dropped`, D7). */\n dropped = 0;\n private readonly knobBuf: GPUBuffer;\n /** What the GPU holds of the knobs: they are written only when they change (K4a — a standing value costs a frame nothing). */\n private readonly knobsSent = sentBytes(MiniMatUniforms.size);\n private group!: GPUBindGroup;\n private boundAssets = -1;\n private boundStore = -1;\n private count = 0;\n private chipsUsed = 0;\n private lawNow: MiniMatLaw = DEFAULT_MINIMAT_LAW;\n /** The mini mat's numbers (theme.ts `MINIMAT`) — the print, the edge, the shadow, the chips. A host tweaks the root's; every slot copies it. A new law repacks every record (the chips' cap is packed). */\n get law(): MiniMatLaw { return this.lawNow; }\n set law(next: MiniMatLaw) { if (next !== this.lawNow) { this.lawNow = next; this.store.invalidate(); } }\n private readonly device: GPUDevice;\n private readonly shared: MiniMatShared;\n private readonly mat: MatPass;\n\n private constructor(device: GPUDevice, shared: MiniMatShared, mat: MatPass) {\n this.device = device; this.shared = shared; this.mat = mat;\n shared.slots += 1;\n this.knobBuf = uniformBuffer(device, MiniMatUniforms.size, \"minimat/knobs\");\n // a mini mat's chips are its block: the law's cap within `CHIPS_PER_MAT`; the live inside's presence is the `aux` folded in\n this.store = createRecordStore<MiniMatInstance, keyof typeof MiniMat.slots, keyof typeof ChipRecord.slots>({\n device, def: MiniMat, capacity: SLOTS_AT_START, max: MAX_MINIMATS * 64, label: \"minimat/mats\",\n blocks: { def: ChipRecord, per: CHIPS_PER_MAT, label: \"minimat/chips\" },\n pack: (m, live, into, slot, blocks, base) => {\n const chips = m.chips ?? [];\n const take = Math.max(0, Math.min(chips.length, this.lawNow.chips.max, CHIPS_PER_MAT));\n if (blocks !== null) for (let j = 0; j < take; j++) blocks.set(chipValues(chips[j] as (typeof chips)[number]), base + j);\n into.set(miniMatValues({ ...m, live }, base, take), slot);\n return take;\n },\n });\n this.rebind();\n }\n\n /** The root's pass, on the root's mat. */\n static async create(device: GPUDevice, format: GPUTextureFormat, src: MiniMatShaders, mat: MatPass): Promise<MiniMatPass> {\n const layout = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 2, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n { binding: 3, stages: [\"fragment\"], buffer: \"read-only-storage\" },\n { binding: 4, stages: [\"fragment\"], texture: \"float\" },\n { binding: 5, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 6, stages: [\"fragment\"], texture: \"float\" },\n { binding: 7, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 8, stages: [\"fragment\"], texture: \"float\" },\n { binding: 9, stages: [\"vertex\"], buffer: \"read-only-storage\" }, // the draw list: paint index → record slot (D6)\n ], \"minimat/mats\");\n const module = await compile(device, compose(src));\n const pl = device.createPipelineLayout({ bindGroupLayouts: [layout] });\n const [pipeline, chipsPipeline] = await Promise.all([\n renderPipeline(device, { label: \"minimat/mats\", layout: pl, module, format, blend: BLEND_PREMUL }),\n renderPipeline(device, { label: \"minimat/chips over\", layout: pl, module, fragment: \"fs_chips\", format, blend: BLEND_PREMUL }),\n ]);\n const shared: MiniMatShared = {\n layout, pipeline, chipsPipeline,\n goboSampler: device.createSampler({ label: \"minimat/gobo\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" }),\n noiseSampler: device.createSampler({ label: \"minimat/noise\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\" }),\n slots: 0,\n };\n return new MiniMatPass(device, shared, mat);\n }\n\n /** A second slot on the same pipeline, reading ITS mat's silhouette — a flight's departed desk, a mini mat's inside. */\n spawn(mat: MatPass): MiniMatPass { const p = new MiniMatPass(this.device, this.shared, mat); p.law = this.law; return p; }\n\n /** Copy the root's tuning — what every slot takes each frame. */\n tune(from: MiniMatPass): void { this.law = from.law; }\n\n private rebind(): void {\n if (this.boundAssets === this.mat.assetVersion && this.boundStore === this.store.version) return;\n const s = this.shared;\n // the glyph atlas the rulers print with (RULER.md) — the numerals and the name are the same mono face; sampled with the gobo's clamp\n this.group = bindGroup(this.device, s.layout, [this.mat.view, this.knobBuf, this.store.records, this.store.blocks as GPUBuffer, this.mat.silhouette, s.goboSampler, this.mat.noiseTexture.createView(), s.noiseSampler, this.mat.glyphTexture.createView(), this.store.order], \"minimat/mats\");\n this.boundAssets = this.mat.assetVersion;\n this.boundStore = this.store.version;\n }\n\n /**\n * Upload this frame's mini mats in paint order, their chips back to back (a mini mat's\n * beyond the law's cap, or past the buffer, are dropped — the face shows fewer, honestly),\n * and the mat's block for this slot's camera and light (`light` the Sun or the Moon, `lit`\n * the lamp it is seen by — MINIMAT.md §4). `live` is the ground's word on each one's live\n * inside — −1 where none is drawn this frame, else its objects' presence — overriding the\n * instance's own (a portal the ground could not draw leaves the face to the far LOD).\n * Returns the count that will draw.\n */\n prepare(view: View & { readonly dpr: number }, fadeIn: FadeIn, cfg: MatConfig, frame: MatFrame | undefined, instances: readonly MiniMatInstance[], present: Presentation | undefined, light: MatLight = DAY_LIGHT, select: RGB = [0, 0, 0], lit?: SlotLight, live?: (index: number) => number, keys?: readonly number[]): number {\n const cap = MAX_MINIMATS * 64;\n const list = instances.length > cap ? instances.slice(0, cap) : instances;\n this.dropped = instances.length - list.length;\n // the store (D6): a mini mat keyed by `keys[i]` keeps its slot (and its chips' block) and is written only when its record or its\n // live inside's presence changed; no keys = every one packed afresh. The ground's word on the live inside overrides the instance's.\n const n = this.store.prepare(list, keys !== undefined && keys.length > cap ? keys.slice(0, cap) : keys, (i) => { const m = list[i] as MiniMatInstance; const pres = live ? live(i) : (m.live ?? -1); return pres < 0 ? -1 : Math.min(pres, 1); });\n this.rebind(); // after: the store's buffers may have grown\n let used = 0;\n for (let i = 0; i < n; i++) used += this.store.entryAt(i).blockN;\n this.count = n; this.chipsUsed = used;\n this.knobs.set(miniMatUniformValues(this.law, { cream: MAT_COLORS.line, cast: MAT_COLORS.cast, select }, this.mat.glyphs));\n writeChanged(this.device.queue, this.knobBuf, this.knobs, this.knobsSent);\n return n;\n }\n\n get drawn(): number { return this.count; }\n /** The chips drawn this frame, every mini mat's together. */\n get chips(): number { return this.chipsUsed; }\n /** The store's counters (a rig's witness): records written, bytes, draw-list writes, slots in use. */\n get records() { return this.store.stats(); }\n\n draw(pass: GPURenderPassEncoder): void { this.drawRange(pass, 0, this.count); }\n\n /** Mini mat `at`'s chips OVER its live inside, fading out as the inside's objects fade in — only while the objects are not whole (MINIMAT.md §5). */\n drawChips(pass: GPURenderPassEncoder, at: number): void {\n const ent = this.store.entryAt(at);\n const live = at < this.count ? ent.aux : -1;\n const n = ent.blockN;\n if (at >= this.count || !(live >= 0 && live < 1) || n === 0) return;\n pass.setPipeline(this.shared.chipsPipeline);\n pass.setBindGroup(0, this.group);\n pass.draw(6, 1, 0, at);\n }\n\n /** Mini mats [first, end) — paint order is the list's; `drawSlot` cuts the range where a live inside goes. */\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void {\n const hi = Math.min(end, this.count);\n if (first >= hi) return;\n pass.setPipeline(this.shared.pipeline);\n pass.setBindGroup(0, this.group);\n pass.draw(6, hi - first, 0, first);\n }\n\n dispose(): void {\n this.knobBuf.destroy(); this.store.dispose();\n this.shared.slots -= 1;\n }\n}\n","// Assemble the mini mat pass's program from the host's shader text — the browser's generated module, the Node oracle's\n// files on disk; byte-identical either way. The kit brings the slot's view block, the portal chain, the shared\n// primitives, the mat's light and the rulers' label arithmetic, which the numerals reuse (kit/wgsl.ts, by name); the\n// mini mat's own records, module and entry follow.\n\nimport type { ComposeOptions } from \"@ice/desk/engine\";\nimport { kitWgsl, type ShaderText } from \"@ice/desk/kit\";\nimport { ChipRecord, MiniMat, MiniMatUniforms } from \"./layout\";\n\n/** The mini mat's own shader files (the kit's pieces come by name). */\nexport const MINIMAT_SHADER_FILES = { minimat: \"minimat/minimat.wgsl\", minimatPass: \"minimat/minimat-pass.wgsl\" } as const;\n\n/** The mini mat pass's program: the kit's view · portal · sdf · light · ruler, then the mini mat's records, module and entry. */\nexport type MiniMatShaders = ComposeOptions;\n\nexport function miniMatShaders(text: ShaderText): MiniMatShaders {\n const t = text(MINIMAT_SHADER_FILES);\n return kitWgsl([\"view\", \"portal\", \"sdf\", \"light\", \"ruler\"], {\n structs: [MiniMatUniforms, MiniMat, ChipRecord],\n modules: [{ label: \"minimat/minimat.wgsl\", text: t.minimat }],\n entry: { label: \"minimat/minimat-pass.wgsl\", text: t.minimatPass },\n }, text);\n}\n","// GENERATED by tools/wgsl-to-ts.mjs from shaders/**/*.wgsl — do not edit.\n// `pnpm --filter @ice/objects gen:shaders` regenerates it; `gen:check` fails the gate when it is stale.\n// The .wgsl files are the source: the Node oracle reads them from disk and composes byte-identical text.\nexport const WGSL = {\n \"board/board-card.wgsl\": \"// The whiteboard as the board pass AND the flat-card pipeline draw it (K7b, design-016 §6 K7): the corner's clip position and\\n// the THUMBNAIL's ink, over the board's bindings by their own names — `boards`, `board_k`, `board_thumbs` … — beside the slot's\\n// `u`, `gobo_tex`, `noise_tex`, which whichever entry composes them declares. (Its fragment is the pass entry's `fs`, written\\n// out — the card splices the same statements, shaders.ts `BOARD_FRAGMENT`.) `shade_board` reads its ink\\n// through `board_ink` and the live board's layers through `board_stroke` / `board_wet`: the pass's entry reads the pool and\\n// the live layers there, else the thumbnail; the card binds neither and reads the thumbnail alone (a board with a raster, or\\n// being written on, is the pass's to draw).\\n\\n// The thumbnails' layer side (board-pass.ts `BOARD_THUMB`).\\nconst BOARD_THUMB = 512.0;\\n\\nconst BD_CORNERS = array<vec2f, 6>(\\n vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0),\\n vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0),\\n);\\n\\n// A board's ink at (uv, lod) from its THUMBNAIL — lod in its raster's chain: the layer (`tier.x`), which starts at the level k of\\n// its source's chain (`tier.y`) — the chain's tail at the layer's origin, its edge carried to the layer's — at lod − k.\\nfn board_thumb(B: Board, uv: vec2f, lod: f32) -> vec4f {\\n let k = B.tier.y;\\n let size = max(floor(B.texels / exp2(k)), vec2f(1.0));\\n return textureSampleLevel(board_thumbs, board_ink_samp, uv * size / BOARD_THUMB, i32(B.tier.x), max(lod - k, 0.0));\\n}\\n\\nfn board_quad(slot: u32, vid: u32) -> vec4f {\\n let B = boards[slot];\\n let zoom = max(u.cam.z, 1.0e-12);\\n let lo = (B.quad.xy - u.cam.xy) * zoom; // CSS px\\n let hi = (B.quad.zw - u.cam.xy) * zoom;\\n if (hi.x < u.box.x || hi.y < u.box.y || lo.x > u.box.x + u.box.z || lo.y > u.box.y + u.box.w) { return vec4f(2.0, 2.0, 2.0, 1.0); } // degenerate: a culled board collapses\\n let corner = BD_CORNERS[vid];\\n let pos = mix(lo, hi, corner * 0.5 + 0.5);\\n return vec4f(pos.x / u.view.x * 2.0 - 1.0, 1.0 - pos.y / u.view.y * 2.0, 0.0, 1.0);\\n}\\n\",\n \"board/board-pass.wgsl\": \"// The board pass — the whiteboards: one quad per board (its extent the record's own: the slab,\\n// its shadow, the tool in the hand — resolved on the CPU), one `shade_board` per covered\\n// fragment, premultiplied output over the mat. Group 0 is the slot's (the mat's block, the\\n// knobs, the records, the gobo, the noise, the samplers); group 1 is the SAME for every board\\n// (K6a, K-L4 — a run of boards is one instanced draw): the far-LOD thumbnails' array, the pool's\\n// rasters' ink (with mips), the live board's stroke and wet layers; a board's record says where\\n// its ink is (`tier`). The camera, the box and the portal chain come through the mat's block, as\\n// for the note and the notebook. The quad, the fragment and the thumbnail's ink are\\n// board-card.wgsl's — the flat-card pipeline draws a board with the same three (K7b).\\n\\n@group(0) @binding(0) var<uniform> u: MatUniforms;\\n@group(0) @binding(1) var<uniform> board_k: BoardUniforms;\\n@group(0) @binding(2) var<storage, read> boards: array<Board>;\\n@group(0) @binding(3) var gobo_tex: texture_2d<f32>; // the mat's animated silhouette (its wind target)\\n@group(0) @binding(4) var board_gobo_samp: sampler;\\n@group(0) @binding(5) var noise_tex: texture_2d<f32>;\\n@group(0) @binding(6) var board_noise_samp: sampler;\\n@group(0) @binding(7) var board_ink_samp: sampler; // trilinear — the ink seen small reads its mips\\n@group(0) @binding(8) var board_lin_samp: sampler; // bilinear, level 0 — the stroke and the wet layer\\n@group(0) @binding(9) var<storage, read> order: array<u32>; // the draw list: paint index → the record's slot (persistent records, D6)\\n@group(1) @binding(0) var board_thumbs: texture_2d_array<f32>; // every board's ink chain from its first level ≤ BOARD_THUMB², a layer each\\n@group(1) @binding(1) var ink0: texture_2d<f32>; // the pool: a board's raster — premultiplied linear ink, coverage in alpha\\n@group(1) @binding(2) var ink1: texture_2d<f32>;\\n@group(1) @binding(3) var ink2: texture_2d<f32>;\\n@group(1) @binding(4) var ink3: texture_2d<f32>;\\n@group(1) @binding(5) var ink4: texture_2d<f32>;\\n@group(1) @binding(6) var ink5: texture_2d<f32>;\\n@group(1) @binding(7) var ink6: texture_2d<f32>;\\n@group(1) @binding(8) var ink7: texture_2d<f32>;\\n@group(1) @binding(9) var stroke_live: texture_2d<f32>; // the live board's stroke being laid (r8)\\n@group(1) @binding(10) var wet_live: texture_2d<f32>; // …and how wet its ink still is (r8)\\n\\n// A board's ink at (uv, lod) — lod in its raster's chain. `tier`: its thumbnail's layer, the level of its source's chain the\\n// layer starts at (k), its pool slot (−1: none), live. The slot's raster, else the layer (board-card.wgsl `board_thumb`).\\nfn board_ink(B: Board, uv: vec2f, lod: f32) -> vec4f {\\n switch i32(B.tier.z) {\\n case 0: { return textureSampleLevel(ink0, board_ink_samp, uv, lod); }\\n case 1: { return textureSampleLevel(ink1, board_ink_samp, uv, lod); }\\n case 2: { return textureSampleLevel(ink2, board_ink_samp, uv, lod); }\\n case 3: { return textureSampleLevel(ink3, board_ink_samp, uv, lod); }\\n case 4: { return textureSampleLevel(ink4, board_ink_samp, uv, lod); }\\n case 5: { return textureSampleLevel(ink5, board_ink_samp, uv, lod); }\\n case 6: { return textureSampleLevel(ink6, board_ink_samp, uv, lod); }\\n case 7: { return textureSampleLevel(ink7, board_ink_samp, uv, lod); }\\n default: {}\\n }\\n return board_thumb(B, uv, lod);\\n}\\n\\n// The live board's stroke being laid, and how wet its ink is — 0 on any other board (their layers are not bound).\\nfn board_stroke(B: Board, uv: vec2f) -> f32 {\\n if (B.tier.w < 0.5) { return 0.0; }\\n return textureSampleLevel(stroke_live, board_lin_samp, uv, 0.0).r;\\n}\\nfn board_wet(B: Board, uv: vec2f) -> f32 {\\n if (B.tier.w < 0.5) { return 0.0; }\\n return textureSampleLevel(wet_live, board_lin_samp, uv, 0.0).r;\\n}\\n\\nstruct BoardOut {\\n @builtin(position) clip: vec4f,\\n @location(0) @interpolate(flat) idx: u32,\\n}\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> BoardOut {\\n var out: BoardOut;\\n out.idx = order[iid];\\n out.clip = board_quad(out.idx, vid);\\n return out;\\n}\\n\\n// The fragment, written out: shade_board reached through one more function compiles to one LSB off on a pixel or two a scene\\n// (K7b, measured) — so the flat-card pipeline splices THESE statements (shaders.ts `BOARD_FRAGMENT`, a test holds them equal).\\n@fragment\\nfn fs(in: BoardOut) -> @location(0) vec4f {\\n let B = boards[in.idx];\\n let zoom = max(u.cam.z, 1.0e-12);\\n let dpr = max(u.cam.w, 1.0);\\n let px = 1.0 / (zoom * dpr); // world per device px\\n let css = 1.0 / zoom; // world per CSS px\\n let p = in.clip.xy * px + u.cam.xy; // device px → world\\n let c = shade_board(B, u, board_k, p, px, css, in.clip.xy, gobo_tex, board_gobo_samp, noise_tex, board_noise_samp);\\n if (c.a < 0.002) { discard; }\\n // Premultiplied: the presentation's opacity through the portal clip scales every channel.\\n return c * (u.view.w * portal_cover(in.clip.xy / dpr, u.portals, u.clips, dpr));\\n}\\n\",\n \"board/board.wgsl\": \"// THE WHITEBOARD (BOARD.md) — a desk dry-erase board under the mat's one lamp. A PURE module:\\n// the record `Board`, the pass's knobs `BoardUniforms`, the mat's block `MatUniforms` and the\\n// textures arrive as parameters; it names no colour.\\n//\\n// The board is a slab on the mat: an aluminium frame round a melamine face recessed a hair\\n// below it. The camera is top-down, so the depth is the lamp's work, as for the note and the\\n// notebook: the slab casts its footprint along the lamp's ground slope from every height it\\n// spans, each blurred by its own height, with a contact shadow at its base; the frame's\\n// profile rolls at both rims — turned toward the lamp it brightens and glints, turned away it\\n// falls into shade; the frame's lip shades the melamine on the lamp's side. The melamine\\n// carries the ink raster — a filter laid into its albedo before the light, so the dapple\\n// crosses the drawing as it crosses the mat — its waviness, the ghost of old erasures, fresh\\n// ink's wet gloss, and a SHEEN: the window the lamp shines through, mirrored in the glossy face\\n// and seen by an eye over the board, so it lands on one part of it and slides as the pointer\\n// moves (the research whiteboard's room, reduced to the one bright thing a desk has over it).\\n// On the board lies a capped marker; while it is open, the tool in the hand is drawn at the\\n// pointer — its shadow meets its tip as it presses. The colour chain is the note's: the\\n// reference's grade on the sRGB byte by day, the eye's chain on its linear value by night.\\n\\nfn bd_cov(d: f32, px: f32) -> f32 { return clamp(0.5 - d / px, 0.0, 1.0); }\\nfn bd_line(d: f32, w: f32, px: f32) -> f32 { return bd_cov(d, px) - bd_cov(d + w, px); }\\nfn bd_erf(x: f32) -> f32 {\\n let s = sign(x);\\n let a = abs(x);\\n let t = 1.0 / (1.0 + 0.3275911 * a);\\n let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-a * a);\\n return s * y;\\n}\\n// Gaussian-blurred coverage — a shadow, straight out of the field.\\nfn bd_blur(d: f32, sigma: f32) -> f32 { return 0.5 - 0.5 * bd_erf(d / max(sigma * 1.4142136, 1.0e-4)); }\\n// Premultiplied \\\"src over dst\\\".\\nfn bd_over(src: vec4f, dst: vec4f) -> vec4f { return src + dst * (1.0 - src.a); }\\n// A world point raised `h` world units off the desk, in the projector's frame (the note's `paper_desk_at`).\\nfn bd_desk_at(u: MatUniforms, world: vec2f, h: f32) -> vec3f {\\n return vec3f(u.plane.x + world.x * u.plane.z, u.plane.w + h * u.plane.z, u.plane.y + world.y * u.plane.z);\\n}\\nfn bd_encode(c: vec3f) -> vec3f {\\n let x = clamp(c, vec3f(0.0), vec3f(1.0));\\n return mix(x * 12.92, 1.055 * pow(x, vec3f(1.0 / 2.4)) - 0.055, step(vec3f(0.0031308), x));\\n}\\n\\n// The chain, as the note's `paper_colour`: by day the reference's grade on the sRGB albedo — lit,\\n// the identity, so a configured byte is the drawn byte — or, at `chain` 1, through the mat's own\\n// double gamma; by night the eye's chain on the linear albedo, as the mat's; between, the cross-fade.\\nfn bd_colour(u: MatUniforms, albedo: vec3f, gobo: f32, noise: f32, chain: f32) -> vec3f {\\n let day = shade_mat(u, mix(albedo, srgb_to_linear(albedo), chain), gobo);\\n if (u.night.x <= 0.0) { return day; }\\n let night = night_mat(u, srgb_to_linear(albedo), gobo, noise);\\n if (u.night.x >= 1.0) { return night; }\\n return mix(day, night, u.night.x);\\n}\\n\\n// The lamp on a face (the notebook's `bk_lambert`): its fill, plus the lambert normalised so a\\n// flat face reads 1 and capped so a face turned toward a low lamp brightens only so far.\\nfn bd_lambert(n: vec3f, L: vec3f, k: BoardUniforms) -> f32 {\\n let d = max(dot(n, L), 0.0) / max(L.z, 0.05);\\n return k.light.x + (1.0 - k.light.x) * min(d, k.light.y);\\n}\\n\\n// A glint: the lamp mirrored by a face toward the eye straight above (Blinn's half vector).\\nfn bd_glint(n: vec3f, L: vec3f, power: f32) -> f32 {\\n return pow(max(dot(n, normalize(L + vec3f(0.0, 0.0, 1.0))), 0.0), power);\\n}\\n\\n// How bright a glint can be under the light in force: the Sun's, or the Moon's much less.\\nfn bd_lit(u: MatUniforms, k: BoardUniforms) -> f32 { return mix(1.0, k.light.w, clamp(u.night.x, 0.0, 1.0)); }\\n\\n// A rounded box's outward gradient, by central differences.\\nfn bd_grad(q: vec2f, half: vec2f, r: f32) -> vec2f {\\n let e = 0.35;\\n let g = vec2f(\\n sdf_round_box(q + vec2f(e, 0.0), half, r) - sdf_round_box(q - vec2f(e, 0.0), half, r),\\n sdf_round_box(q + vec2f(0.0, e), half, r) - sdf_round_box(q - vec2f(0.0, e), half, r));\\n let l = length(g);\\n return select(vec2f(0.0, -1.0), g / l, l > 1.0e-5);\\n}\\n\\n// ---- the shadows\\n\\n// A SLAB (a rounded box, `q` in its frame) whose underside is `bottom` and top `top` above the\\n// receiver: its footprint cast along the ground slope `S` from every height it spans — each\\n// blurred by its own height, the penumbra widening as the slab rises — the union as the max;\\n// with the contact shadow at its base while it rests, fading as it floats off. `grow` scales the\\n// penumbra's growth (the hand's tools cast sharper); `steps` samples the sweep — enough that the\\n// copies never show as steps under that penumbra.\\nfn bd_slab(q: vec2f, half: vec2f, r: f32, bottom: f32, top: f32, S: vec2f, k: BoardUniforms, grow: f32, steps: i32) -> f32 {\\n var sh = 0.0;\\n for (var i = 0; i < steps; i++) {\\n let h = mix(bottom, top, f32(i) / f32(steps - 1));\\n if (h <= 0.0) { continue; }\\n sh = max(sh, bd_blur(sdf_round_box(q - S * h, half, r), k.shadow.x + k.shadow.y * grow * h));\\n }\\n sh = sh * k.shadow.z;\\n let g = max(bottom, 0.0);\\n let con = bd_blur(sdf_round_box(q - S * min(g, 1.0) * 0.5, half, r), k.shadow2.x) * k.shadow.w * exp(-g / max(k.shadow2.y, 1.0e-3));\\n return max(sh, con);\\n}\\n\\n// ---- the marker\\n\\n// The tools in the hand cast in the sun's own sharpness — their penumbra grows at this share of the\\n// desk objects' rate, their umbra this much firmer — so the shadow of a hovering nib is a clear mark\\n// that slides to meet it as it presses: the one cue a hand draws by.\\nconst HAND_PENUMBRA = 0.35;\\nconst HAND_UMBRA = 1.35;\\n\\n// THE PEN seen from above, in its own frame: `m` = (u along it from the nib, w across). Its cap\\n// slides with `cap`: 0 = on the nib (the marker lying capped), 1 = posted on its back (in the\\n// hand), and between, travelling along the barrel as a hand uncaps and posts it. Its ends are\\n// ROUND — a domed cap, a round nib, a chamfered plug — so it reads as a moulded thing, not a\\n// cut-out. Returns its signed distance, the part the point is on (0 nib · 1 holder · 2 barrel ·\\n// 3 stripe · 4 cap · 5 end · 6 the cap's clip · 7 the cap's rim), the local radius, and where\\n// the point is on a rounded end (−1 … 0 toward the nib, 0 … 1 toward the back; 0 along the tube).\\nfn bd_pen(m: vec2f, cap: f32, nib: f32, k: BoardUniforms) -> vec4f {\\n let L = k.pen.x;\\n let R = k.pen.y;\\n let capL = k.pen.z;\\n let u = m.x;\\n let w = abs(m.y);\\n let nr = max(nib, 0.6);\\n let c0 = mix(-2.0, L - capL * 0.55, cap); // the cap: from … to\\n let c1 = c0 + capL;\\n let u0 = min(0.0, c0);\\n let u1 = max(L, c1);\\n var r = R;\\n var part = 2.0;\\n if (u < 3.2) { r = nr; part = 0.0; }\\n else if (u < 14.0) { r = mix(nr + 0.8, R * 0.76, smoothstep(3.2, 14.0, u)); part = 1.0; }\\n else if (u < 16.5) { r = R * 0.94; }\\n else if (u > 44.0 && u < 47.0) { part = 3.0; }\\n else if (u > L - 7.0) { r = R * 0.9; part = 5.0; }\\n if (u >= c0 && u <= c1) {\\n r = R + 0.9; part = 4.0;\\n // the rim at the cap's open end (toward the barrel while it is on, toward the nib once posted), the clip along its top\\n let atBack = u > c1 - 2.2;\\n let atFront = u < c0 + 2.2;\\n if (select(atFront, atBack, cap < 0.5)) { part = 7.0; }\\n else if (w < 1.15 && u > c0 + 6.0 && u < c1 - 7.0) { part = 6.0; }\\n }\\n // a rounded box in (u, w): the nearer end's rounding, never past the tube's own radius\\n let start = u < (u0 + u1) * 0.5;\\n let rc0 = select(nr, R + 0.9, c0 < 0.5);\\n let rc1 = select(2.4, R + 0.9, c1 > L - 0.5);\\n let rc = min(select(rc1, rc0, start), r);\\n let de = select(u - u1, u0 - u, start);\\n let dw = w - r;\\n let q = vec2f(de, dw) + vec2f(rc);\\n let d = length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0) - rc;\\n let s = select(clamp((u - (u1 - rc)) / max(rc, 1.0e-3), 0.0, 1.0), -clamp(((u0 + rc) - u) / max(rc, 1.0e-3), 0.0, 1.0), start);\\n return vec4f(d, part, r, s);\\n}\\n\\n// The pen's silhouette for its SHADOW: the same tube, its steps smoothed out — a shadow is soft,\\n// and a step in the radius (the nib's holder, the cap's lip) would print a line across it.\\nfn bd_pen_soft(m: vec2f, cap: f32, nib: f32, k: BoardUniforms) -> f32 {\\n let L = k.pen.x;\\n let R = k.pen.y;\\n let capL = k.pen.z;\\n let c0 = mix(-2.0, L - capL * 0.55, cap);\\n let c1 = c0 + capL;\\n let u0 = min(0.0, c0);\\n let u1 = max(L, c1);\\n let uu = clamp(m.x, u0, u1);\\n let capped = smoothstep(c0 - 3.0, c0 + 3.0, uu) * (1.0 - smoothstep(c1 - 3.0, c1 + 3.0, uu));\\n let tube = mix(max(nib, 0.6), R, smoothstep(0.0, 16.0, uu)) - 0.1 * R * smoothstep(L - 10.0, L - 4.0, uu);\\n let r = mix(tube, R + 0.9, capped);\\n return length(vec2f(m.x - uu, m.y)) - r;\\n}\\n\\n// Its colour at a point of it, seen from above: a tube lying on its side — its across-position\\n// turns the normal, and on a rounded end its along-position too; the lamp shades it and the\\n// gloss of moulded plastic glints on it; the part picks the material. The clip is a little\\n// half-round rod on the cap, lit on the lamp's side.\\nfn bd_marker_colour(u: MatUniforms, k: BoardUniforms, sd: vec4f, across: f32, axis: vec2f, perp: vec2f, ink: vec3f, L: vec3f, gobo: f32, noise: f32) -> vec3f {\\n var t = clamp(across / max(sd.z, 1.0e-3), -1.0, 1.0);\\n if (sd.y == 6.0) { t = clamp(across / 1.15, -1.0, 1.0) * 0.85; }\\n let s = sd.w;\\n var n = normalize(vec3f(perp * t + axis * s, sqrt(max(1.0 - t * t - s * s, 0.02))));\\n var albedo = k.barrel.rgb;\\n var gloss = 0.3;\\n if (sd.y == 0.0) { albedo = ink * 0.8; gloss = 0.0; } // the felt nib\\n else if (sd.y == 1.0) { albedo = k.barrel.rgb * 0.8; } // the tip's holder, a greyer plastic\\n else if (sd.y == 3.0) { albedo = ink; } // the stripe that names the ink\\n else if (sd.y == 4.0) { albedo = ink; gloss = 0.45; } // the cap\\n else if (sd.y == 5.0) { albedo = ink * 0.9; } // the end plug\\n else if (sd.y == 6.0) { albedo = mix(ink, k.barrel.rgb, 0.18); gloss = 0.7; } // the clip\\n else if (sd.y == 7.0) { albedo = ink * 0.7; } // the cap's rim\\n // a small round thing wants more modelling than a flat face: the lamp's fill is less on it\\n let lam = 0.32 + 0.68 * min(max(dot(n, L), 0.0) / max(L.z, 0.05), k.light.y);\\n albedo = albedo * pow(lam, 1.0 / 2.2);\\n let c = bd_colour(u, clamp(albedo, vec3f(0.0), vec3f(1.0)), gobo, noise, k.light.z);\\n // the gloss: the lamp's glint where it can land, and — where it cannot (a lamp along the axis\\n // has no mirror line on a tube) — the bright sky over the desk, a soft stripe along the top\\n let toward = L.xy / max(length(L.xy), 1.0e-4);\\n let sky = pow(max(dot(n, normalize(vec3f(toward * 0.35, 1.0))), 0.0), 18.0);\\n return c + vec3f((bd_glint(n, L, 40.0) + 0.3 * bd_glint(n, L, 8.0) + 0.55 * sky) * gloss * bd_lit(u, k) * mix(0.45, 1.0, gobo));\\n}\\n\\n// ---- the melamine's sheen\\n\\n// The window the lamp shines through, mirrored in the melamine and seen by an eye over the\\n// board: a soft disc of sky toward the lamp, high up; Schlick's Fresnel on melamine's f0. The\\n// eye rides the pointer (`B.sheen`), so the reflection slides as the hand moves.\\nfn bd_sheen(B: Board, k: BoardUniforms, p: vec2f, n: vec3f) -> f32 {\\n let eye = vec3f(B.centre + B.sheen * B.half, k.sheen.z * 2.0 * B.half.y);\\n let V = normalize(eye - vec3f(p, 0.0));\\n let R = reflect(-V, n);\\n let toward = B.lamp.xy / max(length(B.lamp.xy), 1.0e-4);\\n let W = normalize(vec3f(toward * 0.42, 0.91));\\n let w = smoothstep(cos(k.sheen.y), 1.0, dot(R, W));\\n let f = 0.045 + 0.955 * pow(1.0 - max(dot(n, V), 0.0), 5.0);\\n return w * w * (f / 0.045);\\n}\\n\\n// ---- the board\\n\\n// One board at a world point `p`: premultiplied colour. `px` is world units per DEVICE px, `css`\\n// world units per CSS px; `frag` the framebuffer pixel (the blue noise's key).\\nfn shade_board(B: Board, u: MatUniforms, k: BoardUniforms, p: vec2f, px: f32, css: f32, frag: vec2f,\\n gobo_tex: texture_2d<f32>, gobo_samp: sampler, noise_tex: texture_2d<f32>, noise_samp: sampler) -> vec4f {\\n let q = p - B.centre;\\n let L = B.lamp.xyz;\\n let S = B.slope;\\n let bn = textureSampleLevel(noise_tex, noise_samp, frag * u.noise.z + u.noise.xy, 0.0).rgb;\\n let dOut = sdf_round_box(q, B.half, B.radius);\\n var acc = vec4f(0.0);\\n // what a shadow is made of: the world's darkest value by day (the design's cast), the dark's own grey by night\\n let shadowInk = mix(k.castTint.rgb, bd_encode(u.eigengrau.xyz), clamp(u.night.x, 0.0, 1.0));\\n\\n // The slab's shadow on the mat, outside its footprint.\\n if (dOut > -px) {\\n let sh = bd_slab(q, B.half, B.radius, B.lift, B.lift + B.thick, S, k, 1.0, 6) * (1.0 - bd_cov(dOut, px));\\n acc = vec4f(shadowInk * sh, sh);\\n }\\n\\n let top = B.lift + B.thick; // the frame's top off the mat\\n let face = top - B.recess; // the melamine's\\n if (dOut < px) {\\n let cov = bd_cov(dOut, px);\\n let dIn = sdf_round_box(q, B.inner, B.innerR);\\n var col: vec3f;\\n if (dIn > 0.0) {\\n // THE FRAME — a rounded bar: across the band the rims roll away, outward at the edge,\\n // inward at the lip; brushed along its length; glinting where it turns to the lamp.\\n let t = clamp(dIn / max(dIn - dOut, 1.0e-4), 0.0, 1.0);\\n let e = 2.0 * t - 1.0;\\n // a half-round bar: the normal turns steadily across it, steepest at the rims\\n let theta = k.lip.w * sign(e) * pow(abs(e), 0.85);\\n let g = bd_grad(q, B.half, B.radius);\\n let n = normalize(vec3f(g * sin(theta), cos(theta)));\\n let along = dot(q, vec2f(-g.y, g.x));\\n let across = dot(q, g);\\n let brushed = (felt_noise(vec2f(along * 0.045, across * 2.2)) + 0.5 * felt_noise(vec2f(along * 0.13 + 7.0, across * 6.1))) * k.lip.z;\\n var albedo = B.metal.rgb + vec3f(brushed);\\n albedo = albedo * pow(bd_lambert(n, L, k), 1.0 / 2.2);\\n let gobo = sample_gobo(u, gobo_tex, gobo_samp, bd_desk_at(u, p, top), bn.z);\\n col = bd_colour(u, clamp(albedo, vec3f(0.0), vec3f(1.0)), gobo, bn.y, k.light.z);\\n // the metal: a tight glint where the bar turns the lamp to the eye, and a broad sheen round it\\n let lit = bd_lit(u, k) * mix(0.2, 1.0, gobo);\\n col += vec3f((bd_glint(n, L, 90.0) + 0.6 * bd_glint(n, L, 14.0)) * k.glint.x * lit);\\n // metal mirrors the sky: a face turned up and out catches it — the bar's shaded half is never dead\\n col += vec3f(0.06 * smoothstep(0.2, 1.0, n.z) * bd_lit(u, k));\\n } else {\\n // THE MELAMINE — the raster over it: uv across the face, the ink's mip by the screen's density.\\n let uv = (q + B.inner) / (2.0 * B.inner);\\n let lod = max(log2(max(B.density * px / max(B.scale, 1.0e-3), 1.0e-6)), 0.0);\\n var ink = board_ink(B, uv, lod); // (the entry's: where this board's ink is bound — K6a)\\n if (B.laying > 0.5) {\\n // the stroke being laid, shown as it will land\\n let sc = board_stroke(B, uv);\\n if (B.tool.w < 0.5) { ink = vec4f(ink.rgb * (1.0 - sc) + B.tool.rgb * sc, ink.a * (1.0 - sc) + sc); }\\n else { ink = ink * (1.0 - sc); }\\n }\\n let cov2 = ink.a;\\n var wet = 0.0;\\n if (B.wet > 0.5) { wet = board_wet(B, uv) * smoothstep(0.0, 0.3, cov2); }\\n\\n // the face's normal: a slow waviness, and the ink film standing a few microns proud of it\\n let dt = exp2(lod) / B.texels;\\n let ax = board_ink(B, uv + vec2f(dt.x, 0.0), lod).a - board_ink(B, uv - vec2f(dt.x, 0.0), lod).a;\\n let ay = board_ink(B, uv + vec2f(0.0, dt.y), lod).a - board_ink(B, uv - vec2f(0.0, dt.y), lod).a;\\n let w1 = felt_noised(q * (1.0 / 80.0) + vec2f(3.1, 7.7)).yz;\\n let w2 = felt_noised(q * (1.0 / 31.0) + vec2f(11.0, 5.0)).yz;\\n let slope = (w1 + 0.5 * w2) * 0.006 + vec2f(ax, ay) * k.mel.w;\\n let n = normalize(vec3f(-slope, 1.0));\\n\\n // the albedo: the melamine's tone and grain, the ghost of old erasures, the ink as a filter (linear) over it\\n let tone = felt_noise(q * (1.0 / 140.0) + vec2f(20.0, 4.0)) * k.mel.x;\\n let grain = (bn.x - 0.5) * k.mel.y;\\n let ghost = smoothstep(0.1, 0.45, felt_fbm(q * (1.0 / 21.0) + vec2f(40.0, 3.0))) * k.mel.z;\\n let base = (B.surface.rgb * (1.0 + tone) + vec3f(grain)) * (1.0 - ghost);\\n let filt = vec3f(1.0 - cov2) + ink.rgb * mix(1.0, k.sheen.w, wet);\\n var albedo = bd_encode(srgb_to_linear(clamp(base, vec3f(0.0), vec3f(1.0))) * filt);\\n\\n // the light on it: the lamp over the ink's relief, the frame's lip on the lamp's side, the corner's occlusion\\n let dl = sdf_round_box(q - S * B.recess, B.inner, B.innerR);\\n let lip = bd_blur(-dl, k.lip.y) * k.lip.x;\\n let ao = 1.0 - 0.07 * (1.0 - smoothstep(0.0, 3.0, -dIn));\\n albedo = albedo * pow(bd_lambert(n, L, k) * (1.0 - lip) * ao, 1.0 / 2.2);\\n let gobo = sample_gobo(u, gobo_tex, gobo_samp, bd_desk_at(u, p, face), bn.z);\\n col = bd_colour(u, clamp(albedo, vec3f(0.0), vec3f(1.0)), gobo, bn.y, k.light.z);\\n\\n // the window in the glossy face — stronger on wet ink; it shows most where the face is darkest\\n // (in the leaves' shade, on the ink), as a reflection does\\n let sheen = bd_sheen(B, k, p, n) * k.sheen.x * (1.0 + 1.5 * wet) * bd_lit(u, k);\\n col = col + vec3f(sheen) * (vec3f(1.0) - col * 0.55);\\n }\\n acc = bd_over(vec4f(col * cov, cov), acc);\\n }\\n\\n // THE PEN — one marker in whatever pose the host gives it: lying capped on the melamine, in the\\n // hand at the pointer with its cap posted, or on its way between (BOARD.md §5). Its shadow first\\n // — the axis point at u stands h0 + u·rise over the melamine and casts along the lamp's slope,\\n // softened by that height; a lying pen has its contact line — then the pen itself.\\n if (B.pen.w > 0.001) {\\n let a = vec2f(cos(B.pen.z), sin(B.pen.z));\\n let perp = vec2f(-a.y, a.x);\\n let tip = B.pen.xy;\\n let h0 = B.penPose.x;\\n let rise = B.penPose.y;\\n let cap = B.penPose.z;\\n let nib = B.penPose.w;\\n let pres = B.pen.w;\\n if (distance(p, tip) < k.pen.x * 1.3 + 90.0) {\\n let D = a + S * rise;\\n let A0 = tip + S * h0;\\n let c0 = mix(-2.0, k.pen.x - k.pen.z * 0.55, cap);\\n let tt = clamp(dot(p - A0, D) / max(dot(D, D), 1.0e-6), min(0.0, c0), max(k.pen.x, c0 + k.pen.z));\\n let hs = h0 + tt * rise;\\n let rs = p - (A0 + D * tt);\\n let msd = bd_pen_soft(vec2f(tt, length(rs)), cap, nib, k);\\n let shade = bd_blur(msd, k.shadow.x + k.shadow.y * HAND_PENUMBRA * hs) * k.shadow.z * HAND_UMBRA;\\n let rc = p - tip;\\n let mc = vec2f(dot(rc, a), dot(rc, perp));\\n // lying, it touches the melamine along a line: the contact shadow, gone as it lifts\\n let lying = exp(-max(h0 - k.pen.y, 0.0) / 2.5) * (1.0 - smoothstep(0.0, 0.05, rise));\\n let contact = bd_blur(bd_pen_soft(mc, cap, nib, k) + k.pen.y * 0.45, k.shadow2.x * 1.4) * 0.42 * lying;\\n let msh = min(max(shade, contact), 1.0) * pres;\\n acc = bd_over(vec4f(shadowInk * msh, msh), acc);\\n let sd = bd_pen(mc, cap, nib, k);\\n let mcov = bd_cov(sd.x, px) * pres;\\n if (mcov > 0.0) {\\n let gobo = sample_gobo(u, gobo_tex, gobo_samp, bd_desk_at(u, p, face + h0 + max(mc.x, 0.0) * rise + k.pen.y), bn.z);\\n let c = bd_marker_colour(u, k, sd, mc.y, a, perp, B.penInk.rgb, L, gobo, bn.y);\\n acc = bd_over(vec4f(c * mcov, mcov), acc);\\n }\\n }\\n }\\n\\n // THE ERASER in the hand: a felt block with a wooden back, square to its angle.\\n if (B.eraser.w > 0.001 && distance(p, B.eraser.xy) < 120.0) {\\n let ang = k.block2.x;\\n let a = vec2f(cos(ang), sin(ang));\\n let perp = vec2f(-a.y, a.x);\\n let rc = p - B.eraser.xy;\\n let qe = vec2f(dot(rc, a), dot(rc, perp));\\n let half = k.block.xy;\\n let gap = B.eraser.z;\\n let hTop = gap + k.block.z + k.block.w;\\n let pres = B.eraser.w;\\n let sh = min(bd_slab(qe, half, 3.0, gap, hTop, vec2f(dot(S, a), dot(S, perp)), k, HAND_PENUMBRA, 14) * HAND_UMBRA, 1.0) * pres; // the slope, in the block's frame\\n acc = bd_over(vec4f(shadowInk * sh, sh), acc);\\n let dFelt = sdf_round_box(qe, half, 3.0);\\n let fcov = bd_cov(dFelt, px) * pres;\\n if (fcov > 0.0) {\\n let dWood = sdf_round_box(qe, half - vec2f(1.5), 2.4);\\n let gw = bd_grad(qe, half - vec2f(1.5), 2.4);\\n let bevel = 1.0 - smoothstep(0.0, 2.2, -dWood);\\n let gw3 = vec2f(gw.x * a.x - gw.y * a.y, gw.x * a.y + gw.y * a.x); // back to world axes\\n let n = normalize(vec3f(gw3 * sin(bevel * 0.9), cos(bevel * 0.9)));\\n let grain = felt_noise(vec2f(qe.x * 0.06, qe.y * 1.3)) * 0.05 + felt_noise(vec2f(qe.x * 0.21, qe.y * 3.7)) * 0.025;\\n var albedo = k.felt.rgb;\\n if (dWood < 0.0) {\\n // the wooden back, its grain along the block, a finger groove routed round its top\\n let groove = 1.0 - smoothstep(0.25, 0.9, abs(sdf_round_box(qe, half - vec2f(6.5, 3.4), 1.8)));\\n albedo = (k.wood.rgb + vec3f(grain)) * pow(bd_lambert(n, L, k), 1.0 / 2.2) * (1.0 - 0.2 * groove);\\n }\\n let gobo = sample_gobo(u, gobo_tex, gobo_samp, bd_desk_at(u, p, face + hTop), bn.z);\\n let c = bd_colour(u, clamp(albedo, vec3f(0.0), vec3f(1.0)), gobo, bn.y, k.light.z);\\n acc = bd_over(vec4f(c * fcov, fcov), acc);\\n }\\n }\\n\\n // The sole-selection ring, inside the outer edge, in the theme's select.\\n let ring = bd_line(dOut, k.shadow2.z * css, px) * B.ring;\\n acc = bd_over(vec4f(k.select.rgb * ring, ring), acc);\\n return acc * B.alpha;\\n}\\n\",\n \"board/felt.wgsl\": \"// The FELT's noise (BOARD.md) — a PURE module: the research whiteboard's gradient noise\\n// (research/whiteboard noise.wgsl) with its analytic derivatives, an integer hash so it is\\n// the same on every GPU, prefixed `felt_` beside the mat's own `hash12` / `value_noise`. The\\n// pen's fibre lanes read it in the stamp; the melamine's waviness and orange peel, the\\n// frame's brushing and the eraser's wood read it on the desk.\\n\\nfn felt_hash(p: vec2u) -> u32 {\\n var v = p.x * 1664525u + 1013904223u;\\n v = v ^ (p.y * 22695477u + 374761393u);\\n v = v ^ (v >> 16u);\\n v = v * 0x7feb352du;\\n v = v ^ (v >> 15u);\\n v = v * 0x846ca68bu;\\n v = v ^ (v >> 16u);\\n return v;\\n}\\n\\nfn felt_grad(i: vec2i) -> vec2f {\\n let h = felt_hash(bitcast<vec2u>(i));\\n let a = f32(h & 0xffffu) * (6.283185307 / 65536.0);\\n return vec2f(cos(a), sin(a));\\n}\\n\\n// Gradient noise with its derivatives: (value, d/dx, d/dy); the value roughly in [−0.7, 0.7].\\nfn felt_noised(p: vec2f) -> vec3f {\\n let i = vec2i(floor(p));\\n let f = fract(p);\\n let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);\\n let du = 30.0 * f * f * (f * (f - 2.0) + 1.0);\\n let ga = felt_grad(i);\\n let gb = felt_grad(i + vec2i(1, 0));\\n let gc = felt_grad(i + vec2i(0, 1));\\n let gd = felt_grad(i + vec2i(1, 1));\\n let va = dot(ga, f);\\n let vb = dot(gb, f - vec2f(1.0, 0.0));\\n let vc = dot(gc, f - vec2f(0.0, 1.0));\\n let vd = dot(gd, f - vec2f(1.0, 1.0));\\n let k = va - vb - vc + vd;\\n let v = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;\\n let d = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)\\n + du * (u.yx * k + vec2f(vb, vc) - va);\\n return vec3f(v, d.x, d.y);\\n}\\n\\nfn felt_noise(p: vec2f) -> f32 { return felt_noised(p).x; }\\n\\nfn felt_fbm(p: vec2f) -> f32 {\\n var v = 0.0;\\n var a = 0.5;\\n var q = p;\\n for (var i = 0; i < 4; i++) {\\n v = v + a * felt_noise(q);\\n q = q * 2.03 + vec2f(1.7, 9.2);\\n a = a * 0.5;\\n }\\n return v;\\n}\\n\",\n \"board/ink.wgsl\": \"// The INK — fullscreen passes over a board's raster (the research whiteboard's\\n// composite.wgsl): lay a finished stroke from the stroke layer into the ink layer, mark it wet,\\n// let the wet fade. The ink layer is PREMULTIPLIED LINEAR colour with coverage in alpha, so\\n// its mips average correctly and the melamine can read it as a filter.\\n\\n@group(0) @binding(0) var<uniform> C: InkUniforms;\\n@group(0) @binding(1) var stroke: texture_2d<f32>;\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {\\n let x = f32((vi << 1u) & 2u);\\n let y = f32(vi & 2u);\\n return vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);\\n}\\n\\nfn ink_cov(p: vec4f) -> f32 { return textureLoad(stroke, vec2i(p.xy), 0).r; }\\n\\n// a marker: premultiplied \\\"over\\\" into the ink layer (blend one / one-minus-src-alpha)\\n@fragment\\nfn fs_draw(@builtin(position) p: vec4f) -> @location(0) vec4f {\\n let c = ink_cov(p);\\n return vec4f(C.color.rgb * c, c);\\n}\\n\\n// the eraser: ink *= 1 − coverage (blend zero / one-minus-src-alpha)\\n@fragment\\nfn fs_erase(@builtin(position) p: vec4f) -> @location(0) vec4f {\\n return vec4f(0.0, 0.0, 0.0, ink_cov(p));\\n}\\n\\n// the wet layer: max(wet, coverage)\\n@fragment\\nfn fs_wet(@builtin(position) p: vec4f) -> @location(0) vec4f {\\n return vec4f(ink_cov(p), 0.0, 0.0, 1.0);\\n}\\n\\n// the wet fades: dst *= the blend constant\\n@fragment\\nfn fs_dry(@builtin(position) p: vec4f) -> @location(0) vec4f {\\n return vec4f(0.0);\\n}\\n\",\n \"board/mip.wgsl\": \"// The MIP — one level of a board's ink raster from the level above: each texel the bilinear\\n// average of the 2×2 it covers (premultiplied, so the average is the right one). A board seen\\n// small reads its ink here instead of aliasing the full raster.\\n\\n@group(0) @binding(0) var src: texture_2d<f32>;\\n@group(0) @binding(1) var src_samp: sampler;\\n\\nstruct MipOut {\\n @builtin(position) pos: vec4f,\\n @location(0) uv: vec2f,\\n}\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vi: u32) -> MipOut {\\n let x = f32((vi << 1u) & 2u);\\n let y = f32(vi & 2u);\\n var o: MipOut;\\n o.pos = vec4f(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);\\n o.uv = vec2f(x, y);\\n return o;\\n}\\n\\n@fragment\\nfn fs(in: MipOut) -> @location(0) vec4f {\\n return textureSampleLevel(src, src_samp, in.uv, 0.0);\\n}\\n\",\n \"board/stamp.wgsl\": \"// The STAMP — the pen's footprints into the stroke layer (r8, max-blended: a stroke never\\n// darkens where it crosses itself, as a marker line does not). One instance per stamp, its\\n// quad grown from the stamp's centre by the tip's reach, in the raster's texels; the\\n// footprint, the felt's lanes and the flow in WORLD units (the stamps are the melamine's world\\n// units, stroke.ts), so a stroke is the same stroke at any density. The research\\n// whiteboard's stamp.wgsl, moved off the screen and onto the board.\\n\\n@group(0) @binding(0) var<uniform> S: StampUniforms;\\n@group(0) @binding(1) var<storage, read> stamps: array<Stamp>;\\n\\nstruct StampOut {\\n @builtin(position) pos: vec4f,\\n @location(0) px: vec2f,\\n @location(1) @interpolate(flat) inst: u32,\\n}\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> StampOut {\\n let st = stamps[ii];\\n let k = S.tex.z; // texels per world unit\\n let corner = vec2f(f32(vi & 1u), f32((vi >> 1u) & 1u)) * 2.0 - 1.0;\\n let ext = (length(S.tip.xy) * st.size + S.felt.x + 0.5) * k + 2.0;\\n let px = st.pos * k + corner * ext;\\n var o: StampOut;\\n o.pos = vec4f(px / S.tex.xy * vec2f(2.0, -2.0) + vec2f(-1.0, 1.0), 0.0, 1.0);\\n o.px = px;\\n o.inst = ii;\\n return o;\\n}\\n\\n@fragment\\nfn fs(in: StampOut) -> @location(0) vec4f {\\n let st = stamps[in.inst];\\n let k = S.tex.z;\\n let texel = 1.0 / k;\\n let d = (in.px - st.pos * k) * texel; // world units from the stamp's centre\\n\\n // the footprint in the tip's own frame (the tip keeps its angle, like a hand-held marker)\\n let ca = cos(S.tip.z);\\n let sa = sin(S.tip.z);\\n let q = vec2f(ca * d.x + sa * d.y, -sa * d.x + ca * d.y);\\n let hf = S.tip.xy * st.size;\\n let sd = sdf_round_box(q, hf, S.tip.w * st.size);\\n let soft = S.felt.x;\\n let shape = 1.0 - smoothstep(-soft * 0.5 - texel * 0.5, soft * 0.5 + texel * 0.5, sd);\\n\\n // the felt's fibres: each traces a line parallel to the motion, so the lane pattern is a\\n // function of the offset across the path (stable under max-blending of the stamps)\\n let perp = vec2f(-st.dir.y, st.dir.x);\\n let across = dot(d, perp);\\n let along = st.s;\\n let n1 = felt_noise(vec2f(across * S.lanes.x + st.seed * 37.1, along * S.lanes.y + st.seed * 11.3));\\n let n2 = felt_noise(vec2f(across * S.lanes.x * 1.7 + st.seed * 5.7, along * S.lanes.z + st.seed * 3.1));\\n let lanes = smoothstep(0.08, 0.5, n1 + 0.45 * n2);\\n\\n var density: f32;\\n if (S.felt.y < 0.5) {\\n // a marker: mostly solid ink; a faster stroke runs drier and opens more, deeper lanes\\n let dry = 1.0 - st.flow;\\n let streak = clamp(S.felt.w * (1.0 + 5.0 * dry), 0.0, 1.0);\\n let flowVar = 1.0 + 0.04 * felt_noise(vec2f(along * S.lanes.y, st.seed * 3.3 + 50.0));\\n // the felt presses lighter at its rim\\n let rim = 1.0 - 0.22 * smoothstep(-0.35 * min(hf.x, hf.y), 0.0, sd);\\n density = (1.0 - streak * lanes) * (1.0 - 0.35 * dry) * flowVar * rim * S.felt.z;\\n } else {\\n // the eraser: takes most of the ink, leaves a streaky ghost\\n density = 0.86 + 0.11 * (1.0 - lanes);\\n }\\n return vec4f(clamp(shape * density, 0.0, 1.0), 0.0, 0.0, 1.0);\\n}\\n\",\n \"calendar/calendar-pass.wgsl\": \"// The calendar pass's entries (CALENDAR.md §6). A pad's record is always read through a POINTER into the storage\\n// buffer (`&pads[i]`): a by-value copy of it (a kilobyte, with arrays indexed at run time) is pushed out of\\n// registers into memory and cost a full-screen pad ~10 ms. Into a 4× multisampled layer, per calendar:\\n// vs_moving · fs_sheet the sheet in motion (first, so the month it covers is skipped by the depth test): a grid\\n// laid on the sheet, its rows fine only where the roll is, bent by the roll (cal_roll)\\n// vs_pad · fs_face the month on the pad: its face — the largest thing on the screen, a lean shader of its own\\n// vs_pad · fs_sheet the roll of the months before (seen from behind as much as not)\\n// vs_pad · fs_solid the pad's solid parts: its sides, the chipboard, the cloth tape (a lean shader of their own)\\n// vs_recv · fs_recv the mat under it: its shadow, its contact, its selection ring — after the pad, so\\n// the depth test skips every pixel the pad covers\\n// The layer is resolved and laid on the mat INSIDE the ground's pass, before the cards and the notes\\n// (ground.ts `underlays`): the pad lies beneath everything else on the desk.\\n// The view block `u` is the SLOT's since K4a (design-016 K-L3), shared with the mat and every kind: this layer is drawn at FULL\\n// presence, as it always was (the pass's own copy of the block carried no presentation, and the composite lays the layer whole),\\n// so it reads neither `u.view.w` (the objects' presence) nor `u.presence.x` (the slot's) — its alpha is its coverage alone.\\n\\n@group(0) @binding(0) var<uniform> u: MatUniforms;\\n@group(0) @binding(1) var<uniform> k: CalUniforms;\\n@group(0) @binding(2) var<storage, read> pads: array<CalPad>;\\n@group(0) @binding(3) var gobo_tex: texture_2d<f32>;\\n@group(0) @binding(4) var gobo_samp: sampler;\\n@group(0) @binding(5) var noise_tex: texture_2d<f32>;\\n@group(0) @binding(6) var noise_samp: sampler;\\n@group(0) @binding(7) var tile_tex: texture_2d_array<f32>; // the print's tiles (straight alpha), 260² each\\n@group(0) @binding(8) var tile_samp: sampler;\\n@group(0) @binding(9) var<storage, read> tiles: array<i32>; // the page tables: a layer, −1 missing, −2 empty\\n@group(0) @binding(10) var paper_tex: texture_2d<f32>;\\n@group(0) @binding(11) var paper_samp: sampler;\\n\\n// The print at a sheet point, from the table `slot`: the level at or above the screen's density (`bias`\\n// rungs coarser), falling back a rung at a time to one that is there. Transparent where nothing is printed.\\nfn cal_tile(slot: f32, q: vec2f, px: f32, bias: i32) -> vec4f {\\n if (slot < 0.0) { return vec4f(0.0); }\\n let base = i32(slot + 0.5) * i32(k.tiles.x + 0.5);\\n var l = clamp(i32(ceil(2.0 * log2(max(1.0 / px, 1e-6) / 0.25) - 1e-3)) - bias, 0, 10);\\n for (var i = 0; i < 11; i++) {\\n let band = 0.25 * exp2(f32(l) * 0.5);\\n let t = q * (band / k.tiles.y);\\n let ti = vec2i(floor(t));\\n let nx = i32(k.tileNx[l / 4][l % 4] + 0.5);\\n let ny = i32(k.tileNy[l / 4][l % 4] + 0.5);\\n if (ti.x < 0 || ti.y < 0 || ti.x >= nx || ti.y >= ny) { return vec4f(0.0); }\\n let e = tiles[base + i32(k.tileOff[l / 4][l % 4] + 0.5) + ti.y * nx + ti.x];\\n if (e >= 0) {\\n let uv = (fract(t) * k.tiles.y + vec2f(k.tiles.z)) / k.tiles.w;\\n return textureSampleLevel(tile_tex, tile_samp, uv, e, 0.0);\\n }\\n if (e == -2 || l == 0) { return vec4f(0.0); }\\n l -= 1;\\n }\\n return vec4f(0.0);\\n}\\n\\nstruct VIn {\\n @location(0) pos: vec3f,\\n @location(1) nrm: vec3f,\\n @location(2) uv: vec2f,\\n @location(3) mat: vec4f, // material, unused, flags, ao\\n @location(4) size: vec2f,\\n @location(5) extra: vec2f,\\n}\\n\\nstruct VOut {\\n @builtin(position) clip: vec4f,\\n @location(0) world: vec3f,\\n @location(1) nrm: vec3f,\\n @location(2) uv: vec2f, // the SHEET point (world units from the sheet's top-left)\\n @location(3) @interpolate(flat) mat: vec3f, // material, flags, the calendar\\n @location(4) ao: f32,\\n @location(5) local: vec3f, // the pad's own coordinates\\n}\\n\\n@vertex\\nfn vs_pad(v: VIn, @builtin(instance_index) iid: u32) -> VOut {\\n let B = &pads[iid];\\n var out: VOut;\\n var p = v.pos;\\n // the past roll lies a hair over the sheet coming off it, so the two never fight\\n if (i32(v.mat.x + 0.5) == 2) { p.z += 0.12; }\\n let P = ((*B).model * vec4f(p, 1.0)).xyz;\\n out.clip = cal_clip(k, P);\\n out.world = P;\\n out.nrm = ((*B).model * vec4f(v.nrm, 0.0)).xyz;\\n out.uv = v.uv;\\n out.mat = vec3f(v.mat.x, v.mat.z, f32(iid));\\n out.ao = v.mat.w;\\n out.local = p;\\n return out;\\n}\\n\\n@vertex\\nfn vs_moving(@location(0) g: vec2f, @builtin(instance_index) iid: u32) -> VOut {\\n let B = &pads[iid];\\n var out: VOut;\\n let W = (*B).size.x;\\n let H = (*B).size.y;\\n let T = (*B).size.z;\\n let L = (*B).size.w;\\n let sx = g.x * W;\\n // the grid's rows laid where they are needed: a dozen over the flat part, the rest from just before the\\n // tangent line (wherever it crosses the sheet) to just past the turns drawn — beyond that is inside the roll\\n let ta = tan((*B).roll.y);\\n let a0 = (*B).roll.x + (0.0 - (*B).roll.z) * ta;\\n let a1 = (*B).roll.x + (W - (*B).roll.z) * ta;\\n let sA = clamp(min(a0, a1) - 24.0, 0.0, L);\\n let turnLen = ((*B).roll2.w + 2.0) * (*B).roll2.y;\\n let sB = clamp(max(a0, a1) + turnLen / max(cos((*B).roll.y), 0.3) + 24.0, sA, L);\\n let v0 = 12.0 / 220.0;\\n var s = sA * g.y / v0;\\n if (g.y > v0) { s = sA + (sB - sA) * (g.y - v0) / (1.0 - v0); }\\n var r = cal_roll((*B).roll.x, (*B).roll.y, (*B).roll.z, (*B).roll.w, (*B).roll2.x, L, sx, s);\\n // past the turns drawn a point is inside the roll: it folds onto the last one drawn (its triangles vanish)\\n if (r.phi > (*B).roll2.y) {\\n let sa = sin((*B).roll.y);\\n let ca = cos((*B).roll.y);\\n let d = (sx - (*B).roll.z) * (-sa) + (s - (*B).roll.x) * ca;\\n let D = max((sx - (*B).roll.z) * (-sa) + (L - (*B).roll.x) * ca, d);\\n let R = cal_radius((*B).roll.w, (*B).roll2.x, D);\\n let pm = (*B).roll2.y;\\n let dc = R * pm - (*B).roll2.x * pm * pm / (4.0 * CAL_PI);\\n r = cal_roll((*B).roll.x, (*B).roll.y, (*B).roll.z, (*B).roll.w, (*B).roll2.x, L, sx + (d - dc) * sa, s - (d - dc) * ca);\\n }\\n let local = vec3f(r.p.x - W * 0.5, -H * 0.5 + T + r.p.y, (*B).z.z + r.p.z);\\n let P = ((*B).model * vec4f(local, 1.0)).xyz;\\n out.clip = cal_clip(k, P);\\n out.world = P;\\n out.nrm = ((*B).model * vec4f(r.n, 0.0)).xyz;\\n out.uv = vec2f(sx, T + s);\\n out.mat = vec3f(1.0, 1.0, f32(iid));\\n out.ao = 1.0;\\n out.local = local;\\n return out;\\n}\\n\\n// The rolls' and the tape's shade on a flat sheet at pad point `p` (height `zr`): the lamp's light that gets\\n// through (vis), and the creases' occlusion (ao). Each term only where it can reach: the past roll's within a\\n// shadow's length of the head, the moving roll's near its line, the tape's lip right under it.\\nfn cal_sheet_shade(pi: u32, p: vec2f, zr: f32, L: vec3f, moving: bool) -> vec2f {\\n let B = &pads[pi]; // a pointer: a copy of the record would be pushed out of registers\\n let W = (*B).size.x;\\n let H = (*B).size.y;\\n let T = (*B).size.z;\\n let reach = 2.2 * 60.0 + 40.0; // the longest shadow a roll lying on the pad throws, and its penumbra\\n var vis = 1.0;\\n var ao = 1.0;\\n // the roll of the months before, against the tape\\n let R0 = (*B).roll2.w;\\n let o0 = vec2f(-W * 0.5, -H * 0.5 + T + R0);\\n if (zr < (*B).z.z + R0 && abs(p.y - o0.y) < reach) {\\n vis *= 1.0 - 0.72 * (1.0 - cal_cyl_shadow(k, p, zr, o0, vec2f(1.0, 0.0), R0, (*B).z.z + 0.12 + R0, L, 0.0, W));\\n ao *= cal_crease(p, o0, vec2f(1.0, 0.0), R0);\\n }\\n // the moving sheet's roll, where its tangent line is\\n if ((*B).roll2.z > 0.5) {\\n let a = (*B).roll.x;\\n let al = (*B).roll.y;\\n let dir = vec2f(cos(al), sin(al));\\n let o = vec2f((*B).roll.z - W * 0.5, -H * 0.5 + T + a);\\n let dn = dot(p - o, vec2f(-dir.y, dir.x));\\n if (abs(dn) < reach) {\\n let sx = p.x + W * 0.5;\\n let D = max((sx - (*B).roll.z) * (-sin(al)) + ((*B).size.w - a) * cos(al), 0.0);\\n let R = cal_radius((*B).roll.w, (*B).roll2.x, D) * smoothstep(0.0, 6.0, D);\\n let t0 = -dot(o - vec2f(-W * 0.5, 0.0), dir);\\n if (R > 0.0 && zr < (*B).z.z + R) {\\n vis *= 1.0 - 0.72 * (1.0 - cal_cyl_shadow(k, p, zr, o, dir, R, (*B).z.z + R, L, t0, t0 + W / max(dir.x, 0.2)));\\n if (!moving) { ao *= cal_crease(p, o, dir, R); }\\n }\\n }\\n }\\n // the tape's lip over the sheets: a hairline of contact below its edge\\n let below = p.y - (-H * 0.5 + T);\\n if (below >= 0.0 && below < 12.0) { ao *= 1.0 - 0.28 * exp(-below / 1.6); }\\n return vec2f(vis, ao);\\n}\\n\\n// The face's tangents (world units along the sheet's x and y) from the uv's screen derivatives.\\nfn cal_tangents(n: vec3f, dPdx: vec3f, dPdy: vec3f, dqdx: vec2f, dqdy: vec2f) -> mat2x3f {\\n let det = dqdx.x * dqdy.y - dqdx.y * dqdy.x;\\n var Tu = vec3f(1.0, 0.0, 0.0);\\n var Tv = vec3f(0.0, 1.0, 0.0);\\n if (abs(det) > 1e-14) {\\n Tu = (dPdx * dqdy.y - dPdy * dqdx.y) / det;\\n Tv = (dPdy * dqdx.x - dPdx * dqdy.x) / det;\\n }\\n Tu = Tu - n * dot(n, Tu);\\n Tv = Tv - n * dot(n, Tv);\\n Tu = select(vec3f(1.0, 0.0, 0.0), normalize(Tu), length(Tu) > 1e-8);\\n Tv = select(vec3f(0.0, 1.0, 0.0), normalize(Tv), length(Tv) > 1e-8);\\n return mat2x3f(Tu, Tv);\\n}\\n\\n// The lamp on a face: the bumped normal, the sky's share, the leaves' dapple, the desk's day or night, the sheen.\\nfn cal_lit(albedo: vec3f, n: vec3f, T: mat2x3f, grad: vec2f, world: vec3f, V: vec3f, Lw: vec3f, vis: f32, ao: f32, paper: bool, back: bool, dapple: f32, sheen: vec2f, bn: vec3f) -> vec3f {\\n let nb = normalize(n - T[0] * grad.x - T[1] * grad.y);\\n let lam = min(max(dot(nb, Lw), 0.0) / max(Lw.z, 1e-3), k.light.y);\\n let sky = select(k.light.x, mix(k.light.x, 1.0, 0.22), paper);\\n var light = (sky + (1.0 - sky) * lam * vis) * ao;\\n if (paper && back) {\\n // paper is translucent: the back of a curling sheet glows with the lamp behind it\\n light += 0.18 * (1.0 - k.light.x) * max(-dot(n, Lw), 0.0) * ao;\\n }\\n var g0 = 1.0;\\n if ((u32(k.ring.y) & 4u) == 0u) { g0 = sample_gobo(u, gobo_tex, gobo_samp, nb_desk_at(u, world), bn.z); }\\n let gobo = mix(1.0, g0, dapple);\\n var c = nb_colour(u, albedo, light, gobo, bn.y);\\n let Hh = normalize(Lw + V);\\n let sp = pow(max(dot(nb, Hh), 0.0), sheen.x) * sheen.y * vis * g0;\\n return c + vec3f(sp * (1.0 - u.night.x * 0.85));\\n}\\n\\n// The print on a sheet's FACE: the grid it is printed on, the tiles' ink, the pen's caret and wipe (onto the\\n// albedo), and the host's marks (returned: their coverage). `moving` picks the sheet's grid and table.\\nstruct CalFace { albedo: vec3f, marks: f32 }\\nfn cal_face(pi: u32, albedo0: vec3f, q: vec2f, px: f32, moving: bool, dbg: u32) -> CalFace {\\n let B = &pads[pi];\\n var out: CalFace;\\n var albedo = albedo0;\\n let G0 = select((*B).gridA, (*B).gridC, moving);\\n let G1 = select((*B).gridB, (*B).gridD, moving);\\n let g = cal_grid(k, q, px, G0, G1);\\n albedo *= mix(vec3f(1.0), (*B).col3.rgb, g.weekend * k.alpha.z + g.outside * k.alpha.w);\\n albedo *= mix(vec3f(1.0), (*B).col2.rgb, g.rule * k.alpha.x);\\n albedo *= mix(vec3f(1.0), (*B).col1.rgb, g.head * k.alpha.y);\\n var ink = vec4f(0.0);\\n if ((dbg & 64u) == 0u) { ink = cal_tile(select((*B).slots.x, (*B).slots.y, moving), q, px, 0); }\\n let onMarks = ((*B).slots.z > 0.5) == moving;\\n out.marks = 0.0;\\n if (onMarks) {\\n // the newest glyph is still being written: the pen's stroke reveals it left to right\\n let wp = (*B).wipe;\\n if ((*B).wipe2.x < 1.0 && q.x >= wp.x && q.x <= wp.z && q.y >= wp.y && q.y <= wp.w) {\\n ink.a *= 1.0 - smoothstep(mix(wp.x, wp.z, (*B).wipe2.x) - 1.5, mix(wp.x, wp.z, (*B).wipe2.x) + 1.5, q.x);\\n }\\n }\\n albedo *= mix(vec3f(1.0), ink.rgb, ink.a);\\n if (onMarks) {\\n let cr = (*B).caret;\\n if (cr.w > 0.0) {\\n albedo = mix(albedo, (*B).col8.rgb, nb_cov(abs(q.x - cr.x) - cr.w * 0.5, px) * nb_cov(max(cr.y - q.y, q.y - cr.z), px) * 0.92);\\n }\\n if ((dbg & 32u) == 0u) {\\n // the marks the host draws: the days selected (as many boxes as `wipe2.w` says), the entry selected, the day a note would stick to\\n let w = k.select.w / max(k.eye.w, 1e-6);\\n let reach = 16.0 / max(k.eye.w, 1e-6); // the marks' brackets reach 16 CSS px (D3t-c)\\n let nSel = i32((*B).wipe2.w + 0.5);\\n for (var i = 0; i < nSel; i++) { out.marks = max(out.marks, cal_brackets(q, (*B).sel[i], w, 3.0, px, reach)); }\\n out.marks = max(out.marks, cal_brackets(q, (*B).mark, w, 4.0, px, reach));\\n out.marks = max(out.marks, cal_outline(q, (*B).drop, w * 1.4, 4.0, px) * 0.85);\\n }\\n }\\n out.albedo = albedo;\\n return out;\\n}\\n\\n// The month on the pad (mat 0): the pad's face — the largest thing on the screen, so its own lean shader: a\\n// face only, never seen from behind, never rolled.\\n@fragment\\nfn fs_face(in: VOut) -> @location(0) vec4f {\\n let dPdx = dpdx(in.world);\\n let dPdy = dpdy(in.world);\\n let dqdx = dpdx(in.uv);\\n let dqdy = dpdy(in.uv);\\n let pi = u32(in.mat.z + 0.5);\\n let B = &pads[pi];\\n let px = max(max(length(dqdx), length(dqdy)), 1e-4);\\n let n = vec3f(0.0, 0.0, 1.0);\\n let E = vec3f(k.eye.x, k.eye.y, k.eye.z);\\n let V = normalize(E - in.world);\\n let q = in.uv;\\n let dbg = u32(k.ring.y);\\n if ((dbg & 512u) != 0u) { return vec4f((*B).col0.rgb, 1.0); }\\n let TT = mat2x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0)); // a pad lies square: its x and y are the world's\\n let bn = textureSampleLevel(noise_tex, noise_samp, (in.clip.xy + k.shadow2.yz) * u.noise.z + u.noise.xy, 0.0).rgb;\\n let Lw = (*B).lamp.xyz;\\n let pp = cal_paper(k, (*B).col0.rgb, q, dqdx, dqdy, 3.0, paper_tex, paper_samp);\\n var face = CalFace(pp.albedo, 0.0);\\n if ((dbg & 2u) == 0u) { face = cal_face(pi, pp.albedo, q, px, false, dbg); }\\n var sh = vec2f(1.0);\\n if ((dbg & 8u) == 0u) { sh = cal_sheet_shade(pi, in.local.xy, in.local.z, Lw, false); }\\n var c = cal_lit(face.albedo, n, TT, pp.g, in.world, V, Lw, sh.x, in.ao * sh.y, true, false, k.light.z, vec2f(5.0, 0.02), bn);\\n c = mix(c, k.select.rgb, face.marks);\\n return vec4f(c, 1.0);\\n}\\n\\n// A SHEET that may be seen from behind: the one in motion (mat 1), the roll of the months before (2) — the ivory,\\n// its fibre and tooth; on a face, the print; on a back, the month showing through; the rolls' shade on the flat.\\n@fragment\\nfn fs_sheet(in: VOut) -> @location(0) vec4f {\\n // every derivative first — they must be taken in uniform control flow\\n let dPdx = dpdx(in.world);\\n let dPdy = dpdy(in.world);\\n let dqdx = dpdx(in.uv);\\n let dqdy = dpdy(in.uv);\\n let pi = u32(in.mat.z + 0.5);\\n let B = &pads[pi];\\n let px = max(max(length(dqdx), length(dqdy)), 1e-4); // sheet units per device px\\n let mat = i32(in.mat.x + 0.5);\\n var n = normalize(in.nrm);\\n let E = vec3f(k.eye.x, k.eye.y, k.eye.z);\\n let V = normalize(E - in.world);\\n var back = false;\\n if (dot(n, V) < 0.0) { n = -n; back = true; }\\n let q = in.uv;\\n let dbg = u32(k.ring.y);\\n if ((dbg & 512u) != 0u) { return vec4f((*B).col0.rgb, 1.0); }\\n let TT = cal_tangents(n, dPdx, dPdy, dqdx, dqdy);\\n let bn = textureSampleLevel(noise_tex, noise_samp, (in.clip.xy + k.shadow2.yz) * u.noise.z + u.noise.xy, 0.0).rgb;\\n let Lw = (*B).lamp.xyz; // a pad lies square on the desk: its own frame is the world's, turned by nothing\\n let moving = mat == 1;\\n let pp = cal_paper(k, (*B).col0.rgb, q, dqdx, dqdy, select(3.0, 17.0, moving), paper_tex, paper_samp);\\n var albedo = pp.albedo;\\n var marks = 0.0;\\n var sheen = vec2f(5.0, 0.02);\\n if (!back && moving && (dbg & 2u) == 0u) {\\n let f = cal_face(pi, albedo, q, px, true, dbg);\\n albedo = f.albedo;\\n marks = f.marks;\\n } else if (back) {\\n // the back of a sheet: a shade duller — and a moving sheet's month just showing through it\\n albedo *= 0.975;\\n if (moving) {\\n let through = cal_tile((*B).slots.y, q, px * 6.0, 0);\\n albedo *= mix(vec3f(1.0), through.rgb, through.a * 0.06);\\n }\\n sheen = vec2f(4.0, 0.012);\\n }\\n // the shade of the rolls and the tape, on the flat of a sheet\\n var sh = vec2f(1.0);\\n if (!back && n.z > 0.985 && (dbg & 8u) == 0u) { sh = cal_sheet_shade(pi, in.local.xy, in.local.z, Lw, moving); }\\n var c = cal_lit(albedo, n, TT, pp.g, in.world, V, Lw, sh.x, in.ao * sh.y, true, back, k.light.z, sheen, bn);\\n c = mix(c, k.select.rgb, marks);\\n return vec4f(c, 1.0);\\n}\\n\\n// The pad's SOLID parts: the block's side (mat 3), the chipboard back (4), the cloth tape and its foil (5).\\n@fragment\\nfn fs_solid(in: VOut) -> @location(0) vec4f {\\n let dPdx = dpdx(in.world);\\n let dPdy = dpdy(in.world);\\n let dqdx = dpdx(in.uv);\\n let dqdy = dpdy(in.uv);\\n let pi = u32(in.mat.z + 0.5);\\n let B = &pads[pi];\\n let px = max(max(length(dqdx), length(dqdy)), 1e-4);\\n let mat = i32(in.mat.x + 0.5);\\n let n = normalize(in.nrm);\\n let E = vec3f(k.eye.x, k.eye.y, k.eye.z);\\n let V = normalize(E - in.world);\\n let q = in.uv;\\n let TT = cal_tangents(n, dPdx, dPdy, dqdx, dqdy);\\n let bn = textureSampleLevel(noise_tex, noise_samp, (in.clip.xy + k.shadow2.yz) * u.noise.z + u.noise.xy, 0.0).rgb;\\n let Lw = (*B).lamp.xyz;\\n var albedo = (*B).col0.rgb;\\n var grad = vec2f(0.0);\\n var dapple = k.light.z;\\n var sheen = vec2f(4.0, 0.0);\\n if (mat == 3) {\\n // the BLOCK's side: the months to come, edge on — one stripe a sheet, each its own shade\\n let t = max((*B).z.z - (*B).z.y, 1e-3);\\n let f = q.y / t;\\n let i = floor(f);\\n let gg = fract(f);\\n let vis2 = smoothstep(0.7, 2.2, t / px);\\n let own = hash12(vec2f(i, 7.0)) - 0.5;\\n let gap = pow(1.0 - min(gg, 1.0 - gg) * 2.0, 6.0);\\n albedo = (*B).col0.rgb * (0.9 + own * 0.08 * vis2 - gap * 0.3 * vis2);\\n } else if (mat == 4) {\\n // the chipboard back: pressed fibre, flecked\\n let fb = nb_fbm(q * 0.6);\\n albedo = (*B).col5.rgb * (0.94 + fb.x * 0.12 + (nb_hash(vec2i(floor(q * 1.7))) - 0.5) * 0.06 * nb_detail(0.6, px));\\n sheen = vec2f(3.0, 0.0);\\n dapple = k.light.w;\\n } else {\\n // the TAPE: bookcloth, and the foil stamped on it (the sheet's print under the tape carries it)\\n let cl = nb_cloth(q, k.cloth.x, px);\\n albedo = (*B).col6.rgb * (1.0 + cl.shade * 0.16);\\n grad = cl.g * k.cloth.y;\\n let foil = cal_tile((*B).slots.x, q, px, 0);\\n let f = foil.a * step(q.y, (*B).size.z);\\n albedo = mix(albedo, (*B).col7.rgb * (0.92 + 0.16 * bn.z), f);\\n sheen = vec2f(mix(k.cloth.z, 22.0, f), mix(k.cloth.w, 0.22, f));\\n dapple = k.light.w;\\n }\\n let c = cal_lit(albedo, n, TT, grad, in.world, V, Lw, 1.0, in.ao, false, false, dapple, sheen, bn);\\n return vec4f(c, 1.0);\\n}\\n\\n// ---- the mat under a pad: its shadow, its contact, its ring\\n\\nstruct ROut {\\n @builtin(position) clip: vec4f,\\n @location(0) world: vec2f,\\n @location(1) @interpolate(flat) pad: u32,\\n}\\n\\nconst RQUAD = array<vec2f, 6>(vec2f(0.0, 0.0), vec2f(1.0, 0.0), vec2f(1.0, 1.0), vec2f(0.0, 0.0), vec2f(1.0, 1.0), vec2f(0.0, 1.0));\\n\\n@vertex\\nfn vs_recv(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> ROut {\\n let B = &pads[iid];\\n var out: ROut;\\n let p = mix((*B).recv.xy, (*B).recv.zw, RQUAD[vid]);\\n out.clip = cal_clip(k, vec3f(p, 0.0));\\n out.world = p;\\n out.pad = iid;\\n return out;\\n}\\n\\n@fragment\\nfn fs_recv(in: ROut) -> @location(0) vec4f {\\n let B = &pads[in.pad];\\n let P = ((*B).inv * vec4f(in.world, 0.0, 1.0)).xyz;\\n let Ll = normalize(((*B).inv * vec4f((*B).lamp.xyz, 0.0)).xyz);\\n let half = (*B).size.xy * 0.5;\\n let h = (*B).z.w + (*B).wipe2.z; // the pad's height, and its lift while carried\\n // the slab's shadow: its footprint carried away from the lamp by its height, softened by it\\n let shift = -Ll.xy / max(Ll.z, 1e-3) * h;\\n let sigma = k.shadow.x + k.shadow.y * h;\\n let dS = nb_sd_box(P.xy - shift * 0.5, half + abs(shift) * 0.5, 0.0);\\n let slab = 1.0 - smoothstep(-sigma * 1.5, sigma * 1.5, dS);\\n // the roll of the months before, lying along the head: its end throws a little shade past the pad's side\\n let R0 = (*B).roll2.w;\\n let o0 = vec2f(-half.x, -half.y + (*B).size.z + R0);\\n let rv = cal_cyl_shadow(k, P.xy, 0.0, o0, vec2f(1.0, 0.0), R0, (*B).z.z + R0 + (*B).wipe2.z, Ll, 0.0, (*B).size.x);\\n // a paper roll's end throws a light, soft shade (its ends are open, the lamp's light passes through the paper)\\n let aS = k.shadow.z * max(slab, (1.0 - rv) * 0.45);\\n // the contact where the pad meets the mat (gone as it lifts)\\n let d = nb_sd_box(P.xy, half, 0.0);\\n let touch = 1.0 - smoothstep(0.0, 2.5, (*B).wipe2.z);\\n let s = k.shadow2.x;\\n let aC = k.shadow.w * touch * exp(-max(d, 0.0) * max(d, 0.0) / (2.0 * s * s)) * step(-0.5, d);\\n let a = 1.0 - (1.0 - aS) * (1.0 - aC);\\n var c = vec4f(k.castCol.rgb * a, a);\\n // the selection ring, on the mat around the pad\\n let css = 1.0 / max(k.eye.w, 1e-6);\\n let rw = k.select.w * css;\\n let rd = abs(d - k.ring.x * css) - rw * 0.5;\\n let ring = nb_cov(rd, css / max(k.shadow2.w, 1.0)) * (*B).slots.w;\\n c = vec4f(k.select.rgb * ring, ring) + c * (1.0 - ring);\\n return c;\\n}\\n\",\n \"calendar/calendar.wgsl\": \"// The DESK CALENDAR — a pad of months under the desk's one lamp (CALENDAR.md). A PURE module: the\\n// uniform blocks and the pad's record arrive as parameters, and it names no colour. mat.wgsl and\\n// notebook.wgsl come first: the light, the gobo, the night and the noise are the mat's; the weave,\\n// the colour chain and the coverage helpers are the notebook's — the pad is the same paper and cloth.\\n//\\n// Here: the desk eye (the notebook's `nb_clip`, over this pass's knobs); the ROLL (roll.ts's\\n// `rollPoint`, point for point — the moving sheet is bent in the vertex shader); the paper; the\\n// GRID the month is printed on (its rules, the weekend's wash, a neighbour month's days — analytic,\\n// so they are crisp at every zoom); and the rolls' shadows on the pad, cast by the lamp from a\\n// cylinder lying on the paper (exact, so no shadow map is drawn for a flat thing).\\n\\nconst CAL_PI = 3.14159265;\\n\\nfn cal_clip(k: CalUniforms, P: vec3f) -> vec4f {\\n let H = k.eye.z;\\n let d = H - P.z;\\n let x = 2.0 * k.eye.w * (P.x - k.eye.x) / k.view.x;\\n let y = -2.0 * k.eye.w * (P.y - k.eye.y) / k.view.y;\\n let n = k.view.z;\\n let f = k.view.w;\\n let z = (d - n) * f / ((f - n) * H);\\n return vec4f(x, y, z, d / H);\\n}\\n\\n// ---- the roll: a sheet point (x across, s down from the tape's edge) as the spiral bends it\\nstruct CalRollPt { p: vec3f, n: vec3f, phi: f32 }\\n\\nfn cal_radius(r0: f32, tau: f32, D: f32) -> f32 { return sqrt(r0 * r0 + tau * max(D, 0.0) / CAL_PI); }\\n\\nfn cal_roll(a: f32, alpha: f32, px: f32, r0: f32, tau: f32, L: f32, x: f32, s: f32) -> CalRollPt {\\n var out: CalRollPt;\\n let sa = sin(alpha);\\n let ca = cos(alpha);\\n let d = (x - px) * (-sa) + (s - a) * ca;\\n if (d <= 0.0) {\\n out.p = vec3f(x, s, 0.0);\\n out.n = vec3f(0.0, 0.0, 1.0);\\n out.phi = 0.0;\\n return out;\\n }\\n let D = max((x - px) * (-sa) + (L - a) * ca, d);\\n let R = cal_radius(r0, tau, D);\\n var phi = d / R;\\n if (tau > 1e-6) { phi = (2.0 * CAL_PI / tau) * (R - sqrt(max(R * R - tau * d / CAL_PI, 0.0))); }\\n let rho = R - tau * phi / (2.0 * CAL_PI);\\n let n2 = vec2f(-sa, ca);\\n let b = vec2f(x, s) - d * n2;\\n let sp = sin(phi);\\n let cp = cos(phi);\\n out.p = vec3f(b + n2 * (rho * sp), R - rho * cp);\\n out.n = vec3f(-n2 * sp, cp);\\n out.phi = phi;\\n return out;\\n}\\n\\n// ---- the paper (the notebook's baked texture, over this pass's knobs)\\nstruct CalPaperS { albedo: vec3f, g: vec2f }\\nfn cal_paper(k: CalUniforms, base: vec3f, q: vec2f, dqdx: vec2f, dqdy: vec2f, seed: f32, tex: texture_2d<f32>, samp: sampler) -> CalPaperS {\\n let s = nb_paper_seed(seed);\\n let a = textureSampleGrad(tex, samp, q / 64.0 + s / 64.0, dqdx / 64.0, dqdy / 64.0);\\n let tt = 9.6;\\n let b = textureSampleGrad(tex, samp, q / tt + s.yx / 31.0, dqdx / tt, dqdy / tt);\\n let v = (a.r - 0.5) * k.paper.y * 2.0 + (a.g - 0.5) * k.paper.x * 3.0;\\n var out: CalPaperS;\\n out.albedo = base + vec3f(v * 1.05, v, v * 0.8);\\n let tooth = (b.ba - vec2f(0.5)) * (2.0 * 48.0 / tt) * (k.paper.z * 0.02);\\n let c = nb_vn(q / 55.0 + s * 0.5);\\n out.g = tooth + c.yz / 55.0 * (k.paper.w * 2.0);\\n return out;\\n}\\n\\n// ---- the grid the month is printed on: the rules' coverage, the heading rule's, the weekend's wash, a neighbour's day\\nstruct CalGrid { rule: f32, head: f32, weekend: f32, outside: f32 }\\n\\n// A thin line's coverage at distance `d` (world units) of half-width `hw`, never thinner than a device px's worth of ink.\\nfn cal_line(d: f32, hw: f32, px: f32) -> f32 {\\n let w = max(hw, px * 0.5);\\n return nb_sat(0.5 - (abs(d) - w) / max(px, 1e-5)) * min(hw / w, 1.0);\\n}\\n\\nfn cal_grid(k: CalUniforms, q: vec2f, px: f32, G0: vec4f, G1: vec4f) -> CalGrid {\\n var out: CalGrid;\\n let rows = G1.x;\\n let gw = G0.z * 7.0;\\n let gh = G0.w * rows;\\n let p = q - G0.xy;\\n let inside = step(-px, p.x) * step(p.x, gw + px) * step(-px, p.y) * step(p.y, gh + px);\\n // the nearest rule down and across\\n let cx = p.x / G0.z;\\n let cy = p.y / G0.w;\\n let dx = (cx - round(cx)) * G0.z;\\n let dy = (cy - round(cy)) * G0.w;\\n let hw = k.ring.z * 0.5;\\n out.rule = max(cal_line(dx, hw, px), cal_line(dy, hw, px)) * inside;\\n out.head = cal_line(p.y, k.ring.w * 0.5, px) * step(-px, p.x) * step(p.x, gw + px);\\n let col = i32(floor(cx));\\n let row = i32(floor(cy));\\n let inCell = step(0.0, p.x) * step(p.x, gw) * step(0.0, p.y) * step(p.y, gh);\\n let mask = u32(G1.y + 0.5);\\n out.weekend = select(0.0, 1.0, col >= 0 && col < 7 && ((mask >> u32(clamp(col, 0, 6))) & 1u) != 0u) * inCell;\\n let idx = row * 7 + col;\\n let lead = i32(G1.z + 0.5);\\n let days = i32(G1.w + 0.5);\\n out.outside = select(0.0, 1.0, idx < lead || idx >= lead + days) * inCell;\\n return out;\\n}\\n\\n// ---- a lying cylinder's shadow on the paper: the lamp's ray from a point at height `zr` past an axis\\n// at height `za` (its radius R, lying along `dir` through `o` in the pad's plane): how much light gets\\n// through (1 lit … 0 shadowed), softened by the desk's penumbra law for the gap\\nfn cal_cyl_shadow(k: CalUniforms, P: vec2f, zr: f32, o: vec2f, dir: vec2f, R: f32, za: f32, L: vec3f, x0: f32, x1: f32) -> f32 {\\n if (R <= 0.0) { return 1.0; }\\n let t = dot(P - o, dir);\\n let nrm = vec2f(-dir.y, dir.x);\\n let dn = dot(P - o, nrm);\\n // the ray in the plane across the axis: from (dn, zr) toward the lamp (ln, lz)\\n let ln = dot(L.xy, nrm);\\n let lz = max(L.z, 1e-3);\\n let rel = vec2f(0.0 - dn, za - zr);\\n let dirL = normalize(vec2f(ln, lz));\\n let along = dot(rel, dirL);\\n if (along <= 0.0) { return 1.0; }\\n let miss = abs(rel.x * dirL.y - rel.y * dirL.x);\\n let gap = max(za - zr, 0.0);\\n let sigma = k.shadow.x + k.shadow.y * gap;\\n let s = smoothstep(R - sigma * 1.2, R + sigma * 1.2, miss);\\n // along the axis: the roll ends where the sheet does (its shadow's ends soft too)\\n let ta = t + dot(L.xy, dir) / lz * (za - zr);\\n let ends = smoothstep(x0 - sigma, x0 + sigma, ta) * (1.0 - smoothstep(x1 - sigma, x1 + sigma, ta));\\n return 1.0 - (1.0 - s) * ends;\\n}\\n\\n// The crease where a roll meets the paper: a little dark each side of its line of contact.\\nfn cal_crease(P: vec2f, o: vec2f, dir: vec2f, R: f32) -> f32 {\\n if (R <= 0.0) { return 1.0; }\\n let dn = dot(P - o, vec2f(-dir.y, dir.x));\\n let w = max(R * 0.45, 1.0);\\n return 1.0 - 0.32 * exp(-(dn * dn) / (w * w));\\n}\\n\\n// A box's outline, `w` wide, just inside it: the marks the host draws on the sheet.\\nfn cal_outline(q: vec2f, box: vec4f, w: f32, r: f32, px: f32) -> f32 {\\n if (box.z <= box.x) { return 0.0; }\\n let c = (box.xy + box.zw) * 0.5;\\n let h = (box.zw - box.xy) * 0.5;\\n let d = nb_sd_box(q - c, h - vec2f(w * 0.5 + 1.0), r);\\n return nb_cov(abs(d) - w * 0.5, px);\\n}\\n\\n// The selection's BRACKETS on a box of the sheet (D3t-c — *Marks on the Mat* Q-a on a day or a line): the outline strong along\\n// `reach` of each side from every corner (never past 30 % of a side), the hairline between them one device px at 42 %.\\nfn cal_brackets(q: vec2f, box: vec4f, w: f32, r: f32, px: f32, reach: f32) -> f32 {\\n if (box.z <= box.x) { return 0.0; }\\n let c = (box.xy + box.zw) * 0.5;\\n let h = (box.zw - box.xy) * 0.5;\\n let a = abs(q - c);\\n let arm = min(vec2f(reach), h * 0.3 + vec2f(r + 2.0));\\n let arms = nb_sat((a.x - (h.x - arm.x)) / max(px, 1e-5) + 0.5) * nb_sat((a.y - (h.y - arm.y)) / max(px, 1e-5) + 0.5);\\n let hair = nb_cov(abs(nb_sd_box(q - c, h - vec2f(w * 0.5 + 1.0), r)) - 0.5 * px, px);\\n return max(cal_outline(q, box, w, r, px) * arms, hair * 0.42);\\n}\\n\",\n \"minimat/minimat-pass.wgsl\": \"// The mini mat pass (MINIMAT.md §6) — the desk's containers, instanced: one quad per mini mat,\\n// expanded on the vertex side by its shadow's reach and the AA. Two entries on one layout:\\n//\\n// fs the mini mat: its shadow, the vinyl with its print and its cut edge, the selection\\n// ring — and, while no live inside covers it, the FACE's far LOD: the inside's lattice\\n// and its children as CHIPS (a note's writing greeked). Where a live inside is drawn\\n// (the ground draws it right after the mini mat — ground.ts `drawSlot`) the face is\\n// plain vinyl under it: the inside's own mat covers it, the same lattice by the same lamp.\\n// fs_chips the chips again, OVER the live inside, at 1 − its presence — the far LOD fading out\\n// as the inside's objects fade in (MINIMAT.md §5), drawn only while both are on.\\n//\\n// Premultiplied, through the presentation's opacity and the portal clip.\\n\\n@group(0) @binding(0) var<uniform> u: MatUniforms;\\n@group(0) @binding(1) var<uniform> k: MiniMatUniforms;\\n@group(0) @binding(2) var<storage, read> mats: array<MiniMat>;\\n@group(0) @binding(3) var<storage, read> chips: array<Chip>;\\n@group(0) @binding(4) var gobo_tex: texture_2d<f32>; // the mat's animated silhouette (its wind target)\\n@group(0) @binding(5) var gobo_samp: sampler;\\n@group(0) @binding(6) var noise_tex: texture_2d<f32>;\\n@group(0) @binding(7) var noise_samp: sampler;\\n@group(0) @binding(8) var glyph_tex: texture_2d<f32>; // the rulers' glyph atlas and the capitals (RULER.md, MINIMAT.md §2)\\n@group(0) @binding(9) var<storage, read> order: array<u32>; // the draw list: paint index → the record's slot (persistent records, D6)\\n\\nstruct VSOut {\\n @builtin(position) clip: vec4f,\\n @location(0) @interpolate(flat) idx: u32,\\n}\\n\\nconst CORNERS = array<vec2f, 6>(\\n vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0),\\n vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0),\\n);\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> VSOut {\\n var out: VSOut;\\n out.clip = vec4f(2.0, 2.0, 2.0, 1.0); // degenerate: a culled instance collapses\\n let slot = order[iid];\\n out.idx = slot;\\n let M = &mats[slot];\\n let zoom = mat_zoom(u);\\n let px = 1.0 / (zoom * mat_dpr(u));\\n // the sheet's bounds, grown by everything the fragment can paint outside it: the slab's sweep, its penumbra, the contact, the AA\\n let top = (*M).lift + (*M).thick;\\n let pad = length((*M).slope) * top + 2.5 * (k.shadow.x + k.shadow.y * top) + 2.5 * k.shadow2.x + 3.0 * px;\\n let lo = ((*M).centre - (*M).half - vec2f(pad) - u.cam.xy) * zoom; // CSS px\\n let hi = ((*M).centre + (*M).half + vec2f(pad) - u.cam.xy) * zoom;\\n if (hi.x < u.box.x || hi.y < u.box.y || lo.x > u.box.x + u.box.z || lo.y > u.box.y + u.box.w) { return out; }\\n let pos = mix(lo, hi, CORNERS[vid] * 0.5 + 0.5);\\n out.clip = vec4f(pos.x / u.view.x * 2.0 - 1.0, 1.0 - pos.y / u.view.y * 2.0, 0.0, 1.0);\\n return out;\\n}\\n\\n// What a shadow is made of: the world's darkest value by day (the design's cast), the dark's own grey by night.\\nfn shadow_ink() -> vec3f { return mix(k.castTint.rgb, mm_encode(u.eigengrau.xyz), clamp(u.night.x, 0.0, 1.0)); }\\n\\n// The children as CHIPS (MINIMAT.md §5), composited over `acc` (premultiplied): each flat on the\\n// face in its own colour, its contact shadow cast along the lamp's slope by its height, a note's\\n// writing greeked into strokes of ink along its lines' x-height once the chip is tall enough to\\n// read as writing, a mini mat of its own wearing its frame line. `s` is the inside's scale.\\nfn chips_on(M: MiniMat, p: vec2f, px: f32, css: f32, s: f32, gobo: f32, bn: vec3f, ink0: vec3f, grain3: vec3f, acc0: vec4f) -> vec4f {\\n var acc = acc0;\\n let S = M.slope;\\n for (var i = 0u; i < M.chipCount; i++) {\\n let C = &chips[M.chipFirst + i];\\n let h = (*C).colour.w;\\n let cr = (*C).rot;\\n let ch = (*C).half;\\n // the tilted chip's bounds, grown by its shadow's reach and the AA\\n let ext = vec2f(abs(cr.x) * ch.x + abs(cr.y) * ch.y, abs(cr.y) * ch.x + abs(cr.x) * ch.y) + vec2f(length(S) * h + 3.0 * max(h, px) + 2.0 * px);\\n let rel = p - (*C).centre;\\n if (abs(rel.x) > ext.x || abs(rel.y) > ext.y) { continue; }\\n let lq = vec2f(cr.x * rel.x + cr.y * rel.y, -cr.y * rel.x + cr.x * rel.y);\\n let dc = sdf_round_box(lq, ch, (*C).radius);\\n let rs = rel - S * h;\\n let ls = vec2f(cr.x * rs.x + cr.y * rs.y, -cr.y * rs.x + cr.x * rs.y);\\n let shc = mm_blur(sdf_round_box(ls, ch, (*C).radius), max(0.8 * h, 0.75 * px)) * 0.35 * (1.0 - mm_cov(dc, px));\\n acc = mm_over(vec4f(ink0 * shc, shc), acc);\\n if (dc > px) { continue; }\\n let cc = mm_cov(dc, px);\\n var lit = vec3f(0.0);\\n if ((*C).kind > 0.5) {\\n // a mini mat of its own: its vinyl with the grain, and its frame line just outside its face — never thinner than a device px\\n let fm = (*C).frame.x;\\n let w = max(k.print.w * s, px);\\n let fr = mm_line(sdf_box(lq, max(ch - vec2f(fm), vec2f(1.0e-3))) - w, w, px) * k.print.x * min(k.print.w * s / px, 1.0) * 1.6;\\n lit = mm_vinyl(u, mix((*C).colour.rgb + grain3, k.cream.rgb, min(fr, 1.0)), 1.0, gobo, bn.y);\\n } else {\\n var pa = (*C).colour.rgb;\\n let n = u32((*C).frame.y);\\n let tall = 2.0 * ch.y / css;\\n let greek = smoothstep(0.6 * k.cream.w, k.cream.w, tall) * k.shadow2.z;\\n if (greek > 0.0 && n > 0u) {\\n var wl = 0.0;\\n for (var j = 0u; j < n; j++) {\\n let L = (*C).lines[j];\\n wl = max(wl, mm_cov(sdf_segment(lq, vec2f(L.x, L.z), vec2f(L.y, L.z)) - (*C).ink.w, px));\\n }\\n pa = mix(pa, (*C).ink.rgb, wl * greek);\\n }\\n lit = mm_paper(u, pa, gobo, bn.y);\\n }\\n acc = mm_over(vec4f(lit * cc, cc), acc);\\n }\\n return acc;\\n}\\n\\n@fragment\\nfn fs(in: VSOut) -> @location(0) vec4f {\\n let M = mats[in.idx];\\n let dpr = mat_dpr(u);\\n let zoom = mat_zoom(u);\\n let px = 1.0 / (zoom * dpr); // world per device px\\n let css = px * dpr; // world per CSS px\\n let p = in.clip.xy * px + u.cam.xy; // device px → world\\n let q = p - M.centre;\\n let d = sdf_round_box(q, M.half, M.radius);\\n let ink0 = shadow_ink();\\n let clip = M.alpha * u.view.w * portal_cover(in.clip.xy / dpr, u.portals, u.clips, dpr);\\n\\n // The slab's shadow on the desk, outside the sheet.\\n var acc = vec4f(0.0);\\n if (d > -px) {\\n let sh = mm_slab(q, M.half, M.radius, M.lift, M.lift + M.thick, M.slope, k) * (1.0 - mm_cov(d, px));\\n acc = vec4f(ink0 * sh, sh);\\n }\\n if (d > px) { return acc * clip; }\\n let cov = mm_cov(d, px);\\n\\n // The vinyl: the mat's own sage and grain (mat.wgsl `mat_albedo`'s — screen-anchored, as the desk's is).\\n let frag = in.clip.xy;\\n let bn = textureSampleLevel(noise_tex, noise_samp, frag * u.noise.z + u.noise.xy, 0.0).rgb;\\n var vinyl = M.ground.xyz;\\n let amp = M.ground.w;\\n var g = (hash12(frag * vec2f(0.73, 0.91)) - 0.5) * amp;\\n g += (value_noise(frag * 0.45 + vec2f(u.view.z * 0.9, -u.view.z * 0.6)) - 0.5) * amp;\\n g += (bn.x - 0.5) * amp * 0.5;\\n vinyl += vec3f(g * 0.4, g, g * 0.35);\\n\\n // The inside's point under this fragment (host = o + inside · s), and inside units per device px.\\n let s = max(M.inside.x, 1.0e-9);\\n let a = (p - M.inside.yz) / s;\\n let ipx = px / s;\\n let fh = max(M.half - vec2f(M.margin), vec2f(1.0e-3));\\n let inFace = max(abs(q.x) - fh.x, abs(q.y) - fh.y) < 0.0;\\n let faceOwn = inFace && M.live < 0.0; // the face is drawn here only where no live inside covers it\\n\\n // The lattice on the face, the print in the border — both the mat's cream, mixed in before the light.\\n var lines = 0.0;\\n if (faceOwn) { lines = mm_lattice(M, a, ipx); }\\n let ink = mm_print(u, M, k, q, fh, a, px, ipx, zoom, glyph_tex, gobo_samp);\\n let albedo = mix(mix(vinyl, k.cream.rgb, lines), k.cream.rgb, ink);\\n\\n // The light: the desk's lamp where the slot's light sees this point (MINIMAT.md §4) — the desk plane's\\n // own dapple, as a live inside's mat takes it, so the face and the inside are lit alike; the cut edge's roll.\\n let gobo = lit_gobo(u, gobo_tex, gobo_samp, p, 0.0, desk_of(u, p), bn.z);\\n let bevel = mm_bevel(q, d, M, k);\\n var col = vec4f(mm_vinyl(u, albedo, bevel, gobo, bn.y) * cov, cov);\\n if (faceOwn && M.chipCount > 0u) { col = chips_on(M, p, px, css, s, gobo, bn, ink0, vinyl - M.ground.xyz, col); }\\n\\n // The sole-selection ring, inside the rim, in the theme's select.\\n let ring = mm_line(d, k.edge.w * css, px) * M.ring;\\n col = mm_over(vec4f(k.select.rgb * ring, ring), col);\\n acc = mm_over(col, acc);\\n return acc * clip;\\n}\\n\\n@fragment\\nfn fs_chips(in: VSOut) -> @location(0) vec4f {\\n let M = mats[in.idx];\\n if (M.live < 0.0 || M.live >= 1.0 || M.chipCount == 0u) { discard; }\\n let fade = 1.0 - M.live;\\n let dpr = mat_dpr(u);\\n let px = 1.0 / (mat_zoom(u) * dpr);\\n let p = in.clip.xy * px + u.cam.xy;\\n let q = p - M.centre;\\n let fh = max(M.half - vec2f(M.margin), vec2f(1.0e-3));\\n if (max(abs(q.x) - fh.x, abs(q.y) - fh.y) >= 0.0) { discard; }\\n let bn = textureSampleLevel(noise_tex, noise_samp, in.clip.xy * u.noise.z + u.noise.xy, 0.0).rgb;\\n let gobo = lit_gobo(u, gobo_tex, gobo_samp, p, 0.0, desk_of(u, p), bn.z);\\n let frag = in.clip.xy;\\n let amp = M.ground.w;\\n var g = (hash12(frag * vec2f(0.73, 0.91)) - 0.5) * amp;\\n g += (value_noise(frag * 0.45 + vec2f(u.view.z * 0.9, -u.view.z * 0.6)) - 0.5) * amp;\\n g += (bn.x - 0.5) * amp * 0.5;\\n let acc = chips_on(M, p, px, px * dpr, max(M.inside.x, 1.0e-9), gobo, bn, shadow_ink(), vec3f(g * 0.4, g, g * 0.35), vec4f(0.0));\\n if (acc.a < 0.002) { discard; }\\n return acc * (fade * M.alpha * u.view.w * portal_cover(in.clip.xy / dpr, u.portals, u.clips, dpr));\\n}\\n\",\n \"minimat/minimat.wgsl\": \"// THE MINI MAT (MINIMAT.md) — a smaller self-healing cutting mat lying on the desk, and inside\\n// it another desk. A PURE module: the record `MiniMat`, the pass's knobs `MiniMatUniforms` and\\n// the mat's block `MatUniforms` arrive as parameters; it names no colour.\\n//\\n// The sheet is the mat's own vinyl, so its colour goes through the mat's own chain (`mat_colour`\\n// — the reference's double gamma by day, the Moon by night) and it takes the dapple of the lamp\\n// the desk is lit by. What tells it from the desk is what a small mat on a big one shows: its\\n// shadow — a thin slab's, the board's sweep with a contact line at its base; its CUT EDGE — a\\n// bevel that catches the lamp on the near side and falls away on the far; and its PRINT, in the\\n// mat's cream — a frame round the cutting area; a ruler along the face's top and left edges, its\\n// ticks at the very lattice the face shows (minor · medium · major for its fine, mid and coarse\\n// rungs) and numbered in the inside's own units with the rulers' own digits (ruler.wgsl); and the\\n// mat's NAME in the foot, in the design's print label (mono capitals, tracked), as a mat's maker\\n// prints its own. The FACE, at the far LOD, is the inside's\\n// lattice as the live inside would draw it (the rungs and their weights come from the host,\\n// dressed as the live slot dresses its mat), and its children are drawn over it as CHIPS by the\\n// entry: flat silhouettes in their own colours, a note's writing greeked into lines of ink.\\n\\nfn mm_cov(d: f32, px: f32) -> f32 { return clamp(0.5 - d / px, 0.0, 1.0); }\\n// A band `w` wide INSIDE the edge d = 0.\\nfn mm_line(d: f32, w: f32, px: f32) -> f32 { return mm_cov(d, px) - mm_cov(d + w, px); }\\nfn mm_erf(x: f32) -> f32 {\\n let s = sign(x);\\n let a = abs(x);\\n let t = 1.0 / (1.0 + 0.3275911 * a);\\n let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-a * a);\\n return s * y;\\n}\\n// Gaussian-blurred coverage — a shadow, straight out of the field.\\nfn mm_blur(d: f32, sigma: f32) -> f32 { return 0.5 - 0.5 * mm_erf(d / max(sigma * 1.4142136, 1.0e-4)); }\\n// Premultiplied \\\"src over dst\\\".\\nfn mm_over(src: vec4f, dst: vec4f) -> vec4f { return src + dst * (1.0 - src.a); }\\n// A world point raised `h` world units off the desk, in the projector's frame (mat.wgsl `desk_of` with a height).\\nfn mm_desk_at(u: MatUniforms, world: vec2f, h: f32) -> vec3f {\\n return vec3f(u.plane.x + world.x * u.plane.z, u.plane.w + h * u.plane.z, u.plane.y + world.y * u.plane.z);\\n}\\nfn mm_encode(c: vec3f) -> vec3f {\\n let x = clamp(c, vec3f(0.0), vec3f(1.0));\\n return mix(x * 12.92, 1.055 * pow(x, vec3f(1.0 / 2.4)) - 0.055, step(vec3f(0.0031308), x));\\n}\\n\\n// The shadow a THIN SLAB casts (the board's `bd_slab`): its footprint swept along the ground slope\\n// `S` from its underside `bottom` to its top `top`, each copy blurred by its own height — the union\\n// as the max — and a contact line at its base while it rests, fading as it floats off.\\nfn mm_slab(q: vec2f, half: vec2f, r: f32, bottom: f32, top: f32, S: vec2f, k: MiniMatUniforms) -> f32 {\\n var sh = 0.0;\\n for (var i = 0; i < 4; i++) {\\n let h = mix(bottom, top, f32(i) / 3.0);\\n if (h <= 0.0) { continue; }\\n sh = max(sh, mm_blur(sdf_round_box(q - S * h, half, r), k.shadow.x + k.shadow.y * h));\\n }\\n sh = sh * k.shadow.z;\\n let g = max(bottom, 0.0);\\n let con = mm_blur(sdf_round_box(q - S * min(g, 1.0) * 0.5, half, r), k.shadow2.x) * k.shadow.w * exp(-g / max(k.shadow2.y, 1.0e-3));\\n return max(sh, con);\\n}\\n\\n// The CUT EDGE: within `k.edge.x` of the rim the sheet's surface rolls over — turned toward the\\n// lamp it brightens, turned away it darkens. `q` in the sheet's frame, `d` its distance; a factor\\n// on the linear albedo (1 on the flat).\\nfn mm_bevel(q: vec2f, d: f32, M: MiniMat, k: MiniMatUniforms) -> f32 {\\n let t = smoothstep(-k.edge.x, 0.0, d);\\n if (t <= 0.0) { return 1.0; }\\n // the rim's outward normal: along the corner's radius, or the nearer side's axis\\n let e = abs(q) - (M.half - vec2f(M.radius));\\n var n = vec2f(0.0);\\n if (e.x > 0.0 && e.y > 0.0) { n = normalize(e) * sign(q); }\\n else if (e.x > e.y) { n = vec2f(sign(q.x), 0.0); }\\n else { n = vec2f(0.0, sign(q.y)); }\\n let facing = dot(n, M.lamp);\\n return 1.0 + t * select(facing * k.edge.z, facing * k.edge.y, facing > 0.0);\\n}\\n\\n// The face's own lattice at the far LOD (mat.wgsl `grid2` per rung, weighed as the live inside\\n// weighs it): `a` the inside point, `ipx` inside units per DEVICE px.\\nfn mm_lattice(M: MiniMat, a: vec2f, ipx: f32) -> f32 {\\n var cover = 0.0;\\n if (M.weights.x > 0.0) { cover = grid2(a, M.rungs.x, M.widths.x * ipx, ipx) * M.weights.x; }\\n if (M.weights.y > 0.0) { cover = max(cover, grid2(a, M.rungs.y, M.widths.y * ipx, ipx) * M.weights.y); }\\n if (M.weights.z > 0.0) { cover = max(cover, grid2(a, M.rungs.z, M.widths.z * ipx, ipx) * M.weights.z); }\\n return cover;\\n}\\n\\n// One rung's ticks along one edge: the site's line across the edge (`along` the inside coordinate\\n// along it, `ipx` inside units per device px, `hw` the print's half-width in inside units), standing\\n// out of the face by `len` world units (`out` how far out the point is, world; `px` world per device px).\\nfn mm_tick(along: f32, spacing: f32, hw: f32, ipx: f32, out: f32, len: f32, px: f32) -> f32 {\\n return line_coverage(along, spacing, hw, ipx) * mm_cov(out - len, px) * mm_cov(-out, px);\\n}\\n\\n// A texel of the glyph atlas (RULER.md; mat/layout.ts `GLYPHS`): glyph `g` at `tx` texels from its\\n// origin (its cell's left edge + the pad) and `ty` texels down from its cell's top; 0 outside it.\\nfn mm_glyph(tex: texture_2d<f32>, samp: sampler, k: MiniMatUniforms, g: i32, tx: f32, ty: f32) -> f32 {\\n if (g < 0 || f32(g) >= k.atlas2.w || tx < -GLYPH_PAD || tx >= k.atlas.x - GLYPH_PAD || ty < 0.0 || ty >= k.atlas.y) { return 0.0; }\\n return textureSampleLevel(tex, samp, vec2f(f32(g) * k.atlas.x + GLYPH_PAD + tx, ty) / k.atlas2.yz, 0.0).r;\\n}\\n\\n// A NUMERAL along one edge: `A` the inside coordinate along it at the fragment, `host` the fragment's\\n// host coordinate along it and `o` the host coordinate of inside 0 (the embedding's offset on that\\n// axis); `acrossOuter` how far in from the sheet's outer edge (world); `turned` the left edge (the\\n// glyph turned a quarter clockwise, read down, its top toward the face — the desk rulers' hand).\\n// The label is the site at or before the fragment: `index · mult · 10^exp` (ruler.wgsl `ruler_label`).\\nfn mm_numeral(M: MiniMat, k: MiniMatUniforms, tex: texture_2d<f32>, samp: sampler, A: f32, host: f32, o: f32, acrossOuter: f32, turned: bool) -> f32 {\\n let S = M.numerals.x;\\n if (S <= 0.0 || k.atlas2.w <= 0.0) { return 0.0; }\\n let s = max(M.inside.x, 1.0e-9);\\n let n = floor(A / S);\\n let index = i32(n);\\n let presence = select(M.numerals.w, 1.0, index % 10 == 0);\\n if (presence <= 0.0) { return 0.0; }\\n let tpw = k.atlas2.x / max(k.digits.x, 1.0e-6); // atlas texels per world unit, the cap on the digits' cap\\n let adv = k.atlas.z / tpw; // a digit's advance, world\\n let t = host - (o + n * S * s) - k.digits.y; // world along, after the tick and the gap\\n if (t < 0.0) { return 0.0; }\\n let slot = i32(floor(t / adv));\\n let g = ruler_label(index, i32(M.numerals.y), i32(M.numerals.z), slot);\\n if (g < 0) { return 0.0; }\\n var v = 0.0;\\n if (turned) { v = k.atlas.w - (acrossOuter - k.digits.z) * tpw; }\\n else { v = (acrossOuter - (k.digits.z - (k.atlas.w - k.atlas2.x) / tpw)) * tpw; }\\n return mm_glyph(tex, samp, k, g, (t - f32(slot) * adv) * tpw, v) * presence;\\n}\\n\\n// The NAME's glyph at slot `i` (minimat.ts `packGlyphs`: four 6-bit indices to a float).\\nfn mm_name_glyph(M: MiniMat, i: i32) -> i32 {\\n let f = M.name[i / 16][(i / 4) % 4];\\n return i32((u32(f) >> (6u * u32(i % 4))) & 63u);\\n}\\n\\n// The PRINT in the border, as a presence of the cream: the frame just outside the face; the ruler\\n// along its top and left edges — ticks on the inside's lattice (each rung at its line's presence,\\n// relative to the law's thickest: a tick is the line it stands for, printed on) and the numerals; and\\n// the NAME in the foot, from the face's left edge. A line never prints thinner than a device px (the\\n// ink thins instead); the words print only once their cap is legible. `q` in the sheet's frame, `fh`\\n// the face's half extents, `a` the inside point, `zoom` the camera's.\\nfn mm_print(u: MatUniforms, M: MiniMat, k: MiniMatUniforms, q: vec2f, fh: vec2f, a: vec2f, px: f32, ipx: f32, zoom: f32, tex: texture_2d<f32>, samp: sampler) -> f32 {\\n let w = max(k.print.w, px);\\n let thin = min(k.print.w / px, 1.0);\\n let dF = sdf_box(q, fh);\\n // the frame: a band hugging the face from outside (the live inside is clipped to the face, so it never covers it)\\n var ink = mm_line(dF - w, w, px) * k.print.x * thin;\\n if (dF <= 0.0) { return ink; }\\n // the ruler's ticks: out of the top edge (−y) and the left (−x)\\n let hw = 0.5 * w / max(M.inside.x, 1.0e-9);\\n let thick = max(u.line.w, 1.0e-3);\\n let outTop = -fh.y - q.y;\\n let outLeft = -fh.x - q.x;\\n var t = 0.0;\\n if (outTop > -px && q.x > -fh.x - px && q.x < fh.x + px) {\\n if (M.weights.x > 0.0) { t = max(t, mm_tick(a.x, M.rungs.x, hw, ipx, outTop, k.ticks.x, px) * min(M.weights.x / thick, 1.0)); }\\n if (M.weights.y > 0.0) { t = max(t, mm_tick(a.x, M.rungs.y, hw, ipx, outTop, k.ticks.y, px) * min(M.weights.y / thick, 1.0)); }\\n if (M.weights.z > 0.0) { t = max(t, mm_tick(a.x, M.rungs.z, hw, ipx, outTop, k.ticks.z, px) * min(M.weights.z / thick, 1.0)); }\\n }\\n if (outLeft > -px && q.y > -fh.y - px && q.y < fh.y + px) {\\n if (M.weights.x > 0.0) { t = max(t, mm_tick(a.y, M.rungs.x, hw, ipx, outLeft, k.ticks.x, px) * min(M.weights.x / thick, 1.0)); }\\n if (M.weights.y > 0.0) { t = max(t, mm_tick(a.y, M.rungs.y, hw, ipx, outLeft, k.ticks.y, px) * min(M.weights.y / thick, 1.0)); }\\n if (M.weights.z > 0.0) { t = max(t, mm_tick(a.y, M.rungs.z, hw, ipx, outLeft, k.ticks.z, px) * min(M.weights.z / thick, 1.0)); }\\n }\\n ink = max(ink, t * k.print.y * thin);\\n // the words, once their cap is legible on screen\\n let digitsOn = smoothstep(k.text.z, k.text.w, k.digits.x * zoom);\\n if (digitsOn > 0.0) {\\n if (outTop > 0.0 && q.x > -fh.x && q.x < fh.x) { ink = max(ink, mm_numeral(M, k, tex, samp, a.x, q.x + M.centre.x, M.inside.y, q.y + M.half.y, false) * k.print.y * digitsOn); }\\n if (outLeft > 0.0 && q.y > -fh.y && q.y < fh.y) { ink = max(ink, mm_numeral(M, k, tex, samp, a.y, q.y + M.centre.y, M.inside.z, q.x + M.half.x, true) * k.print.y * digitsOn); }\\n }\\n let nameOn = smoothstep(k.text.z, k.text.w, k.text.x * zoom);\\n if (nameOn > 0.0 && M.nameLen > 0.0 && q.y > fh.y) {\\n let tpw = k.atlas2.x / max(k.text.x, 1.0e-6);\\n // a mono face's cap is ~0.72 of its em: the tracking is in em\\n let adv = k.atlas.z / tpw + k.text.y * k.text.x / 0.72;\\n let x = q.x + fh.x; // world from the face's left edge\\n let baseline = 0.5 * (fh.y + M.half.y) + 0.5 * k.text.x; // the cap centred in the foot\\n if (x >= 0.0 && x < 2.0 * fh.x) {\\n let slot = i32(floor(x / adv));\\n if (f32(slot) < M.nameLen) {\\n let g = mm_name_glyph(M, slot);\\n let v = (q.y - baseline) * tpw + k.atlas.w;\\n ink = max(ink, mm_glyph(tex, samp, k, g, (x - f32(slot) * adv) * tpw, v) * k.print.y * nameOn);\\n }\\n }\\n }\\n return ink;\\n}\\n\\n// The vinyl's colour on screen under the desk's light: its albedo (sRGB, the print mixed in) through\\n// the mat's own chain — the same double gamma the desk's sage takes, the Moon by night — with the\\n// cut edge's roll on the linear value.\\nfn mm_vinyl(u: MatUniforms, albedo: vec3f, bevel: f32, gobo: f32, noise: f32) -> vec3f {\\n return mat_colour(u, srgb_to_linear(clamp(albedo, vec3f(0.0), vec3f(1.0))) * bevel, gobo, noise);\\n}\\n\\n// Paper on the face (a chip): the note's chain — the reference's grade on the sRGB albedo by day\\n// (lit, the identity), the eye's chain on its linear value by night.\\nfn mm_paper(u: MatUniforms, albedo: vec3f, gobo: f32, noise: f32) -> vec3f {\\n let day = shade_mat(u, albedo, gobo);\\n if (u.night.x <= 0.0) { return day; }\\n let night = night_mat(u, srgb_to_linear(albedo), gobo, noise);\\n if (u.night.x >= 1.0) { return night; }\\n return mix(day, night, u.night.x);\\n}\\n\",\n \"notebook/notebook-pass.wgsl\": \"// The notebook pass's entries (NOTEBOOK.md §6). Three draws per book into a 4× multisampled\\n// layer, then one composite onto the canvas:\\n// vs_shadow the book's depth from its lamp, into its layer of the shadow map\\n// vs_book · fs_book the book itself — depth-tested, opaque, its page corners rounded by the sample mask\\n// vs_recv · fs_recv the mat under it: the book's shadow (PCSS) and its contact, the selection ring —\\n// drawn after the book, so the depth test skips every pixel the book covers\\n// The book's record carries its placement, its lamp and its shadow map's frame.\\n// The view block `u` is the SLOT's since K4a (design-016 K-L3), shared with the mat and every kind: this layer is drawn at FULL\\n// presence, as it always was (the pass's own copy of the block carried no presentation, and the composite lays the layer whole),\\n// so it reads neither `u.view.w` (the objects' presence) nor `u.presence.x` (the slot's) — its alpha is its coverage alone.\\n\\n@group(0) @binding(0) var<uniform> u: MatUniforms;\\n@group(0) @binding(1) var<uniform> k: NbUniforms;\\n@group(0) @binding(2) var<storage, read> books: array<NbBook>;\\n@group(0) @binding(3) var gobo_tex: texture_2d<f32>;\\n@group(0) @binding(4) var gobo_samp: sampler;\\n@group(0) @binding(5) var noise_tex: texture_2d<f32>;\\n@group(0) @binding(6) var noise_samp: sampler;\\n@group(0) @binding(7) var shadow_tex: texture_depth_2d_array;\\n@group(0) @binding(8) var shadow_cmp: sampler_comparison;\\n@group(0) @binding(9) var ink_tex: texture_2d_array<f32>; // the pages' ink rasters (straight alpha)\\n@group(0) @binding(10) var ink_samp: sampler;\\n@group(0) @binding(11) var paper_tex: texture_2d<f32>; // the baked paper (mottle · fibres · the tooth's slope), mipmapped\\n@group(0) @binding(12) var paper_samp: sampler; // repeat, trilinear, anisotropic\\n\\n// The layer a page's ink is in, from the book's table; −1 when the page has none on the device. Read\\n// straight from the storage buffer: indexing the arrays of a by-value record would push the whole\\n// record out of registers.\\nfn nb_ink_layer(bi: u32, page: f32) -> i32 {\\n let pa = books[bi].inkPage[0];\\n let pb = books[bi].inkPage[1];\\n let hitA = (abs(pa - vec4f(page)) < vec4f(0.5)) & (pa >= vec4f(0.0));\\n let hitB = (abs(pb - vec4f(page)) < vec4f(0.5)) & (pb >= vec4f(0.0));\\n if (any(hitA)) { return i32(dot(select(vec4f(0.0), books[bi].inkLayer[0], hitA), vec4f(1.0)) + 0.5); }\\n if (any(hitB)) { return i32(dot(select(vec4f(0.0), books[bi].inkLayer[1], hitB), vec4f(1.0)) + 0.5); }\\n return -1;\\n}\\n\\nstruct VIn {\\n @location(0) pos: vec3f,\\n @location(1) nrm: vec3f,\\n @location(2) uv: vec2f,\\n @location(3) mat: vec4f, // material, page, flags, ao\\n @location(4) size: vec2f, // the face's size, world units\\n @location(5) extra: vec2f,\\n}\\n\\nstruct VOut {\\n @builtin(position) clip: vec4f,\\n @location(0) world: vec3f,\\n @location(1) nrm: vec3f,\\n @location(2) uv: vec2f,\\n @location(3) @interpolate(flat) mat: vec3f,\\n @location(4) ao: f32,\\n @location(5) @interpolate(flat) size: vec4f,\\n @location(6) @interpolate(flat) book: u32,\\n}\\n\\n@vertex\\nfn vs_shadow(@location(0) pos: vec3f, @builtin(instance_index) iid: u32) -> @builtin(position) vec4f {\\n let B = books[iid];\\n return B.light * (B.model * vec4f(pos, 1.0));\\n}\\n\\n@vertex\\nfn vs_book(v: VIn, @builtin(instance_index) iid: u32) -> VOut {\\n let B = books[iid];\\n var out: VOut;\\n let P = (B.model * vec4f(v.pos, 1.0)).xyz;\\n out.clip = nb_clip(k, P);\\n out.world = P;\\n out.nrm = (B.model * vec4f(v.nrm, 0.0)).xyz;\\n out.uv = v.uv;\\n out.mat = v.mat.xyz;\\n out.ao = v.mat.w;\\n out.size = vec4f(v.size, v.extra);\\n out.book = iid;\\n return out;\\n}\\n\\n@fragment\\nfn fs_book(in: VOut) -> @location(0) vec4f {\\n // every derivative first — they must be taken in uniform control flow\\n let dPdx = dpdx(in.world);\\n let dPdy = dpdy(in.world);\\n let dUdx = dpdx(in.uv);\\n let dUdy = dpdy(in.uv);\\n let dqdx = dUdx * in.size.xy;\\n let dqdy = dUdy * in.size.xy;\\n let B = books[in.book];\\n let px = max(max(length(dPdx), length(dPdy)), 1e-4); // world units per device px\\n let mat = i32(in.mat.x + 0.5);\\n let flags = u32(in.mat.z + 0.5);\\n var n = normalize(in.nrm);\\n let E = vec3f(k.eye.x, k.eye.y, k.eye.z);\\n let V = normalize(E - in.world);\\n var page = in.mat.y;\\n let q = in.uv * in.size.xy;\\n var inside = false;\\n if ((flags & 1u) != 0u && dot(n, V) < 0.0) { n = -n; page += 1.0; inside = true; }\\n\\n // the face's tangents (world units along its u and v) from the uv's screen derivatives\\n let det = dUdx.x * dUdy.y - dUdx.y * dUdy.x;\\n var Tu = vec3f(1.0, 0.0, 0.0);\\n var Tv = vec3f(0.0, 1.0, 0.0);\\n if (abs(det) > 1e-14) {\\n Tu = (dPdx * dUdy.y - dPdy * dUdx.y) / det;\\n Tv = (dPdy * dUdx.x - dPdx * dUdy.x) / det;\\n }\\n Tu = Tu - n * dot(n, Tu);\\n Tv = Tv - n * dot(n, Tv);\\n Tu = select(vec3f(1.0, 0.0, 0.0), normalize(Tu), length(Tu) > 1e-8);\\n Tv = select(vec3f(0.0, 1.0, 0.0), normalize(Tv), length(Tv) > 1e-8);\\n\\n let bn = textureSampleLevel(noise_tex, noise_samp, (in.clip.xy + k.ring.zw) * u.noise.z + u.noise.xy, 0.0).rgb;\\n var albedo = B.col6.rgb;\\n var grad = vec2f(0.0); // the surface's height slope along u and v\\n var ao = in.ao;\\n var dapple = k.light.w;\\n var sheen = vec2f(k.cloth.z, k.cloth.w);\\n let dbg = u32(k.ring.y);\\n\\n if ((dbg & 2u) != 0u) {\\n albedo = select(B.col0.rgb, B.col6.rgb, mat == 3 || mat == 4);\\n } else if (mat == 3) {\\n // a PAGE: ivory with its fibre and tooth, dots printed on it, its fore-edge corners rounded\\n let w = in.size.x;\\n let h = in.size.y;\\n let pp = nb_paper(k, B.col6.rgb, q, dqdx, dqdy, page, paper_tex, paper_samp);\\n albedo = pp.albedo;\\n grad = pp.g;\\n albedo = mix(albedo, k.ruleInk.rgb, nb_ruling(k, B, q, w, h, px) * k.ruleInk.a);\\n // the pen's ink, laid into the paper before the light: it takes the gutter, the dapple and the night with it\\n let layer = nb_ink_layer(in.book, page);\\n if (layer >= 0) {\\n let ink = textureSampleLevel(ink_tex, ink_samp, in.uv, layer, 0.0);\\n albedo = mix(albedo, ink.rgb, ink.a);\\n }\\n // the gutter's occlusion, and the page's own edge a breath darker\\n ao *= 1.0 - 0.3 * exp(-q.x / 4.5) - 0.12 * exp(-q.x / 18.0);\\n dapple = k.light.z;\\n sheen = vec2f(5.0, 0.02);\\n } else if (mat == 0) {\\n // the COVER: the cloth, the band, the design\\n albedo = nb_cover_albedo(k, B, q, px);\\n grad = nb_cover_g(k, B, q, px);\\n if (B.foot.y > 0.5 && q.x > B.page.w) { sheen = vec2f(6.0, 0.02); }\\n } else if (mat == 1) {\\n let end = nb_endpaper(k, B, q, px, in.size.w > 0.5, dqdx, dqdy, paper_tex, paper_samp);\\n albedo = end.albedo;\\n ao *= end.ao;\\n grad = nb_paper(k, B.col5.rgb, q, dqdx, dqdy, 77.0, paper_tex, paper_samp).g * 0.6;\\n dapple = k.light.z;\\n sheen = vec2f(5.0, 0.015);\\n } else if (mat == 2) {\\n albedo = nb_board(k, B, q, px);\\n } else if (mat == 4) {\\n albedo = nb_edge(k, B, q, in.size.z, in.size.w, px);\\n sheen = vec2f(4.0, 0.0);\\n dapple = k.light.z;\\n } else if (mat == 6) {\\n // the RIBBON: satin — a grosgrain of fine ribs along it, and a sheen that runs along its length (Kajiya–Kay on the weave's direction)\\n albedo = B.col4.rgb * (0.9 + 0.1 * sin(in.uv.y * 44.0));\\n grad = vec2f(0.0, cos(in.uv.y * 44.0) * 0.12);\\n sheen = vec2f(0.0, 0.0);\\n let Hs = normalize(B.lamp.xyz + V);\\n let th = dot(Tu, Hs);\\n let satin = pow(max(sqrt(max(1.0 - th * th, 0.0)), 0.0), 48.0) * 0.16;\\n albedo += vec3f(satin);\\n dapple = k.light.w;\\n } else {\\n // the SPINE: the band's cloth; seen from inside (the hollow of an open book), in shade\\n albedo = B.col1.rgb * (1.0 + nb_cloth(q, k.cloth.x, px).shade * 0.16);\\n if (inside) { albedo *= 0.5; ao *= 0.7; }\\n }\\n\\n // the bumped normal: the height's slope tips the face\\n let nb = normalize(n - Tu * grad.x - Tv * grad.y);\\n let L = B.lamp.xyz;\\n let lam = min(max(dot(nb, L), 0.0) / max(L.z, 1e-3), k.light.y);\\n // the book shades itself only while something of it rises over the rest (a sheet in the air, the cover swinging)\\n var vis = 1.0;\\n if (B.foot.w > 0.5) { vis = nb_shadow(k, B, in.world, n, bn.x * 6.2831853, shadow_tex, shadow_cmp); }\\n // paper sees more sky than cloth: the facing page and the desk bounce light onto it\\n let sky = select(k.light.x, mix(k.light.x, 1.0, 0.22), mat == 3);\\n var light = (sky + (1.0 - sky) * lam * vis) * ao;\\n if (mat == 3) {\\n // paper is translucent: a sheet with the lamp behind it glows with what comes through\\n let back = max(-dot(n, L), 0.0) / max(L.z, 1e-3);\\n light += 0.32 * (1.0 - k.light.x) * min(back, 1.2) * vis * ao;\\n }\\n var g0 = 1.0;\\n if ((dbg & 4u) == 0u) { g0 = sample_gobo(u, gobo_tex, gobo_samp, nb_desk_at(u, in.world), bn.z); }\\n let gobo = mix(1.0, g0, dapple);\\n var c = nb_colour(u, albedo, light, gobo, bn.y);\\n // the sheen: the lamp's glint on cloth and paper, where the lamp reaches\\n let Hh = normalize(L + V);\\n let sp = pow(max(dot(nb, Hh), 0.0), sheen.x) * sheen.y * vis * g0;\\n c += vec3f(sp * (1.0 - u.night.x * 0.85));\\n\\n return vec4f(c, 1.0);\\n}\\n\\n// ---- the mat under a book: its shadow, its contact, its ring\\n\\nstruct ROut {\\n @builtin(position) clip: vec4f,\\n @location(0) world: vec2f,\\n @location(1) @interpolate(flat) book: u32,\\n}\\n\\nconst RQUAD = array<vec2f, 6>(vec2f(0.0, 0.0), vec2f(1.0, 0.0), vec2f(1.0, 1.0), vec2f(0.0, 0.0), vec2f(1.0, 1.0), vec2f(0.0, 1.0));\\n\\n@vertex\\nfn vs_recv(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> ROut {\\n let B = books[iid];\\n var out: ROut;\\n let p = mix(B.recv.xy, B.recv.zw, RQUAD[vid]);\\n out.clip = nb_clip(k, vec3f(p, 0.0));\\n out.world = p;\\n out.book = iid;\\n return out;\\n}\\n\\n// The book's footprint on the desk, in its own coordinates: the back board, and — once the cover has come down — the spine and the front board beside it.\\nfn nb_footprint(B: NbBook, p: vec2f) -> f32 {\\n let w = B.size.x;\\n let h = B.size.y;\\n let r = B.size.w;\\n let back = nb_sd_fore(p + vec2f(w * 0.5, h * 0.5), w, h, r);\\n if (B.foot.x < 0.5) { return back; }\\n let sw = B.open.z;\\n let front = nb_sd_fore(vec2f(-w * 0.5 - sw - p.x, p.y + h * 0.5), w, h, r);\\n let spine = nb_sd_box(p - vec2f(-w * 0.5 - sw * 0.5, 0.0), vec2f(sw * 0.5 + 0.5, h * 0.5), 0.0);\\n return min(back, min(front, spine));\\n}\\n\\n@fragment\\nfn fs_recv(in: ROut) -> @location(0) vec4f {\\n let B = books[in.book];\\n let P = vec3f(in.world, 0.0);\\n let bn = textureSampleLevel(noise_tex, noise_samp, (in.clip.xy + k.ring.zw) * u.noise.z + u.noise.xy, 0.0).rgb;\\n let vis = nb_shadow(k, B, P, vec3f(0.0, 0.0, 1.0), bn.x * 6.2831853, shadow_tex, shadow_cmp);\\n let aS = k.shadow.z * (1.0 - vis);\\n // the contact: where the case meets the mat, fading as it rises\\n let L = (B.inv * vec4f(P, 1.0)).xyz;\\n let d = nb_footprint(B, L.xy);\\n let rise = max(-L.z, 0.0);\\n let touch = 1.0 - smoothstep(0.0, k.shadow2.y, rise);\\n let s = k.shadow2.x;\\n let aC = k.shadow.w * touch * exp(-max(d, 0.0) * max(d, 0.0) / (2.0 * s * s)) * step(-0.5, d);\\n let a = 1.0 - (1.0 - aS) * (1.0 - aC);\\n var c = vec4f(k.castCol.rgb * a, a);\\n // the selection ring, on the mat around the book\\n let css = 1.0 / max(k.eye.w, 1e-6);\\n let rw = k.select.w * css;\\n let rd = abs(d - k.ring.x * css) - rw * 0.5;\\n let ring = nb_cov(rd, css / max(k.shadow2.w, 1.0)) * B.look.z;\\n c = vec4f(k.select.rgb * ring, ring) + c * (1.0 - ring);\\n return c;\\n}\\n\",\n \"paper/paper-card.wgsl\": \"// The note as the paper pass AND the flat-card pipeline draw it (K7b, design-016 §6 K7): the corner's clip position and\\n// the fragment, over the note's bindings by their own names — `papers`, `paper_k`, `paper_ink` … — beside the slot's `u`,\\n// `gobo_tex`, `noise_tex` and the pipeline's `LIT_ELSEWHERE`, which whichever entry composes them declares. One quad per\\n// sheet, expanded by the shadow's reach and the AA; one `shade_paper` per covered fragment in world units, premultiplied,\\n// through the presentation's opacity and the portal clip; alpha < 0 = discard.\\n\\nconst PAPER_CORNERS = array<vec2f, 6>(\\n vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0),\\n vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0),\\n);\\n\\nfn paper_quad(slot: u32, vid: u32) -> vec4f {\\n let P = papers[slot];\\n let zoom = mat_zoom(u);\\n let px = 1.0 / (zoom * mat_dpr(u));\\n // the tilted sheet's bounds, grown by everything the fragment can paint outside it: the shadow's reach and the AA\\n let hmax = P.lift + P.curl * (1.0 + P.cornerCurl);\\n let pad = length(P.slope) * hmax + 2.5 * (P.shadow.x + P.shadow.z * hmax) + 3.0 * px;\\n let ext = vec2f(abs(P.rot.x) * P.half.x + abs(P.rot.y) * P.half.y, abs(P.rot.y) * P.half.x + abs(P.rot.x) * P.half.y) + vec2f(pad);\\n let lo = (P.centre - ext - u.cam.xy) * zoom; // CSS px\\n let hi = (P.centre + ext - u.cam.xy) * zoom;\\n if (hi.x < u.box.x || hi.y < u.box.y || lo.x > u.box.x + u.box.z || lo.y > u.box.y + u.box.w) { return vec4f(2.0, 2.0, 2.0, 1.0); } // degenerate: a culled instance collapses\\n let corner = PAPER_CORNERS[vid];\\n let pos = mix(lo, hi, corner * 0.5 + 0.5);\\n return vec4f(pos.x / u.view.x * 2.0 - 1.0, 1.0 - pos.y / u.view.y * 2.0, 0.0, 1.0);\\n}\\n\\nfn paper_frag(slot: u32, clip: vec4f) -> vec4f {\\n let P = papers[slot];\\n let dpr = mat_dpr(u);\\n let px = 1.0 / (mat_zoom(u) * dpr);\\n let p = clip.xy * px + u.cam.xy; // device px → world\\n let c = shade_paper(P, u, paper_k, p, px, px * dpr, clip.xy, gobo_tex, paper_gobo_samp, noise_tex, paper_noise_samp, paper_ink, paper_ink_samp, LIT_ELSEWHERE);\\n if (c.a < 0.002) { return vec4f(-1.0); }\\n return c * (u.view.w * portal_cover(clip.xy / dpr, u.portals, u.clips, dpr));\\n}\\n\",\n \"paper/paper-pass.wgsl\": \"// The paper pass — the notes, instanced: one quad per sheet, expanded on the\\n// vertex side by the shadow's reach and the AA, one `shade_paper` per covered\\n// fragment in world units, premultiplied output through the presentation's\\n// opacity and the portal clip (like the frames). The quad and the fragment are\\n// paper-card.wgsl's — the flat-card pipeline draws a note with the same two (K7b).\\n\\n// The slot is lit from elsewhere (MINIMAT.md §4): the pass's second pipeline — a pipeline constant, never a uniform flag.\\noverride LIT_ELSEWHERE: bool = false;\\n\\n@group(0) @binding(0) var<uniform> u: MatUniforms;\\n@group(0) @binding(1) var<uniform> paper_k: PaperUniforms;\\n@group(0) @binding(2) var<storage, read> papers: array<Paper>;\\n@group(0) @binding(3) var gobo_tex: texture_2d<f32>; // the mat's animated silhouette (its wind target)\\n@group(0) @binding(4) var paper_gobo_samp: sampler;\\n@group(0) @binding(5) var noise_tex: texture_2d<f32>;\\n@group(0) @binding(6) var paper_noise_samp: sampler;\\n@group(0) @binding(7) var paper_ink: texture_2d_array<f32>; // the ink pages: r8 coverage, one layer of rasters per binding\\n@group(0) @binding(8) var paper_ink_samp: sampler;\\n@group(0) @binding(9) var<storage, read> order: array<u32>; // the draw list: paint index → the record's slot (persistent records, D6)\\n\\nstruct VSOut {\\n @builtin(position) clip: vec4f,\\n @location(0) @interpolate(flat) idx: u32,\\n}\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> VSOut {\\n var out: VSOut;\\n out.idx = order[iid];\\n out.clip = paper_quad(out.idx, vid);\\n return out;\\n}\\n\\n@fragment\\nfn fs(in: VSOut) -> @location(0) vec4f {\\n let c = paper_frag(in.idx, in.clip);\\n if (c.a < 0.0) { discard; }\\n return c;\\n}\\n\",\n \"paper/paper.wgsl\": \"// The PAPER — a sticky note as a material under the mat's one light\\n// (STICKY.md). A PURE module: the records, the two uniform blocks and the\\n// textures arrive as parameters; it names no colour. The sheet is a rounded\\n// box in its own tilted frame with a HEIGHT off the mat — flat under the\\n// adhesive strip, rising as t² to the free edge, its corners most, the whole\\n// sheet raised while held — and that height does three things: it tilts the\\n// normal the lamp shades, it moves the point the gobo is read at, and it casts\\n// the sheet's shadow along the lamp's ground slope, blurred by how high the\\n// rim is there. The ink is a coverage raster laid into the paper's albedo\\n// before the light, so the dapple crosses the writing as it crosses the mat.\\n\\nfn paper_cov(d: f32, px: f32) -> f32 { return clamp(0.5 - d / px, 0.0, 1.0); }\\nfn paper_line(d: f32, w: f32, px: f32) -> f32 { return paper_cov(d, px) - paper_cov(d + w, px); }\\n\\nfn paper_erf(x: f32) -> f32 {\\n let s = sign(x);\\n let a = abs(x);\\n let t = 1.0 / (1.0 + 0.3275911 * a);\\n let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-a * a);\\n return s * y;\\n}\\n// Gaussian-blurred coverage — the shadow, straight out of the field.\\nfn paper_blur_cov(d: f32, sigma: f32) -> f32 { return 0.5 - 0.5 * paper_erf(d / max(sigma * 1.4142136, 1.0e-4)); }\\n\\n// Premultiplied \\\"src over dst\\\".\\nfn paper_over(src: vec4f, dst: vec4f) -> vec4f { return src + dst * (1.0 - src.a); }\\n\\n// World → the sheet's own frame; a world direction → the same.\\nfn paper_local(P: Paper, p: vec2f) -> vec2f {\\n let d = p - P.centre;\\n return vec2f(P.rot.x * d.x + P.rot.y * d.y, -P.rot.y * d.x + P.rot.x * d.y);\\n}\\nfn paper_dir(P: Paper, v: vec2f) -> vec2f { return vec2f(P.rot.x * v.x + P.rot.y * v.y, -P.rot.y * v.x + P.rot.x * v.y); }\\n\\n// The sheet's height off the mat at a local point (paper.ts `heightAt` is the same arithmetic).\\nfn paper_height(P: Paper, q: vec2f) -> f32 {\\n let hy = P.half.y;\\n let flat = -hy + P.glue * 2.0 * hy;\\n let t = saturate((q.y - flat) / max(2.0 * hy * (1.0 - P.glue), 1.0e-6));\\n let c = pow(min(abs(q.x) / max(P.half.x, 1.0e-6), 1.0), 6.0);\\n return P.lift + P.curl * t * t * (1.0 + P.cornerCurl * c);\\n}\\n\\n// The sheet's normal from its height, by central differences one world unit apart — the slope\\n// exaggerated by the relief (`shadow.w`), or a few px of curl over a hundred would shade nothing.\\nfn paper_normal(P: Paper, q: vec2f) -> vec3f {\\n let e = 1.0;\\n let dx = paper_height(P, q + vec2f(e, 0.0)) - paper_height(P, q - vec2f(e, 0.0));\\n let dy = paper_height(P, q + vec2f(0.0, e)) - paper_height(P, q - vec2f(0.0, e));\\n return normalize(vec3f(-dx * P.shadow.w / (2.0 * e), -dy * P.shadow.w / (2.0 * e), 1.0));\\n}\\n\\n// A world point raised `h` world units off the desk, in the projector's frame (mat.wgsl `desk_of` with a height).\\nfn paper_desk_at(u: MatUniforms, world: vec2f, h: f32) -> vec3f {\\n return vec3f(u.plane.x + world.x * u.plane.z, u.plane.w + h * u.plane.z, u.plane.y + world.y * u.plane.z);\\n}\\n\\n// The paper's colour on screen under the mat's light: by day the reference's grade on the\\n// sheet's sRGB albedo — lit, the identity, so a configured byte is the drawn byte — or, at\\n// `chain` 1, through the mat's own double gamma (what the sage goes through); by night the\\n// eye's chain on the sheet's linear albedo, as the mat's. Between, the cross-fade.\\nfn paper_colour(u: MatUniforms, albedo: vec3f, gobo: f32, noise: f32, chain: f32) -> vec3f {\\n let day = shade_mat(u, mix(albedo, srgb_to_linear(albedo), chain), gobo);\\n if (u.night.x <= 0.0) { return day; }\\n let night = night_mat(u, srgb_to_linear(albedo), gobo, noise);\\n if (u.night.x >= 1.0) { return night; }\\n return mix(day, night, u.night.x);\\n}\\n\\n// K7b — the writing GREEKED at `nq` (note units from the sheet's top-left), as a mini mat's chip greeks a note (MINIMAT.md §5):\\n// each line a stroke of the pen's ink from the text's left edge along its width, on its x-height's middle (0.32 em over the\\n// baseline), `far.z` × the em thick — its coverage at `far.w`, the greek's presence (theme.ts `PAPER.far`).\\nfn paper_greek(P: Paper, k: PaperUniforms, nq: vec2f, px: f32) -> f32 {\\n let n = min(u32(P.greek.z), 6u);\\n let em = P.greek.y;\\n let r = 0.5 * k.far.z * em;\\n var lines = P.glines;\\n var cov = 0.0;\\n for (var i = 0u; i < n; i++) {\\n let v = lines[i / 2u];\\n let L = select(v.xy, v.zw, (i & 1u) == 1u);\\n let y = L.x - 0.32 * em;\\n cov = max(cov, paper_cov(sdf_segment(nq, vec2f(P.greek.x, y), vec2f(P.greek.x + L.y, y)) - r, px));\\n }\\n return cov * k.far.w;\\n}\\n\\n// One note at a world point `p`: premultiplied colour. `px` is world units per DEVICE px,\\n// `css` world units per CSS px; `frag` the framebuffer pixel (the blue noise's key); `lit` the\\n// slot is lit from elsewhere (a mini mat's inside, a handover — MINIMAT.md §4): a PIPELINE constant,\\n// never a uniform flag, so a note under its own lamp compiles to exactly what it always did.\\nfn shade_paper(P: Paper, u: MatUniforms, k: PaperUniforms, p: vec2f, px: f32, css: f32, frag: vec2f,\\n gobo_tex: texture_2d<f32>, gobo_samp: sampler, noise_tex: texture_2d<f32>, noise_samp: sampler,\\n ink_tex: texture_2d_array<f32>, ink_samp: sampler, lit: bool) -> vec4f {\\n let q = paper_local(P, p);\\n let d = sdf_round_box(q, P.half, P.radius);\\n // The shadow, outside the sheet only: the silhouette cast along the lamp's ground slope\\n // by the height of the nearest rim point, blurred by that height — a flat strip lies in\\n // a tight contact shadow, the curled edge and a held sheet in a wider, softer one.\\n let rim = clamp(q, -P.half, P.half);\\n let hr = paper_height(P, rim);\\n let ds = sdf_round_box(q - paper_dir(P, P.slope) * hr, P.half, P.radius);\\n let sh = paper_blur_cov(ds, P.shadow.x + P.shadow.z * hr) * P.shadow.y * (1.0 - paper_cov(d, px));\\n var acc = vec4f(0.0, 0.0, 0.0, sh);\\n if (d > px) { return acc * P.alpha; }\\n let cov = paper_cov(d, px);\\n\\n // K7b — THE FAR LOD (theme.ts `PAPER.far`): the sheet's longer side on screen, CSS px. Under the band's high edge the writing\\n // crossfades to its greeked lines and the FIBRE — the finest detail, a grain that only aliases once a texel spans units — fades\\n // out; under its low edge the lines alone and no fibre is computed. The lamp's shading of the curl stays (it reads at any size).\\n // Above the band `fine` is 1: the full path, the very arithmetic it always was.\\n let size = 2.0 * max(P.half.x, P.half.y) / css;\\n let far = 1.0 - smoothstep(k.far.x, k.far.y, size); // edges ascending: a descending smoothstep is undefined in Metal (two Dawns differ)\\n let fine = 1.0 - far;\\n\\n // The sheet: its height, its normal, the lamp — the flat strip reads 1, the curl turns toward or from the light.\\n let h = paper_height(P, q);\\n let n = paper_normal(P, q);\\n let L = vec3f(paper_dir(P, P.lamp.xy), P.lamp.z);\\n let diffuse = saturate(dot(n, L)) / max(L.z, 1.0e-3);\\n\\n // The albedo: the paper with its fibre (in the sheet's own units, so the grain sticks to it), the ink laid into it.\\n let bn = textureSampleLevel(noise_tex, noise_samp, frag * u.noise.z + u.noise.xy, 0.0).rgb;\\n var fibre = 0.0;\\n if (fine > 0.0) {\\n fibre = ((value_noise(q * 0.9) - 0.5) + (value_noise(q * 3.1) - 0.5) * 0.5 + (bn.x - 0.5) * 0.5) * P.paper.w;\\n if (fine < 1.0) { fibre = fibre * fine; }\\n }\\n var albedo = P.paper.xyz + vec3f(fibre * 1.1, fibre, fibre * 0.7);\\n let nq = q + P.half; // note units from the sheet's top-left\\n let uv = P.uv.xy + (nq / (2.0 * P.half)) * (P.uv.zw - P.uv.xy);\\n var ink = 0.0;\\n if (P.layer >= 0) { ink = textureSampleLevel(ink_tex, ink_samp, uv, P.layer, 0.0).r; }\\n // The wipe: the pen still writing the newest glyph — inside its box the ink appears left to right.\\n if (P.wipe.z > P.wipe.x && nq.x >= P.wipe.x && nq.x <= P.wipe.z && nq.y >= P.wipe.y && nq.y <= P.wipe.w) {\\n let edge = P.wipe.x + P.marks.x * (P.wipe.z - P.wipe.x + k.knobs.y);\\n ink *= 1.0 - smoothstep(edge - k.knobs.y, edge, nq.x);\\n }\\n // K7b: the greeked lines in the raster's place — crossfaded within the band, alone under it (where no raster is held).\\n // K9 R6: and held at FULL while the sheet holds no raster at any size (`layer < 0` — its ink is on the frame queue's way, or\\n // was let go at far and not yet laid on the way back): the greek stands in for the writing until the raster lands, never a\\n // blank sheet. The fibre keeps the band's word (`fine`): the paper's grain is the size's, not the raster's.\\n var greeked = far;\\n if (P.layer < 0 && P.greek.z > 0.5) { greeked = 1.0; }\\n if (greeked > 0.0 && P.greek.z > 0.5) { ink = mix(ink, paper_greek(P, k, nq, px), greeked); }\\n albedo = mix(albedo, P.ink.xyz, ink * P.ink.w);\\n // the lamp's shading, in the display's own gamma (the mat's law: a linear multiply shows as shade^(1/2.2))\\n albedo = albedo * pow(max(diffuse, 0.0), 1.0 / 2.2);\\n // the dapple: under the slot's own lamp the desk point itself — else where the LIGHT sees it: the lamp of the desk a mini mat lies on (MINIMAT.md §4)\\n var gobo = sample_gobo(u, gobo_tex, gobo_samp, paper_desk_at(u, p, h), bn.z);\\n if (lit) { gobo = lit_gobo(u, gobo_tex, gobo_samp, p, h, paper_desk_at(u, p, h), bn.z); }\\n let colour = paper_colour(u, clamp(albedo, vec3f(0.0), vec3f(1.0)), gobo, bn.y, k.knobs.x);\\n acc = paper_over(vec4f(colour * cov, cov), acc);\\n\\n // The caret: a bar of the ink at the writing head, on the host's blink.\\n if (P.marks.y > 0.5) {\\n let cw = k.knobs.z * css;\\n let cq = nq - vec2f(P.caret.x, P.caret.y - P.caret.z);\\n let ch = P.caret.z + P.caret.w;\\n let cd = sdf_box(cq - vec2f(cw * 0.5, ch * 0.5), vec2f(cw * 0.5, ch * 0.5));\\n let cc = paper_cov(cd, px) * 0.9;\\n acc = paper_over(vec4f(P.ink.xyz * cc, cc), acc);\\n }\\n // The sole-selection ring, inside the edge, in the theme's select.\\n let ring = paper_line(d, k.knobs.w * css, px) * P.ring;\\n acc = paper_over(vec4f(k.select.xyz * ring, ring), acc);\\n return acc * P.alpha;\\n}\\n\",\n \"photo/photo-card.wgsl\": \"// The print as the photo pass AND the flat-card pipeline draw it (K7b, design-016 §6 K7): the corner's clip position, the\\n// fragment and the THUMBNAIL's texel, over the print's bindings by their own names — `photos`, `photo_k`, `photo_thumbs` … —\\n// beside the slot's `u`, `gobo_tex`, `noise_tex` and the pipeline's `LIT_ELSEWHERE`, which whichever entry composes them\\n// declares. `shade_photo` reads a picture through `photo_texel`: the pass's entry reads the detail pool there, else the\\n// thumbnail; the card binds no pool and reads the thumbnail alone (a print with a detail bound is the pass's to draw).\\n\\n// The thumbnail array's layer side (pictures.ts `THUMB`).\\nconst PHOTO_THUMB = 512.0;\\n\\nconst PHOTO_CORNERS = array<vec2f, 6>(\\n vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0),\\n vec2f(-1.0, -1.0), vec2f(1.0, 1.0), vec2f(-1.0, 1.0),\\n);\\n\\n// A picture's texel at (uv, lod) from its THUMBNAIL — lod in its whole chain's levels: the layer (its `tier.x`), which starts at\\n// the chain's level k (`tier.y`) — the picture at its origin, its edge carried to the layer's — at lod − k (a print larger than\\n// the layer serves, before its detail comes, magnifies the layer's first level).\\nfn photo_thumb(P: Photo, uv: vec2f, lod: f32) -> vec4f {\\n let k = P.tier.y;\\n let size = max(floor(P.image.xy / exp2(k)), vec2f(1.0)); // the layer's picture at its level 0, texels\\n return textureSampleLevel(photo_thumbs, photo_pic_samp, uv * size / PHOTO_THUMB, i32(P.tier.x), max(lod - k, 0.0));\\n}\\n\\nfn photo_quad(slot: u32, vid: u32) -> vec4f {\\n let P = photos[slot];\\n let zoom = mat_zoom(u);\\n let lo = (P.bounds.xy - u.cam.xy) * zoom; // CSS px\\n let hi = (P.bounds.zw - u.cam.xy) * zoom;\\n if (P.centre.w <= 0.0 || hi.x < 0.0 || hi.y < 0.0 || lo.x > u.view.x || lo.y > u.view.y) { return vec4f(2.0, 2.0, 2.0, 1.0); } // degenerate: a culled instance collapses\\n let pos = mix(lo, hi, PHOTO_CORNERS[vid] * 0.5 + 0.5);\\n return vec4f(pos.x / u.view.x * 2.0 - 1.0, 1.0 - pos.y / u.view.y * 2.0, 0.0, 1.0);\\n}\\n\\nfn photo_frag(slot: u32, clip: vec4f) -> vec4f {\\n let P = photos[slot];\\n let dpr = mat_dpr(u);\\n let px = 1.0 / (mat_zoom(u) * dpr);\\n let s = clip.xy * px + u.cam.xy; // device px → world\\n let c = shade_photo(P, u, photo_k, s, px, clip.xy, gobo_tex, photo_gobo_samp, noise_tex, photo_noise_samp, LIT_ELSEWHERE);\\n if (c.a < 0.002) { return vec4f(-1.0); }\\n return c * (u.view.w * portal_cover(clip.xy / dpr, u.portals, u.clips, dpr));\\n}\\n\",\n \"photo/photo-pass.wgsl\": \"// The photo pass — one quad per print over the world rect `resolvePhoto`\\n// measured (the sheet as seen and its shadow), one `shade_photo` per covered\\n// fragment, premultiplied output through the presentation's opacity and the\\n// portal clip. The pictures are SHARED (group 1 — K6a, K-L4): a print's record\\n// names its thumbnail's layer in one array and, while it is large on screen, the\\n// pool slot of its detail — so a run of prints is ONE instanced draw; the paint\\n// order is the instance order. The quad, the fragment and the thumbnail's texel are\\n// photo-card.wgsl's — the flat-card pipeline draws a print with the same three (K7b).\\n\\n// The slot is lit from elsewhere (MINIMAT.md §4): the pass's second pipeline — a pipeline constant, never a uniform flag.\\noverride LIT_ELSEWHERE: bool = false;\\n\\n@group(0) @binding(0) var<uniform> u: MatUniforms;\\n@group(0) @binding(1) var<uniform> photo_k: PhotoUniforms;\\n@group(0) @binding(2) var<storage, read> photos: array<Photo>;\\n@group(0) @binding(3) var gobo_tex: texture_2d<f32>; // the mat's animated silhouette (its wind target)\\n@group(0) @binding(4) var photo_gobo_samp: sampler;\\n@group(0) @binding(5) var noise_tex: texture_2d<f32>;\\n@group(0) @binding(6) var photo_noise_samp: sampler;\\n@group(0) @binding(7) var photo_pic_samp: sampler; // trilinear, clamped\\n@group(0) @binding(8) var<storage, read> order: array<u32>; // the draw list: paint index → the record's slot (persistent records, D6)\\n@group(1) @binding(0) var photo_thumbs: texture_2d_array<f32>; // every picture's chain from its first level ≤ THUMB² (rgba8unorm-srgb), a layer each\\n@group(1) @binding(1) var detail0: texture_2d<f32>; // the pool: a large print's chain from the finest level it samples\\n@group(1) @binding(2) var detail1: texture_2d<f32>;\\n@group(1) @binding(3) var detail2: texture_2d<f32>;\\n@group(1) @binding(4) var detail3: texture_2d<f32>;\\n@group(1) @binding(5) var detail4: texture_2d<f32>;\\n@group(1) @binding(6) var detail5: texture_2d<f32>;\\n@group(1) @binding(7) var detail6: texture_2d<f32>;\\n@group(1) @binding(8) var detail7: texture_2d<f32>;\\n\\n// A picture's texel at (uv, lod) — lod in its WHOLE chain's levels. `tier`: its thumbnail's layer, the chain level that layer\\n// starts at (k), the pool slot of its detail (−1: none) and the level the detail starts at (j). Both are cuts of one chain: the\\n// detail at lod − j, else the layer (photo-card.wgsl `photo_thumb`).\\nfn photo_texel(P: Photo, uv: vec2f, lod: f32) -> vec4f {\\n let slot = i32(P.tier.z);\\n let l = max(lod - P.tier.w, 0.0);\\n switch slot {\\n case 0: { return textureSampleLevel(detail0, photo_pic_samp, uv, l); }\\n case 1: { return textureSampleLevel(detail1, photo_pic_samp, uv, l); }\\n case 2: { return textureSampleLevel(detail2, photo_pic_samp, uv, l); }\\n case 3: { return textureSampleLevel(detail3, photo_pic_samp, uv, l); }\\n case 4: { return textureSampleLevel(detail4, photo_pic_samp, uv, l); }\\n case 5: { return textureSampleLevel(detail5, photo_pic_samp, uv, l); }\\n case 6: { return textureSampleLevel(detail6, photo_pic_samp, uv, l); }\\n case 7: { return textureSampleLevel(detail7, photo_pic_samp, uv, l); }\\n default: {}\\n }\\n return photo_thumb(P, uv, lod);\\n}\\n\\nstruct VSOut {\\n @builtin(position) clip: vec4f,\\n @location(0) @interpolate(flat) idx: u32,\\n}\\n\\n@vertex\\nfn vs(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> VSOut {\\n var out: VSOut;\\n out.idx = order[iid];\\n out.clip = photo_quad(out.idx, vid);\\n return out;\\n}\\n\\n@fragment\\nfn fs(in: VSOut) -> @location(0) vec4f {\\n let c = photo_frag(in.idx, in.clip);\\n if (c.a < 0.0) { discard; }\\n return c;\\n}\\n\",\n \"photo/photo.wgsl\": \"// The PHOTO — a glossy print as a material under the desk's one light\\n// (PHOTO.md). A PURE module: the record, the two uniform blocks and the\\n// textures arrive as parameters. The sheet is a rounded box in 3D — a centre\\n// with a height, its own axes on a tilted plane, a bend — seen through a\\n// LOCAL eye over its anchor (photo.ts `unproject` is this arithmetic on the\\n// CPU): the fragment's desk point is a ray from that eye, cast onto the sheet.\\n// Its shadow is the same cast from the desk point toward the light: where the\\n// ray meets the sheet, how high the sheet is there sets the blur. The picture\\n// is laid into the paper's albedo before the light (so the dapple crosses it\\n// as it crosses the mat); the coating's gloss is added after it — the lamp's\\n// highlight where the sheet turns toward it, and the room's sheen at a slant.\\n\\nfn photo_cov(d: f32, px: f32) -> f32 { return clamp(0.5 - d / px, 0.0, 1.0); }\\n\\nfn photo_erf(x: f32) -> f32 {\\n let s = sign(x);\\n let a = abs(x);\\n let t = 1.0 / (1.0 + 0.3275911 * a);\\n let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-a * a);\\n return s * y;\\n}\\n// Gaussian-blurred coverage of the silhouette — the shadow, straight out of the field.\\nfn photo_blur_cov(d: f32, sigma: f32) -> f32 { return 0.5 - 0.5 * photo_erf(d / max(sigma * 1.4142136, 1.0e-4)); }\\n\\nfn photo_over(src: vec4f, dst: vec4f) -> vec4f { return src + dst * (1.0 - src.a); }\\n\\nfn photo_encode(c: vec3f) -> vec3f {\\n return mix(c * 12.92, 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055, step(vec3f(0.0031308), c));\\n}\\n\\n// The bend's offset along the normal at a point of the sheet (photo.ts `bendAt`):\\n// the rest curl rises toward the short edges; a held sheet droops away from the grab point.\\nfn photo_bend(P: Photo, q: vec2f) -> f32 {\\n let d = length(q - P.bend.zw) / (2.0 * length(vec2f(P.ex.w, P.ey.w)));\\n let cu = q.x / max(P.ex.w, P.ey.w);\\n return P.bend.y * cu * cu - P.bend.x * d * d;\\n}\\n\\n// The sheet's normal with its bend, by central differences one world unit apart.\\nfn photo_normal(P: Photo, q: vec2f) -> vec3f {\\n let dx = photo_bend(P, q + vec2f(1.0, 0.0)) - photo_bend(P, q - vec2f(1.0, 0.0));\\n let dy = photo_bend(P, q + vec2f(0.0, 1.0)) - photo_bend(P, q - vec2f(0.0, 1.0));\\n return normalize(P.n.xyz - P.ex.xyz * (dx * 0.5) - P.ey.xyz * (dy * 0.5));\\n}\\n\\n// A ray (origin o, direction D) onto the sheet: the point in 3D and the sheet's frame, with one bend correction.\\nstruct PhotoHit { p: vec3f, q: vec2f, ok: bool }\\nfn photo_cast(P: Photo, o: vec3f, D: vec3f) -> PhotoHit {\\n var h: PhotoHit;\\n let n = P.n.xyz;\\n let dn = dot(n, D);\\n if (abs(dn) < 1.0e-5) { h.ok = false; return h; }\\n var t = dot(n, P.centre.xyz - o) / dn;\\n var p = o + D * t;\\n var q = vec2f(dot(p - P.centre.xyz, P.ex.xyz), dot(p - P.centre.xyz, P.ey.xyz));\\n t = dot(n, P.centre.xyz + n * photo_bend(P, q) - o) / dn;\\n p = o + D * t;\\n let r = p - (P.centre.xyz + n * photo_bend(P, q));\\n h.p = p;\\n h.q = vec2f(dot(r, P.ex.xyz), dot(r, P.ey.xyz));\\n h.ok = t > 0.0;\\n return h;\\n}\\n\\n// The picture at a point of the sheet: sRGB-encoded rgb, and whether this point is the picture (1) or the border (0). Its texel\\n// at (uv, lod) is the entry's `photo_texel` (K6a: the entry binds where the pixels live — a shared array's layer, a pool's detail).\\nfn photo_picture(P: Photo, q: vec2f, px: f32) -> vec4f {\\n let inner = vec2f(P.ex.w, P.ey.w) - vec2f(P.eye.w);\\n if (P.image.w < 0.5 || inner.x <= 0.0 || inner.y <= 0.0) { return vec4f(0.0); }\\n let d = sdf_box(q, inner);\\n let cov = photo_cov(d, px);\\n if (cov <= 0.0) { return vec4f(0.0); }\\n let uv = clamp((q + inner) / (2.0 * inner), vec2f(0.0), vec2f(1.0));\\n // the mip: texels per device pixel along the picture's wider axis (the ray's own foreshortening is small; the eye is far)\\n let lod = clamp(log2(max(P.image.x / (2.0 * inner.x), P.image.y / (2.0 * inner.y)) * px), 0.0, P.image.z - 1.0);\\n let c = photo_texel(P, uv, lod);\\n return vec4f(photo_encode(c.rgb), cov * c.a);\\n}\\n\\n// The print by day: the mat's light — the reference's grade on the sRGB albedo, lit the identity (a\\n// picture's byte is the drawn byte), the palm's shade darkening it as it darkens the mat.\\n//\\n// The print by NIGHT (PHOTO.md §4a): the same Moon, the same palm, seen by the eye that sees by moonlight\\n// — but the print keeps its colour where it is a PICTURE. The fovea has no rods: what the eye looks at it\\n// sees with cones alone, white-balanced to the thing it attends to (CIECAM's D → 1), so a picture keeps its\\n// hue while its light is the Moon's. The paper around it is seen as the mat is (night_mat's model: the\\n// Moon's partly adapted warmth, the rods' blue by the mesopic weight at its own luminance, their noise).\\n// The level is the mat's night LAW, not its exposure number: moonlit = `k.night.x` (½) of the day's\\n// luminance (MAT.md §2; the mat's exposure is fitted to its double-gamma day look, a print's day look is\\n// its plain sRGB). The shade is the night's: the sky's fill `moon.w` where the palm blocks the Moon.\\n// `keep` = how far a picture's pixel is seen foveally (1 = its hue exactly).\\nfn photo_night(u: MatUniforms, k: PhotoUniforms, albedo: vec3f, gobo: f32, pic: f32, noise: f32) -> vec3f {\\n let lin = srgb_to_linear(albedo);\\n let shade = u.moon.w + (1.0 - u.moon.w) * gobo;\\n let fovea = pic * k.night.y;\\n // the cones: the paper takes the Moon's partly adapted warmth, the picture the eye's own white\\n let cone = lin * mix(u.moon.xyz, vec3f(1.0), fovea) * shade * k.night.x;\\n // the rods, as night_mat has them: V' normalised to white, drawn in the rods' blue\\n let rod = max(night_scotopic(cone), 0.0) / night_scotopic(vec3f(1.0));\\n let L = u.night.y * night_luminance(lin * u.moon.xyz * shade) * 0.3183098862; // cd/m² on the print: E · ρ / π\\n let m = mix(night_mesopic(L), 1.0, fovea);\\n let see = mix(rod * u.rod.xyz, cone, m);\\n // the dark is not black (MAT.md §1.5): the paper wears Eigengrau and the rods' snow as the mat does; the fovea's\\n // picture takes the same floor as a NEUTRAL grey of Eigengrau's luminance — a grey keeps the hue, the blue would not\\n let floor = mix(u.eigengrau.xyz, vec3f(night_luminance(u.eigengrau.xyz)), fovea);\\n return night_encode(floor + see) + (noise - 0.5) * u.night.w * (1.0 - fovea);\\n}\\n\\nfn photo_colour(u: MatUniforms, k: PhotoUniforms, albedo: vec3f, gobo: f32, pic: f32, noise: f32) -> vec3f {\\n let day = shade_mat(u, albedo, gobo);\\n if (u.night.x <= 0.0) { return day; }\\n let night = photo_night(u, k, albedo, gobo, pic, noise);\\n if (u.night.x >= 1.0) { return night; }\\n return mix(day, night, u.night.x);\\n}\\n\\n// A world point raised `h` world units off the desk, in the projector's frame (mat.wgsl `desk_of` with a height).\\nfn photo_desk_at(u: MatUniforms, world: vec2f, h: f32) -> vec3f {\\n return vec3f(u.plane.x + world.x * u.plane.z, u.plane.w + h * u.plane.z, u.plane.y + world.y * u.plane.z);\\n}\\n\\n// One print at a desk point `s`: premultiplied colour. `px` is world units per DEVICE px; `frag` the framebuffer pixel; `lit`\\n// the slot is lit from elsewhere (a mini mat's inside, a handover — MINIMAT.md §4): a PIPELINE constant, never a uniform flag,\\n// so a print under its own lamp compiles to exactly what it always did (the note's precedent, paper.wgsl `shade_paper`).\\nfn shade_photo(P: Photo, u: MatUniforms, k: PhotoUniforms, s: vec2f, px: f32, frag: vec2f,\\n gobo_tex: texture_2d<f32>, gobo_samp: sampler, noise_tex: texture_2d<f32>, noise_samp: sampler, lit: bool) -> vec4f {\\n let half = vec2f(P.ex.w, P.ey.w);\\n let L = P.light.xyz;\\n\\n // THE SHADOW: from the desk point toward the light, onto the sheet. Its height there is the ray's\\n // own parameter (the ray rises one unit per unit), so a flat sheet lies in its contact shadow and a\\n // lifted or tilted one casts a wider, softer, offset one — the tilted outline, not a rect's.\\n var sh = 0.0;\\n let a = vec3f(-P.slope.xy, 1.0);\\n let hs = photo_cast(P, vec3f(s, 0.0), a);\\n if (hs.ok || P.centre.z < 0.5) {\\n let height = max(hs.p.z, 0.0);\\n let ds = sdf_round_box(hs.q, half, P.n.w);\\n let pen = photo_blur_cov(ds, k.penumbra.y + k.penumbra.z * height) * P.light.w;\\n let con = photo_blur_cov(ds, k.contact.y) * k.contact.x * (1.0 - smoothstep(0.0, k.contact.z, height));\\n sh = 1.0 - (1.0 - pen) * (1.0 - con);\\n }\\n var acc = vec4f(k.shade.xyz * sh, sh);\\n\\n // THE SHEET: the ray from the local eye through the desk point.\\n let eye = P.eye.xyz;\\n let hit = photo_cast(P, eye, vec3f(s, 0.0) - eye);\\n if (!hit.ok) { return acc * P.centre.w; }\\n let q = hit.q;\\n // a device pixel on the desk is (eye − h)/eye of that on the sheet\\n let pxs = px * max(eye.z - hit.p.z, 1.0) / eye.z;\\n let d = sdf_round_box(q, half, P.n.w);\\n if (d > pxs) { return acc * P.centre.w; }\\n let cov = photo_cov(d, pxs);\\n\\n let bn = textureSampleLevel(noise_tex, noise_samp, frag * u.noise.z + u.noise.xy, 0.0).rgb;\\n // the paper: resin-coated, a faint fibre that sticks to the sheet\\n let fibre = ((value_noise(q * 0.7) - 0.5) + (bn.x - 0.5) * 0.5) * k.paper.w;\\n var albedo = k.paper.xyz + vec3f(fibre);\\n let pic = photo_picture(P, q, pxs);\\n albedo = mix(albedo, pic.rgb, pic.a);\\n\\n // the light: the lamp's diffuse on the bent sheet (flat = 1, the configured byte), in the display's gamma as the mat's law\\n let n = photo_normal(P, q);\\n let diffuse = clamp(dot(n, L) / max(L.z, 1.0e-3), 0.0, 1.6);\\n albedo = clamp(albedo * pow(diffuse, 1.0 / 2.2), vec3f(0.0), vec3f(1.0));\\n // the dapple: under the slot's own lamp the sheet's point itself — else where the LIGHT sees it: the lamp of the desk a mini mat lies on (MINIMAT.md §4)\\n var gobo = sample_gobo(u, gobo_tex, gobo_samp, photo_desk_at(u, hit.p.xy, hit.p.z), bn.z);\\n if (lit) { gobo = lit_gobo(u, gobo_tex, gobo_samp, hit.p.xy, hit.p.z, photo_desk_at(u, hit.p.xy, hit.p.z), bn.z); }\\n var colour = photo_colour(u, k, albedo, gobo, pic.a, bn.y);\\n // the light on the coating: the Sun's, or by night the Moon's — the same palm blocks both, and the Moon's\\n // glint is dimmer (the night's level) and cooler (what the rods make of a white highlight)\\n let night = saturate(u.night.x);\\n let glint = mix(vec3f(1.0, 0.985, 0.95), vec3f(0.78, 0.86, 1.0) * k.night.x, night);\\n\\n // the coating: the lamp's highlight (blocked where the palm shades it) and the room's sheen at a slant (Schlick)\\n let V = normalize(eye - hit.p);\\n let H = normalize(L + V);\\n let spec = pow(max(dot(n, H), 0.0), k.gloss.y) * k.gloss.x * gobo;\\n let R = reflect(-V, n);\\n let window = smoothstep(0.62, 0.97, dot(R, L));\\n let fres = 0.04 + 0.96 * pow(1.0 - max(dot(n, V), 0.0), 5.0);\\n let sheen = (0.12 + 0.88 * window) * fres * k.gloss.z * (0.4 + 0.6 * gobo);\\n colour = colour + glint * (spec + sheen);\\n // the cut edge: a hairline a shade darker, where the light grazes the paper's thickness\\n let edge = photo_cov(d + 0.9 * pxs, pxs) ;\\n colour = colour * (1.0 - 0.18 * (1.0 - edge));\\n colour = clamp(colour + (bn.y - 0.5) / 255.0, vec3f(0.0), vec3f(1.0));\\n\\n acc = photo_over(vec4f(colour * cov, cov), acc);\\n return acc * P.centre.w;\\n}\\n\",\n} as const;\nexport type WgslFile = keyof typeof WGSL;\n","// The reference kinds' SHADER TEXT (design-016 K4b: per-package shader generation). A kind's own WGSL — shaders/<kind>/ — is\n// this package's generated module (shaders.gen.ts); the kit's pieces (the slot's view block, the portal chain, the sdf, the\n// light, the book kit — what `kitWgsl` names) are the desk's, asked of `@ice/desk`'s `shaderText`, so a kind composes the kit by\n// name and never reads the desk's files. What a browser host composes the kinds from (`deskKinds()`, each kind's default); the\n// Node oracle composes the same two roots from disk, byte for byte.\nimport { type ShaderText, shaderText as deskText } from \"@ice/desk\";\nimport { WGSL, type WgslFile } from \"./shaders.gen\";\n\n/** The text of every file a shader-file map names, by the map's keys: a kind's file from this package, the kit's from the desk. */\nexport const shaderText: ShaderText = <T extends Record<string, string>>(files: T): { readonly [K in keyof T]: string } => {\n const own: Record<string, string> = {};\n const kit: Record<string, string> = {};\n for (const [key, file] of Object.entries(files)) {\n if (Object.hasOwn(WGSL, file)) own[key] = WGSL[file as WgslFile];\n else kit[key] = file;\n }\n return { ...deskText(kit), ...own } as { readonly [K in keyof T]: string };\n};\n","// The MINI MAT (MINIMAT.md) as a kind (kind.ts): the mini mat pass behind the registry's door —\n// a thin adapter, the pass and its WGSL as they were. Stratum `sheets`: a mini mat lies flat on\n// the mat beneath every thing, and it HOLDS a desk — the ground draws a live inside right after\n// its mini mat and tells the pass (the `extra`'s `live`) which faces give way to one, and the\n// chips come back over the inside while its objects fade in (`drawOver`, MINIMAT.md §5).\n//\n// And its WORLD half (kinds/world.ts; D2a-world): `minimatKind` — an entity of the mini mat's\n// widget type becomes a `MiniMatInstance` through the prototype's own laws: `resolveMiniMat` on\n// the rect and the flux (lift ← `Grab`, hover ← the pointer's exact hit — a mini mat RISES under\n// the pointer, Marks on the Mat Q-j —, ring ← `Selected`, fade ← a ghost), `miniMatInstance` over\n// an EMPTY inside — no chips, `live` −1 — the far LOD's lattice dressed for the inside's arrival\n// as `insideView` makes it (D2b brings the inside's members, the chips and the live slot);\n// `pickMiniMat` is the mirror: the face is `content`, the border `frame`. Its vinyl is the\n// product's (`theme()`, the palette's `vinyls`); `sage` is the desk's own ground.\n\nimport { type KindExtra, type KindPass, type KindProgram, type SlotContext, type Palette, type RGB, rgb, type ThemeName, type TokenRef, type ObjectContext, type ObjectHit, type ObjectKind, stringProp } from \"@ice/desk\";\nimport { DEFAULT_GRID, type GridConfig, type MatPass, type MarkFrame, type ChildShape, FIT, PORTAL_GATE, type ShaderText, VINYL_FINISH } from \"@ice/desk/kit\";\nimport { insideView, miniMatInstance } from \"./inside\";\nimport type { MiniMatInstance } from \"./layout\";\nimport { chipOf, DEFAULT_MINIMAT_LAW, faceClip, faceOf, MINIMAT_FINISHES, type MiniMatGeometry, type MiniMatLaw, pickMiniMat, resolveMiniMat } from \"./minimat\";\nimport { MiniMatPass } from \"./pass\";\nimport { MINIMAT_SHADER_FILES, miniMatShaders } from \"./shaders\";\nimport { shaderText } from \"../shaders\";\nimport { MINIMAT } from \"./theme\";\n\n/** The mini mat's kind name — its key in the registry and in every slot's `objects`. */\nexport const MINIMAT_KIND = \"minimat\";\n\nexport class MiniMatKind implements KindPass<MiniMatInstance> {\n /** The mini mat pass itself: a host's door to its law (`law`) and this frame's chips. */\n readonly pass: MiniMatPass;\n constructor(pass: MiniMatPass) { this.pass = pass; }\n\n spawn(mat: MatPass): MiniMatKind { return new MiniMatKind(this.pass.spawn(mat)); }\n\n tune(root: KindPass<MiniMatInstance>): void { if (root instanceof MiniMatKind) this.pass.tune(root.pass); }\n\n setLaw(law: unknown): void { this.pass.law = law as MiniMatLaw; }\n\n /**\n * The pass's own `prepare`, argument for argument; the ground's word on each mini mat's live inside (`extra.live`,\n * by this kind's record index) overrides the instance's own — absent, the instances say.\n */\n prepare(_encoder: GPUCommandEncoder, s: SlotContext, records: readonly MiniMatInstance[], extra?: KindExtra): number {\n return this.pass.prepare(s.view, s.fadeIn, s.cfg, s.frame, records, s.present, s.light, s.select, s.lit, extra?.live, extra?.keys);\n }\n\n dropped(): number { return this.pass.dropped; }\n\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void { this.pass.drawRange(pass, first, end); }\n records() { return this.pass.records; }\n\n /** Mini mat `index`'s chips over its live inside, while the inside's objects are not whole. */\n drawOver(pass: GPURenderPassEncoder, index: number): void { this.pass.drawChips(pass, index); }\n\n dispose(): void { this.pass.dispose(); }\n}\n\n/** The mini mat's program for a host's shader text: its pass made on the root's mat. */\nexport function miniMatProgram(text: ShaderText): KindProgram<MiniMatInstance> {\n return {\n name: MINIMAT_KIND,\n stratum: \"sheets\",\n create: async (device, format, mat) => new MiniMatKind(await MiniMatPass.create(device, format, miniMatShaders(text), mat)),\n };\n}\n\n// ---------------------------------------------------------------- the world half (D2a-world)\n\n/** What the mini mat's kind takes from the host's palette: the vinyls by the `vinyl` prop's value (`sage` needs none — it is the desk's own ground). */\nexport interface MiniMatPalette extends Palette {\n readonly vinyls?: Readonly<Record<string, TokenRef>>;\n}\n\n/** The mini mat's look for a theme: its vinyls, parsed. */\nexport interface MiniMatLook {\n readonly vinyls: Readonly<Record<string, RGB>>;\n}\n\n/** The vinyl the desk's own mat is: the `vinyl` prop's value that means \"the ground's colour\". */\nexport const SAGE = \"sage\";\n\n/** How far a mini mat's drawing reaches past its rect, world units: the slab's shadow swept from its top, its penumbra and contact term, the held scale. */\nexport function miniMatReach(law: MiniMatLaw = DEFAULT_MINIMAT_LAW): number {\n const top = law.lift.height + law.thick;\n const p = law.shadow.penumbra;\n const shadow = law.shadow.slopeMax * top + 2.5 * (p.sigma0 + p.sigmaPerHeight * top) + 2.5 * law.shadow.contact.sigma;\n const held = (Math.max(law.size.w, law.size.h) * (law.lift.scale - 1)) / 2;\n return shadow + held;\n}\n\nexport interface MiniMatKindOptions {\n /** The host's shader text; the generated module unless a host says. */\n readonly text?: ShaderText;\n /** The mini mat's numbers (theme.ts `MINIMAT`) — the engine's unless a host tweaks them. */\n readonly law?: MiniMatLaw;\n}\n\n/** The mini mat's kind, whole (kinds/world.ts `ObjectKind`): the program, and the world half on the prototype's laws over an empty inside. */\n/** The grid a mini mat's inside draws with: the desk's own fade-in, the mat in the mini mat's vinyl, no rulers (a portal's inside never prints them). */\nfunction insideGrid(ctx: Pick<ObjectContext, \"props\" | \"look\">, root: GridConfig): GridConfig {\n const look = ctx.look as MiniMatLook | undefined;\n const vinylName = stringProp(ctx.props, \"vinyl\", SAGE);\n const vinyl = vinylName === SAGE ? root.mat.ground : (look?.vinyls[vinylName] ?? root.mat.ground);\n return { fadeIn: root.fadeIn, mat: { ...root.mat, ground: vinyl, ruler: { ...root.mat.ruler, on: false } } };\n}\n\nexport function minimatKind(opts: MiniMatKindOptions = {}): ObjectKind<MiniMatGeometry, MiniMatInstance, MiniMatLook> {\n let law = opts.law ?? DEFAULT_MINIMAT_LAW;\n const program = miniMatProgram(opts.text ?? shaderText);\n return {\n ...program,\n // the reach is the construction law's: a live law moves the face, not the shadow's reach (the dev panel's rows — D5a)\n reach: miniMatReach(law),\n // the record reads the inside camera's zoom for the face's far-LOD lattice and its numerals (inside.ts `miniMatInstance`) and nothing\n // else of the camera (D6) — CONTINUOUSLY (K6b, D-K6b.1): every rung's weight and width ramps over its decade of the zoom (lattice/\n // line.ts `lineWeight`) and the three rungs span every zoom, so no step of it leaves the face's pixels as they were — no `rung`\n rezoom: true,\n tune(next: unknown): void { law = next as MiniMatLaw; },\n resolve(ctx: ObjectContext): MiniMatGeometry {\n const r = ctx.rect;\n return resolveMiniMat({ cx: r.cx, cy: r.cy, w: r.w, h: r.h }, { held: ctx.flux.lift, hover: ctx.flux.hover, ring: ctx.flux.ring, fade: ctx.flux.fade }, law, ctx.lamp);\n },\n record(G: MiniMatGeometry, ctx: ObjectContext): MiniMatInstance {\n const grid = insideGrid(ctx, ctx.grid);\n const cam = { x: ctx.view.camX, y: ctx.view.camY, zoom: ctx.view.zoom };\n const vp = { width: ctx.view.width, height: ctx.view.height };\n // the inside as the builder saw it (D2b: its content's bounds, its view through this face, its children as chips); with no\n // word from the builder — a bare kind — the inside is EMPTY: its arrival is the origin at zoom 1, its face's far LOD the lattice\n // of that desk, no chips. The view is the flight's own numbers, so the far LOD and the live inside agree to the bit.\n const view = ctx.inside?.view ?? insideView(G, ctx.inside?.content ?? null, cam, vp, FIT, PORTAL_GATE) ?? {\n M: { s: 1, ox: G.centre[0], oy: G.centre[1] }, arrival: cam, cam, clip: faceClip(G, cam), presence: 0, box: { x: 0, y: 0, w: 0, h: 0 },\n };\n const chips = (ctx.inside?.chips ?? []).map((c) => chipOf(c, view.M, law.chips.greekWeight));\n const name = stringProp(ctx.props, \"name\", \"\");\n return { ...miniMatInstance(G, view, grid, chips, name || undefined, true, law), live: -1 };\n },\n hit(G: MiniMatGeometry, wx: number, wy: number): ObjectHit | null {\n const h = pickMiniMat(G, wx, wy);\n return h === \"face\" ? \"content\" : h === \"border\" ? \"frame\" : null;\n },\n /** The face as drawn: the sheet inset by its printed border, through its springs (`faceOf` — what the live inside and the nav cut read). */\n face(G: MiniMatGeometry) { return faceOf(G); },\n // its face law (K8a — the container's own numbers, never the kit's): its square corner, its far face's chip cap (the live law's)\n // and the finishes it draws a child's chip in\n get faceLaw() { return { radius: MINIMAT.faceRadius, chips: law.chips.max, finishes: MINIMAT_FINISHES }; },\n /** Inside another mini mat, a mini mat is a vinyl chip with its border (the prototype's `childrenOf`). */\n chip(G: MiniMatGeometry, ctx: ObjectContext): ChildShape {\n const look = ctx.look as MiniMatLook | undefined;\n const vinylName = stringProp(ctx.props, \"vinyl\", SAGE);\n const vinyl = vinylName === SAGE ? ctx.grid.mat.ground : (look?.vinyls[vinylName] ?? ctx.grid.mat.ground);\n return { finish: VINYL_FINISH, cx: G.centre[0], cy: G.centre[1], hx: G.half[0], hy: G.half[1], angle: 0, radius: G.radius, colour: vinyl, height: G.thick, margin: G.margin };\n },\n insideGrid,\n frame: miniMatFrame,\n theme(palette: Palette, _name: ThemeName): MiniMatLook {\n const p = palette as MiniMatPalette;\n return { vinyls: Object.fromEntries(Object.entries(p.vinyls ?? {}).map(([k, t]) => [k, rgb(t.css)])) };\n },\n };\n}\n\n/** The grid a mini mat's inside is drawn with when a host names none: the engine's (re-exported for D2b's live insides). */\nexport const INSIDE_GRID: GridConfig = DEFAULT_GRID;\n\n/** The mini mat's silhouette for the desk's marks (D4a): the sheet as drawn, square to the mat, its die-cut corner. */\nexport function miniMatFrame(G: MiniMatGeometry): MarkFrame {\n return { cx: G.centre[0], cy: G.centre[1], hx: G.half[0], hy: G.half[1], angle: 0, r: G.radius };\n}\n","// The MINI MAT (MINIMAT.md) as an OBJECT — the desk's CONTAINER through `defineObject` (design-015\n// §6): a small cutting mat lying on the big one with a desk inside it. Durable props: its printed\n// `name` and its `vinyl` (sage — the desk's own — slate, charcoal: the product's colours through\n// the palette, kinds/minimat.ts `MiniMatPalette`). Sheets, movable, selectable; a container that\n// holds what provides `CONTAINABLE` (notes, mini mats — K8a), its FACE — the inside's window — the sheet inset by the printed\n// border (`portal` = `MINIMAT.margin` on every side, the same rect `faceOf` cuts). Flat in this\n// slice: the inside's members, the chips, the live slot and the flight are D2b's.\n\nimport { p } from \"@ice/core\";\nimport { minimatKind } from \"./kind\";\nimport { CONTAINABLE, DESK_OBJECT, defineObject } from \"@ice/desk\";\nimport { MINIMAT } from \"./theme\";\n\n/** The vinyls a mini mat is sold in (MINIMAT.md §2) — names; `sage` is the desk's ground, the rest the host's. */\nexport const VINYLS = [\"sage\", \"slate\", \"charcoal\"] as const;\nexport type VinylName = (typeof VINYLS)[number];\n\n/** The mini mat's durable type id. */\nexport const MINIMAT_TYPE = \"desk.minimat\";\n\n/** Its selection-menu act's id (K8a): the vinyl cycles — an app's key (`t`) runs it through `ops.runMenuAction`. */\nexport const VINYL_ACT = \"vinyl\";\n/** The act's glyph, the mat's own drawing in the bar's 24-unit box: a vinyl sample — a swatch with two strokes of its grain. */\nconst VINYL_GLYPH = \"M6.5 5h11A1.5 1.5 0 0 1 19 6.5v11a1.5 1.5 0 0 1-1.5 1.5h-11A1.5 1.5 0 0 1 5 17.5v-11A1.5 1.5 0 0 1 6.5 5ZM5 13l8-8M11 19l8-8\";\n\nexport const MiniMat = defineObject({\n type: MINIMAT_TYPE,\n version: 1,\n props: {\n name: p.string({ default: \"\" }),\n vinyl: p.enum(VINYLS, { default: \"sage\" }),\n },\n size: { w: MINIMAT.size.w, h: MINIMAT.size.h },\n kind: minimatKind(),\n // on the pegboard tray (design-017 §8): a mini mat on a shelf\n tray: { label: \"Mini mat\", category: \"surfaces\", order: 0, hang: { w: 213, h: 160, accessory: \"shelf\", pegs: [[-2, 0.5], [2, 0.5]] } },\n interaction: { selectable: true, movable: true, resizable: false, snap: \"both\" },\n // its act in the selection menu (K8a — the kind's own, where the app's `t` key held it over the type name until then): the\n // selected mini mats' vinyl cycles sage → slate → charcoal, each mat one undo step; the inside's mat is the same vinyl, so it follows\n menu: [{\n id: VINYL_ACT, label: \"Change the vinyl\", keys: \"T\", glyph: { path: VINYL_GLYPH },\n run: (api) => {\n for (const e of api.entities) {\n const cur = api.props(e).vinyl;\n const next = VINYLS[(VINYLS.indexOf(cur as VinylName) + 1) % VINYLS.length] ?? VINYLS[0];\n api.setProps(e, { vinyl: next });\n }\n },\n }],\n container: {\n // it holds what provides `CONTAINABLE` (K8a — a note, a mini mat, a plugin kind that declares its chip), never a list of types;\n // and it lies on the desk, and in another mini mat, by what it provides itself\n accepts: [CONTAINABLE],\n provides: [MINIMAT_TYPE, DESK_OBJECT, CONTAINABLE],\n portal: { top: MINIMAT.margin, right: MINIMAT.margin, bottom: MINIMAT.margin, left: MINIMAT.margin },\n },\n});\n","// The NOTE's own theme — its law as numbers (design-015 §4.1: beside the engine's src/theme.ts, a kind's own theme.ts is\n// the one other literal home; moved out of the engine's at K4a, design-016 §5). What it shares with every desk object —\n// the lift, the shadow, the selection ring — is the kit's ONE PHYSICS (kit/physics.ts), by name.\n\nimport { PHYSICS } from \"@ice/desk/kit\";\n\n/**\n * PAPER — the desk's first object (STICKY.md): a sticky note as a MATERIAL under the\n * mat's one light. A square of thin paper pressed flat under its adhesive strip and\n * free below it, where it rises a little off the mat and its corners rise most; stuck\n * a degree or two off square, as a hand leaves it; lit by the lamp that casts the\n * palm's shadow (the gobo projector — `paper.ts` `lampOf`), so the dapple crosses it\n * and its shadow falls away from that lamp; by night, under the Moon like the mat.\n * Lengths are world units (CSS px at zoom 1). The paper's colour is the product's\n * (`--vf-note-surface`, lab/theme.ts); the pen's ink is the host's too.\n */\nexport const PAPER = {\n /** The note's side — a 3″ square read at about the card grid's scale (DESIGN.md §4: small 155). */\n size: 200,\n /** The die-cut corner. */\n radius: 1.5,\n /** Never stuck square: each note takes its own tilt within ± this, degrees. */\n tilt: 2.5,\n /** The fraction of the height pressed flat under the adhesive strip. */\n glue: 0.3,\n /** How far the free edge rises off the mat, and how much more its corners rise than its middle. */\n curl: 3, cornerCurl: 0.6,\n /** How far a HELD note rises and the scale it reads at: the one physics's (kit/physics.ts). */\n lift: PHYSICS.lift,\n /** The contact shadow on the mat: the one physics's penumbra (kit/physics.ts). */\n shadow: PHYSICS.shadow,\n /** How much the sheet's slope is exaggerated for the lamp's shading: a curl of a few px over a hundred is invisible at 1; at this it reads as paper. */\n relief: 3.5,\n /** The paper's fibre: ±/255 on the albedo. */\n grain: 2.5 / 255,\n /** The sole-selection ring (DESIGN.md §7), CSS px, in `--vf-select`: the one physics's. */\n ring: PHYSICS.ring,\n /** The caret: CSS px wide, the platform's blink. */\n caret: { width: 1.5, blinkMs: 530 },\n /**\n * The FAR LOD (K7b, design-016 §6 K7): under `px[1]` CSS px (the sheet's longer side on screen) the writing crossfades to its\n * GREEKED lines — bars of the pen's ink at `alpha`, `weight` × the em thick through each line's x-height, as a mini mat's chip\n * greeks a note (MINIMAT.md §5) — and the fibre fades out with it (the cheap path: the grain aliases once a device px spans units\n * of paper); under `px[0]` the note is greeked alone: no raster held, none asked, no fibre computed.\n */\n far: { px: [48, 64], weight: 0.3, alpha: 0.42 },\n} as const;\n","// The PAPER's law — pure: no GPU. A sticky note on the desk is a rect with a\n// tilt; `resolvePaper` turns it and its motion (held · selected · fading)\n// into the GEOMETRY the pass draws and the hit-test reads, in plain numbers,\n// and the functions beside it are the CPU mirror of paper.wgsl — the local\n// frame, the sheet's distance, its height off the mat — so what is clicked is\n// what is drawn. The lamp is the mat's gobo projector (MAT.md), placed on the\n// desk plane in world units by `lampOf`: one light for the dapple, the\n// paper's shading and its shadow. The raster ladder (`rasterBand`) decides\n// how many texels a note's ink is drawn with at a zoom, with hysteresis so a\n// note re-rasters on a band crossing, never on a frame.\n\nimport { type Lamp, lampOf, sdRoundBox, hashHand } from \"@ice/desk/kit\";\nimport { PAPER } from \"./theme\";\n\n/** The paper's numbers (theme.ts `PAPER`) — the engine's unless a host tweaks them. */\nexport interface PaperLaw {\n readonly size: number;\n readonly radius: number;\n readonly tilt: number;\n readonly glue: number;\n readonly curl: number;\n readonly cornerCurl: number;\n readonly relief: number;\n readonly lift: { readonly height: number; readonly scale: number };\n readonly shadow: { readonly sigma: number; readonly alpha: number; readonly sigmaPerUnit: number; readonly alphaHeld: number; readonly slopeMax: number };\n readonly grain: number;\n readonly ring: number;\n readonly caret: { readonly width: number; readonly blinkMs: number };\n readonly far: { readonly px: readonly [number, number]; readonly weight: number; readonly alpha: number };\n}\nexport const DEFAULT_PAPER_LAW: PaperLaw = PAPER;\n\n// The lamp is the MAT's (mat/lamp.ts — D7 #5, the kit's door since K4a): every kind's shadow falls from it; the paper keeps its door for its importers.\nexport { type Lamp, lampOf } from \"@ice/desk/kit\";\n\n/** A note's tilt from its seed: within ± `maxDeg`, radians — never square, never the same twice. */\nexport const tiltOf = (seed: number, maxDeg: number): number => ((hashHand(seed, 11)[1] - 0.5) * 2 * maxDeg * Math.PI) / 180;\n\nexport interface PaperRect {\n /** World centre. */\n readonly cx: number; readonly cy: number;\n /** The sheet, world units. */\n readonly w: number; readonly h: number;\n /** Radians; positive turns clockwise on screen. */\n readonly angle: number;\n}\n\n/** What moves: the hold's lift (0..1), the selection ring's presence (0..1), the presence itself (1 … 0 gone). */\nexport interface PaperMotion { readonly held: number; readonly ring: number; readonly fade: number }\nexport const PAPER_REST: PaperMotion = { held: 0, ring: 0, fade: 1 };\n\nexport interface PaperGeometry {\n readonly centre: readonly [number, number];\n /** Half extents as drawn (the hold's scale applied). */\n readonly half: readonly [number, number];\n readonly cos: number; readonly sin: number; readonly angle: number;\n /** World units off the mat: the hold's rise; the free edge's curl over it; the corners' extra; the flat strip's share. */\n readonly lift: number; readonly curl: number; readonly cornerCurl: number; readonly glue: number;\n /** The slope's exaggeration for the shading. */\n readonly relief: number;\n readonly radius: number;\n readonly shadow: { readonly sigma: number; readonly alpha: number; readonly sigmaPerUnit: number };\n /** The shadow's ground offset per unit of height, world axes — away from the lamp, capped. */\n readonly slope: readonly [number, number];\n /** The unit direction to the lamp, world axes (x right, y down the screen, z off the desk). */\n readonly lamp: readonly [number, number, number];\n readonly ring: number;\n readonly alpha: number;\n readonly scale: number;\n}\n\nconst mix = (a: number, b: number, t: number) => a + (b - a) * t;\n\nexport function resolvePaper(n: PaperRect, m: PaperMotion, law: PaperLaw, lamp: Lamp): PaperGeometry {\n const scale = 1 + (law.lift.scale - 1) * m.held;\n const dx = lamp.x - n.cx;\n const dy = lamp.y - n.cy;\n const h = Math.max(lamp.h, 1e-6);\n const len = Math.hypot(dx, dy, h);\n let sx = -dx / h;\n let sy = -dy / h;\n const s = Math.hypot(sx, sy);\n if (s > law.shadow.slopeMax) { sx *= law.shadow.slopeMax / s; sy *= law.shadow.slopeMax / s; }\n return {\n centre: [n.cx, n.cy], half: [(n.w / 2) * scale, (n.h / 2) * scale],\n cos: Math.cos(n.angle), sin: Math.sin(n.angle), angle: n.angle,\n lift: law.lift.height * m.held, curl: law.curl, cornerCurl: law.cornerCurl, glue: law.glue, relief: law.relief, radius: law.radius,\n shadow: { sigma: law.shadow.sigma, alpha: mix(law.shadow.alpha, law.shadow.alphaHeld, m.held), sigmaPerUnit: law.shadow.sigmaPerUnit },\n slope: [sx, sy], lamp: [dx / len, dy / len, h / len],\n ring: m.ring, alpha: m.fade, scale,\n };\n}\n\n/** World → the sheet's own frame (paper.wgsl `paper_local`). */\nexport function localOf(G: PaperGeometry, wx: number, wy: number): readonly [number, number] {\n const x = wx - G.centre[0];\n const y = wy - G.centre[1];\n return [G.cos * x + G.sin * y, -G.sin * x + G.cos * y];\n}\n/** The sheet's own frame → world. */\nexport function worldOf(G: PaperGeometry, qx: number, qy: number): readonly [number, number] {\n return [G.centre[0] + G.cos * qx - G.sin * qy, G.centre[1] + G.sin * qx + G.cos * qy];\n}\n\n/** The sheet's signed distance at a world point. */\nexport function sdPaper(G: PaperGeometry, wx: number, wy: number): number {\n const [qx, qy] = localOf(G, wx, wy);\n return sdRoundBox(qx, qy, G.half[0], G.half[1], G.radius);\n}\nexport type PaperHit = \"paper\" | \"outside\";\nexport const pickPaper = (G: PaperGeometry, wx: number, wy: number): PaperHit => (sdPaper(G, wx, wy) < 0 ? \"paper\" : \"outside\");\n\n/**\n * The sheet's height off the mat at a local point (paper.wgsl `paper_height`):\n * the hold's rise everywhere; flat under the strip; from the strip's lower edge\n * to the free edge the curl rises as t², the corners by `cornerCurl` more.\n */\nexport function heightAt(G: PaperGeometry, qx: number, qy: number): number {\n const hy = G.half[1];\n const hx = Math.max(G.half[0], 1e-6);\n const flat = -hy + G.glue * 2 * hy;\n const t = Math.min(Math.max((qy - flat) / Math.max(2 * hy * (1 - G.glue), 1e-6), 0), 1);\n const corner = Math.min(Math.abs(qx) / hx, 1) ** 6;\n return G.lift + G.curl * t * t * (1 + G.cornerCurl * corner);\n}\n\n/** How far the shadow can reach past the sheet, world units — the vertex quad's pad. */\nexport function shadowReach(G: PaperGeometry): number {\n const hmax = G.lift + G.curl * (1 + G.cornerCurl);\n return Math.hypot(G.slope[0], G.slope[1]) * hmax + 2.5 * (G.shadow.sigma + G.shadow.sigmaPerUnit * hmax);\n}\n\n/** The sheet's axis-aligned bounds in world units, grown by `pad`. */\nexport function boundsOf(G: PaperGeometry, pad = 0): { readonly x: number; readonly y: number; readonly w: number; readonly h: number } {\n const ex = Math.abs(G.cos) * G.half[0] + Math.abs(G.sin) * G.half[1] + pad;\n const ey = Math.abs(G.sin) * G.half[0] + Math.abs(G.cos) * G.half[1] + pad;\n return { x: G.centre[0] - ex, y: G.centre[1] - ey, w: 2 * ex, h: 2 * ey };\n}\n\n// ---------------------------------------------------------------- the raster ladder\n\n/** Texels per world unit a note's ink is drawn with: the bands are powers of two between these. */\nexport const BAND_MIN = 0.25;\nexport const BAND_MAX = 8;\n\n/**\n * The band for a zoom: the smallest power of two at or above the screen's own\n * density (`zoom × dpr`), so the ink is never magnified — and, given the band\n * in use, that band stays while it is still at or above the density and under\n * 2.3× it (a hysteresis that crosses no band on a frame's wobble). `cap` is the\n * most the note's raster may take (the page's side over the note's).\n */\nexport function rasterBand(zoom: number, dpr: number, current = 0, cap = BAND_MAX): number {\n const target = zoom * dpr;\n const hi = Math.min(BAND_MAX, cap);\n if (current > 0 && (target <= current * 1.0001 || current >= hi) && target >= current / 2.3) return current;\n // the rungs are √2 apart: the ink is never magnified, and never drawn with more than √2 the texels it shows\n const b = 2 ** (Math.ceil(2 * Math.log2(Math.max(target, 1e-9)) - 1e-9) / 2);\n return Math.min(Math.max(b, BAND_MIN), hi);\n}\n","// The paper pass's GPU records, declared once. `Paper` is one note as drawn —\n// what `resolvePaper` returns, the paper's and the pen's colours, where its\n// ink lives in the pages, the writing head (the wipe) and the caret.\n// `PaperUniforms` is the pass's own knobs; the camera, the light, the gobo\n// and the portal chain arrive through the mat's block (`MatUniforms`), which\n// the pass fills for itself so a note is lit like the mat whether or not the\n// mat is the grid this frame.\n\nimport { defineStruct } from \"@ice/desk/engine\";\nimport type { RGB } from \"@ice/desk\";\nimport type { UvRect } from \"./pages\";\nimport type { PaperGeometry } from \"./paper\";\n\n// vec2s first, then scalars, then vec4s: tight under the alignment rules.\n/** The most lines of a note's writing its far LOD greeks (K7b) — a mini mat's chip greeks as many (minimat.ts `CHIP_LINES`). */\nexport const GREEK_LINES = 6;\n\nexport const Paper = defineStruct(\"Paper\", [\n [\"centre\", \"vec2f\"], [\"half\", \"vec2f\"],\n [\"rot\", \"vec2f\"], // cos, sin of the tilt\n [\"slope\", \"vec2f\"], // the shadow's ground offset per unit of height, world axes\n [\"lift\", \"f32\"], [\"curl\", \"f32\"], [\"cornerCurl\", \"f32\"], [\"glue\", \"f32\"],\n [\"radius\", \"f32\"], [\"ring\", \"f32\"], [\"alpha\", \"f32\"],\n [\"layer\", \"i32\"], // the ink page's layer; −1 = no ink\n [\"lamp\", \"vec4f\"], // the unit direction to the lamp, world axes; unused\n [\"paper\", \"vec4f\"], // the sheet's colour (sRGB), its fibre's amplitude\n [\"ink\", \"vec4f\"], // the pen's colour (sRGB), its density\n [\"shadow\", \"vec4f\"], // σ at contact, alpha, σ per unit of height, the relief (the slope's exaggeration for the shading)\n [\"uv\", \"vec4f\"], // the raster's rect in its layer, normalised: u0 v0 u1 v1 — it covers the whole sheet\n [\"wipe\", \"vec4f\"], // the newest glyph's box, note units from the sheet's top-left: x0 y0 x1 y1 (x1 < x0 = none)\n [\"caret\", \"vec4f\"], // the caret: x, baseline y (note units), its reach above and below\n [\"marks\", \"vec4f\"], // the wipe's progress, the caret on (0/1), unused ×2\n [\"greek\", \"vec4f\"], // K7b — the writing GREEKED (the far LOD): the text's left edge and em (note units), how many lines, unused\n [\"glines\", `array<vec4f, ${GREEK_LINES / 2}>`], // …each line's baseline and width (note units), two lines a vec4\n] as const);\n\nexport const PaperUniforms = defineStruct(\"PaperUniforms\", [\n [\"knobs\", \"vec4f\"], // the mat's chain on the paper (0 = a lit byte is the token's byte, 1 = the mat's double gamma), the wipe's softness (note units), the caret's width (CSS px), the ring's width (CSS px)\n [\"select\", \"vec4f\"], // --vf-select, the ring's colour\n [\"far\", \"vec4f\"], // K7b — the far LOD (theme.ts `PAPER.far`): its band's low and high edges (CSS px of the sheet's longer side), the greek's weight and alpha\n] as const);\n\nexport const MAX_PAPERS = 1024;\n\n/** One note for the pass: its geometry, its two colours, its ink and its live marks. */\nexport interface PaperInstance {\n readonly geometry: PaperGeometry;\n /** The sheet's colour — the product's note surface (§2.2), or the host's. */\n readonly paper: RGB;\n /** The pen's colour and how dark it lays (1 = the colour itself where the raster is full). */\n readonly ink: RGB;\n readonly inkDensity?: number;\n /** The fibre's amplitude, ±/255 — theme.ts `PAPER.grain` unless the host says. */\n readonly grain?: number;\n /** Where the ink lives (pages.ts): absent = a blank sheet. */\n readonly raster?: { readonly layer: number; readonly uv: UvRect } | undefined;\n /** The newest glyph's box and how far the pen has got through it. */\n readonly wipe?: { readonly x0: number; readonly y0: number; readonly x1: number; readonly y1: number; readonly t: number } | undefined;\n /** The caret, when the note is being written. */\n readonly caret?: { readonly x: number; readonly y: number; readonly above: number; readonly below: number; readonly on: boolean } | undefined;\n /** K7b — its writing GREEKED (the far LOD): the text's left edge and em, each line's baseline and width (note units); absent = unwritten. */\n readonly greek?: { readonly x0: number; readonly em: number; readonly lines: readonly { readonly y: number; readonly width: number }[] } | undefined;\n}\n\nexport function paperValues(p: PaperInstance, grain: number) {\n const G = p.geometry;\n const r = p.raster;\n const w = p.wipe;\n const c = p.caret;\n const gk = p.greek;\n const gl = new Array<number>(2 * GREEK_LINES).fill(0);\n const gn = gk === undefined ? 0 : Math.min(gk.lines.length, GREEK_LINES);\n for (let i = 0; i < gn; i++) { const L = gk?.lines[i] as { readonly y: number; readonly width: number }; gl[2 * i] = L.y; gl[2 * i + 1] = L.width; }\n return {\n centre: G.centre, half: G.half, rot: [G.cos, G.sin], slope: G.slope,\n lift: G.lift, curl: G.curl, cornerCurl: G.cornerCurl, glue: G.glue, radius: G.radius, ring: G.ring, alpha: G.alpha,\n layer: r ? r.layer : -1,\n lamp: [G.lamp[0], G.lamp[1], G.lamp[2], 0],\n paper: [p.paper[0], p.paper[1], p.paper[2], p.grain ?? grain],\n ink: [p.ink[0], p.ink[1], p.ink[2], p.inkDensity ?? 1],\n shadow: [G.shadow.sigma, G.shadow.alpha, G.shadow.sigmaPerUnit, G.relief],\n uv: r ? [r.uv.u0, r.uv.v0, r.uv.u1, r.uv.v1] : [0, 0, 0, 0],\n wipe: w ? [w.x0, w.y0, w.x1, w.y1] : [0, 0, -1, -1],\n caret: c ? [c.x, c.y, c.above, c.below] : [0, 0, 0, 0],\n marks: [w ? w.t : 1, c?.on ? 1 : 0, 0, 0],\n greek: [gk?.x0 ?? 0, gk?.em ?? 0, gn, 0],\n glines: gl,\n };\n}\n","// The INK pages — where a note's raster lives on the GPU: fixed-size r8\n// layers (coverage, one byte a texel), carved into rows of one height, each\n// row into spans (a SHELF allocator — notes are near one size, so rows fill\n// and a freed span is reused by the next raster of that height). Pure: the\n// texture is the pass's (paper-pass.ts); this decides WHERE, so the lab and\n// the Node oracle, allocating the same notes in the same order, land the same\n// bytes at the same texels — what the parity witness needs.\n\nexport interface InkRect { readonly layer: number; readonly x: number; readonly y: number; readonly w: number; readonly h: number }\n\n/** A WRITTEN rect inside a layer, normalised — the record's `u0 v0 u1 v1` (design-013 §5's; the card's content term had it first). */\nexport interface UvRect { readonly u0: number; readonly v0: number; readonly u1: number; readonly v1: number }\n\n/** A written rect in texels as the record's normalised uv. */\nexport function uvOf(x: number, y: number, w: number, h: number, texW: number, texH: number): UvRect {\n return { u0: x / texW, v0: y / texH, u1: (x + w) / texW, v1: (y + h) / texH };\n}\n\ninterface Span { x: number; w: number; free: boolean }\ninterface Row { readonly y: number; readonly h: number; readonly spans: Span[] }\ninterface Layer { readonly rows: Row[]; cursor: number }\n\nexport class InkShelves {\n readonly size: number;\n readonly layers: number;\n private readonly stack: Layer[];\n\n constructor(size = 2048, layers = 2) {\n this.size = size; this.layers = layers;\n this.stack = Array.from({ length: layers }, () => ({ rows: [], cursor: 0 }));\n }\n\n /** A rect for a `w × h` raster, or null when no layer has room (the note then draws its paper alone). */\n alloc(w0: number, h0: number): InkRect | null {\n let w = w0;\n let h = h0;\n w = Math.ceil(w); h = Math.ceil(h);\n if (w <= 0 || h <= 0 || w > this.size || h > this.size) return null;\n for (let l = 0; l < this.stack.length; l++) {\n const L = this.stack[l] as Layer;\n // a row of this height, or a little taller (a fifth: the waste a shelf accepts)\n for (const row of L.rows) {\n if (row.h < h || row.h > h * 1.2) continue;\n for (let i = 0; i < row.spans.length; i++) {\n const s = row.spans[i] as Span;\n if (!s.free || s.w < w) continue;\n const rect = { layer: l, x: s.x, y: row.y, w, h };\n if (s.w === w) s.free = false;\n else { row.spans.splice(i, 0, { x: s.x, w, free: false }); s.x += w; s.w -= w; }\n return rect;\n }\n }\n if (L.cursor + h <= this.size) {\n const row: Row = { y: L.cursor, h, spans: [{ x: 0, w, free: false }, { x: w, w: this.size - w, free: true }] };\n if (w === this.size) row.spans.pop();\n L.rows.push(row); L.cursor += h;\n return { layer: l, x: 0, y: row.y, w, h };\n }\n }\n // no row fits and no layer has room below its rows: a run of EMPTY rows re-carved (K6b) — the band ladder leaves a layer carved\n // into rows of every rung, and after a zoom out and back the texels are free in rows too short for the new band. Taken only\n // where the two ways above found nothing, so pages that never gave a rect back (a still's) land every rect where they did.\n for (let l = 0; l < this.stack.length; l++) {\n const rect = this.recarve(l, w, h);\n if (rect !== null) return rect;\n }\n return null;\n }\n\n /** In layer `l`, the first run of adjacent rows that hold nothing and are `h` tall together: one row of `h` holding the rect, the rest one empty row. */\n private recarve(l: number, w: number, h: number): InkRect | null {\n const L = this.stack[l] as Layer;\n const empty = (row: Row): boolean => row.spans.every((s) => s.free);\n for (let i = 0; i < L.rows.length; i++) {\n if (!empty(L.rows[i] as Row)) continue;\n let j = i;\n let tall = 0;\n while (j < L.rows.length && empty(L.rows[j] as Row) && tall < h) { tall += (L.rows[j] as Row).h; j += 1; }\n if (tall < h) { i = j; continue; }\n const y = (L.rows[i] as Row).y;\n const row: Row = { y, h, spans: [{ x: 0, w, free: false }, { x: w, w: this.size - w, free: true }] };\n if (w === this.size) row.spans.pop();\n const rest: Row[] = tall > h ? [{ y: y + h, h: tall - h, spans: [{ x: 0, w: this.size, free: true }] }] : [];\n L.rows.splice(i, j - i, row, ...rest);\n return { layer: l, x: 0, y, w, h };\n }\n return null;\n }\n\n /** Give a rect back; adjacent free spans merge. A rect not from `alloc` is ignored. */\n free(r: InkRect): void {\n const L = this.stack[r.layer];\n if (!L) return;\n const row = L.rows.find((q) => q.y === r.y);\n if (!row) return;\n const i = row.spans.findIndex((s) => s.x === r.x && !s.free);\n if (i < 0) return;\n (row.spans[i] as Span).free = true;\n // merge with the neighbours\n for (let k = row.spans.length - 2; k >= 0; k--) {\n const a = row.spans[k] as Span;\n const b = row.spans[k + 1] as Span;\n if (a.free && b.free) { a.w += b.w; row.spans.splice(k + 1, 1); }\n }\n }\n\n reset(): void { for (const L of this.stack) { L.rows.length = 0; L.cursor = 0; } }\n\n /**\n * Give back every layer's TRAILING rows that hold nothing (D2c): a row keeps its height for life, so a\n * zoom through the band ladder would otherwise leave each layer carved into rows of every rung, and a\n * raster of a new height would find no room though the texels are free. A trimmed layer's cursor\n * retreats; a layer emptied entirely is carved afresh. Rows before a used one stay — the rects in\n * them are the notes' own. Returns the rows given back.\n */\n trim(): number {\n let n = 0;\n for (const L of this.stack) {\n for (;;) {\n const last = L.rows.at(-1);\n if (last === undefined || !last.spans.every((s) => s.free)) break;\n L.rows.pop();\n L.cursor = last.y;\n n += 1;\n }\n }\n return n;\n }\n\n /** Texels in use, rows opened, layers touched — the churn instrument. */\n get stats(): { readonly used: number; readonly rows: number; readonly layersUsed: number } {\n let used = 0;\n let rows = 0;\n let layersUsed = 0;\n for (const L of this.stack) {\n if (L.rows.length) layersUsed += 1;\n rows += L.rows.length;\n for (const row of L.rows) for (const s of row.spans) if (!s.free) used += s.w * row.h;\n }\n return { used, rows, layersUsed };\n }\n}\n","// The paper pass — the notes, instanced, one draw in paint order. Owns its\n// copy of the mat's uniform block (filled for the slot's camera and light\n// every frame), its own knobs, the per-note record buffer and the bind group;\n// shares — with every slot spawned from the first — the pipeline, the samplers\n// and the INK PAGES: an r8 `2d-array` the rasters live in, carved by\n// `InkShelves` so both hosts put the same bytes at the same texels. A slot\n// reads its OWN mat's animated silhouette (the wind target) and its light, so\n// a note inside a mini mat is dappled by the lamp of the desk the mini mat\n// lies on (MINIMAT.md §4). Notes lie above every mini mat on their desk.\n\nimport { bindGroup, bindLayout, renderPipeline, uniformBuffer, compile, compose } from \"@ice/desk/engine\";\nimport { createRecordStore, type RecordStore, type GroundTheme, type RGB } from \"@ice/desk\";\nimport { type FadeIn, type View, litByOwn, type MatConfig, type MatFrame, type SlotLight, type MatPass, type Presentation, DAY_LIGHT, type MatLight, sentBytes, writeChanged } from \"@ice/desk/kit\";\nimport { MAX_PAPERS, Paper, PaperUniforms, type PaperInstance, paperValues } from \"./layout\";\nimport { InkShelves, type InkRect, uvOf, type UvRect } from \"./pages\";\nimport { DEFAULT_PAPER_LAW, type PaperLaw } from \"./paper\";\nimport type { PaperShaders } from \"./shaders\";\n\n/** Premultiplied \"source over\" — every desk object's blend. */\nconst BLEND_PREMUL: GPUBlendState = {\n color: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n alpha: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n};\n\n/** The ink pages: this many texels a side, this many layers — 4 MB a layer as r8, 16 MB in all. */\nexport const INK_PAGE = 2048;\nexport const INK_LAYERS = 4;\n\ninterface PaperShared {\n readonly layout: GPUBindGroupLayout;\n readonly pipeline: GPURenderPipeline;\n /** The same, for a slot lit from elsewhere — a mini mat's inside, a handover (MINIMAT.md §4): `LIT_ELSEWHERE` is a pipeline constant. */\n readonly litPipeline: GPURenderPipeline;\n readonly goboSampler: GPUSampler;\n readonly noiseSampler: GPUSampler;\n readonly inkSampler: GPUSampler;\n readonly pages: GPUTexture;\n readonly pagesView: GPUTextureView;\n readonly shelves: InkShelves;\n slots: number;\n}\n\nexport class PaperPass {\n readonly name = \"paper/notes\";\n private readonly knobs = PaperUniforms.alloc(1);\n /** The notes' PERSISTENT records (engine/records.ts, design-015 §4.3; D6): a slot per note while it is drawn, written when it changed. */\n private readonly store: RecordStore<PaperInstance>;\n /** The records the last prepare turned away at the pass's cap — not drawn; the ground reports them (`GroundStats.dropped`, D7). */\n dropped = 0;\n private readonly knobBuf: GPUBuffer;\n /** What the GPU holds of the knobs: they are written only when they change (K4a — a standing value costs a frame nothing). */\n private readonly knobsSent = sentBytes(PaperUniforms.size);\n private group!: GPUBindGroup;\n private boundAssets = -1;\n private boundStore = -1;\n private count = 0;\n /** This frame's slot is lit from elsewhere: it draws with the second pipeline. */\n private litElsewhere = false;\n private lawNow: PaperLaw = DEFAULT_PAPER_LAW;\n /** The paper's numbers (theme.ts `PAPER`) — the caret's and the ring's widths, the fibre. A host tweaks the root's; every slot copies it. A new law repacks every record (the fibre is packed). */\n get law(): PaperLaw { return this.lawNow; }\n set law(next: PaperLaw) { if (next !== this.lawNow) { this.lawNow = next; this.store.invalidate(); } }\n /** The day's chain on the paper: false = a lit sheet shows its configured byte; true = the mat's own double gamma (the golden note). */\n chain = false;\n /** The wipe's softness — how wide the pen's edge is as a glyph arrives, note units. */\n wipeSoft = 6;\n private readonly device: GPUDevice;\n private readonly shared: PaperShared;\n private readonly mat: MatPass;\n\n private constructor(device: GPUDevice, shared: PaperShared, mat: MatPass) {\n this.device = device; this.shared = shared; this.mat = mat;\n shared.slots += 1;\n this.knobBuf = uniformBuffer(device, PaperUniforms.size, \"paper/knobs\");\n this.store = createRecordStore<PaperInstance, keyof typeof Paper.slots>({\n device, def: Paper, capacity: MAX_PAPERS, max: MAX_PAPERS * 64, label: \"paper/notes\",\n pack: (p, _aux, into, slot) => { into.set(paperValues(p, this.lawNow.grain), slot); return 0; },\n });\n this.rebind();\n }\n\n /** The root's pass, on the root's mat. */\n static async create(device: GPUDevice, format: GPUTextureFormat, src: PaperShaders, mat: MatPass): Promise<PaperPass> {\n const layout = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"fragment\"], buffer: \"uniform\" },\n { binding: 2, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n { binding: 3, stages: [\"fragment\"], texture: \"float\" },\n { binding: 4, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 5, stages: [\"fragment\"], texture: \"float\" },\n { binding: 6, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 7, stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" },\n { binding: 8, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 9, stages: [\"vertex\"], buffer: \"read-only-storage\" }, // the draw list: paint index → record slot (D6)\n ], \"paper/notes\");\n const module = await compile(device, compose(src));\n const pl = device.createPipelineLayout({ bindGroupLayouts: [layout] });\n const [pipeline, litPipeline] = await Promise.all([\n renderPipeline(device, { label: \"paper/notes\", layout: pl, module, format, blend: BLEND_PREMUL }),\n renderPipeline(device, { label: \"paper/notes, lit from elsewhere\", layout: pl, module, format, blend: BLEND_PREMUL, constants: { LIT_ELSEWHERE: 1 } }),\n ]);\n const pages = device.createTexture({ label: \"paper/ink pages\", size: [INK_PAGE, INK_PAGE, INK_LAYERS], format: \"r8unorm\", dimension: \"2d\", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });\n const shared: PaperShared = {\n layout, pipeline, litPipeline,\n goboSampler: device.createSampler({ label: \"paper/gobo\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" }),\n noiseSampler: device.createSampler({ label: \"paper/noise\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\" }),\n inkSampler: device.createSampler({ label: \"paper/ink\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" }),\n pages, pagesView: pages.createView({ dimension: \"2d-array\" }), shelves: new InkShelves(INK_PAGE, INK_LAYERS), slots: 0,\n };\n return new PaperPass(device, shared, mat);\n }\n\n /** A second slot on the same pipeline and pages, reading ITS mat's silhouette — a portal's inside, a flight's departed frame. */\n spawn(mat: MatPass): PaperPass {\n const p = new PaperPass(this.device, this.shared, mat);\n p.law = this.law; p.chain = this.chain; p.wipeSoft = this.wipeSoft;\n return p;\n }\n\n /** Copy the root's tuning — what every slot takes each frame. */\n tune(from: PaperPass): void { this.law = from.law; this.chain = from.chain; this.wipeSoft = from.wipeSoft; }\n\n /** The ink pages' carving — shared by every slot: a raster's place is the same on both hosts when the notes come in the same order. */\n get shelves(): InkShelves { return this.shared.shelves; }\n /** Room for a `w × h` raster, or null when the pages are full (the note then draws its paper alone). */\n alloc(w: number, h: number): InkRect | null { return this.shared.shelves.alloc(w, h); }\n free(r: InkRect): void { this.shared.shelves.free(r); }\n /** Give back the layers' trailing empty rows (pages.ts `trim`) — the writing's own housekeeping after a free (D2c). */\n trim(): number { return this.shared.shelves.trim(); }\n /**\n * Every raster forgotten — a scene reload. The texels stay until overwritten — and a raster's\n * edge, sampled bilinearly, reads one texel beyond its rect, so a host that wants the pages as a\n * fresh device has them (a parity scene: the Node oracle's pages start blank) passes `clear`.\n */\n reset(clear = false): void {\n this.shared.shelves.reset();\n if (!clear) return;\n const zero = new Uint8Array(INK_PAGE * INK_PAGE);\n for (let l = 0; l < INK_LAYERS; l++) this.device.queue.writeTexture({ texture: this.shared.pages, origin: [0, 0, l] }, zero, { bytesPerRow: INK_PAGE }, [INK_PAGE, INK_PAGE, 1]);\n }\n\n /** Write r8 coverage rows (row 0 = top) into a rect `alloc` gave; returns the rect's uv for the record. */\n write(r: InkRect, bytes: Uint8Array<ArrayBuffer>): UvRect {\n if (bytes.byteLength !== r.w * r.h) throw new Error(`paper/ink: expected ${r.w}×${r.h} r8 (${r.w * r.h} bytes), got ${bytes.byteLength}`);\n this.device.queue.writeTexture({ texture: this.shared.pages, origin: [r.x, r.y, r.layer] }, bytes, { bytesPerRow: r.w }, [r.w, r.h, 1]);\n return uvOf(r.x, r.y, r.w, r.h, INK_PAGE, INK_PAGE);\n }\n\n private rebind(): void {\n if (this.boundAssets === this.mat.assetVersion && this.boundStore === this.store.version) return;\n const s = this.shared;\n this.group = bindGroup(this.device, s.layout, [this.mat.view, this.knobBuf, this.store.records, this.mat.silhouette, s.goboSampler, this.mat.noiseTexture.createView(), s.noiseSampler, s.pagesView, s.inkSampler, this.store.order], \"paper/notes\");\n this.boundAssets = this.mat.assetVersion;\n this.boundStore = this.store.version;\n }\n\n /**\n * This frame's notes in paint order — through the persistent store (D6): a note keyed by `keys[i]` keeps its slot and is\n * written only when its record changed; no keys = every record packed afresh (the oracle's form) — and the mat's block for\n * this slot's camera, its light (`light` the Sun or the Moon, `lit` the lamp it is seen by — MINIMAT.md §4): the dapple,\n * the lamp's shading and the shadow. Returns the count that will draw.\n */\n prepare(view: View & { readonly dpr: number }, fadeIn: FadeIn, cfg: MatConfig, frame: MatFrame | undefined, instances: readonly PaperInstance[], present: Presentation | undefined, light: MatLight = DAY_LIGHT, select: RGB = [0, 0, 0], lit?: SlotLight, keys?: readonly number[]): number {\n const cap = MAX_PAPERS * 64;\n const list = instances.length > cap ? instances.slice(0, cap) : instances;\n this.dropped = instances.length - list.length;\n const n = this.store.prepare(list, keys !== undefined && keys.length > cap ? keys.slice(0, cap) : keys);\n this.rebind(); // after: the store's buffers may have grown\n this.count = n;\n this.litElsewhere = !litByOwn(view, lit);\n const far = this.law.far;\n this.knobs.set({ knobs: [this.chain ? 1 : 0, this.wipeSoft, this.law.caret.width, this.law.ring], select: [select[0], select[1], select[2], 1], far: [far.px[0], far.px[1], far.weight, far.alpha] });\n writeChanged(this.device.queue, this.knobBuf, this.knobs, this.knobsSent);\n return n;\n }\n\n /** The store's counters (a rig's witness): records written, bytes, draw-list writes, slots in use. */\n get records() { return this.store.stats(); }\n\n /** K7b: this slot's resources for the note's card material (shaders.ts `paperCard`), in its bindings' order — made again when the store grew. */\n cardResources(): { readonly version: number; readonly resources: readonly (GPUBuffer | GPUTextureView | GPUSampler)[] } {\n if (this.card === null || this.card.version !== this.store.version) {\n const s = this.shared;\n this.card = { version: this.store.version, resources: [this.knobBuf, this.store.records, s.goboSampler, s.noiseSampler, s.pagesView, s.inkSampler] };\n }\n return this.card;\n }\n private card: { readonly version: number; readonly resources: readonly (GPUBuffer | GPUTextureView | GPUSampler)[] } | null = null;\n\n /** K7b: every note of the last prepare is the card's to draw — its slot in the store. */\n cardSlot(index: number): number { return this.store.slotAt(index); }\n\n get drawn(): number { return this.count; }\n\n draw(pass: GPURenderPassEncoder): void { this.drawRange(pass, 0, this.count); }\n\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void {\n const hi = Math.min(end, this.count);\n if (first >= hi) return;\n pass.setPipeline(this.litElsewhere ? this.shared.litPipeline : this.shared.pipeline);\n pass.setBindGroup(0, this.group);\n pass.draw(6, hi - first, 0, first);\n }\n\n /** This slot's buffers; the pages go with the last slot standing. */\n dispose(): void {\n this.knobBuf.destroy(); this.store.dispose();\n const s = this.shared;\n s.slots -= 1;\n if (s.slots === 0) s.pages.destroy();\n }\n}\n\n/** A theme's select for the ring — the one colour the pass takes from the theme. */\nexport const selectOf = (theme: GroundTheme): RGB => theme.select;\n","// Assemble the paper pass's program from the host's shader text — the browser's generated module, the Node oracle's\n// files on disk; byte-identical either way. The kit brings the slot's view block, the portal chain, the card's\n// primitives and the mat's light (kit/wgsl.ts, by name); the note's own records, module and entry follow.\n\nimport type { CardMaterial } from \"@ice/desk\";\nimport type { ComposeOptions } from \"@ice/desk/engine\";\nimport { kitWgsl, type ShaderText } from \"@ice/desk/kit\";\nimport { Paper, PaperUniforms } from \"./layout\";\n\n/** The note's own shader files (the kit's pieces come by name). */\nexport const PAPER_SHADER_FILES = { paper: \"paper/paper.wgsl\", paperCard: \"paper/paper-card.wgsl\", paperPass: \"paper/paper-pass.wgsl\" } as const;\n\n/** The paper pass's program: the kit's view · portal · sdf · light, then the note's records, module, its quad and fragment, and its entry. */\nexport type PaperShaders = ComposeOptions;\n\nexport function paperShaders(text: ShaderText): PaperShaders {\n const t = text(PAPER_SHADER_FILES);\n return kitWgsl([\"view\", \"portal\", \"sdf\", \"light\"], {\n structs: [PaperUniforms, Paper],\n modules: [{ label: \"paper/paper.wgsl\", text: t.paper }, { label: \"paper/paper-card.wgsl\", text: t.paperCard }],\n entry: { label: \"paper/paper-pass.wgsl\", text: t.paperPass },\n }, text);\n}\n\n/**\n * The note's CARD MATERIAL (K7b, design-016 §6 K7): the flat-card pipeline draws a note with paper-card.wgsl's quad and fragment\n * over the paper pass's own records, knobs, samplers and ink pages (`PaperPass.cardResources`, in this order) — every note, so\n * interleaved with the prints and the boards it is one run.\n */\nexport function paperCard(text: ShaderText): CardMaterial {\n return {\n shaders: () => {\n const t = text(PAPER_SHADER_FILES);\n return kitWgsl([\"view\", \"portal\", \"sdf\", \"light\"], {\n structs: [PaperUniforms, Paper],\n modules: [{ label: \"paper/paper.wgsl\", text: t.paper }],\n entry: { label: \"paper/paper-card.wgsl\", text: t.paperCard },\n }, text);\n },\n bindings: [\n { wgsl: \"var<uniform> paper_k: PaperUniforms\", entry: { stages: [\"fragment\"], buffer: \"uniform\" } },\n { wgsl: \"var<storage, read> papers: array<Paper>\", entry: { stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" } },\n { wgsl: \"var paper_gobo_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var paper_noise_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var paper_ink: texture_2d_array<f32>\", entry: { stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" } },\n { wgsl: \"var paper_ink_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n ],\n quad: \"paper_quad\",\n frag: \"paper_frag\",\n };\n}\n","// The desk's WRITING (design-015 §6.1; D2c) — the paper kind's own state on one desk: every note's\n// hand LAYOUT, where its INK lives in the pages, the pen's WIPE and the editor's CARET. Flux, never a\n// world fact (design-015 §2.3): the facts are the note's durable cells (its text and its seeds —\n// seeds.ts — its seed, its size); what is drawn from them is cached here, per entity, keyed so that\n// nothing is redone on a frame:\n//\n// - the LAYOUT (text.ts `layoutText`, pure) is keyed by the face, the text raster's version (a face\n// landing re-lays every note — the prototype's `fontVersion`), the hand's law, the sheet's size, the\n// note's seed, and the text with its seeds — the \"text revision\" is the content itself, so two equal\n// writings share a layout and an undo that restores a text restores its layout;\n// - the RASTER (the host's `TextRaster`) is keyed by that layout, the BAND and the pen's bleed. The band\n// is the prototype's √2 ladder with hysteresis (paper.ts `rasterBand`): re-rastered on an edit or a\n// rung crossing only, never on a pan or a wobble. Only a note within `marginPx` (200) CSS px of the\n// view pays for a raster; one further out keeps what it has.\n// - its PAGES are the paper pass's shelves (pages.ts): a raster of the same size is redrawn in its own\n// rect; a new size frees the old rect first; a note that leaves the desk for good (`forget` — its ghost\n// faded, a nav cut) frees its rect, so a delete leaks no page slot and an undo that respawns re-rasters.\n// Pages full ⇒ the rasters no one drew in the last two frames are evicted, oldest first; still full ⇒\n// the sheet draws BLANK, honestly, and `stats().blanks` says so.\n//\n// - THE QUEUE (K6b, design-016 §6 — the desk's frame raster queue, `KindHost.rasters`): a raster at another BAND (a rung\n// crossed) or a note's FIRST (it came on screen holding none, the face landed) is ASKED, not drawn in the frame that asked — a\n// zoom across a rung asked it of every note near the view at once (193 ms: 108 notes). The queue lays it in its turn, under the\n// frame's budget: first what shows nothing (a blank sheet), then what shows its ink magnified (a band short of the screen's),\n// then what shows it minified (a band past it — the pages' room), the nearest the view's centre first within each; meanwhile the\n// raster it holds STANDS, scaled by the pass (a rung is √2: a magnified stand-in is at most one rung soft until its turn), and\n// the new one is found room BEFORE the old is let go. Laid, the note's record is remade (`remake`) — the record says where its\n// ink is. A raster whose WORDS moved (an edit, a resize) is laid at once, in the frame that asked: the ink never lags the caret.\n// Without a queue (a bare host, the tests) every raster is laid at once, as before.\n//\n// A PINNED raster (a parity still's committed ink, `pin`) wins over the live one and is never re-rastered.\n// Without a text raster (the Node oracle) nothing is rastered live: the pinned rasters only.\n//\n// The WIPE (110 ms) and the CARET (blink 530 ms) are the editor's flux, clocked by the frame's `now`\n// (`tick`, once a tick, before the draw): `tick` answers whether a frame is wanted — every tick while a\n// wipe runs, once per blink phase while the caret stands, once when a face lands or the editor moves.\n\nimport type { Entity } from \"@ice/core\";\nimport { type KindHost, rasterPriority } from \"@ice/desk\";\nimport { type View, HAND, caretAt, glyphBox, type HandLaw, type HandLayout, layoutText, type TextRaster, seedsFor } from \"@ice/desk/kit\";\nimport { PAPER } from \"./theme\";\nimport type { PaperInstance } from \"./layout\";\nimport type { InkRect, UvRect } from \"./pages\";\nimport { INK_PAGE } from \"./paper-pass\";\nimport { type PaperGeometry, localOf, rasterBand, sdPaper } from \"./paper\";\n\n/** The pages a writing allocates in — the root paper pass (paper-pass.ts) satisfies it. */\nexport interface InkPages {\n alloc(w: number, h: number): InkRect | null;\n free(r: InkRect): void;\n write(r: InkRect, bytes: Uint8Array<ArrayBuffer>): UvRect;\n /** Every rect forgotten (the shelves carved afresh); `clear` zeroes the texels too. */\n reset(clear?: boolean): void;\n /** Give back the layers' trailing empty rows (pages.ts `trim`). */\n trim?(): number;\n}\n\n/** The hand's law as theme.ts states it (`HAND`) — the engine's unless a host says. */\nexport const DEFAULT_HAND_LAW: HandLaw = HAND;\n/** The default face — Caveat medium (STICKY.md §3; the app ships the file). */\nexport const DEFAULT_FACE = \"caveat\";\n/** The pen's bleed, note units — a faint stroke under each glyph (STICKY.md §3). */\nexport const DEFAULT_BLEED = 0.3;\n\nexport interface WritingOptions {\n /** The ink pages — the root paper pass once the ground is made; `undefined` before (a sheet waits). */\n readonly pages: () => InkPages | undefined;\n /** The host's text raster (desk/host/ink.ts); absent — the Node oracle — nothing is rastered live. */\n readonly text?: TextRaster | undefined;\n readonly hand?: HandLaw;\n readonly face?: string;\n readonly bleed?: number;\n /** K7b — the far LOD's low edge (theme.ts `PAPER.far`), CSS px of the sheet's longer side: under it no raster is held or asked (the note greeks). */\n readonly far?: number;\n /** A typed glyph's wipe, ms (theme.ts `HAND.wipeMs`). */\n readonly wipeMs?: number;\n /** The caret's blink, ms (theme.ts `PAPER.caret.blinkMs`). */\n readonly blinkMs?: number;\n /** Only a note within this many CSS px of the view pays for a raster (the prototype's 200). */\n readonly marginPx?: number;\n /**\n * The builder's word on what is DRAWN (D6, persistent records — `KindHost.drawn`): the paint rank of a note in the root slot this\n * frame, undefined when it is not drawn. With it, \"drawn\" means the builder's set, not the last `draw` call (a reused record makes\n * none): the eviction spares what is on screen and `noteAt` ranks by paint order. Absent, the writing counts its own draws.\n */\n readonly drawn?: ((e: Entity) => number | undefined) | undefined;\n /** The desk's frame raster queue (K6b, `KindHost.rasters`): a new band or a first raster is asked there; absent, laid at once. */\n readonly queue?: KindHost[\"rasters\"];\n /** The builder's door (K6b, `KindHost.remake`): a note's record remade once the queue laid its raster. */\n readonly remake?: KindHost[\"remake\"];\n}\n\n/** What a note draws with this frame — the paper kind's record takes it whole. */\nexport interface NoteInk {\n readonly raster?: { readonly layer: number; readonly uv: UvRect };\n readonly wipe?: PaperInstance[\"wipe\"];\n readonly caret?: PaperInstance[\"caret\"];\n}\n\n/** Where a note's ink lives and what it was drawn at — the rigs' witness. */\nexport interface NoteRasterInfo {\n readonly band: number;\n readonly w: number;\n readonly h: number;\n readonly layer: number;\n readonly x: number;\n readonly y: number;\n readonly pinned: boolean;\n}\n\nexport interface WritingStats {\n /** Notes holding a raster now (pinned included). */\n readonly resident: number;\n readonly pinned: number;\n /** Layouts laid and rasters drawn since the mount — the \"re-rasters on an edit or a rung only\" instrument. */\n readonly layouts: number;\n readonly rasters: number;\n /** Rasters refused because the pages were full (the sheet drew blank). */\n readonly blanks: number;\n /** Rasters evicted to make room. */\n readonly evicted: number;\n /** Notes whose raster is asked of the queue and not laid yet (K6b) — each draws what it holds meanwhile. */\n readonly queued: number;\n}\n\nexport interface Writing {\n /** The frame's clock, once a tick before the draw: does the writing want a frame now? */\n tick(now: number): boolean;\n /**\n * When the writing is next live (K7a — `KindLocal.due`): now while a frame is owed or a wipe runs on a drawn note; the\n * caret's next blink phase while it stands; never otherwise — a face landing is the text raster's wake, an edit the\n * editor's. A desk at rest with a caret standing takes one frame a blink phase, and none without one.\n */\n due(now: number): number;\n /**\n * What note `e` draws with this frame: its ink (pinned or live), the pen's wipe, the caret. A `fading` note (a\n * delete ghost) draws only the raster it already holds — never a new layout or raster, no marks.\n */\n draw(e: Entity, props: Readonly<Record<string, unknown>>, rect: { readonly cx: number; readonly cy: number; readonly w: number; readonly h: number }, view: View & { readonly dpr: number }, geometry: PaperGeometry, fading?: boolean): NoteInk;\n /**\n * The band note `e` asks at `zoom` × `dpr` (K6b — the paper kind's RUNG): its raster's band under the ladder's hysteresis, the one\n * `draw` would raster at; 0 when it asks none (an empty sheet, a pinned still, no text raster). The note's record reads the zoom\n * through this alone, so a zoom within the band remakes nothing.\n */\n bandOf(e: Entity, props: Readonly<Record<string, unknown>>, rect: { readonly w: number; readonly h: number }, zoom: number, dpr: number): number;\n /**\n * Note `e`'s RUNG at `zoom` × `dpr` (K6b — the paper kind's `rung`): without a queue, the band it asks (`bandOf` — its record,\n * remade at a crossing, rasters it at once); with one, the band of the raster it HOLDS — what its record shows — the band the zoom\n * asks being ASKED of the queue here, `px` (screen px from the view's centre) its order: a crossing remakes no record, the raster's\n * landing does (`remake`).\n */\n rungOf(e: Entity, props: Readonly<Record<string, unknown>>, rect: { readonly w: number; readonly h: number }, zoom: number, dpr: number, px: number): number;\n /** The note's layout as last drawn (undefined before, for a still, or while the face loads). */\n layoutOf(e: Entity): HandLayout | undefined;\n rasterOf(e: Entity): NoteRasterInfo | undefined;\n /** Pin a committed raster (r8 rows) on a note — allocated NOW, in call order (the oracle's texels). */\n pin(e: Entity, bytes: Uint8Array<ArrayBuffer>, size: { readonly w: number; readonly h: number }): boolean;\n isPinned(e: Entity): boolean;\n /** The editor's caret: on note `e` before glyph `index`, its blink restarted at `now`; `undefined` lifts it. */\n caret(e: Entity | undefined, index?: number, now?: number): void;\n /** The caret as drawn: its note, its index, whether it shows. */\n caretOf(): { readonly entity: Entity; readonly index: number; readonly on: boolean } | undefined;\n /** A glyph was just written at `index` (the pen's wipe from `now`); `undefined` = nothing to wipe (a paste, a newline). */\n wrote(e: Entity, index: number | undefined, now: number): void;\n wipeOf(e: Entity): { readonly index: number; readonly t0: number } | undefined;\n /** What has LANDED on the note, counted — its raster laid, its wipe let go (D7 — `KindLocal.landed`); never the wipe running. */\n landed(e: Entity): number;\n /** The caret index nearest a world point on a drawn note — where a tap puts the pen. */\n caretIndexAt(e: Entity, wx: number, wy: number): number | undefined;\n /** The topmost note drawn last frame under a world point. */\n noteAt(wx: number, wy: number): Entity | undefined;\n /** The note left the desk for good: its rect back to the pages. */\n forget(e: Entity): void;\n /** Every raster forgotten and the pages carved afresh (a scene reload). */\n reset(): void;\n stats(): WritingStats;\n dispose(): void;\n}\n\ninterface Raster {\n readonly rect: InkRect;\n readonly uv: UvRect;\n readonly band: number;\n /** The layout it drew (identity: a new layout is a new writing), absent for a pinned still. */\n readonly layout: HandLayout | undefined;\n readonly bleed: number;\n}\n\ninterface Entry {\n text: string;\n seeds: string;\n seed: number;\n w: number;\n h: number;\n version: number;\n layout: HandLayout | undefined;\n keyed: boolean;\n raster: Raster | null;\n pinned: boolean;\n /** The band asked of the queue and not laid yet (K6b); 0 = nothing asked. */\n want: number;\n /** The note's run for the queue, made once. */\n run: (() => \"done\" | \"wait\") | undefined;\n /** The render it was last drawn in, and its place in that render's paint order. */\n drawnAt: number;\n order: number;\n geometry: PaperGeometry | undefined;\n}\n\n/** The queue's name for the paper's asks (K6b) — the kind's. */\nconst OWNER = \"paper\";\n\nconst str = (props: Readonly<Record<string, unknown>>, name: string): string => { const v = props[name]; return typeof v === \"string\" ? v : \"\"; };\nconst num = (props: Readonly<Record<string, unknown>>, name: string): number => { const v = props[name]; return typeof v === \"number\" && Number.isFinite(v) ? v : 0; };\n\n/** The caret index nearest a point in a note's own units (the prototype's `caretIndexAt`): lines weigh three times the columns. */\nexport function caretIndexIn(L: HandLayout, nx: number, ny: number, length: number): number {\n let best = 0;\n let bestScore = Number.POSITIVE_INFINITY;\n for (let i = 0; i <= length; i++) {\n const px = L.positions[2 * i] as number;\n const py = L.positions[2 * i + 1] as number;\n const score = Math.abs(py - L.ascent * 0.4 - ny) * 3 + Math.abs(px - nx);\n if (score < bestScore) { bestScore = score; best = i; }\n }\n return best;\n}\n\nexport function createWriting(opts: WritingOptions): Writing {\n const law = opts.hand ?? DEFAULT_HAND_LAW;\n const face = opts.face ?? DEFAULT_FACE;\n const bleed = opts.bleed ?? DEFAULT_BLEED;\n /** K7b: the note is FAR — under the far LOD's low edge on screen — and holds and asks no raster (its writing is greeked). */\n const far = (rect: { readonly w: number; readonly h: number }, zoom: number): boolean => Math.max(rect.w, rect.h) * zoom < (opts.far ?? 0);\n const wipeMs = Math.max(opts.wipeMs ?? HAND.wipeMs, 1);\n const blinkMs = Math.max(opts.blinkMs ?? PAPER.caret.blinkMs, 60);\n const marginPx = opts.marginPx ?? 200;\n const text = opts.text;\n const entries = new Map<Entity, Entry>();\n const wipes = new Map<Entity, { index: number; t0: number }>();\n const landedOf = new Map<Entity, number>();\n const land = (e: Entity): void => { landedOf.set(e, (landedOf.get(e) ?? 0) + 1); };\n let focus: { entity: Entity; index: number; t0: number } | undefined;\n let now = 0;\n let ticks = 0;\n let render = 0;\n let renderTick = -1;\n let order = 0;\n let dirty = false;\n let seenVersion = text?.version() ?? 0;\n let lastPhase: boolean | undefined;\n let layouts = 0;\n let rasters = 0;\n let blanks = 0;\n let evicted = 0;\n\n const phaseAt = (t: number): boolean => (focus === undefined ? false : Math.floor(Math.max(0, t - focus.t0) / blinkMs) % 2 === 0);\n\n const queue = opts.queue;\n const remake = opts.remake;\n const release = (pages: InkPages | undefined, en: Entry): void => {\n if (en.raster === null) return;\n pages?.free(en.raster.rect);\n en.raster = null;\n pages?.trim?.();\n queue?.wake(OWNER); // room made: a note held for it tries again\n };\n\n const drawn = opts.drawn;\n /** Not on screen this frame: the builder's word when it gives one (D6), else not drawn in the last two renders. */\n const offScreen = (e: Entity, q: Entry): boolean => (drawn !== undefined ? drawn(e) === undefined : q.drawnAt < render - 1);\n /** Room for a `w × h` raster: the pages' own, else what no one drew in the last two frames, oldest first. */\n const room = (pages: InkPages, w: number, h: number): InkRect | null => {\n const got = pages.alloc(w, h);\n if (got !== null) return got;\n const stale = [...entries.entries()].filter(([e, q]) => q.raster !== null && !q.pinned && offScreen(e, q)).map(([, q]) => q).sort((a, b) => a.drawnAt - b.drawnAt);\n for (const q of stale) {\n release(pages, q);\n evicted += 1;\n const r = pages.alloc(w, h);\n if (r !== null) return r;\n }\n return null;\n };\n\n /** The band a note asks at `zoom` × `dpr`: the ladder's, with the hysteresis around the band its raster holds, capped at the page. */\n const askBand = (en: Entry | undefined, w: number, h: number, zoom: number, dpr: number): number => rasterBand(zoom, dpr, en?.raster?.band ?? 0, INK_PAGE / Math.max(w, h, 1));\n\n const near = (rect: { readonly cx: number; readonly cy: number; readonly w: number; readonly h: number }, view: View): boolean => {\n const m = marginPx / view.zoom;\n const r = Math.hypot(rect.w, rect.h) / 2;\n return rect.cx + r >= view.camX - m && rect.cx - r <= view.camX + view.width / view.zoom + m && rect.cy + r >= view.camY - m && rect.cy - r <= view.camY + view.height / view.zoom + m;\n };\n\n /**\n * Lay note `e`'s ink at `band` for its layout `L` on a `w × h` sheet: in its own rect when the size is the same, else a new one.\n * `keep` (the queue's run): the new rect is found BEFORE the old is let go — no room, and the old raster stands; else (the frame\n * that asked) the old goes first and no room draws the sheet blank, honestly. False: no room.\n */\n const lay = (e: Entity, en: Entry, pages: InkPages, T: TextRaster, L: HandLayout, w: number, h: number, band: number, keep: boolean): boolean => {\n const pw = Math.max(1, Math.ceil(w * band));\n const ph = Math.max(1, Math.ceil(h * band));\n const r = en.raster;\n let at: InkRect | null = r !== null && r.rect.w === pw && r.rect.h === ph ? r.rect : null;\n if (at === null && keep) {\n at = room(pages, pw, ph);\n if (at === null) return false;\n release(pages, en);\n } else if (at === null) {\n release(pages, en);\n at = room(pages, pw, ph);\n if (at === null) { blanks += 1; return false; }\n }\n const bmp = T.raster(L, face, { w, h }, band, bleed);\n en.raster = { rect: at, uv: pages.write(at, bmp.bytes), band, layout: L, bleed };\n rasters += 1;\n land(e);\n return true;\n };\n\n /** The band note `e` asks (`bandOf`): 0 for an empty sheet, a pinned still, no text raster. */\n const bandAsked = (e: Entity, props: Readonly<Record<string, unknown>>, rect: { readonly w: number; readonly h: number }, zoom: number, dpr: number): number => {\n const en = entries.get(e);\n if (text === undefined || en?.pinned === true || str(props, \"text\").length === 0 || far(rect, zoom)) return 0;\n return askBand(en, rect.w, rect.h, zoom, dpr);\n };\n\n /** Nothing owed to the queue for `e` any more (its band came back, its words moved, it left): its ask withdrawn. */\n const unask = (e: Entity, en: Entry): void => {\n if (en.want === 0) return;\n en.want = 0;\n queue?.drop(OWNER, e);\n };\n\n /**\n * The queue's turn for note `e` (K6b): its ink laid at the band it last asked — the old raster standing until the new one has\n * room — and its record remade. No room: it waits, held until a raster is let go. Nothing owed any more: done.\n */\n const run = (e: Entity): \"done\" | \"wait\" => {\n const en = entries.get(e);\n const pages = opts.pages();\n const L = en?.layout;\n if (en === undefined || en.want === 0 || en.pinned || pages === undefined || text === undefined || L === undefined) { if (en !== undefined) en.want = 0; return \"done\"; }\n if (!lay(e, en, pages, text, L, en.w, en.h, en.want, true)) {\n if (en.raster === null) blanks += 1;\n return \"wait\";\n }\n en.want = 0;\n remake?.(e);\n return \"done\";\n };\n\n /** Ask the queue for note `e`'s raster at `band`: its tier by what it shows meanwhile, the nearest the view's centre (`px`) first within it. */\n const ask = (e: Entity, en: Entry, band: number, px: number, Q: NonNullable<KindHost[\"rasters\"]>): void => {\n en.want = band;\n const shows = en.raster === null ? \"nothing\" : en.raster.band < band ? \"magnified\" : \"minified\";\n en.run ??= () => run(e);\n Q.ask(OWNER, e, rasterPriority(shows, px), en.run);\n };\n\n const entryOf = (e: Entity): Entry => {\n let en = entries.get(e);\n if (en === undefined) {\n en = { text: \"\", seeds: \"\", seed: 0, w: 0, h: 0, version: -1, layout: undefined, keyed: false, raster: null, pinned: false, want: 0, run: undefined, drawnAt: -1, order: 0, geometry: undefined };\n entries.set(e, en);\n }\n return en;\n };\n\n return {\n due(t) {\n if (dirty || (text !== undefined && text.version() !== seenVersion)) return t;\n for (const e of wipes.keys()) if (drawn === undefined || drawn(e) !== undefined) return t;\n // the first phase boundary after the LAST tick (`now`): the caret it drew stands until then\n if (focus !== undefined) return focus.t0 + (Math.floor(Math.max(0, now - focus.t0) / blinkMs) + 1) * blinkMs;\n return Number.POSITIVE_INFINITY;\n },\n\n tick(t) {\n now = t;\n ticks += 1;\n let want = dirty;\n dirty = false;\n if (text !== undefined && text.version() !== seenVersion) { seenVersion = text.version(); want = true; }\n // a wipe runs on the clock whether or not its note is drawn (D7): a frame for it while it runs — and once as its time is up, to\n // draw it done — only for a note on screen (the builder's word, when it gives one); a note panned off or never drawn again\n // asked a frame every tick forever, its wipe let go only by a draw that never came\n for (const [e, wp] of wipes) {\n if (t - wp.t0 >= wipeMs) { wipes.delete(e); land(e); }\n if (drawn === undefined || drawn(e) !== undefined) want = true;\n }\n const phase = focus === undefined ? undefined : phaseAt(t);\n if (phase !== lastPhase) { lastPhase = phase; want = true; }\n return want;\n },\n\n draw(e, props, rect, view, G, fading = false) {\n if (renderTick !== ticks) { renderTick = ticks; render += 1; order = 0; }\n // a delete ghost keeps what it has and asks for nothing: after a reset it fades blank, never re-rastered\n if (fading) { const r = entries.get(e)?.raster; return r === null || r === undefined ? {} : { raster: { layer: r.rect.layer, uv: r.uv } }; }\n const en = entryOf(e);\n en.drawnAt = render;\n en.order = ++order;\n en.geometry = G;\n const pages = opts.pages();\n if (en.pinned) return en.raster === null ? {} : { raster: { layer: en.raster.rect.layer, uv: en.raster.uv } };\n // the layout: re-laid only when one of its inputs moved\n const t = str(props, \"text\");\n const s = str(props, \"seeds\");\n const seed = num(props, \"seed\");\n const version = text?.version() ?? 0;\n if (!en.keyed || en.text !== t || en.seeds !== s || en.seed !== seed || en.w !== rect.w || en.h !== rect.h || en.version !== version) {\n const metrics = text?.metrics(face);\n en.layout = metrics === undefined ? undefined : layoutText(t, { w: rect.w, h: rect.h }, law, metrics, seed, seedsFor(t, s, seed));\n en.text = t; en.seeds = s; en.seed = seed; en.w = rect.w; en.h = rect.h; en.version = version; en.keyed = true;\n if (en.layout !== undefined) layouts += 1;\n }\n const L = en.layout;\n // the raster: none for an unwritten sheet; else at the band the view asks, redrawn on a new layout or a rung only\n if (t.length === 0 || L === undefined || text === undefined || far(rect, view.zoom)) { release(pages, en); unask(e, en); }\n else if (pages !== undefined && near(rect, view)) {\n const band = askBand(en, rect.w, rect.h, view.zoom, view.dpr);\n const r = en.raster;\n // its WORDS moved under the raster it holds (an edit, a resize): laid in this frame — the ink never lags the caret\n if (r !== null && (r.layout !== L || r.bleed !== bleed)) { unask(e, en); lay(e, en, pages, text, L, rect.w, rect.h, band, false); }\n // none yet, or another band (a rung crossed): the queue's (K6b) — what it holds stands until its turn; without one, at once\n else if (r === null || r.band !== band) {\n if (queue !== undefined) ask(e, en, band, Math.hypot(rect.cx - (view.camX + view.width / (2 * view.zoom)), rect.cy - (view.camY + view.height / (2 * view.zoom))) * view.zoom, queue);\n else lay(e, en, pages, text, L, rect.w, rect.h, band, false);\n } else unask(e, en); // nothing owed: the zoom came back to the band it holds\n }\n // the pen's wipe over the newest glyph, and the caret\n let wipe: NoteInk[\"wipe\"];\n const wp = wipes.get(e);\n if (wp !== undefined && L !== undefined) {\n const g = L.glyphs.find((q) => q.index === wp.index);\n const u = (now - wp.t0) / wipeMs;\n if (g === undefined || u >= 1) { wipes.delete(e); land(e); }\n else wipe = { ...glyphBox(L, g), t: Math.max(0, u) };\n }\n const caret = focus !== undefined && focus.entity === e && L !== undefined ? { ...caretAt(L, focus.index), on: phaseAt(now) } : undefined;\n return {\n ...(en.raster !== null ? { raster: { layer: en.raster.rect.layer, uv: en.raster.uv } } : {}),\n ...(wipe !== undefined ? { wipe } : {}),\n ...(caret !== undefined ? { caret } : {}),\n };\n },\n\n bandOf: (e, props, rect, zoom, dpr) => bandAsked(e, props, rect, zoom, dpr),\n\n rungOf(e, props, rect, zoom, dpr, px) {\n const band = bandAsked(e, props, rect, zoom, dpr);\n const en = entries.get(e);\n // no queue, or nothing laid out to raster yet (a record not made, the face loading): the record's own draw asks, at once\n if (queue === undefined || band === 0 || en?.layout === undefined) return band;\n const held = en.raster?.band ?? 0;\n if (band !== held) ask(e, en, band, px, queue);\n else unask(e, en);\n return held;\n },\n\n layoutOf: (e) => entries.get(e)?.layout,\n rasterOf(e) {\n const r = entries.get(e)?.raster;\n if (r === null || r === undefined) return undefined;\n return { band: r.band, w: r.rect.w, h: r.rect.h, layer: r.rect.layer, x: r.rect.x, y: r.rect.y, pinned: entries.get(e)?.pinned === true };\n },\n\n pin(e, bytes, size) {\n const pages = opts.pages();\n if (pages === undefined) return false;\n const en = entryOf(e);\n unask(e, en);\n release(pages, en);\n const at = pages.alloc(size.w, size.h);\n dirty = true;\n if (at === null) { en.pinned = false; return false; }\n en.raster = { rect: at, uv: pages.write(at, bytes), band: 0, layout: undefined, bleed };\n en.pinned = true;\n return true;\n },\n isPinned: (e) => entries.get(e)?.pinned === true,\n\n caret(e, index = 0, t = now) {\n if (e === undefined) { if (focus !== undefined) { focus = undefined; dirty = true; } return; }\n focus = { entity: e, index, t0: t };\n dirty = true;\n },\n caretOf: () => (focus === undefined ? undefined : { entity: focus.entity, index: focus.index, on: phaseAt(now) }),\n\n wrote(e, index, t) {\n if (index === undefined) wipes.delete(e);\n else wipes.set(e, { index, t0: t });\n dirty = true;\n },\n wipeOf: (e) => wipes.get(e),\n landed: (e) => landedOf.get(e) ?? 0,\n\n caretIndexAt(e, wx, wy) {\n const en = entries.get(e);\n const L = en?.layout;\n const G = en?.geometry;\n if (en === undefined || L === undefined || G === undefined) return undefined;\n const [qx, qy] = localOf(G, wx, wy);\n return caretIndexIn(L, qx / G.scale + en.w / 2, qy / G.scale + en.h / 2, en.text.length);\n },\n\n noteAt(wx, wy) {\n let best: Entity | undefined;\n let bestOrder = -1;\n for (const [e, en] of entries) {\n // the builder's word on what is drawn and in what order (D6), else this writing's own draws of the last render\n const order = drawn !== undefined ? drawn(e) : en.drawnAt === render ? en.order : undefined;\n if (order === undefined || en.geometry === undefined || order <= bestOrder) continue;\n if (sdPaper(en.geometry, wx, wy) < 0) { best = e; bestOrder = order; }\n }\n return best;\n },\n\n forget(e) {\n const en = entries.get(e);\n if (en !== undefined) { unask(e, en); release(opts.pages(), en); entries.delete(e); }\n wipes.delete(e);\n landedOf.delete(e);\n if (focus?.entity === e) { focus = undefined; dirty = true; }\n },\n\n reset() {\n queue?.clear(OWNER);\n entries.clear();\n wipes.clear();\n opts.pages()?.reset(true);\n dirty = true;\n },\n\n stats() {\n let resident = 0;\n let pinned = 0;\n let queued = 0;\n for (const [e, en] of entries) { if (en.raster !== null) resident += 1; if (en.pinned) pinned += 1; if (en.want !== 0 && queue?.has(OWNER, e) !== false) queued += 1; }\n return { resident, pinned, layouts, rasters, blanks, evicted, queued };\n },\n\n dispose() {\n queue?.clear(OWNER);\n entries.clear();\n wipes.clear();\n focus = undefined;\n },\n };\n}\n","// The NOTE (STICKY.md) as a kind (kind.ts): the paper pass behind the registry's door — a thin\n// adapter, the pass and its WGSL as they were. Stratum `things`: a note lies over every sheet\n// and pad, in the desk's own order among the other things. A spawned slot's pass takes the\n// root's law every frame (`tune`), as the ground always had it do.\n//\n// And its WORLD half (kinds/world.ts; D2a-world): `paperKind` — an entity of the note's widget\n// type becomes a `PaperInstance` through the prototype's own laws: `resolvePaper` on the rect,\n// the seed's tilt (`tiltOf`), the flux the builder stepped (lift ← `Grab`, ring ← `Selected`,\n// fade ← a delete ghost — a note never hovers); `pickPaper` is the mirror. The sheet's colour and\n// the pen's ink are the PRODUCT's (the theme gate: no literal here) — `theme()` takes them from the\n// palette's `papers` and `pens` by the prop's value.\n//\n// And its TEXT (D2c, design-015 §6.1): the kind's own state on each desk is a WRITING\n// (paper/writing.ts — `local()`): the hand's layout from the note's durable `text` and `seeds`, the\n// ink raster on the √2 band ladder in the pass's pages, the pen's wipe, the editor's caret. `record`\n// takes all three from it; a raster a host pinned through the builder (`ctx.asset`) is the fallback.\n\nimport { type KindExtra, type KindPass, type KindProgram, type SlotContext, type Palette, type RGB, rgb, type ThemeName, type TokenRef, type KindHost, numberProp, type ObjectContext, type ObjectHit, type ObjectKind, type RungContext, stringProp } from \"@ice/desk\";\nimport { type MatPass, type MarkFrame, type ChildShape, type HandLaw, type HandLayout, HAND, PAPER_FINISH, type ShaderText, TEXT_RASTER } from \"@ice/desk/kit\";\nimport type { PaperInstance } from \"./layout\";\nimport { DEFAULT_PAPER_LAW, type PaperGeometry, type PaperLaw, pickPaper, resolvePaper, tiltOf } from \"./paper\";\nimport { PaperPass } from \"./paper-pass\";\nimport { PAPER_SHADER_FILES, paperCard, paperShaders } from \"./shaders\";\nimport type { UvRect } from \"./pages\";\nimport { createWriting, type Writing } from \"./writing\";\nimport { shaderText } from \"../shaders\";\n\n/** The note's kind name — its key in the registry and in every slot's `objects`. */\nexport const PAPER_KIND = \"paper\";\n\nexport class PaperKind implements KindPass<PaperInstance> {\n /** The paper pass itself: a host's door to the ink pages (`alloc`, `write`, `reset`) and the note's law (`law`, `chain`, `wipeSoft`). */\n readonly pass: PaperPass;\n constructor(pass: PaperPass) { this.pass = pass; }\n\n spawn(mat: MatPass): PaperKind { return new PaperKind(this.pass.spawn(mat)); }\n\n tune(root: KindPass<PaperInstance>): void { if (root instanceof PaperKind) this.pass.tune(root.pass); }\n\n /** The pass's own `prepare`, argument for argument: the slot's camera, grid, clocks, the objects' presence, the light, the ring's colour, the lamp — and the records' keys (D6). */\n prepare(_encoder: GPUCommandEncoder, s: SlotContext, records: readonly PaperInstance[], extra?: KindExtra): number {\n return this.pass.prepare(s.view, s.fadeIn, s.cfg, s.frame, records, s.present, s.light, s.select, s.lit, extra?.keys);\n }\n\n dropped(): number { return this.pass.dropped; }\n\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void { this.pass.drawRange(pass, first, end); }\n records() { return this.pass.records; }\n cardResources() { return this.pass.cardResources(); }\n cardSlot(index: number): number { return this.pass.cardSlot(index); }\n\n dispose(): void { this.pass.dispose(); }\n}\n\n/** The note's program for a host's shader text: its pass made on the root's mat. */\nexport function paperProgram(text: ShaderText): KindProgram<PaperInstance> {\n return {\n name: PAPER_KIND,\n stratum: \"things\",\n card: paperCard(text),\n create: async (device, format, mat) => new PaperKind(await PaperPass.create(device, format, paperShaders(text), mat)),\n };\n}\n\n// ---------------------------------------------------------------- the world half (D2a-world)\n\n/**\n * What the note's kind takes from the host's palette (theme.ts `Palette`, extended): the sheets by\n * the `paper` prop's value and the pens' inks by the `pen` prop's — each a token (`--vf-note-surface`,\n * STICKY.md §3's pens), the product's colours, never the engine's (the theme gate).\n */\nexport interface PaperPalette extends Palette {\n readonly papers?: Readonly<Record<string, TokenRef>>;\n readonly pens?: Readonly<Record<string, TokenRef>>;\n}\n\n/** The note's look for a theme: its sheets and inks, parsed. */\nexport interface PaperLook {\n readonly papers: Readonly<Record<string, RGB>>;\n readonly pens: Readonly<Record<string, RGB>>;\n}\n\n/** A note's writing as the far LOD greeks it (MINIMAT.md §5): the text's left edge and em (note units from the sheet's top-left) and each line's baseline and width. */\nexport interface PaperWriting { readonly x0: number; readonly em: number; readonly lines: readonly { readonly y: number; readonly width: number }[] }\n\n/**\n * What the host pins on a note (`ctx.asset`): a committed raster's place in the ink pages (`layer` + `uv`),\n * and/or its writing's lines for the chip (`greek` — a still states them; the live text's layout is D2c's).\n */\nexport interface PaperAsset { readonly layer?: number; readonly uv?: UvRect; readonly greek?: PaperWriting }\n\nconst asPaperAsset = (a: unknown): PaperAsset | undefined => (typeof a === \"object\" && a !== null ? (a as PaperAsset) : undefined);\nconst hasRaster = (a: PaperAsset | undefined): a is PaperAsset & { readonly layer: number; readonly uv: UvRect } => a !== undefined && typeof a.layer === \"number\" && typeof a.uv === \"object\" && a.uv !== null;\n\n/**\n * How far a note's drawing reaches past its rect, world units: its shadow at full lift and curl,\n * cast along the lamp's slope and blurred; the held scale; the tilt's overhang of the sheet's box.\n */\nexport function paperReach(law: PaperLaw = DEFAULT_PAPER_LAW): number {\n const hmax = law.lift.height + law.curl * (1 + law.cornerCurl);\n const shadow = law.shadow.slopeMax * hmax + 2.5 * (law.shadow.sigma + law.shadow.sigmaPerUnit * hmax);\n const tilt = law.size * Math.sin((law.tilt * Math.PI) / 180);\n const held = (law.size * (law.lift.scale - 1)) / 2;\n return shadow + tilt + held;\n}\n\nexport interface PaperKindOptions {\n /** The host's shader text; the generated module unless a host says (the Node oracle hands the .wgsl files on disk). */\n readonly text?: ShaderText;\n /** The paper's numbers (theme.ts `PAPER`) — the engine's unless a host tweaks them. */\n readonly law?: PaperLaw;\n /** The hand (D2c): its law (theme.ts `HAND`), its face (`caveat`) and the pen's bleed (0.3 note units). */\n readonly hand?: { readonly law?: HandLaw; readonly face?: string; readonly bleed?: number };\n}\n\n/** The root paper pass's pages behind a kind host — the writing's `pages()`. */\nconst pagesOf = (host: KindHost) => (): PaperPass | undefined => {\n const pass = host.pass();\n return pass instanceof PaperKind ? pass.pass : undefined;\n};\n\n/** A note's writing greeked (a mini mat's chip, the far LOD — K7b): the lines a still pinned, else the hand's layout of its text; undefined = none. */\nfunction greekOf(asset: PaperAsset | undefined, laid: HandLayout | undefined, hand: { readonly pad: number; readonly size: number }): PaperWriting | undefined {\n const g = asset?.greek ?? (laid === undefined ? undefined : { x0: hand.pad, em: hand.size, lines: laid.lines.map((L) => ({ y: L.y, width: L.width })) });\n return g === undefined || g.lines.length === 0 ? undefined : g;\n}\n\n/** The note's kind, whole (kinds/world.ts `ObjectKind`): the program, and the world half on the prototype's laws. */\nexport function paperKind(opts: PaperKindOptions = {}): ObjectKind<PaperGeometry, PaperInstance, PaperLook> {\n const law = opts.law ?? DEFAULT_PAPER_LAW;\n const program = paperProgram(opts.text ?? shaderText);\n const parse = (table: Readonly<Record<string, TokenRef>> | undefined): Readonly<Record<string, RGB>> =>\n Object.fromEntries(Object.entries(table ?? {}).map(([k, t]) => [k, rgb(t.css)]));\n return {\n ...program,\n reach: paperReach(law),\n // the record reads the view's zoom and dpr ONLY through the ink's band (paper.ts `rasterBand`) — its RUNG (K6b): a zoom within the\n // band remakes nothing; a crossing remakes the note, or — the frame queue's — asks for the new band and remakes it when it lands\n // (writing.ts `rungOf`); nothing else of the camera (D6)\n rung: (c: RungContext): number => (c.local as Partial<Pick<Writing, \"rungOf\">> | undefined)?.rungOf?.(c.entity, c.props, c.rect, c.zoom, c.dpr, c.px) ?? 0,\n local: (host: KindHost): Writing => createWriting({\n pages: pagesOf(host),\n text: host.use?.(TEXT_RASTER),\n drawn: host.drawn,\n queue: host.rasters,\n remake: host.remake,\n wipeMs: HAND.wipeMs,\n far: law.far.px[0],\n blinkMs: law.caret.blinkMs,\n ...(opts.hand?.law !== undefined ? { hand: opts.hand.law } : {}),\n ...(opts.hand?.face !== undefined ? { face: opts.hand.face } : {}),\n ...(opts.hand?.bleed !== undefined ? { bleed: opts.hand.bleed } : {}),\n }),\n resolve(ctx: ObjectContext): PaperGeometry {\n const r = ctx.rect;\n const seed = numberProp(ctx.props, \"seed\", 0);\n return resolvePaper({ cx: r.cx, cy: r.cy, w: r.w, h: r.h, angle: tiltOf(seed, law.tilt) }, { held: ctx.flux.lift, ring: ctx.flux.ring, fade: ctx.flux.fade }, law, ctx.lamp);\n },\n record(G: PaperGeometry, ctx: ObjectContext): PaperInstance {\n const look = ctx.look as PaperLook | undefined;\n const papers = look?.papers ?? {};\n const pens = look?.pens ?? {};\n const paper = papers[stringProp(ctx.props, \"paper\", \"\")] ?? Object.values(papers)[0];\n const ink = pens[stringProp(ctx.props, \"pen\", \"\")] ?? Object.values(pens)[0];\n if (paper === undefined || ink === undefined) throw new Error(\"desk/paper: the note's colours are the host's — the palette names no `papers`/`pens` (kinds/paper.ts `PaperPalette`)\");\n // the writing on this desk: the live (or pinned) ink, the pen's wipe, the caret; a builder pin is the fallback\n const w = ctx.local as Writing | undefined;\n const hand = w?.draw(ctx.entity, ctx.props, ctx.rect, ctx.view, G, ctx.flux.fade < 1) ?? {}; // a ghost fades on what it has\n const asset = asPaperAsset(ctx.asset);\n const raster = hand.raster ?? (hasRaster(asset) ? { layer: asset.layer, uv: asset.uv } : undefined);\n // K7b — its writing GREEKED (the far LOD, theme.ts `PAPER.far`): the lines a still pinned, else the hand's own layout of its text\n const greek = greekOf(asset, w?.layoutOf?.(ctx.entity), opts.hand?.law ?? HAND);\n return { geometry: G, paper, ink, ...(raster !== undefined ? { raster } : {}), ...(hand.wipe !== undefined ? { wipe: hand.wipe } : {}), ...(hand.caret !== undefined ? { caret: hand.caret } : {}), ...(greek !== undefined ? { greek } : {}) };\n },\n hit(G: PaperGeometry, wx: number, wy: number): ObjectHit | null {\n return pickPaper(G, wx, wy) === \"paper\" ? \"content\" : null;\n },\n /**\n * Inside a mini mat, a note is a paper chip with its writing greeked (the prototype's `childrenOf`): the sheet's\n * colour, the pen's ink, and the lines — the ones a still pinned (`greek`), else the hand's own layout of the note's\n * text as the writing laid it out (D2c's `layoutOf`; a note never laid out yet shows no lines, the prototype's\n * `ensureLayout` on demand is owed).\n */\n chip(G: PaperGeometry, ctx: ObjectContext): ChildShape {\n const look = ctx.look as PaperLook | undefined;\n const papers = look?.papers ?? {};\n const pens = look?.pens ?? {};\n const paper = papers[stringProp(ctx.props, \"paper\", \"\")] ?? Object.values(papers)[0] ?? ([0, 0, 0] as unknown as RGB);\n const ink = pens[stringProp(ctx.props, \"pen\", \"\")] ?? Object.values(pens)[0] ?? paper;\n const greek = greekOf(asPaperAsset(ctx.asset), (ctx.local as Partial<Writing> | undefined)?.layoutOf?.(ctx.entity), opts.hand?.law ?? HAND);\n return {\n finish: PAPER_FINISH, cx: G.centre[0], cy: G.centre[1], hx: G.half[0], hy: G.half[1], angle: G.angle, radius: G.radius, colour: paper, height: G.curl * 0.5,\n ...(greek !== undefined && greek.lines.length > 0 ? { writing: { ink, x0: greek.x0, em: greek.em, lines: greek.lines } } : {}),\n };\n },\n frame: paperFrame,\n theme(palette: Palette, _name: ThemeName): PaperLook {\n const p = palette as PaperPalette;\n return { papers: parse(p.papers), pens: parse(p.pens) };\n },\n };\n}\n\n/** The note's silhouette for the desk's marks (D4a): the sheet as drawn — tilted, lifted to scale — its corner scaled with it. */\nexport function paperFrame(G: PaperGeometry): MarkFrame {\n return { cx: G.centre[0], cy: G.centre[1], hx: G.half[0], hy: G.half[1], angle: G.angle, r: G.radius * G.scale };\n}\n","// TYPING IS A GESTURE (design-015 §6.1; D2c) — the note's typing session, the world half of the ONE\n// focused editor (desk/host/editor.ts is its DOM half, as the keymap is the DOM half of `ops.*` —\n// design-003 §2: no system-side keyboard logic; a key resolves to a write path).\n//\n// The CLAIM: `begin(e)` stamps the runtime `Editing` rider on the note — core's fact with ONE writer,\n// this module — and `makeDefaultMayDiverge` reads it as a gesture claim, so the note's `ink` cell\n// (`{ text, seeds }`) may be written LIVE through the session's guarded live writer. Every keystroke\n// (`input(value)`) carries the seeds (`carrySeeds`: the common prefix and suffix keep their hands, the\n// inserted run gets fresh ones) and writes the whole cell live: the renderer draws it at once, the\n// document does not move. The SESSION ends — blur, Esc, 1 s without input: the editor's call — with\n// `commit()`: ONE undoable transaction with the live cell; a session that nets to nothing (the text\n// and the hand it found) commits nothing and puts the cell back exactly. So ⌘Z undoes a typing\n// session, never a keystroke.\n//\n// Collaboration is strata's reconcile matrix (006 C5), the claimed-cell rule every gesture has: while\n// the live cell differs from the baseline, a remote value for it is DROPPED and banked; the session's\n// commit wins over it (committer-wins); a session that nets to nothing reconverges silently and the\n// banked remote value applies. Between sessions the cell is not diverging and a remote edit applies.\n// A note deleted mid-session takes its uncommitted run with it — the gesture was interrupted; an undo\n// of the delete restores the note as last committed.\n\nimport { type Component, Editing, type Entity, guardedTransaction, type World } from \"@ice/core\";\nimport { tapHit, type TypingDocs, writable, type WritableSession } from \"@ice/desk\";\nimport { encodeSeeds, freshSeed, seedsFor, carrySeeds } from \"@ice/desk/kit\";\n\n// The document's doors live in docs.ts (D-D7-A.3: no kind in them, so the host holds them without naming one); the drivers\n// keep reaching them here.\nexport { type TypingDocs, writable, type WritableSession } from \"@ice/desk\";\n\n/**\n * THE TAP'S NOTE (D7 #4): the note a tap by the local pointer `pid` writes into — the interaction stack's exact hit for that\n * pointer — or none. NONE while any object is in hand: a tap in hand is the hand's (a put-down, a held tool), and the pointer's\n * hit is frozen at the pick-up anyway (l1-pick skips `HandledByWidget` pointers, which the hold stamps every tick), so it would\n * name whatever the pointer touched then — the note hovered before ⏎ opened the board. `found` says whether the pointer is\n * known at all (a touch that has lifted is gone: the caller may ask the drawn notes instead).\n */\nexport function tapNote(world: World, pid: string, isNote: (e: Entity) => boolean): { readonly found: boolean; readonly note: Entity | undefined } {\n // the desk's generic tap (K8a — `tapHit`, the stack's exact hit, none in hand): a note when it hit one\n const t = tapHit(world, pid);\n return { found: t.found, note: t.hit !== undefined && isNote(t.hit) ? t.hit : undefined };\n}\n\nexport interface NoteTypingOptions {\n readonly world: World;\n readonly docs: TypingDocs;\n /** The note's cells: its writing (`{ text, seeds }`, live-written and committed whole) and its other props (the seed). The object hands its own (D-D7-A.3). */\n readonly ink: Component<{ text: string; seeds: string }>;\n readonly props: Component<{ seed?: number }>;\n /** A fresh seed for a glyph just written (`Math.random` unless a test says). */\n readonly fresh?: () => number;\n}\n\nexport interface NoteTyping {\n /** The note the editor is on — the `Editing` claim — or undefined. */\n editing(): Entity | undefined;\n /** A session is open: the note's ink written live and not yet committed. */\n open(): boolean;\n /** The note's writing as the world holds it now (the live value mid-session). */\n ink(e: Entity): { readonly text: string; readonly seeds: string } | undefined;\n /** Claim `e` for writing (`Editing`); a claim on another note ends first. False for a dead entity or a non-note. */\n begin(e: Entity): boolean;\n /** The platform's value for the claimed note: seeds carried, the cell written LIVE. The inserted run, or null when nothing changed. */\n input(value: string): { readonly from: number; readonly to: number } | null;\n /** End the SESSION: ONE transaction with the live cell, unless it nets to nothing. Whether it committed. The claim stays. */\n commit(): boolean;\n /** End the claim: commit, then lift `Editing`. A dead note has nothing to commit — the claim died with it. */\n end(): void;\n}\n\ntype Ink = { readonly text: string; readonly seeds: string };\n\n/** The same hand: glyph for glyph the same seed, stored or implied (`seedsFor`). */\nfunction sameHand(a: Ink, b: Ink, noteSeed: number): boolean {\n const x = seedsFor(a.text, a.seeds, noteSeed);\n const y = seedsFor(b.text, b.seeds, noteSeed);\n return x.length === y.length && x.every((v, i) => v === y[i]);\n}\n\nexport function createNoteTyping(opts: NoteTypingOptions): NoteTyping {\n const { world, docs, ink: NOTE_INK, props: NOTE_PROPS } = opts;\n const fresh = opts.fresh ?? freshSeed;\n let editing: Entity | undefined;\n let open = false;\n /** The cell as the session found it (before its first live write) — what \"nets to nothing\" means. */\n let start: Ink | undefined;\n\n const alive = (e: Entity | undefined): e is Entity => e !== undefined && world.isAlive(e);\n const inkOf = (e: Entity): Ink | undefined => world.get(e, NOTE_INK) as Ink | undefined;\n const seedOf = (e: Entity): number => (world.get(e, NOTE_PROPS) as { seed?: number } | undefined)?.seed ?? 0;\n /** The live write — through the guarded live writer, legal only under the claim (`Editing`: core's makeDefaultMayDiverge). */\n const write = (session: WritableSession | undefined, e: Entity, ink: Ink): void => {\n if (session !== undefined) session.liveWriter.set(e, NOTE_INK, { text: ink.text, seeds: ink.seeds });\n else world.edit(e).set(NOTE_INK, { text: ink.text, seeds: ink.seeds }); // no document: the runtime is all there is\n };\n\n const commit = (): boolean => {\n const e = editing;\n if (!open) return false;\n open = false;\n if (!alive(e)) return false;\n const doc = docs.current();\n const session = writable(docs);\n const live = inkOf(e);\n const from = start;\n start = undefined;\n if (doc === undefined || live === undefined) return false;\n // the document went read-only mid-session (the gate's verdict moved under a peer's pack): nothing lands, the cell goes back as found\n if (session === undefined) {\n if (from !== undefined) write(doc, e, from);\n return false;\n }\n // NETS TO NOTHING — the same text in the same hand as the session found it: no transaction. The cell is put back\n // EXACTLY as found (an implicit hand made explicit by the carry is the same hand, but not the same bytes), so the\n // runtime reconverges to its baseline and a remote value strata banked meanwhile applies at the next drain. Compared\n // with the START, never the doc: the doc may already hold that remote value.\n if (from !== undefined && from.text === live.text && sameHand(from, live, seedOf(e))) {\n if (from.seeds !== live.seeds) write(session, e, from);\n return false;\n }\n guardedTransaction(session.store, world, (tx) => { tx.edit(e).set(NOTE_INK, { text: live.text, seeds: live.seeds }); });\n return true;\n };\n\n const end = (): void => {\n const e = editing;\n commit();\n editing = undefined;\n open = false;\n if (alive(e) && world.hasTag(e, Editing)) world.removeTag(e, Editing);\n };\n\n return {\n editing: () => (alive(editing) ? editing : undefined),\n open: () => open,\n ink: (e) => (alive(e) ? inkOf(e) : undefined),\n begin(e) {\n if (editing === e && alive(e)) return true;\n if (editing !== undefined) end();\n if (!alive(e) || inkOf(e) === undefined) return false;\n if (docs.current() !== undefined && writable(docs) === undefined) return false; // a read-only document: no session opens on it (no document at all: the runtime's)\n world.addTag(e, Editing);\n editing = e;\n open = false;\n start = undefined;\n return true;\n },\n input(value) {\n const e = editing;\n if (!alive(e)) return null;\n const cur = inkOf(e);\n if (cur === undefined || cur.text === value) return null;\n const carried = carrySeeds(cur.text, seedsFor(cur.text, cur.seeds, seedOf(e)), value, fresh);\n if (!open) start = { text: cur.text, seeds: cur.seeds };\n write(docs.current(), e, { text: value, seeds: encodeSeeds(carried.seeds) });\n open = true;\n return { from: carried.from, to: carried.to };\n },\n commit,\n end,\n };\n}\n","// THE NOTE'S BODY — its TEXT PART (design-015 §6.1; STICKY.md §4; design-016 §5 · K-L2, K8a): the part of a note the desk's ONE\n// editor is lent to. Until K8a the editor itself was the note's (this file made the textarea, and a desk with no note kind had\n// none); now the editor is the DESK's (desk/host/editor.ts) and the note LEASES it exactly as the desk calendar's day line does,\n// and as a plugin kind's part would: the note declares this part with its object (`defineObject({ host: { text } })`) and the\n// desk routes every TAP to it.\n//\n// A TAP on a note — a press and release within the drag slop, no modifier, the note not carried — puts the editor on it with the\n// caret at the tap (the layout's nearest position). The note under the tap is the interaction stack's exact hit (the desk's\n// `tapHit`), the writing's last-drawn notes when the pointer is already gone (a touch lifted). A pinned note (a still) is refused.\n//\n// The world half is `paper/typing.ts`: `begin` on the tap (the `Editing` claim), `input` on every `input` event (the live write,\n// the seeds carried), `commit` after 1 s without input (the idle end of a SESSION — the focus stays), `end` when the lease ends\n// (Escape, a blur, another part taking the editor, the note deleted or cut away). A write the world makes between sessions — a\n// peer's edit, an undo — reaches the textarea on the next frame (the lease's `value`). The pen's wipe and the caret are the\n// writing's flux, stamped on ONE clock, `performance.now()` (the rAF clock lags wall time headless).\n\nimport { Active, Camera, type Entity, Grab, type World } from \"@ice/core\";\nimport type { PaperDriver } from \"../object\";\nimport { PEN_FACES, type HandLaw, type DeskEditor, type EditorLease, type TextPart } from \"@ice/desk/kit\";\nimport type { PaperGeometry } from \"../paper\";\nimport { DEFAULT_FACE, DEFAULT_HAND_LAW, type Writing } from \"../writing\";\n\n/** The note's text part's name — what the editor's lease carries while a note is being written (`DeskEditor.lease().part`). */\nexport const NOTE_BODY = \"note.body\";\n\nexport interface NoteBodyOptions {\n /** The desk's ONE editor (the desk makes it — `ObjectDomHost.editor`). */\n readonly editor: DeskEditor;\n readonly world: World;\n /** The note's driver (`PaperDriver`, D-D7-A.3): the host hands the note's own; none, no body. */\n readonly driver: PaperDriver | undefined;\n /** The builder's drawn geometry for an entity. */\n readonly geometryOf: (e: Entity) => unknown;\n /** The hand's face for the platform's own layout of the text (arrow keys by line): family and weight (the paper's default face). */\n readonly font?: { readonly family: string; readonly weight: number };\n readonly hand?: Pick<HandLaw, \"size\" | \"lineHeight\" | \"pad\">;\n /** The clock the writing's flux runs on (`performance.now`). */\n readonly now?: () => number;\n}\n\n/** The note's body: its text part (the desk routes taps to it) and the doors a rig and the keys use. */\nexport interface NoteBody extends TextPart {\n /** Put the editor on note `e`, the caret before glyph `index` (the end by default). False for a still, a non-note or a read-only document. */\n focus(e: Entity, index?: number): boolean;\n /** The note being written, or undefined (the editor lent elsewhere, or to nothing). */\n editing(): Entity | undefined;\n}\n\nexport function createNoteBody(opts: NoteBodyOptions): NoteBody | undefined {\n const { editor, world } = opts;\n const paper = opts.driver;\n if (paper === undefined) return undefined; // no note kind on this desk: no body\n const typing = paper.typing;\n const font = opts.font ?? PEN_FACES[DEFAULT_FACE] ?? { family: \"Caveat\", weight: 500 };\n const hand = opts.hand ?? DEFAULT_HAND_LAW;\n const clock = opts.now ?? (() => performance.now());\n const writing = (): Writing | undefined => paper.writing();\n /** The note being written and ITS lease — one lease a note, so a tap on the same note keeps it and a tap on another hands over. */\n let current: { readonly entity: Entity; readonly lease: EditorLease } | undefined;\n\n const leaseFor = (e: Entity): EditorLease => {\n const lease: EditorLease = {\n part: NOTE_BODY,\n label: \"write on the note\",\n // between sessions the world's text reaches the field (a peer, an undo); while a session is open the field is the truth\n value: () => (typing.open() ? null : (typing.ink(e)?.text ?? \"\")),\n input(value) {\n const r = typing.input(value);\n if (r !== null) {\n const ch = value[r.from];\n // a typed glyph is WRITTEN (the pen's wipe); a paste, a space or a newline arrives whole\n writing()?.wrote(e, r.to - r.from === 1 && ch !== undefined && ch !== \" \" && ch !== \"\\n\" ? r.from : undefined, clock());\n }\n writing()?.caret(e, editor.element.selectionStart, clock());\n },\n // Escape lets the note go (the keymap's gate 1 stands down; the release is ours)\n keydown(ev) { if (ev.key !== \"Escape\") return false; editor.release(lease); return true; },\n caret(index) { writing()?.caret(e, index, clock()); },\n place() {\n const G = opts.geometryOf(e) as PaperGeometry | undefined;\n const cam = world.getResource(Camera);\n if (G === undefined || cam === undefined) return null;\n const z = cam.zoom;\n const w = 2 * G.half[0] * z;\n const h = 2 * G.half[1] * z;\n const s = z * G.scale;\n // the sheet's box, turned at its tilt about its centre: its font the hand's × the zoom\n return { x: (G.centre[0] - cam.x) * z - w / 2, y: (G.centre[1] - cam.y) * z - h / 2, w, h, angle: G.angle, fontPx: hand.size * s, pad: hand.pad * s, lineHeight: hand.lineHeight * hand.size * s, wrap: true, font };\n },\n idle() { typing.commit(); },\n ended() {\n // the claim is lifted only if it is still this note's (a tap on another note claimed that one first)\n if (typing.editing() === e) typing.end();\n if (current?.entity === e) { current = undefined; writing()?.caret(undefined); }\n },\n // a delete or a nav cut ends the writing\n live: () => world.isAlive(e) && world.hasTag(e, Active),\n };\n return lease;\n };\n\n /** The lease a note takes, the claim begun — or undefined: refused (dead, not a note, pinned, a read-only document). */\n const take = (e: Entity): EditorLease | undefined => {\n if (!world.isAlive(e) || !paper.isNote(e) || writing()?.isPinned(e) === true) return undefined;\n if (!typing.begin(e)) return undefined;\n if (current?.entity === e && editor.lease() === current.lease) return current.lease;\n current = { entity: e, lease: leaseFor(e) };\n return current.lease;\n };\n /** Where the caret goes: `index`, else the end — of the field when the lease already holds it (the editor puts a new lease's there itself). */\n const caretOf = (lease: EditorLease, index: number | undefined): number | undefined => index ?? (editor.lease() === lease ? editor.element.value.length : undefined);\n\n return {\n part: NOTE_BODY,\n tap({ wx, wy, found, hit }) {\n // the stack's exact hit when the pointer is known; the writing's topmost drawn note when it is gone (a touch lifted)\n const e = found ? (hit !== undefined && paper.isNote(hit) ? hit : undefined) : writing()?.noteAt(wx, wy);\n if (e === undefined || world.has(e, Grab)) return undefined;\n const lease = take(e);\n if (lease === undefined) return undefined;\n const caret = caretOf(lease, writing()?.caretIndexAt(e, wx, wy));\n return caret === undefined ? { lease } : { lease, caret };\n },\n focus(e, index) {\n const lease = take(e);\n if (lease === undefined) return false;\n editor.lend(lease, caretOf(lease, index));\n return true;\n },\n editing: () => (current !== undefined && editor.lease() === current.lease ? current.entity : undefined),\n };\n}\n","// The NOTE (STICKY.md) as an OBJECT — the desk's first reference kind through `defineObject`\n// (design-015 §6): a sheet of paper on the mat. Durable props: its writing — `text`, and `seeds`, each\n// glyph's own hand (paper/seeds.ts; D-D13: the seeds persist or a reload re-draws the hand) — in ONE\n// conflict group, `ink`, so the two are one cell written in one transaction and a concurrent edit can\n// never pair one peer's text with another's seeds (D2c); its pen and its paper by name (the product's\n// colours through the palette, kinds/paper.ts `PaperPalette`), and its `seed` — the tilt it is stuck\n// at, never square (`tiltOf`), and the hand of a glyph with no stored seed. Things, movable,\n// selectable, snapping both ways; it offers itself to the desk, a mini mat (D2b's drop-into) and a calendar's day by what it\n// `provides` (K8a — the desk's keys).\n\nimport { type Component, type Entity, p } from \"@ice/core\";\nimport { paperKind } from \"./kind\";\nimport { CONTAINABLE, DESK_OBJECT, type KindDriver, defineObject, PINNABLE } from \"@ice/desk\";\nimport type { Writing } from \"./writing\";\nimport { PAPER } from \"./theme\";\nimport { PENS } from \"@ice/desk/kit\";\nimport { createNoteTyping, type NoteTyping } from \"./typing\";\nimport { createNoteBody, type NoteBody } from \"./host/body\";\n\n// the pens are the HAND's (kit/text.ts since K4a — the desk calendar writes with them too); the note keeps its door\nexport { PENS, type PenName } from \"@ice/desk/kit\";\n/** The papers a note is cut from — names; the sheets are the host's (the product's `--vf-note-surface` is `yellow`). */\nexport const PAPERS = [\"yellow\"] as const;\nexport type PaperName = (typeof PAPERS)[number];\n\n/** The note's durable type id — what `PrefabId` carries (a mini mat accepts it by what it provides — K8a, `CONTAINABLE`). */\nexport const NOTE_TYPE = \"desk.note\";\n\nexport const Note = defineObject({\n type: NOTE_TYPE,\n version: 1,\n props: {\n text: p.string({ default: \"\" }),\n seeds: p.string({ default: \"\" }),\n pen: p.enum(PENS, { default: \"fountain\" }),\n paper: p.enum(PAPERS, { default: \"yellow\" }),\n seed: p.number({ default: 0 }),\n },\n groups: { ink: [\"text\", \"seeds\"] },\n size: { w: PAPER.size, h: PAPER.size },\n kind: paperKind(),\n // on the pegboard tray (design-017 §8): a pad of notes on two hooks\n // …with a word on it in the note's own hand, written through its writing (K5b — `local`); one taken is blank\n tray: { label: \"Note\", category: \"paper\", order: 0, props: { text: \"hello\" }, local: true, hang: { w: 120, h: 120, accessory: \"hook\", pegs: [[-1, -0.5], [1, -0.5]] } },\n interaction: { selectable: true, movable: true, resizable: false, snap: \"both\" },\n // what it provides is what places it (K8a): on the desk, into a mini mat, onto a calendar's day — as a plugin kind's would\n provides: [NOTE_TYPE, DESK_OBJECT, CONTAINABLE, PINNABLE],\n // TYPING IS A GESTURE (design-015 §6.1; D2c): the note's driver is its typing session — the world half its body's lease on the\n // desk's ONE editor drives (host/body.ts); it follows nothing on its own (D-D7-A.3)\n drivers: (h): PaperDriver => ({\n typing: createNoteTyping({ world: h.world, docs: h.docs, ink: NOTE_INK, props: NOTE_PROPS }),\n writing: () => h.local as Writing | undefined,\n isNote: h.isKind,\n body: undefined,\n follow: () => {},\n idle: () => true,\n }),\n // its DOM HALF (K4b — declared, never found by type): its BODY, the note's TEXT PART (K8a, host/body.ts) — the desk routes a tap on\n // a note to it and it leases the desk's ONE editor, as any kind's part does; the body joins the note's own driver (`body`)\n host: {\n text: (h) => {\n const driver = h.driver as PaperDriver | undefined;\n const body = createNoteBody({ editor: h.editor, world: h.world, driver, geometryOf: h.geometryOf });\n if (driver !== undefined) driver.body = body;\n return body === undefined ? [] : [body];\n },\n },\n});\n\n/** The note's writing as a cell (`desk.note:ink` — `{ text, seeds }`): what a typing session live-writes and commits whole. */\nexport const NOTE_INK = groupOf(\"ink\") as Component<{ text: string; seeds: string }>;\n/** The note's other props (`desk.note:props` — `{ pen, paper, seed }`). */\nexport const NOTE_PROPS = groupOf(\"props\") as Component<{ pen: string; paper: string; seed: number }>;\n\n/** The note's driver (`driversOf(Note)`): its typing session, its writing local and its membership — what its body asks of it. */\nexport interface PaperDriver extends KindDriver {\n readonly typing: NoteTyping;\n readonly writing: () => Writing | undefined;\n readonly isNote: (e: Entity) => boolean;\n /** Its BODY (K8a — the note's text part, host/body.ts), once the host has made it: the doors that put the editor on a note. */\n body: NoteBody | undefined;\n}\n\nfunction groupOf(name: string): Component {\n const g = Note.groups.find((q) => q.name === name);\n if (g === undefined) throw new Error(`desk: the note has no \"${name}\" group`);\n return g.component;\n}\n","// The WHITEBOARD's own theme — its law as numbers (moved out of the engine's src/theme.ts at K4a, design-016 §5). What it\n// shares with the note and the notebook — the lift, the slab's shadow, the face's light, the ring — is the kit's ONE\n// PHYSICS (kit/physics.ts), by name.\n\nimport { PHYSICS } from \"@ice/desk/kit\";\n\n/**\n * The WHITEBOARD (BOARD.md) — a desk dry-erase board under the mat's one lamp, ONE PHYSICS with\n * the note and the notebook: it lifts as they lift (`PAPER.lift`), its slab casts the note's\n * penumbra swept down its height with the notebook's contact term at its base (`BOOK.shadow`),\n * and a face reads by the notebook's light (`BOOK.light`). What a board has of its own is the\n * research whiteboard (research/whiteboard): melamine with an orange-peel grain and a sheen that\n * slides with the eye, felt-tip ink laid by max-blended stamps — streaky when fast, bleeding when\n * held, glossy while wet — and an eraser that leaves a ghost. The board is 3:2 like every\n * whiteboard, on the tree-shadow design's 80-unit module, at the notebook's scale: 480 × 320\n * beside the A6 notebook's 176 × 248 is a ~29 × 19 cm desk board. World units throughout; the\n * research's tip and stroke numbers were CSS px on a full-screen board and are scaled into them.\n * The colours are the product's (lab/theme.ts `BOARD_LOOK`, `MARKERS`).\n */\nexport const BOARD = {\n /** A board as a host spawns one: its outer size, the aluminium frame's width, the frame's outer radius, the slab's height, the melamine's recess below the frame's top. */\n spec: { width: 480, height: 320, frame: 9, radius: 7, thick: 8, recess: 1.2 },\n lift: PHYSICS.lift,\n shadow: PHYSICS.slab,\n light: PHYSICS.light,\n /**\n * The melamine: its tone's drift (±), its orange-peel grain (±/255), the ghost old erasures\n * leave; the SHEEN — the window's reflection — its strength, its spread, the eye's height over\n * the board (× the board's height) and how far it slides with the pointer; the frame's lip on\n * the surface: its shadow's alpha and σ.\n */\n surface: { tone: 0.012, grain: 1.5 / 255, ghost: 0.012, sheen: 0.16, spread: 0.35, eye: 1.6, parallax: 0.12, lip: { alpha: 0.2, sigma: 0.9 } },\n /** The frame: brushed along its length (±/255), its profile's roll at the rims (rad), the metal's glint. */\n frame: { brushed: 9 / 255, roll: 0.85, glint: 0.35 },\n /** The ink raster (texels per world unit — the open board fills the view at ~1.8× on a 2× display), how long fresh ink stays wet (s) and how dark it lays wet, the film's edge relief. */\n ink: { density: 4, wetSeconds: 1.2, wetDarken: 0.8, film: 0.04 },\n /** The tips, world units: half extents (along, across the tip), corner radius, edge softness, the angle it is held at (deg). The research's, scaled to the desk board. */\n tips: {\n fine: { half: [0.75, 0.75], radius: 0.75, softness: 0.3, angle: 0 },\n bullet: { half: [1.35, 1.35], radius: 1.35, softness: 0.35, angle: 0 },\n chisel: { half: [2.4, 0.9], radius: 0.5, softness: 0.35, angle: -50 },\n },\n eraser: { half: [16, 7], radius: 2.5, softness: 1.6, angle: 8 },\n /**\n * The felt: its streaks (strength, lanes per world unit across, drift along ×2), how fast a\n * stroke runs dry (world units/s: from, full) and how much flow it loses, a held pen's bleed\n * (after ms, growth, its time constant ms), and the stamps' pitch (× the tip's narrow half, clamped).\n */\n felt: { streak: 0.45, lanes: 0.75, along: [0.058, 0.145], dry: [200, 1450], dryLoss: 0.16, bleed: { after: 150, grow: 0.35, tau: 700 }, pitch: { k: 0.3, min: 0.12, max: 0.5 } },\n /** The pen in the hand and on the board: its length, barrel radius, the cap's length, how steeply it rises from the tip (height per unit of length), how high it hovers unpressed, its lean with speed (rad). */\n pen: { length: 150, radius: 6.5, cap: 42, rise: 0.18, hover: 6, lean: 0.16 },\n /** The eraser in the hand: the felt block's half extents, the felt's and the wooden back's heights. */\n block: { half: [18, 8], felt: 4, wood: 10 },\n ring: PHYSICS.ring,\n /** The open board: CSS px kept clear round it and for the tray under it, the zoom band, and the pinch-out that closes it (× the framing's zoom). */\n focus: { pad: 48, tray: 92, minZoom: 0.5, maxZoom: 3, close: 0.72 },\n} as const;\n","// The PEN's law — pure (BOARD.md §3): pointer samples in, marker STAMPS out. A stroke is a\n// dense run of footprints along the path (the research whiteboard's input.ts, moved from\n// device px into the melamine's world units): each stamp carries where it sits, the direction\n// of travel, how far along the stroke it is, how much ink the felt still gives (it runs dry as\n// the hand speeds up), its size (a pen's pressure; a held pen's bleed) and the stroke's fibre\n// seed. Deterministic: the same samples make the same stamps, so a stroke's stamps ARE the\n// stroke — the history keeps them, and an undo replays them into a fresh raster at whatever\n// density the board is drawn at.\n\nimport type { RGB } from \"@ice/desk\";\nimport { BOARD } from \"./theme\";\n\n/** A stamp's floats: x, y (world units from the melamine's top-left) · dir x, y · s (arc length) · flow · size · seed. */\nexport const STAMP_FLOATS = 8;\n\n/** A felt tip, world units: half extents (along the tip's long axis, across it), corner radius, edge softness, the angle it is held at (radians, screen space, y down). */\nexport interface Tip { readonly half: readonly [number, number]; readonly radius: number; readonly softness: number; readonly angle: number }\n\nexport type TipName = keyof typeof BOARD.tips;\nexport const TIP_NAMES: readonly TipName[] = [\"fine\", \"bullet\", \"chisel\"];\nconst deg = (d: number) => (d * Math.PI) / 180;\n/** A tip from the theme's numbers (degrees → radians). */\nexport const tipOf = (t: { readonly half: readonly [number, number]; readonly radius: number; readonly softness: number; readonly angle: number }): Tip => ({ half: t.half, radius: t.radius, softness: t.softness, angle: deg(t.angle) });\nexport const TIPS: Record<TipName, Tip> = { fine: tipOf(BOARD.tips.fine), bullet: tipOf(BOARD.tips.bullet), chisel: tipOf(BOARD.tips.chisel) };\nexport const ERASER_TIP: Tip = tipOf(BOARD.eraser);\n\n/** What lays the stamps down: a marker (its ink in LINEAR rgb, the coverage one pass lays) or the eraser. */\nexport interface Tool {\n readonly mode: \"ink\" | \"erase\";\n readonly color: RGB;\n readonly opacity: number;\n readonly tip: Tip;\n /** The felt's streaks, 0..1 — none for the eraser's own pattern. */\n readonly streak: number;\n}\n\nexport interface FeltLaw {\n readonly streak: number;\n readonly lanes: number;\n readonly along: readonly [number, number];\n readonly dry: readonly [number, number];\n readonly dryLoss: number;\n readonly bleed: { readonly after: number; readonly grow: number; readonly tau: number };\n readonly pitch: { readonly k: number; readonly min: number; readonly max: number };\n}\nexport const DEFAULT_FELT: FeltLaw = BOARD.felt;\n\nexport function markerTool(color: RGB, opacity: number, tip: Tip, felt: FeltLaw = DEFAULT_FELT): Tool {\n return { mode: \"ink\", color, opacity, tip, streak: felt.streak };\n}\nexport const ERASER_TOOL: Tool = { mode: \"erase\", color: [0, 0, 0], opacity: 1, tip: ERASER_TIP, streak: 0 };\n\n/** The distance between stamps for a tip: a fraction of its narrow half, clamped (world units). */\nexport const pitchOf = (tip: Tip, felt: FeltLaw = DEFAULT_FELT): number =>\n Math.min(felt.pitch.max, Math.max(felt.pitch.min, Math.min(tip.half[0], tip.half[1]) * felt.pitch.k));\n\nconst smoothstep = (a: number, b: number, x: number): number => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };\n\n/**\n * One stroke being drawn. `begin` at the press, `move` per pointer sample (coalesced events\n * in order), `hold` once a frame while the pen rests (its bleed), `end` at the lift. Times are\n * milliseconds (the events' own clock), positions the melamine's world units. `pending()`\n * hands the stamps made since the last call — what the pass uploads this frame — and\n * `stamps()` all of them, for the history.\n */\nexport class StrokeBuilder {\n readonly tool: Tool;\n readonly seed: number;\n readonly spacing: number;\n private readonly felt: FeltLaw;\n private buf = new Float32Array(STAMP_FLOATS * 1024);\n private n = 0;\n private sent = 0;\n private x = 0; private y = 0; private t = 0;\n private dirX = 1; private dirY = 0;\n private s = 0; private carry = 0; private speed = 0;\n private flow = 1; private size = 1;\n private lastMove = 0;\n private active = false;\n\n constructor(tool: Tool, seed: number, felt: FeltLaw = DEFAULT_FELT) {\n this.tool = tool; this.seed = seed; this.felt = felt;\n this.spacing = pitchOf(tool.tip, felt);\n }\n\n get count(): number { return this.n; }\n get live(): boolean { return this.active; }\n\n private push(x: number, y: number, dx: number, dy: number, s: number, flow: number, size: number): void {\n if ((this.n + 1) * STAMP_FLOATS > this.buf.length) { const b = new Float32Array(this.buf.length * 2); b.set(this.buf); this.buf = b; }\n const o = this.n * STAMP_FLOATS;\n const b = this.buf;\n b[o] = x; b[o + 1] = y; b[o + 2] = dx; b[o + 3] = dy; b[o + 4] = s; b[o + 5] = flow; b[o + 6] = size; b[o + 7] = this.seed;\n this.n += 1;\n }\n\n /** The press: the first footprint, where the tip lands. */\n begin(x: number, y: number, t: number, size = 1): void {\n this.active = true;\n this.x = x; this.y = y; this.t = t; this.lastMove = t;\n this.dirX = 1; this.dirY = 0; this.s = 0; this.carry = this.spacing; this.speed = 0;\n this.flow = 1; this.size = size;\n this.push(x, y, 1, 0, 0, 1, size);\n }\n\n /** A pointer sample: footprints every `spacing` along the segment since the last, the flow and size interpolated. */\n move(x: number, y: number, t: number, size = this.size): void {\n if (!this.active) return;\n const dx = x - this.x;\n const dy = y - this.y;\n const dist = Math.hypot(dx, dy);\n if (dist < this.spacing * 0.25) return;\n const dt = Math.max(1, t - this.t);\n const v = (dist / dt) * 1000; // world units / s\n this.speed += (v - this.speed) * 0.35;\n const flow = 1 - this.felt.dryLoss * smoothstep(this.felt.dry[0], this.felt.dry[1], this.speed);\n const ux = dx / dist;\n const uy = dy / dist;\n let p = this.carry;\n while (p <= dist) {\n const k = p / dist;\n this.push(this.x + ux * p, this.y + uy * p, ux, uy, this.s + p, this.flow + (flow - this.flow) * k, this.size + (size - this.size) * k);\n p += this.spacing;\n }\n this.carry = p - dist;\n this.s += dist;\n this.x = x; this.y = y; this.t = t; this.lastMove = t;\n this.dirX = ux; this.dirY = uy;\n this.flow = flow; this.size = size;\n }\n\n /** The pen held still: past `bleed.after` ms the ink spreads into the melamine, growing toward `1 + grow`. */\n hold(now: number): void {\n if (!this.active) return;\n const idle = now - this.lastMove - this.felt.bleed.after;\n if (idle <= 0) return;\n const grow = 1 + this.felt.bleed.grow * (1 - Math.exp(-idle / this.felt.bleed.tau));\n this.push(this.x, this.y, this.dirX, this.dirY, this.s, 1, this.size * grow);\n }\n\n /** The lift: the last sample's footprints; the stroke is complete. */\n end(x?: number, y?: number, t?: number, size?: number): void {\n if (x !== undefined && y !== undefined && t !== undefined) this.move(x, y, t, size);\n this.active = false;\n }\n\n /** The stamps made since the last call (a view — copy it before the next push). */\n pending(): Float32Array {\n const out = this.buf.subarray(this.sent * STAMP_FLOATS, this.n * STAMP_FLOATS);\n this.sent = this.n;\n return out;\n }\n\n /** Every stamp of the stroke, as its own array. */\n stamps(): Float32Array { return this.buf.slice(0, this.n * STAMP_FLOATS); }\n}\n\n/** A stroke's path for a reader — an agent, an export: one point per `every` stamps, world units from the melamine's top-left. */\nexport function pathOf(stamps: Float32Array, every = 6): Array<readonly [number, number]> {\n const out: Array<readonly [number, number]> = [];\n const n = stamps.length / STAMP_FLOATS;\n for (let i = 0; i < n; i += every) out.push([stamps[i * STAMP_FLOATS] as number, stamps[i * STAMP_FLOATS + 1] as number]);\n if (n > 0 && (n - 1) % every !== 0) out.push([stamps[(n - 1) * STAMP_FLOATS] as number, stamps[(n - 1) * STAMP_FLOATS + 1] as number]);\n return out;\n}\n","// A board's HISTORY — pure (BOARD.md §4). What is on a whiteboard is the list of what was\n// done to it: strokes (a tool and its stamps) and wipes. The raster on the GPU is a cache of\n// that list, replayed in order — so an undo is \"replay one fewer\", a redo \"one more\", and the\n// board can be re-rastered at any density. The list is also what an agent reads: every\n// stroke's tool, colour and path, in world units.\n\nimport { pathOf, type Tool } from \"./stroke\";\n\nexport type BoardOp =\n | { readonly kind: \"stroke\"; readonly tool: Tool; readonly stamps: Float32Array; readonly ink?: string }\n | { readonly kind: \"wipe\" };\n\nexport class BoardHistory {\n private ops: BoardOp[] = [];\n private cursor = 0;\n /** Bumps on every change — what a host compares to know the raster is stale. */\n version = 0;\n\n /** Do something new: anything undone past the cursor is forgotten. */\n push(op: BoardOp): void {\n this.ops.length = this.cursor;\n this.ops.push(op);\n this.cursor += 1;\n this.version += 1;\n }\n\n get canUndo(): boolean { return this.cursor > 0; }\n get canRedo(): boolean { return this.cursor < this.ops.length; }\n\n undo(): boolean { if (!this.canUndo) return false; this.cursor -= 1; this.version += 1; return true; }\n redo(): boolean { if (!this.canRedo) return false; this.cursor += 1; this.version += 1; return true; }\n\n /** What is on the board now, in the order it was done. */\n get done(): readonly BoardOp[] { return this.ops.slice(0, this.cursor); }\n\n /** What a replay needs: everything after the last wipe (a wipe clears all before it). */\n get replay(): readonly BoardOp[] {\n const done = this.done;\n let from = 0;\n for (let i = done.length - 1; i >= 0; i--) if ((done[i] as BoardOp).kind === \"wipe\") { from = i + 1; break; }\n return done.slice(from);\n }\n\n /** Is there ink on the board? (A stroke after the last wipe — the eraser's count too: it may leave a ghost.) */\n get inked(): boolean { return this.replay.some((op) => op.kind === \"stroke\"); }\n\n /** The board as a reader sees it: each stroke's tool, ink and path since the last wipe. */\n read(every = 6): Array<{ tool: \"marker\" | \"eraser\"; ink: string | null; path: Array<readonly [number, number]> }> {\n return this.replay.flatMap((op) => op.kind === \"stroke\" ? [{ tool: op.tool.mode === \"erase\" ? \"eraser\" as const : \"marker\" as const, ink: op.ink ?? null, path: pathOf(op.stamps, every) }] : []);\n }\n}\n","// The whiteboard's DATA (design-015 §5.1, D-D5; D3w) — what is on a board is not a raster: it is\n// the list of what was done to it, and every item of that list is an ENTITY, a durable child of\n// its board (`ChildOf`, never a member of the desk's paint order): a STROKE (a marker's ink and\n// tip, or the eraser, along a path at a pace) or a WIPE (the board wiped clean). One stroke is one\n// transaction, so undo, redo, sync, persistence and presence come from strata; the prototype's\n// private `history.ts` stack survives only as what a REPLAY walks (`boardOps`): the raster on the\n// GPU is a cache of the children, rebuilt when the set changes (kinds/board.ts).\n//\n// THE ENCODING (strata has no bytes field): a stroke's path is `points`, base64 without padding of\n// its little-endian f32 (x, y) pairs — melamine world units from the board's top-left, the bench's\n// `sketch` coordinates — 8 bytes a point, the seeds' codec (paper/seeds.ts) over the floats' bits.\n// The tool is a NAME (`marker` | `wipe`), the ink and the tip are names (the colours are the host's\n// palette, BOARD.md's markers), `erase` = the eraser's felt.\n//\n// ITS PACE (D3t-a — version 2): a stroke laid by hand keeps each sample's TIME, `times` — base64 of LE\n// f32 millisecond offsets from its first, one per point, the same codec — so the replay feeds the pen\n// exactly the samples the hand did (the felt runs dry as the hand speeds up; a pen held still bleeds:\n// a sample that repeats its point exactly is the pen RESTING — `hold` — never a move). The live pen\n// sees the samples through the same f32s, so a stroke's stamps are the same laid and replayed. `speed`\n// (world units/s) stays: an old stroke (v1 — no `times`, the migration's empty string) spaces its\n// points by distance / speed as the bench's `sketch` does, and a v2 stroke carries its mean pace there\n// for a reader that knows no `times`.\n//\n// ITS PAGE (D3t-b — version 3): the notebook's strokes are the same data, children of a BOOK — each on one page, `page` (a\n// sheet's recto is page 2i + 1, its verso 2i + 2; 0 = no page: a board's stroke, which is every stroke a v2 document holds),\n// its path in PAGE units (`s` from the gutter, `y` from the head — the same on both faces of a sheet), its tool the `pen` and\n// its ink the pen's name (the note's `PENS`; the colours are the host's). The pace is the same codec: the pen's nib law\n// (notebook/ink.ts) reads each sample's time, so a page's replay lays the widths the hand did.\n//\n// ITS SEED (D7 #13 — version 4): the fibre seed the live pen laid with is the ROW's, `seed`, not the seed its position in\n// the replay gives it — a peer's stroke landing before it, or an earlier one undone, moved every later stroke's stamps. A row\n// from before (or one spawned without a seed) carries −1 and keeps the positional seed (`seedOfRow`), so nothing it drew changes.\n\nimport { ChildOf, defineComponent, definePrefab, type Entity, field, type GuardedTx, init } from \"@ice/core\";\nimport { linear, decodePoints, decodeTimes, seedOfRow, type StrokeRow, type StrokeSpec, strokeSeed } from \"@ice/desk/kit\";\nimport type { RGB } from \"@ice/desk\";\nimport { type BoardOp, BoardHistory } from \"./history\";\n\n// the stroke model is the kit's since K4a (kit/strokes.ts — the notebook's pages take strokes too); the board keeps its door\nexport { addStroke, BoardStroke, decodePoints, decodeTimes, encodePoints, encodeTimes, meanSpeed, seedOfRow, STROKE_TYPE, StrokePrefab, type StrokeRow, strokeRow, strokeSeed, type StrokeSpec } from \"@ice/desk/kit\";\nimport { ERASER_TOOL, markerTool, StrokeBuilder, type TipName, TIPS } from \"./stroke\";\n\n/** The dry-erase markers a board is written with (BOARD.md §3) — names; the inks are the host's palette. */\nexport const MARKERS = [\"black\", \"blue\", \"red\", \"green\"] as const;\nexport type MarkerName = (typeof MARKERS)[number];\n\n/** A marker's ink as the palette gives it: the colour (sRGB) and the coverage one pass lays. */\nexport interface MarkerInk { readonly color: RGB; readonly opacity: number }\n\n\n/**\n * Feed a stroke's samples to the pen, as the hand did: the first is the press (`begin`), a sample that repeats its point exactly is\n * the pen RESTING (`hold` — its bleed), any other a move, the last the lift (`end`). Timed (`times`, one per point), the samples keep\n * their own clocks; else they are spaced by distance / `speed` (an old stroke — the bench's `sketch`, which never rests).\n */\nexport function feedStroke(builder: StrokeBuilder, points: readonly (readonly [number, number])[], times: readonly number[] | null, speed: number, upto: number = points.length): void {\n const timed = times !== null && times.length === points.length;\n // `upto` < the samples: the stroke MID-DRAW (a still's) — its first `upto` samples fed, never lifted\n const n = Math.min(Math.max(upto, 0), points.length);\n const lifts = n === points.length;\n let t = 0;\n for (let i = 0; i < n; i++) {\n const [x, y] = points[i] as readonly [number, number];\n if (timed) t = times[i] as number;\n else if (i > 0) { const [px, py] = points[i - 1] as readonly [number, number]; t += (Math.hypot(x - px, y - py) / speed) * 1000; }\n if (i === 0) { builder.begin(x, y, t); continue; }\n const [px, py] = points[i - 1] as readonly [number, number];\n if (lifts && i === points.length - 1) { builder.end(x, y, t); continue; }\n if (timed && x === px && y === py) builder.hold(t);\n else builder.move(x, y, t);\n }\n if (lifts && points.length === 1) builder.end();\n}\n\n/**\n * The pen a spec is drawn with and its builder at seed `seed` — the replay's own choice (`boardOps`): the eraser's felt, or the\n * marker in the palette's ink (the first it names when it names not this one) at the spec's tip; undefined = no ink to draw with.\n */\nexport function strokePen(s: StrokeSpec, markers: Readonly<Record<string, MarkerInk>>, seed: number): StrokeBuilder | undefined {\n const erase = s.erase === true;\n const m = markers[s.ink ?? \"black\"] ?? Object.values(markers)[0];\n if (!erase && m === undefined) return undefined;\n const tip = TIPS[(s.tip ?? \"bullet\") as TipName] ?? TIPS.bullet; // a tip the board does not know draws with the bullet\n return new StrokeBuilder(erase || m === undefined ? ERASER_TOOL : markerTool(linear(m.color), m.opacity, tip), seed);\n}\n\n/**\n * A board's strokes as the history a replay walks — the bench's `sketch` (and the oracle's `opsOf`), stroke for stroke: each\n * through the StrokeBuilder at the bench's seed (`strokeSeed` of the ops before it), its samples fed as the hand laid them\n * (`feedStroke`), committed dry; a wipe clears what came before. An ink the palette does not name draws in the first it does\n * (never a blank); no ink at all draws no marker.\n */\nexport function boardOps(rows: readonly StrokeRow[], markers: Readonly<Record<string, MarkerInk>>): readonly BoardOp[] {\n const history = new BoardHistory();\n const fallback = Object.values(markers)[0];\n for (const s of rows) {\n if (s.tool === \"wipe\") { history.push({ kind: \"wipe\" }); continue; }\n const ink = s.ink ?? \"black\";\n const erase = s.erase === true;\n if (!erase && fallback === undefined) continue;\n const builder = strokePen({ ink, tip: (s.tip ?? \"bullet\") as TipName, erase }, markers, seedOfRow(s, history.done.length));\n if (builder === undefined) continue;\n const speed = s.speed !== null && s.speed > 0 ? s.speed : 400;\n const times = s.times !== null && s.times !== undefined && s.times !== \"\" ? decodeTimes(s.times) : null;\n feedStroke(builder, decodePoints(s.points ?? \"\"), times, speed);\n history.push({ kind: \"stroke\", tool: builder.tool, stamps: builder.stamps(), ...(erase ? {} : { ink }) });\n }\n return history.replay;\n}\n","// The WHITEBOARD's law — pure: no GPU (BOARD.md). A board on the desk is an axis-aligned\n// slab: a melamine surface recessed in an aluminium frame, `thick` world units off the mat.\n// `resolveBoard` turns it and its motion (held · selected · fading) into the GEOMETRY the\n// pass draws and the hit-test reads, in plain numbers, and the functions beside it are the\n// CPU mirror of board.wgsl — the footprint, the frame, the melamine — so what is clicked is\n// what is drawn. The lamp is the desk's one light (paper.ts `lampOf`): its ground slope casts\n// the slab's shadow and its direction shades the frame's roll, as for the note and the\n// notebook. `framing` is the camera an OPEN board is seen under: the board above the marker\n// tray, the one number the focus glide (book/focus.ts) flies to.\n\nimport { sdRoundBox, type CameraState, type Viewport, type Lamp } from \"@ice/desk/kit\";\nimport { BOARD } from \"./theme\";\n\n/** The board's numbers (theme.ts `BOARD`) — the engine's unless a host tweaks them. */\nexport interface BoardLaw {\n readonly spec: { readonly width: number; readonly height: number; readonly frame: number; readonly radius: number; readonly thick: number; readonly recess: number };\n readonly lift: { readonly height: number; readonly scale: number };\n readonly shadow: {\n readonly penumbra: { readonly sigma0: number; readonly sigmaPerHeight: number; readonly alpha: number };\n readonly contact: { readonly sigma: number; readonly alpha: number; readonly reach: number };\n readonly slopeMax: number;\n };\n readonly focus: { readonly pad: number; readonly tray: number; readonly minZoom: number; readonly maxZoom: number; readonly close: number };\n}\nexport const DEFAULT_BOARD_LAW: BoardLaw = BOARD;\n\n/** Where a board lies: its world centre and its outer size (world units). Boards stay square to the desk — an open one is drawn on under a camera that never turns. */\nexport interface BoardRect { readonly cx: number; readonly cy: number; readonly w: number; readonly h: number }\n\n/** What moves: the hold's lift (0..1), the selection ring's presence (0..1), the presence itself (1 … 0 gone). */\nexport interface BoardMotion { readonly held: number; readonly ring: number; readonly fade: number }\nexport const BOARD_REST: BoardMotion = { held: 0, ring: 0, fade: 1 };\n\nexport interface BoardGeometry {\n readonly centre: readonly [number, number];\n /** The outer half extents as drawn (the hold's scale applied). */\n readonly half: readonly [number, number];\n /** The melamine's half extents and corner radius (inside the frame). */\n readonly inner: readonly [number, number];\n readonly innerR: number;\n readonly frame: number;\n readonly radius: number;\n /** The slab: its height, the melamine's recess below the frame's top, how far its underside floats (the hold's rise). */\n readonly thick: number;\n readonly recess: number;\n readonly lift: number;\n readonly scale: number;\n /** The shadow's ground offset per unit of height, world axes — away from the lamp, capped. */\n readonly slope: readonly [number, number];\n /** The unit direction TO the lamp, world axes (x right, y down the screen, z off the desk). */\n readonly lamp: readonly [number, number, number];\n readonly ring: number;\n readonly alpha: number;\n}\n\n/** The melamine's corner: the frame's outer radius less its width, never sharper than this. */\nexport const INNER_RADIUS_MIN = 1.5;\n\nexport function resolveBoard(b: BoardRect, m: BoardMotion, lamp: Lamp, law: BoardLaw = DEFAULT_BOARD_LAW): BoardGeometry {\n const s = law.spec;\n const scale = 1 + (law.lift.scale - 1) * m.held;\n const hx = (b.w / 2) * scale;\n const hy = (b.h / 2) * scale;\n const frame = s.frame * scale;\n const radius = s.radius * scale;\n const dx = lamp.x - b.cx;\n const dy = lamp.y - b.cy;\n const h = Math.max(lamp.h, 1e-6);\n const len = Math.hypot(dx, dy, h);\n let sx = -dx / h;\n let sy = -dy / h;\n const sl = Math.hypot(sx, sy);\n if (sl > law.shadow.slopeMax) { sx *= law.shadow.slopeMax / sl; sy *= law.shadow.slopeMax / sl; }\n return {\n centre: [b.cx, b.cy], half: [hx, hy],\n inner: [Math.max(hx - frame, 1e-3), Math.max(hy - frame, 1e-3)], innerR: Math.max(radius - frame, INNER_RADIUS_MIN * scale),\n frame, radius, thick: s.thick, recess: s.recess, lift: law.lift.height * m.held, scale,\n slope: [sx, sy], lamp: [dx / len, dy / len, h / len],\n ring: m.ring, alpha: m.fade,\n };\n}\n\n/** The outer silhouette's signed distance at a world point. */\nexport const sdBoard = (G: BoardGeometry, wx: number, wy: number): number => sdRoundBox(wx - G.centre[0], wy - G.centre[1], G.half[0], G.half[1], G.radius);\n/** The melamine's signed distance at a world point. */\nexport const sdSurface = (G: BoardGeometry, wx: number, wy: number): number => sdRoundBox(wx - G.centre[0], wy - G.centre[1], G.inner[0], G.inner[1], G.innerR);\n\nexport type BoardHit = \"surface\" | \"frame\" | \"outside\";\n/** What is under a world point: the melamine (drawn on when open), the frame, or nothing. */\nexport function pickBoard(G: BoardGeometry, wx: number, wy: number): BoardHit {\n if (sdBoard(G, wx, wy) >= 0) return \"outside\";\n return sdSurface(G, wx, wy) < 0 ? \"surface\" : \"frame\";\n}\n\n/** A world point in the melamine's own units: world units from its top-left (what a stamp carries). */\nexport function toSurface(G: BoardGeometry, wx: number, wy: number): readonly [number, number] {\n return [wx - (G.centre[0] - G.inner[0]), wy - (G.centre[1] - G.inner[1])];\n}\n/** The melamine's size in world units at scale 1 — what its raster covers, whatever the hold's scale. */\nexport const surfaceSize = (G: BoardGeometry): readonly [number, number] => [(2 * G.inner[0]) / G.scale, (2 * G.inner[1]) / G.scale];\n\n/** The raster a melamine of this size takes at `density` texels per world unit (BOARD.ink.density). */\nexport function rasterSize(surface: readonly [number, number], density: number): readonly [number, number] {\n return [Math.max(1, Math.ceil(surface[0] * density)), Math.max(1, Math.ceil(surface[1] * density))];\n}\n\n/** How far the slab's shadow can reach past the board, world units: the top's offset along the slope, and 2.5 σ of its penumbra. */\nexport function shadowReach(G: BoardGeometry, law: BoardLaw = DEFAULT_BOARD_LAW): number {\n const top = G.lift + G.thick;\n return Math.hypot(G.slope[0], G.slope[1]) * top + 2.5 * (law.shadow.penumbra.sigma0 + law.shadow.penumbra.sigmaPerHeight * top);\n}\n\nexport interface WorldBox { readonly x0: number; readonly y0: number; readonly x1: number; readonly y1: number }\n\n/** The world rect the fragment may paint: the board and its shadow's reach, grown to take in `extra` (the pen in the hand, when it is shown). */\nexport function quadOf(G: BoardGeometry, extra?: WorldBox, law: BoardLaw = DEFAULT_BOARD_LAW): WorldBox {\n const r = shadowReach(G, law);\n let x0 = G.centre[0] - G.half[0] - r;\n let y0 = G.centre[1] - G.half[1] - r;\n let x1 = G.centre[0] + G.half[0] + r;\n let y1 = G.centre[1] + G.half[1] + r;\n if (extra) { x0 = Math.min(x0, extra.x0); y0 = Math.min(y0, extra.y0); x1 = Math.max(x1, extra.x1); y1 = Math.max(y1, extra.y1); }\n return { x0, y0, x1, y1 };\n}\n\n/**\n * The camera an OPEN board is seen under: the whole board, `pad` CSS px clear on every side, in\n * the view above the marker tray's `tray` px band — its zoom in the band, its centre at the\n * centre of what the tray leaves. The focus glide (book/focus.ts `glideTo`) flies here.\n */\nexport function framing(b: BoardRect, vp: Viewport, law: BoardLaw = DEFAULT_BOARD_LAW): CameraState {\n const f = law.focus;\n const availW = Math.max(vp.width - 2 * f.pad, 1);\n const availH = Math.max(vp.height - 2 * f.pad - f.tray, 1);\n const zoom = Math.min(f.maxZoom, Math.max(f.minZoom, Math.min(availW / b.w, availH / b.h)));\n return { x: b.cx - vp.width / (2 * zoom), y: b.cy - (vp.height - f.tray) / (2 * zoom), zoom };\n}\n","// The board pass's GPU records, declared once (README §2 rule 2). `Board` is one whiteboard\n// as drawn — what `resolveBoard` returns, its two materials, where its raster is, the stroke\n// in progress, the pen in the hand and the capped marker lying on it. `BoardUniforms` is the\n// pass's own knobs; the camera, the light, the gobo and the portal chain arrive through the\n// mat's block (`MatUniforms`), which the pass fills for itself, as the note's and the\n// notebook's passes do. `Stamp` is one footprint of the pen (stroke.ts), `StampUniforms` the\n// tip it is stamped with, `InkUniforms` the colour a finished stroke is laid in.\n\nimport { defineStruct } from \"@ice/desk/engine\";\nimport type { RGB } from \"@ice/desk\";\nimport type { BoardGeometry, WorldBox } from \"./board\";\n\n// vec2s first, then scalars, then vec4s: tight under the alignment rules.\nexport const Board = defineStruct(\"Board\", [\n [\"centre\", \"vec2f\"], [\"half\", \"vec2f\"],\n [\"inner\", \"vec2f\"], // the melamine's half extents\n [\"slope\", \"vec2f\"], // the shadow's ground offset per unit of height, world axes\n [\"sheen\", \"vec2f\"], // where the eye is over the board, × its half extents — the pointer's parallax\n [\"texels\", \"vec2f\"], // the raster's size in texels\n [\"frame\", \"f32\"], [\"radius\", \"f32\"], [\"innerR\", \"f32\"], [\"thick\", \"f32\"],\n [\"recess\", \"f32\"], [\"lift\", \"f32\"], [\"alpha\", \"f32\"], [\"ring\", \"f32\"],\n [\"density\", \"f32\"], // texels per world unit\n [\"wet\", \"f32\"], // 1 = the wet layer holds something (else it is not sampled)\n [\"laying\", \"f32\"], // 1 = a stroke is being laid on this board (the stroke layer is read)\n [\"scale\", \"f32\"], // the hold's scale (the raster is the melamine at scale 1)\n [\"lamp\", \"vec4f\"], // the unit direction to the lamp, world axes; unused\n [\"quad\", \"vec4f\"], // the world rect the fragment may paint: x0 y0 x1 y1\n [\"surface\", \"vec4f\"], // the melamine (sRGB), unused\n [\"metal\", \"vec4f\"], // the aluminium (sRGB), unused\n [\"tool\", \"vec4f\"], // the stroke in progress: its ink (LINEAR), mode (0 marker · 1 eraser)\n [\"pen\", \"vec4f\"], // THE marker, in whatever pose: its nib's end (world x y), its angle (rad), its presence\n [\"penPose\", \"vec4f\"], // its axis' height over the melamine at the nib's end, its rise (height per unit of length), its cap (0 on the nib … 1 posted), the nib's half-width\n [\"penInk\", \"vec4f\"], // its colour (sRGB), unused\n [\"eraser\", \"vec4f\"], // the eraser in the hand: world x y, its height over the melamine, its presence\n [\"tier\", \"vec4f\"], // where its ink is (K6a): its thumbnail's layer, the level of its source's chain the layer starts at, its pool slot (−1: the thumbnail), live (1: its stroke and wet are bound)\n] as const);\n\nexport const BoardUniforms = defineStruct(\"BoardUniforms\", [\n [\"light\", \"vec4f\"], // the lamp's fill on a face turned from it, the cap past flat, the day's chain (0 = a lit byte is the token's byte), the glints' strength by night\n [\"shadow\", \"vec4f\"], // penumbra σ at contact, σ per unit of height, alpha, the contact term's alpha\n [\"shadow2\", \"vec4f\"], // contact σ, the gap it fades over (world), the ring's width (CSS px), unused\n [\"castTint\", \"vec4f\"], // what a shadow is made of on this ground (sRGB)\n [\"select\", \"vec4f\"], // --vf-select, the ring\n [\"mel\", \"vec4f\"], // the melamine: tone (±), grain (±), the ghost, the ink film's relief\n [\"sheen\", \"vec4f\"], // the window's reflection: strength, its angular half-size (rad), the eye's height (× the board's height), wet ink's darkening\n [\"lip\", \"vec4f\"], // the frame's lip on the melamine: its shadow's alpha, σ; the frame: brushed (±), its roll at the rims (rad)\n [\"glint\", \"vec4f\"], // the metal's glint, unused ×3\n [\"barrel\", \"vec4f\"], // a marker's barrel (sRGB)\n [\"felt\", \"vec4f\"], // the eraser's felt (sRGB)\n [\"wood\", \"vec4f\"], // the eraser's back (sRGB)\n [\"pen\", \"vec4f\"], // a marker: length, barrel radius, the cap's length, rise (height per unit of length)\n [\"pen2\", \"vec4f\"], // how high the pen hovers unpressed, unused ×3\n [\"block\", \"vec4f\"], // the eraser: half extents x y, the felt's height, the back's height\n [\"block2\", \"vec4f\"], // the eraser: its angle (rad), unused ×3\n] as const);\n\n/** One footprint of the pen (stroke.ts `STAMP_FLOATS` — the same eight floats, in the same order). */\nexport const Stamp = defineStruct(\"Stamp\", [\n [\"pos\", \"vec2f\"], [\"dir\", \"vec2f\"], [\"s\", \"f32\"], [\"flow\", \"f32\"], [\"size\", \"f32\"], [\"seed\", \"f32\"],\n] as const);\n\nexport const StampUniforms = defineStruct(\"StampUniforms\", [\n [\"tex\", \"vec4f\"], // the raster's size (texels), texels per world unit, unused\n [\"tip\", \"vec4f\"], // half along, half across (world), angle (rad), corner radius\n [\"felt\", \"vec4f\"], // softness (world), mode (0 ink · 1 erase), opacity, streak\n [\"lanes\", \"vec4f\"], // lanes per world unit across, drift along ×2, unused\n] as const);\n\nexport const InkUniforms = defineStruct(\"InkUniforms\", [\n [\"color\", \"vec4f\"], // the finished stroke's ink (LINEAR), unused\n] as const);\n\nexport const MAX_BOARDS = 64;\n\n/**\n * THE marker of a board, in whatever pose it is in: lying capped on the melamine, in the hand at\n * the pointer with its cap posted, or anywhere between as it is picked up or put down (lab/board.ts\n * moves it; the shader draws it). Heights are over the melamine.\n */\nexport interface BoardPen {\n /** The nib's end, world units. */\n readonly x: number;\n readonly y: number;\n /** Radians: the direction from the nib along the barrel. */\n readonly angle: number;\n /** The axis' height over the melamine at the nib's end, and how steeply it rises along the barrel. */\n readonly height: number;\n readonly rise: number;\n /** Where the cap is: 0 on the nib … 1 posted on the back. */\n readonly cap: number;\n /** The nib's half-width (the tip in use). */\n readonly nib: number;\n readonly presence: number;\n /** Its colour as it looks (sRGB). */\n readonly ink: RGB;\n}\n\n/** The eraser in the hand of an open board. */\nexport interface BoardEraser { readonly x: number; readonly y: number; readonly height: number; readonly presence: number }\n\n/** One board for the pass: its geometry, its materials, its raster, and what is on and over it this frame. */\nexport interface BoardInstance {\n /** Its raster (BoardPass.ensure) — the ink the melamine shows. */\n readonly id: number;\n readonly geometry: BoardGeometry;\n readonly surface: RGB;\n readonly metal: RGB;\n /** The world rect it may paint (board.ts `quadOf`). */\n readonly quad: WorldBox;\n /** The eye's offset over the board, −1..1 each way (the pointer's parallax); absent = straight over its centre. */\n readonly sheen?: readonly [number, number] | undefined;\n /** The stroke being laid: its ink (LINEAR) and whether it erases. */\n readonly stroke?: { readonly color: RGB; readonly erase: boolean } | undefined;\n readonly pen?: BoardPen | undefined;\n readonly eraser?: BoardEraser | undefined;\n /**\n * The pen's MATERIALS (a marker's barrel, the eraser's felt and back) when the record was made WITHOUT the desk's local — a tray\n * specimen (K5b): nobody else sets them on the pass that draws it (the local's raster sets the root's, and only for a desk board\n * drawn), so the specimen carries its look's; else the one its slot's pass copied from the root showed whatever the last desk board\n * left there — black before any was drawn (an order-dependent still). Absent: the pass's own.\n */\n readonly materials?: { readonly barrel: RGB; readonly felt: RGB; readonly wood: RGB } | undefined;\n}\n\nexport function boardValues(b: BoardInstance, raster: { readonly size: readonly [number, number]; readonly density: number; readonly wet: boolean }, tier: readonly [number, number, number, number] = [0, 0, 0, 1]) {\n const G = b.geometry;\n const pn = b.pen;\n const er = b.eraser;\n const s = b.stroke;\n return {\n centre: G.centre, half: G.half, inner: G.inner, slope: G.slope,\n sheen: b.sheen ?? [0, 0], texels: raster.size,\n frame: G.frame, radius: G.radius, innerR: G.innerR, thick: G.thick,\n recess: G.recess, lift: G.lift, alpha: G.alpha, ring: G.ring,\n density: raster.density, wet: raster.wet ? 1 : 0, laying: s ? 1 : 0, scale: G.scale,\n lamp: [G.lamp[0], G.lamp[1], G.lamp[2], 0],\n quad: [b.quad.x0, b.quad.y0, b.quad.x1, b.quad.y1],\n surface: [b.surface[0], b.surface[1], b.surface[2], 0],\n metal: [b.metal[0], b.metal[1], b.metal[2], 0],\n tool: s ? [s.color[0], s.color[1], s.color[2], s.erase ? 1 : 0] : [0, 0, 0, 0],\n pen: pn ? [pn.x, pn.y, pn.angle, pn.presence] : [0, 0, 0, 0],\n penPose: pn ? [pn.height, pn.rise, pn.cap, pn.nib] : [0, 0, 0, 0],\n penInk: pn ? [pn.ink[0], pn.ink[1], pn.ink[2], 0] : [0, 0, 0, 0],\n eraser: er ? [er.x, er.y, er.height, er.presence] : [0, 0, 0, 0],\n tier: [tier[0], tier[1], tier[2], tier[3]],\n };\n}\n","// The board pass — the whiteboards, and the ink on them. Owns, like the note's and the\n// notebook's passes, its copy of the mat's uniform block (filled for the slot's camera and\n// light every frame, the gobo on only when the mat is the grid), its own knobs, the per-board\n// record buffer and the slot's bind group; shares with every slot spawned from the first the\n// pipelines, the samplers and the RASTERS — each board's ink (rgba8, premultiplied LINEAR\n// colour with its coverage, a full mip chain so a board seen small reads a filtered copy), the\n// stroke being laid (r8, max-blended stamps) and the wet layer (r8, fading). Four programs:\n// the board on the desk (a run of boards ONE instanced draw — K6a, K-L4: group 1 is shared, see\n// below), the STAMP, the INK (a finished stroke laid into the raster; the wet marked and dried) and\n// the MIP.\n//\n// RESIDENCY (K6a, design-016 §6): every board keeps a FAR-LOD THUMBNAIL — the tail of its ink's mip\n// chain from the first level that fits BOARD_THUMB², a layer of one shared array (`board/thumbnails`,\n// the kit's `LayerArray`), cut again whenever its ink changes — and, while it is large on screen, its\n// RASTER at the density its zoom rung asks (`boardRung`, never a fixed 4 texels a unit) bound in one\n// of BOARD_SLOTS pool slots; the board being laid on (or drying) binds its stroke and wet layers in the\n// one LIVE slot. A board's record says where its ink is (`tier`), so every board of a run is an\n// instance of one draw. A raster not bound is a cache the budget may take (its strokes replay it).\n// K6b: a raster to MAKE (none held, or a density raised) is the desk's frame raster queue's — the kind asks,\n// the queue makes it in its turn (`makes` says whether `ensure` would); a board with no ink at all\n// meanwhile draws its melamine BARE, from one layer of the thumbnails kept empty (`bare`).\n//\n// The raster is a CACHE of the board's history (history.ts): a stroke is laid live as its\n// stamps arrive and committed at the lift; an undo, a redo or a new density REPLAYS the\n// history into a cleared raster — stamps are world units, so a replay at any density is the\n// same drawing. Uploads are the host's pace: `lay` queues stamps, `prepare` sends them before\n// the frame's pass (its own small submit, so the frame's encoder never waits on it).\n\nimport { bindGroup, bindLayout, renderPipeline, storageBuffer, uniformBuffer, compile, compose, readback } from \"@ice/desk/engine\";\nimport { createRecordStore, type RecordStore, type GroundTheme, MAT_COLORS, type RGB } from \"@ice/desk\";\nimport { type FadeIn, type View, type MatConfig, type MatFrame, type MatPass, type Presentation, DAY_LIGHT, LayerArray, type MatLight, sentBytes, tailBase, writeChanged } from \"@ice/desk/kit\";\nimport { BOARD } from \"./theme\";\nimport { rasterSize } from \"./board\";\nimport type { BoardOp } from \"./history\";\nimport { Board, type BoardInstance, BoardUniforms, boardValues, InkUniforms, MAX_BOARDS, Stamp, StampUniforms } from \"./layout\";\nimport type { BoardShaders } from \"./shaders\";\nimport { STAMP_FLOATS, type Tool } from \"./stroke\";\n\n/** Premultiplied \"source over\" — the frames' blend. */\nconst BLEND_PREMUL: GPUBlendState = {\n color: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n alpha: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n};\n/** A stroke never darkens where it crosses itself: the footprints meet by MAX. */\nconst BLEND_MAX: GPUBlendState = { color: { srcFactor: \"one\", dstFactor: \"one\", operation: \"max\" }, alpha: { srcFactor: \"one\", dstFactor: \"one\", operation: \"max\" } };\n/** The eraser: ink *= 1 − coverage. */\nconst BLEND_ERASE: GPUBlendState = { color: { srcFactor: \"zero\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" }, alpha: { srcFactor: \"zero\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" } };\n/** The wet fades: dst *= the blend constant. */\nconst BLEND_DRY: GPUBlendState = { color: { srcFactor: \"zero\", dstFactor: \"constant\", operation: \"add\" }, alpha: { srcFactor: \"zero\", dstFactor: \"constant\", operation: \"add\" } };\n\n/** Stamps one upload carries — a longer stroke replays in chunks. */\nexport const STAMP_CAP = 1 << 16;\n/** The far-LOD thumbnails' layer side, texels (a board's ink chain from its first level that fits: 1 texel a unit for the law's board). */\nexport const BOARD_THUMB = 512;\n/** What a BARE board's record reads its ink from (K6b): the empty layer, whole — a thumbnail's side, a texel a unit. */\nconst BARE = { size: [BOARD_THUMB, BOARD_THUMB] as readonly [number, number], density: 1 };\n/** The pool: the rasters one frame binds (the boards larger on screen than their thumbnail serves). */\nexport const BOARD_SLOTS = 8;\n/** Density changes (re-rasters) one step asks for — the rest wait a frame, their old raster standing. */\nexport const BOARD_RASTERS_A_STEP = 2;\n/**\n * THE ZOOM RUNG (K6a): the density a board's raster is made at for `zd` device px a world unit (zoom × dpr × the hold's scale) —\n * two texels a device px as the law's 4 gave at zoom 1 on a 2× screen, a power of two, from 1 (the thumbnail's own) to `max`.\n */\nexport function boardRung(zd: number, max: number = BOARD.ink.density): number {\n let d = 1;\n while (d < max && d < 2 * zd) d *= 2;\n return Math.min(d, max);\n}\n/** How long ink keeps some of its wet after its stroke lands, in `wetSeconds` (the research's six time constants: e⁻⁶ of the wet is left). */\nconst WET_HOLD = 6;\n\n/** The board's materials the host hands in (lab/theme.ts `BOARD_LOOK`): a marker's barrel, the eraser's felt and back. */\nexport interface BoardLook { readonly barrel: RGB; readonly felt: RGB; readonly wood: RGB }\n\ninterface Raster {\n readonly id: number;\n readonly size: readonly [number, number];\n readonly density: number;\n readonly levels: number;\n readonly ink: GPUTexture;\n readonly stroke: GPUTexture;\n readonly wet: GPUTexture;\n readonly level0: GPUTextureView;\n readonly strokeView: GPUTextureView;\n readonly wetView: GPUTextureView;\n readonly mipDst: readonly GPUTextureView[];\n readonly mipGroups: readonly GPUBindGroup[];\n readonly inkGroup: GPUBindGroup;\n /** The stroke being laid: its tool and the stamps not yet sent. */\n tool: Tool | null;\n pending: Float32Array[];\n /** The wet layer holds something, and for how many seconds more it fades. */\n wetting: boolean;\n wetLeft: number;\n dryBy: number;\n clearWet: boolean;\n}\n\ninterface BoardShared {\n readonly device: GPUDevice;\n readonly layout0: GPUBindGroupLayout;\n /** Group 1, the same for every board: the thumbnail array, BOARD_SLOTS rasters' ink, the live board's stroke and wet. */\n readonly layout1: GPUBindGroupLayout;\n group1: GPUBindGroup;\n readonly thumbs: LayerArray;\n /** Each board's thumbnail: its layer, the level of its source's chain the layer starts at, that source's size and density. */\n readonly thumbOf: Map<number, BoardThumb>;\n /** The pool: the board each slot binds (null: free), and the live board (its stroke and wet bound). */\n readonly pool: (number | null)[];\n live: number | null;\n /** K7b: a frame drew boards since the last step — the step frees the slots none of them asked for (a board gone FAR asks nothing). */\n drew: boolean;\n /** The boards on screen since the last step and the density each asked (the most). */\n readonly asked: Map<number, number>;\n /** K6b: the thumbnails' layer kept EMPTY — a board with no ink yet (its first replay the queue's) draws its melamine from it; taken on first need. */\n bare: number | null;\n /** K9 R1: the drawn frames counted at the step (one per frame that drew boards — every slot's prepare of a frame shares it); a thumbnail's `drawnAt` is stamped from it, so the array full can tell a board drawn lately from one long off screen. */\n frame: number;\n readonly blank: GPUTexture;\n readonly blankR: GPUTexture;\n readonly blankArray: GPUTexture;\n readonly pipeline: GPURenderPipeline;\n readonly stampPipeline: GPURenderPipeline;\n readonly stampU: GPUBuffer;\n readonly stampBuf: GPUBuffer;\n readonly stampGroup: GPUBindGroup;\n readonly inkLayout: GPUBindGroupLayout;\n readonly inkU: GPUBuffer;\n readonly inkDraw: GPURenderPipeline;\n readonly inkErase: GPURenderPipeline;\n readonly inkWet: GPURenderPipeline;\n readonly inkDry: GPURenderPipeline;\n readonly mipLayout: GPUBindGroupLayout;\n readonly mipPipeline: GPURenderPipeline;\n readonly goboSampler: GPUSampler;\n readonly noiseSampler: GPUSampler;\n readonly inkSampler: GPUSampler;\n readonly linSampler: GPUSampler;\n readonly rasters: Map<number, Raster>;\n slots: number;\n}\n\n/** A board's far-LOD thumbnail: its layer, the level of its source's ink chain the layer starts at, that source's texels and density. */\ninterface BoardThumb { readonly layer: number; base: number; size: readonly [number, number]; density: number; tier: number; /** The drawn frame (`BoardShared.frame`) its board was last drawn in; −1 before any. */ drawnAt: number }\n\n/** Group 1 made again: the array (or its stand-in), each pool slot's ink (a blank where free), the live board's stroke and wet. */\nfunction bindPool(s: BoardShared): void {\n const ink = s.pool.map((id) => (id === null ? undefined : s.rasters.get(id)));\n const live = s.live === null ? undefined : s.rasters.get(s.live);\n s.group1 = bindGroup(s.device, s.layout1, [\n s.thumbs.view(s.blankArray),\n ...ink.map((r) => (r === undefined ? s.blank.createView() : r.ink.createView())),\n live === undefined ? s.blankR.createView() : live.strokeView,\n live === undefined ? s.blankR.createView() : live.wetView,\n ], \"board/pool\");\n}\n\nexport class BoardPass {\n readonly name = \"board/whiteboards\";\n private readonly knobs = BoardUniforms.alloc(1);\n /** The boards' PERSISTENT records (engine/records.ts, design-015 §4.3; D6): a slot per drawn board, written when its record or its raster's facts changed. */\n private readonly store: RecordStore<BoardInstance>;\n /** The records the last prepare turned away at the pass's cap — not drawn; the ground reports them (`GroundStats.dropped`, D7). */\n dropped = 0;\n private readonly stampU = StampUniforms.alloc(1);\n private readonly inkU = InkUniforms.alloc(1);\n private readonly knobBuf: GPUBuffer;\n /** What the GPU holds of the knobs: they are written only when they change (K4a — a standing value costs a frame nothing). */\n private readonly knobsSent = sentBytes(BoardUniforms.size);\n private group!: GPUBindGroup;\n private boundAssets = -1;\n private boundStore = -1;\n /** Each drawn board's index in the list `prepare` was handed (a board with no ink to show is skipped) — what `drawRange` counts in. */\n private drawnFrom: number[] = [];\n /** The materials a host projects (lab/theme.ts); black until it says. */\n look: BoardLook = { barrel: [0, 0, 0], felt: [0, 0, 0], wood: [0, 0, 0] };\n /** The day's chain on the board: false = a lit melamine shows its configured byte; true = the mat's double gamma. */\n chain = false;\n private readonly device: GPUDevice;\n private readonly shared: BoardShared;\n private readonly mat: MatPass;\n\n private constructor(device: GPUDevice, shared: BoardShared, mat: MatPass) {\n this.device = device; this.shared = shared; this.mat = mat;\n shared.slots += 1;\n this.knobBuf = uniformBuffer(device, BoardUniforms.size, \"board/knobs\");\n // the pack reads the board's raster afresh (its size, density and wet are the `aux` the change test folds in)\n this.store = createRecordStore<BoardInstance, keyof typeof Board.slots>({\n device, def: Board, capacity: MAX_BOARDS, max: MAX_BOARDS * 64, label: \"board/boards\",\n // (with where its ink is — the pool slot, the live slot, the thumbnail's layer and base: the `tier`, K6a)\n pack: (b, _aux, into, slot) => {\n const r = shared.rasters.get(b.id);\n const src = inkOf(shared, b.id);\n if (src) into.set(boardValues(b, { size: src.size, density: src.density, wet: r?.wetting === true && shared.live === b.id }, tierOf(shared, b.id)), slot);\n return 0;\n },\n });\n this.rebind();\n }\n\n /** The root's pass, on the root's mat. */\n static async create(device: GPUDevice, format: GPUTextureFormat, src: BoardShaders, mat: MatPass): Promise<BoardPass> {\n const layout0 = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"fragment\"], buffer: \"uniform\" },\n { binding: 2, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n { binding: 3, stages: [\"fragment\"], texture: \"float\" },\n { binding: 4, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 5, stages: [\"fragment\"], texture: \"float\" },\n { binding: 6, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 7, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 8, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 9, stages: [\"vertex\"], buffer: \"read-only-storage\" }, // the draw list: paint index → record slot (D6)\n ], \"board/slot\");\n const layout1 = bindLayout(device, [\n { binding: 0, stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" }, // the far-LOD thumbnails\n ...Array.from({ length: BOARD_SLOTS }, (_, i) => ({ binding: 1 + i, stages: [\"fragment\"] as const, texture: \"float\" as const })), // the pool's ink\n { binding: 1 + BOARD_SLOTS, stages: [\"fragment\"], texture: \"float\" }, // the live board's stroke\n { binding: 2 + BOARD_SLOTS, stages: [\"fragment\"], texture: \"float\" }, // …and its wet\n ], \"board/pool\");\n const stampLayout = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n ], \"board/stamp\");\n const inkLayout = bindLayout(device, [\n { binding: 0, stages: [\"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"fragment\"], texture: \"unfilterable-float\" },\n ], \"board/ink\");\n const mipLayout = bindLayout(device, [\n { binding: 0, stages: [\"fragment\"], texture: \"float\" },\n { binding: 1, stages: [\"fragment\"], sampler: \"filtering\" },\n ], \"board/mip\");\n\n const [boardModule, stampModule, inkModule, mipModule] = await Promise.all([\n compile(device, compose(src.board)),\n compile(device, compose(src.stamp)),\n compile(device, compose(src.ink)),\n compile(device, compose(src.mip)),\n ]);\n const inkPL = device.createPipelineLayout({ bindGroupLayouts: [inkLayout] });\n const [pipeline, stampPipeline, inkDraw, inkErase, inkWet, inkDry, mipPipeline] = await Promise.all([\n renderPipeline(device, { label: \"board/desk\", layout: device.createPipelineLayout({ bindGroupLayouts: [layout0, layout1] }), module: boardModule, format, blend: BLEND_PREMUL }),\n renderPipeline(device, { label: \"board/stamp\", layout: device.createPipelineLayout({ bindGroupLayouts: [stampLayout] }), module: stampModule, format: \"r8unorm\", blend: BLEND_MAX, topology: \"triangle-strip\" }),\n renderPipeline(device, { label: \"board/ink draw\", layout: inkPL, module: inkModule, fragment: \"fs_draw\", format: \"rgba8unorm\", blend: BLEND_PREMUL }),\n renderPipeline(device, { label: \"board/ink erase\", layout: inkPL, module: inkModule, fragment: \"fs_erase\", format: \"rgba8unorm\", blend: BLEND_ERASE }),\n renderPipeline(device, { label: \"board/ink wet\", layout: inkPL, module: inkModule, fragment: \"fs_wet\", format: \"r8unorm\", blend: BLEND_MAX }),\n renderPipeline(device, { label: \"board/ink dry\", layout: inkPL, module: inkModule, fragment: \"fs_dry\", format: \"r8unorm\", blend: BLEND_DRY }),\n renderPipeline(device, { label: \"board/mip\", layout: device.createPipelineLayout({ bindGroupLayouts: [mipLayout] }), module: mipModule, format: \"rgba8unorm\" }),\n ]);\n const stampU = uniformBuffer(device, StampUniforms.size, \"board/stamp uniforms\");\n const stampBuf = storageBuffer(device, Stamp.size * STAMP_CAP, \"board/stamps\");\n const linear = { magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" } as const;\n const shared: BoardShared = {\n device, layout0, layout1, pipeline,\n stampPipeline, stampU, stampBuf, stampGroup: bindGroup(device, stampLayout, [stampU, stampBuf], \"board/stamp\"),\n inkLayout, inkU: uniformBuffer(device, InkUniforms.size, \"board/ink uniforms\"), inkDraw, inkErase, inkWet, inkDry,\n mipLayout, mipPipeline,\n goboSampler: device.createSampler({ label: \"board/gobo\", ...linear }),\n noiseSampler: device.createSampler({ label: \"board/noise\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\" }),\n inkSampler: device.createSampler({ label: \"board/ink\", ...linear, mipmapFilter: \"linear\" }),\n linSampler: device.createSampler({ label: \"board/linear\", ...linear }),\n rasters: new Map(), slots: 0,\n group1: undefined as unknown as GPUBindGroup,\n thumbs: new LayerArray(device, { label: \"board/thumbnails\", format: \"rgba8unorm\", side: BOARD_THUMB }),\n thumbOf: new Map(), pool: Array.from({ length: BOARD_SLOTS }, () => null), live: null, asked: new Map(), drew: false, bare: null, frame: 0,\n blank: device.createTexture({ label: \"board/pool blank\", size: [1, 1], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING }),\n blankR: device.createTexture({ label: \"board/pool blank r8\", size: [1, 1], format: \"r8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING }),\n blankArray: device.createTexture({ label: \"board/thumbnails (none yet)\", size: [1, 1, 1], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING }),\n };\n bindPool(shared);\n return new BoardPass(device, shared, mat);\n }\n\n /** A second slot on the same pipelines and rasters, reading ITS mat's silhouette — a portal's inside, a flight's departed frame. */\n spawn(mat: MatPass): BoardPass {\n const b = new BoardPass(this.device, this.shared, mat);\n b.copy(this);\n return b;\n }\n\n /** Copy the root's tuning — what every slot takes each frame. */\n copy(from: BoardPass): void { this.look = from.look; this.chain = from.chain; }\n\n /** K7b: instance `index` of the last prepare drawn by the flat-card pipeline — its slot in the store — or −1: this pass draws it (or no one). */\n cardSlot(index: number): number { return index < this.cardsN ? (this.cards[index] as number) : -1; }\n private cards = new Int32Array(64);\n private cardsN = 0;\n\n /** K7b: this slot's resources for the board's card material (shaders.ts `boardCard`), in its bindings' order — made again when the store or the thumbnails grew. */\n cardResources(): { readonly version: number; readonly resources: readonly (GPUBuffer | GPUTextureView | GPUSampler)[] } {\n const s = this.shared;\n if (this.card === null || this.cardOver[0] !== this.store.version || this.cardOver[1] !== s.thumbs.version) {\n this.cardOver = [this.store.version, s.thumbs.version];\n this.card = { version: (this.card?.version ?? 0) + 1, resources: [this.knobBuf, this.store.records, s.goboSampler, s.noiseSampler, s.inkSampler, s.thumbs.view(s.blankArray)] };\n }\n return this.card;\n }\n private card: { readonly version: number; readonly resources: readonly (GPUBuffer | GPUTextureView | GPUSampler)[] } | null = null;\n private cardOver: readonly number[] = [];\n\n private rebind(): void {\n if (this.boundAssets === this.mat.assetVersion && this.boundStore === this.store.version) return;\n const s = this.shared;\n this.group = bindGroup(this.device, s.layout0, [this.mat.view, this.knobBuf, this.store.records, this.mat.silhouette, s.goboSampler, this.mat.noiseTexture.createView(), s.noiseSampler, s.inkSampler, s.linSampler, this.store.order], \"board/slot\");\n this.boundAssets = this.mat.assetVersion;\n this.boundStore = this.store.version;\n }\n\n // ---------------------------------------------------------------- the rasters\n\n /**\n * The raster board `id` draws with: a melamine `surface` world units across at `density`\n * texels a unit. Made on first ask and whenever the size or density changes — `true` then:\n * it is blank, and the host replays the board's history into it.\n */\n ensure(id: number, surface: readonly [number, number], density: number = BOARD.ink.density): boolean {\n const size = rasterSize(surface, density);\n const had = this.shared.rasters.get(id);\n if (had && had.size[0] === size[0] && had.size[1] === size[1] && had.density === density) return false;\n if (had) this.release(id);\n const d = this.device;\n const s = this.shared;\n const levels = Math.floor(Math.log2(Math.max(size[0], size[1]))) + 1;\n const RW = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING;\n const ink = d.createTexture({ label: `board/ink ${id}`, size: [size[0], size[1]], format: \"rgba8unorm\", mipLevelCount: levels, usage: RW | GPUTextureUsage.COPY_SRC });\n const stroke = d.createTexture({ label: `board/stroke ${id}`, size: [size[0], size[1]], format: \"r8unorm\", usage: RW });\n const wet = d.createTexture({ label: `board/wet ${id}`, size: [size[0], size[1]], format: \"r8unorm\", usage: RW });\n const level = (i: number) => ink.createView({ baseMipLevel: i, mipLevelCount: 1 });\n const mipDst: GPUTextureView[] = [];\n const mipGroups: GPUBindGroup[] = [];\n for (let i = 1; i < levels; i++) { mipDst.push(level(i)); mipGroups.push(bindGroup(d, s.mipLayout, [level(i - 1), s.linSampler], `board/mip ${id}.${i}`)); }\n const strokeView = stroke.createView();\n const wetView = wet.createView();\n const r: Raster = {\n id, size, density, levels, ink, stroke, wet, level0: level(0), strokeView, wetView, mipDst, mipGroups,\n inkGroup: bindGroup(d, s.inkLayout, [s.inkU, strokeView], `board/ink ${id}`),\n tool: null, pending: [], wetting: false, wetLeft: 0, dryBy: 1, clearWet: false,\n };\n s.rasters.set(id, r);\n const enc = d.createCommandEncoder({ label: \"board/new raster\" });\n this.clear(enc, r.level0); this.clear(enc, strokeView); this.clear(enc, wetView);\n d.queue.submit([enc.finish()]);\n if (s.pool.includes(id) || s.live === id) bindPool(s); // a bound board's new raster: the pool binds it\n return true;\n }\n\n /**\n * Would `ensure` make board `id`'s raster — none held (never made, or evicted), or another size or density (K6b: the frame raster\n * queue's to make, in its turn)?\n */\n makes(id: number, surface: readonly [number, number], density: number = BOARD.ink.density): boolean {\n const size = rasterSize(surface, density);\n const had = this.shared.rasters.get(id);\n return !(had && had.size[0] === size[0] && had.size[1] === size[1] && had.density === density);\n }\n\n /** The thumbnails' EMPTY layer (K6b): taken and filled with nothing on first need; null when the device holds no more layers. */\n private bareLayer(): number | null {\n const s = this.shared;\n if (s.bare !== null) return s.bare;\n const was = s.thumbs.version;\n const layer = this.takeLayer();\n if (layer === null) return null;\n s.thumbs.fill(s.blank, 1, layer, 0); // a layer given back holds a board's old thumbnail: filled from the 1 × 1 transparent\n s.bare = layer;\n if (s.thumbs.version !== was) bindPool(s); // the array grew\n return layer;\n }\n\n /**\n * A layer of the thumbnails' array (K9 R1) — the array's own while it has one; at the device's cap, RECLAIMED from the board\n * that can best spare it: one whose raster the budget evicted (its thumbnail was its only ink on the device — replayed when it is\n * next drawn, as after any eviction) and that was drawn neither in this frame nor the last, the least recently drawn of those;\n * failing that, one of a board that HOLDS its raster (its thumbnail is cut again from it at its next commit or replay) drawn as\n * long ago. Null when every thumbnail is a board's drawn lately — the caller draws without a layer, honestly.\n */\n private takeLayer(): number | null {\n const s = this.shared;\n const own = s.thumbs.take();\n if (own !== null) return own;\n let victim: number | null = null;\n let oldest = Number.POSITIVE_INFINITY;\n let spared = false; // a victim with no raster is preferred over one holding its raster\n for (const [id, t] of s.thumbOf) {\n if (t.drawnAt >= s.frame - 1 || s.pool.includes(id) || s.live === id) continue;\n const gone = !s.rasters.has(id);\n if (gone && !spared) { spared = true; oldest = t.drawnAt; victim = id; continue; }\n if (gone === spared && t.drawnAt < oldest) { oldest = t.drawnAt; victim = id; }\n }\n if (victim === null) return null;\n const t = s.thumbOf.get(victim) as BoardThumb;\n s.thumbOf.delete(victim);\n s.thumbs.give(t.layer);\n return s.thumbs.take();\n }\n\n /** Forget board `id` — its raster, its thumbnail's layer, its slot (it left the desk; a scene's board). */\n release(id: number): void {\n this.evict(id);\n const s = this.shared;\n const t = s.thumbOf.get(id);\n if (t !== undefined) {\n const was = s.thumbs.version;\n s.thumbs.give(t.layer);\n s.thumbOf.delete(id);\n if (s.bare !== null && s.thumbs.texture === null) s.bare = null; // the array let go whole (K9 R2): the empty layer is taken again on need\n if (s.thumbs.version !== was) bindPool(s); // the array shrank (K9 R2)\n }\n }\n\n /**\n * Let board `id`'s RASTER go and keep its thumbnail (the budget's eviction — the raster is a cache of its strokes, replayed\n * when it is next wanted): destroyed, its slot freed.\n */\n evict(id: number): void {\n const s = this.shared;\n const r = s.rasters.get(id);\n if (!r) return;\n r.ink.destroy(); r.stroke.destroy(); r.wet.destroy();\n s.rasters.delete(id);\n const slot = s.pool.indexOf(id);\n if (slot >= 0) s.pool[slot] = null;\n const live = s.live === id;\n if (live) s.live = null;\n const t = s.thumbOf.get(id);\n if (t !== undefined) t.tier += 1;\n if (slot >= 0 || live) bindPool(s);\n }\n\n /** Board `id`'s far-LOD thumbnail cut again from its raster's chain (the ink changed): its layer taken on the first cut. */\n private cutThumb(r: Raster): void {\n const s = this.shared;\n let t = s.thumbOf.get(r.id);\n if (t === undefined) {\n const was = s.thumbs.version;\n const layer = this.takeLayer();\n if (layer === null) return; // the device holds no more layers and none can be spared: the board draws while its raster is bound, bare otherwise (K9 R1)\n t = { layer, base: 0, size: r.size, density: r.density, tier: 0, drawnAt: -1 };\n s.thumbOf.set(r.id, t);\n if (s.thumbs.version !== was) bindPool(s); // the array grew\n }\n t.base = tailBase(r.size[0], r.size[1], BOARD_THUMB);\n t.size = r.size;\n t.density = r.density;\n t.tier += 1;\n s.thumbs.fill(r.ink, r.levels, t.layer, t.base);\n }\n\n /** Is board `id`'s raster bound this frame (a pool slot, or the live one)? The budget keeps what is. */\n bound(id: number): boolean { return this.shared.pool.includes(id) || this.shared.live === id; }\n\n /** The thumbnails' array: what it weighs on the device, its whole capacity (the GPU ledger's row). */\n get thumbnailBytes(): number { return this.shared.thumbs.bytes; }\n /** What the thumbnails' layers IN USE weigh — the budget's resident `board`/`thumbnails` charge (K9 R2). */\n get thumbnailUsedBytes(): number { return this.shared.thumbs.usedBytes; }\n /** The thumbnails' layers in use, and the array's capacity (K9 R5 — the kind's `stats`). */\n get thumbnailLayers(): number { return this.shared.thumbs.used; }\n get thumbnailCapacity(): number { return this.shared.thumbs.capacity; }\n\n /** Has board `id` its far-LOD thumbnail (a layer, cut)? */\n thumbed(id: number): boolean { return this.shared.thumbOf.has(id); }\n\n /** Board `id`'s raster density (texels a unit), or null without one. */\n densityOf(id: number): number | null { return this.shared.rasters.get(id)?.density ?? null; }\n\n /**\n * THE FRAME BOUNDARY (the kind's tick, before the next build): the slots of boards no frame asked for since the last step are\n * freed (their rasters stay, a cache), the live slot of a board no longer laid on or wet; and the boards that asked for more\n * than their raster holds — largest first, BOARD_RASTERS_A_STEP a step — are returned with the density to remake them at\n * (the kind replays their strokes into it). Nothing is freed when nothing was drawn since the last step — a frame that drew only\n * FAR boards (K7b: they ask nothing) frees the slots they held.\n */\n step(): { readonly id: number; readonly density: number }[] {\n const s = this.shared;\n if (s.asked.size === 0 && !s.drew) return [];\n if (s.drew) s.frame += 1; // K9 R1: a drawn frame passed — what the thumbnails' `drawnAt` is stamped from\n s.drew = false;\n let moved = false;\n if (s.live !== null && !liveOf(s.rasters.get(s.live))) { s.live = null; moved = true; }\n for (let i = 0; i < s.pool.length; i++) {\n const id = s.pool[i];\n if (id !== null && id !== undefined && !s.asked.has(id) && s.live !== id) { s.pool[i] = null; moved = true; const t = s.thumbOf.get(id); if (t) t.tier += 1; }\n }\n const raise = [...s.asked].filter(([id, want]) => (s.rasters.get(id)?.density ?? 0) < want).sort((a, b) => b[1] - a[1]).slice(0, BOARD_RASTERS_A_STEP).map(([id, density]) => ({ id, density }));\n s.asked.clear();\n if (moved) bindPool(s);\n return raise;\n }\n\n /** The last frame's asks still unanswered (K7a): the next tick owes them a `step` — a slot freed, a board raised to its rung. */\n // (K7b: a board gone FAR asks nothing, so it owes no step: the slot it held is freed by the step the next tick takes anyway — a\n // wake of its own was a frame the loop did not need: rig:tray's slide drew two more than its motion)\n get stepOwed(): boolean { return this.shared.asked.size > 0; }\n\n /** The raster's size in texels, or null. */\n sizeOf(id: number): readonly [number, number] | null { return this.shared.rasters.get(id)?.size ?? null; }\n\n /** Is any board's ink still drying (the host keeps its clock awake)? */\n get wetting(): boolean { for (const r of this.shared.rasters.values()) if (r.wetting || r.pending.length) return true; return false; }\n\n private clear(enc: GPUCommandEncoder, view: GPUTextureView): void {\n enc.beginRenderPass({ label: \"board/clear\", colorAttachments: [{ view, clearValue: { r: 0, g: 0, b: 0, a: 0 }, loadOp: \"clear\", storeOp: \"store\" }] }).end();\n }\n\n private writeStampTool(r: Raster, tool: Tool): void {\n const t = tool.tip;\n this.stampU.set({\n tex: [r.size[0], r.size[1], r.density, 0],\n tip: [t.half[0], t.half[1], t.angle, t.radius],\n felt: [t.softness, tool.mode === \"erase\" ? 1 : 0, tool.opacity, tool.streak],\n lanes: [BOARD.felt.lanes, BOARD.felt.along[0], BOARD.felt.along[1], 0],\n });\n this.device.queue.writeBuffer(this.shared.stampU, 0, this.stampU.view());\n }\n\n /** Stamp `count` stamps (from `data`) into the raster's stroke layer. The caller submits `enc` before the next upload. */\n private stampInto(enc: GPUCommandEncoder, r: Raster, data: Float32Array, count: number): void {\n if (count === 0) return;\n this.device.queue.writeBuffer(this.shared.stampBuf, 0, data.buffer, data.byteOffset, count * STAMP_FLOATS * 4);\n const pass = enc.beginRenderPass({ label: \"board/stamp\", colorAttachments: [{ view: r.strokeView, loadOp: \"load\", storeOp: \"store\" }] });\n pass.setPipeline(this.shared.stampPipeline);\n pass.setBindGroup(0, this.shared.stampGroup);\n pass.draw(4, count);\n pass.end();\n }\n\n /** Every stamp of `data`, in chunks: one upload and one submit each. */\n private stampAll(r: Raster, tool: Tool, data: Float32Array): void {\n this.writeStampTool(r, tool);\n const n = data.length / STAMP_FLOATS;\n for (let i = 0; i < n; i += STAMP_CAP) {\n const count = Math.min(STAMP_CAP, n - i);\n const enc = this.device.createCommandEncoder({ label: \"board/stamps\" });\n this.stampInto(enc, r, data.subarray(i * STAMP_FLOATS), count);\n this.device.queue.submit([enc.finish()]);\n }\n }\n\n /** Lay the stroke layer into the ink (and, live, mark it wet), then clear the stroke layer. */\n private composite(enc: GPUCommandEncoder, r: Raster, tool: Tool, wet: boolean): void {\n this.inkU.set({ color: [tool.color[0], tool.color[1], tool.color[2], 0] });\n this.device.queue.writeBuffer(this.shared.inkU, 0, this.inkU.view());\n const full = (view: GPUTextureView, pipeline: GPURenderPipeline) => {\n const pass = enc.beginRenderPass({ label: \"board/ink\", colorAttachments: [{ view, loadOp: \"load\", storeOp: \"store\" }] });\n pass.setPipeline(pipeline); pass.setBindGroup(0, r.inkGroup); pass.draw(3); pass.end();\n };\n full(r.level0, tool.mode === \"erase\" ? this.shared.inkErase : this.shared.inkDraw);\n if (wet && tool.mode === \"ink\") full(r.wetView, this.shared.inkWet);\n this.clear(enc, r.strokeView);\n }\n\n /** The ink's mip chain, from level 0 down. */\n private mips(enc: GPUCommandEncoder, r: Raster): void {\n for (let i = 0; i < r.mipDst.length; i++) {\n const pass = enc.beginRenderPass({ label: \"board/mip\", colorAttachments: [{ view: r.mipDst[i] as GPUTextureView, loadOp: \"clear\", clearValue: { r: 0, g: 0, b: 0, a: 0 }, storeOp: \"store\" }] });\n pass.setPipeline(this.shared.mipPipeline); pass.setBindGroup(0, r.mipGroups[i] as GPUBindGroup); pass.draw(3); pass.end();\n }\n }\n\n // ---------------------------------------------------------------- a stroke, live\n\n /** Queue stamps for the stroke being laid on board `id` (they reach its stroke layer at the next `prepare`). */\n lay(id: number, tool: Tool, stamps: Float32Array): void {\n const r = this.shared.rasters.get(id);\n if (!r || stamps.length === 0) return;\n r.tool = tool;\n r.pending.push(stamps.slice());\n }\n\n /** Send the queued stamps now: one upload, one submit, per board with any. */\n private flush(): void {\n for (const r of this.shared.rasters.values()) {\n if (!r.pending.length || !r.tool) continue;\n const all = r.pending.length === 1 ? (r.pending[0] as Float32Array) : concat(r.pending);\n r.pending = [];\n this.stampAll(r, r.tool, all);\n }\n }\n\n /** The lift: the stroke's last stamps, laid into the ink, marked wet; the mips follow. */\n commit(id: number, tool: Tool): void {\n const r = this.shared.rasters.get(id);\n if (!r) return;\n r.tool = tool;\n this.flush();\n const enc = this.device.createCommandEncoder({ label: \"board/commit\" });\n this.composite(enc, r, tool, true);\n this.mips(enc, r);\n this.device.queue.submit([enc.finish()]);\n this.cutThumb(r);\n r.tool = null;\n if (tool.mode === \"ink\") { r.wetting = true; r.wetLeft = BOARD.ink.wetSeconds * WET_HOLD; }\n }\n\n /** A stroke abandoned: its stamps dropped, its layer cleared. */\n cancel(id: number): void {\n const r = this.shared.rasters.get(id);\n if (!r) return;\n r.pending = []; r.tool = null;\n const enc = this.device.createCommandEncoder({ label: \"board/cancel\" });\n this.clear(enc, r.strokeView);\n this.device.queue.submit([enc.finish()]);\n }\n\n /** The board's ink rebuilt from its history (history.ts `replay`): a cleared raster, every op in order, dry. */\n replay(id: number, ops: readonly BoardOp[]): void {\n const r = this.shared.rasters.get(id);\n if (!r) return;\n r.pending = []; r.tool = null; r.wetting = false; r.wetLeft = 0;\n let enc = this.device.createCommandEncoder({ label: \"board/replay clear\" });\n this.clear(enc, r.level0); this.clear(enc, r.strokeView); this.clear(enc, r.wetView);\n this.device.queue.submit([enc.finish()]);\n for (const op of ops) {\n enc = this.device.createCommandEncoder({ label: \"board/replay\" });\n if (op.kind === \"wipe\") { this.clear(enc, r.level0); this.device.queue.submit([enc.finish()]); continue; }\n this.stampAll(r, op.tool, op.stamps);\n this.composite(enc, r, op.tool, false);\n this.device.queue.submit([enc.finish()]);\n }\n enc = this.device.createCommandEncoder({ label: \"board/replay mips\" });\n this.mips(enc, r);\n this.device.queue.submit([enc.finish()]);\n this.cutThumb(r);\n }\n\n /** Fresh ink dries: every wet raster's wet layer fades by `dt` seconds (sent at the next `prepare`). */\n dry(dt: number): void {\n if (dt <= 0) return;\n for (const r of this.shared.rasters.values()) {\n if (!r.wetting) continue;\n r.dryBy *= Math.exp(-dt / BOARD.ink.wetSeconds);\n r.wetLeft -= dt;\n if (r.wetLeft <= 0) { r.wetting = false; r.clearWet = true; }\n }\n }\n\n /** The ink's bytes, level 0 — rgba8 premultiplied linear, row 0 the melamine's top (a harness's witness). */\n async readInk(id: number): Promise<{ width: number; height: number; bytes: Uint8Array } | null> {\n const r = this.shared.rasters.get(id);\n if (!r) return null;\n const bytes = await readback(this.device, r.ink, 4);\n return { width: r.size[0], height: r.size[1], bytes };\n }\n\n // ---------------------------------------------------------------- the frame\n\n /**\n * Send what the host queued (stamps, the drying), then upload this frame's boards (in paint\n * order) and the mat's block for this slot's camera and light: the dapple, the lamp's shading\n * and the shadows. A board whose raster is missing is skipped. Returns the count that will draw.\n */\n prepare(view: View & { readonly dpr: number }, fadeIn: FadeIn, cfg: MatConfig, frame: MatFrame | undefined, instances: readonly BoardInstance[], present: Presentation | undefined, light: MatLight = DAY_LIGHT, theme?: GroundTheme, keys?: readonly number[], hand = false): number {\n this.flush();\n this.dryNow();\n const s = this.shared;\n // K9 R4 — THE HAND's prepare (the carried board alone, every frame of the carry): the desk copy behind it was prepared once\n // per stamp and its boards ask nothing on the frames between, so every board the pool binds is asked again here at its\n // raster's own density (no raise) — else the step would free their slots (a pop at the put-down; a raster behind the hand evictable)\n if (hand) for (const id of s.pool) if (id !== null && id !== undefined) s.asked.set(id, Math.max(s.asked.get(id) ?? 0, s.rasters.get(id)?.density ?? 0));\n const from: number[] = [];\n // the boards with ink to show (a raster, or its thumbnail), in paint order — the store's records (D6); their keys alongside,\n // and each one's facts as the aux (its raster's, and where its ink is bound: a tier move repacks it)\n const drawn: BoardInstance[] = [];\n const drawnKeys: number[] | undefined = keys === undefined ? undefined : [];\n const aux: number[] = [];\n const cap = MAX_BOARDS * 64;\n this.dropped = 0;\n const zd = view.zoom * view.dpr;\n const x0 = view.camX;\n const y0 = view.camY;\n const x1 = x0 + view.width / view.zoom;\n const y1 = y0 + view.height / view.zoom;\n let bind = false;\n for (const [i, b] of instances.entries()) {\n // a board recorded without the desk's local asked for no raster (id 0 — a tray specimen, K5a): it draws on the one clean raster,\n // made once at the lowest rung (blank ink reads the same at any density — ≈ 1 MB, never a full raster the budget cannot see),\n // bound in the pool like any board on screen\n if (b.id === 0 && !s.rasters.has(0)) this.ensure(0, [BOARD.spec.width, BOARD.spec.height], 1);\n const r = s.rasters.get(b.id);\n const t = s.thumbOf.get(b.id);\n const q = b.quad;\n const seen = q.x1 >= x0 && q.x0 <= x1 && q.y1 >= y0 && q.y0 <= y1;\n // no ink yet (K6b — its first replay the queue's): its melamine drawn BARE, from the empty layer, until its turn\n // (K9 R1: no layer even for that — the array at the device's cap with none to spare — is a board NOT drawn; on screen, said: `dropped`)\n if (!r && !t && this.bareLayer() === null) { if (seen) this.dropped += 1; continue; }\n if (drawn.length >= cap) { this.dropped += 1; continue; }\n // ON SCREEN it asks for the density its size wants (the step raises its raster to it); a frame only ADDS to the pool (the\n // step frees it between frames): a board on screen with a raster takes a free slot — one in the cull's margin draws its\n // thumbnail (unseen; a slot it took would be freed at the next step, every frame) — and the one laid on or drying the live slot\n // K7b — THE FAR LOD: a board at the ladder's FIRST rung whose thumbnail is made draws from it — the rung-1 raster's own\n // texels (its chain's tail from the first level that fits BOARD_THUMB², a texel a unit) — so it asks for no raster and takes\n // no pool slot: the flat card draws it, nothing is replayed at low zoom, an evicted raster stays evicted. Not the live board,\n // nor the tray's specimen (id 0: its one clean raster, K5a — bound and asked as it always was; far, it cost the slide frames)\n const rung = boardRung(zd * b.geometry.scale);\n const far = b.id !== 0 && rung === 1 && t !== undefined && s.live !== b.id && b.stroke === undefined;\n if (r) {\n if (seen && !far && !s.pool.includes(b.id)) { const free = s.pool.indexOf(null); if (free >= 0) { s.pool[free] = b.id; bind = true; } }\n if (s.live === null && (liveOf(r) || b.stroke !== undefined)) { s.live = b.id; bind = true; }\n }\n // D-K9-d.4 — a board on screen ASKS for a raster only when it can bind one: a pool slot held, or one free (a raster made in the\n // queue's turn takes it next frame); with no thumbnail yet (its first replay cuts it — K6b's bare state must end); in hand (the\n // live board, a stroke); the tray's specimen (K5a). A THUMBED board past the pool draws its thumbnail through the card, a little\n // soft, as a print past the detail slots does — before K9 it asked every frame, the queue made its raster, the budget's trim took\n // it at once (never bound, never kept) and it asked again: a thrash as fast as the host let the queue run (rig:scale at N 3,000,\n // zoom 0.5: 13 boards on screen, 8 slots — 8,469 evictions at load 7 on 7a7602f, 17,149 on this tree; 43–808 at load 100–300,\n // where the queue managed a replay or two a turn — and the gate's memory row could not fail until K9 R5)\n const asks = seen && !far && (s.pool.includes(b.id) || s.pool.includes(null) || t === undefined || s.live === b.id || b.stroke !== undefined || b.id === 0);\n if (asks) s.asked.set(b.id, Math.max(s.asked.get(b.id) ?? 0, rung));\n // K9 R1: a raster with no layer and no slot (the array at the device's cap, the pool full) — nothing to draw its INK from this\n // frame: the board is drawn BARE (its melamine from the empty layer — honestly blank, never another board's layer) and counted\n // in `dropped` when on screen, so the ground's stats say what the desk does not show; without even the empty layer it is not drawn\n if (t === undefined && r !== undefined && !s.pool.includes(b.id)) { if (seen) this.dropped += 1; if (this.bareLayer() === null) continue; }\n if (t !== undefined) t.drawnAt = s.frame;\n drawn.push(b);\n drawnKeys?.push(keys?.[i] as number);\n const facts = r === undefined ? 0 : (r.wetting ? 1 : 0) + 2 * r.density + 64 * r.size[0] + 64 * 8192 * r.size[1];\n const [, , slot, live] = tierOf(s, b.id);\n aux.push(facts + 5e9 * (2 + slot + 10 * live + 20 * ((t?.tier ?? 0) % 100000)));\n from.push(i);\n }\n if (bind) bindPool(s);\n if (drawn.length > 0) s.drew = true;\n this.store.prepare(drawn, drawnKeys, (i) => aux[i] as number);\n this.rebind(); // after: the store's buffers may have grown\n this.drawnFrom = from;\n // K7b: the boards the flat-card pipeline draws — every one drawn from its THUMBNAIL (no pool raster, not the live board: the card\n // binds neither), by its instance index; the rest are this pass's\n if (this.cards.length < instances.length) this.cards = new Int32Array(Math.max(instances.length, this.cards.length * 2));\n this.cards.fill(-1, 0, instances.length);\n this.cardsN = instances.length;\n for (let j = 0; j < drawn.length; j++) {\n const [, , slot, live] = tierOf(s, (drawn[j] as BoardInstance).id);\n if (slot < 0 && live < 0.5) this.cards[from[j] as number] = this.store.slotAt(j);\n }\n const sh = BOARD.shadow;\n const sf = BOARD.surface;\n const fr = BOARD.frame;\n const pen = BOARD.pen;\n const blk = BOARD.block;\n const look = this.look;\n const cast = MAT_COLORS.cast;\n const select = theme?.select ?? [0, 0, 0];\n this.knobs.set({\n light: [BOARD.light.ambient, BOARD.light.cap, this.chain ? 1 : 0, 0.22],\n shadow: [sh.penumbra.sigma0, sh.penumbra.sigmaPerHeight, sh.penumbra.alpha, sh.contact.alpha],\n shadow2: [sh.contact.sigma, sh.contact.reach, BOARD.ring, 0],\n castTint: [cast[0], cast[1], cast[2], 1],\n select: [select[0], select[1], select[2], 1],\n mel: [sf.tone, sf.grain, sf.ghost, BOARD.ink.film],\n sheen: [sf.sheen, sf.spread, sf.eye, BOARD.ink.wetDarken],\n lip: [sf.lip.alpha, sf.lip.sigma, fr.brushed, fr.roll],\n glint: [fr.glint, 0, 0, 0],\n barrel: [look.barrel[0], look.barrel[1], look.barrel[2], 1],\n felt: [look.felt[0], look.felt[1], look.felt[2], 1],\n wood: [look.wood[0], look.wood[1], look.wood[2], 1],\n pen: [pen.length, pen.radius, pen.cap, pen.rise],\n pen2: [pen.hover, pen.lean, 0, 0],\n block: [blk.half[0], blk.half[1], blk.felt, blk.wood],\n block2: [(BOARD.eraser.angle * Math.PI) / 180, 0, 0, 0],\n });\n writeChanged(this.device.queue, this.knobBuf, this.knobs, this.knobsSent);\n return from.length;\n }\n\n /** The store's counters (a rig's witness): records written, bytes, draw-list writes, slots in use. */\n get records() { return this.store.stats(); }\n\n /** The wet layers' fading, sent: one pass each at the accumulated factor, or a clear once dry. */\n private dryNow(): void {\n let enc: GPUCommandEncoder | null = null;\n for (const r of this.shared.rasters.values()) {\n if (r.clearWet) { enc ??= this.device.createCommandEncoder({ label: \"board/dry\" }); this.clear(enc, r.wetView); r.clearWet = false; r.dryBy = 1; continue; }\n if (!r.wetting || r.dryBy >= 1) continue;\n enc ??= this.device.createCommandEncoder({ label: \"board/dry\" });\n const pass = enc.beginRenderPass({ label: \"board/dry\", colorAttachments: [{ view: r.wetView, loadOp: \"load\", storeOp: \"store\" }] });\n pass.setPipeline(this.shared.inkDry); pass.setBindGroup(0, r.inkGroup);\n pass.setBlendConstant({ r: r.dryBy, g: r.dryBy, b: r.dryBy, a: r.dryBy });\n pass.draw(3); pass.end();\n r.dryBy = 1;\n }\n if (enc) this.device.queue.submit([enc.finish()]);\n }\n\n get drawn(): number { return this.drawnFrom.length; }\n\n /** Every board drawn this frame. */\n draw(pass: GPURenderPassEncoder): void { this.drawRange(pass, 0, Number.POSITIVE_INFINITY); }\n\n /**\n * The boards `prepare` was handed at [first, end) — indices into ITS list, as the ground's runs count a\n * kind's records (a board with no ink to show draws nothing) — as ONE instanced draw (K6a, K-L4): the\n * slot's group and the pool's bound once, each board an instance whose record says where its ink is.\n */\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void {\n let lo = -1;\n let hi = -1;\n for (let i = 0; i < this.drawnFrom.length; i++) {\n const at = this.drawnFrom[i] as number;\n if (at >= end) break; // ascending: nothing further is in range\n if (at < first) continue;\n if (lo < 0) lo = i;\n hi = i + 1;\n }\n if (lo < 0) return;\n pass.setPipeline(this.shared.pipeline);\n pass.setBindGroup(0, this.group);\n pass.setBindGroup(1, this.shared.group1);\n pass.draw(6, hi - lo, 0, lo);\n }\n\n /** This slot's buffers; the rasters and the stamp buffers go with the last slot standing. */\n dispose(): void {\n this.knobBuf.destroy(); this.store.dispose();\n const s = this.shared;\n s.slots -= 1;\n if (s.slots === 0) {\n for (const id of [...new Set([...s.rasters.keys(), ...s.thumbOf.keys()])]) this.release(id);\n s.stampBuf.destroy(); s.stampU.destroy(); s.inkU.destroy();\n s.thumbs.destroy(); s.blank.destroy(); s.blankR.destroy(); s.blankArray.destroy();\n }\n }\n}\n\n/** A raster in use by the hand: a stroke being laid, stamps waiting, or ink still wet — its stroke and wet layers are read. */\nconst liveOf = (r: Raster | undefined): boolean => r !== undefined && (r.wetting || r.tool !== null || r.pending.length > 0);\n\n/** Where board `id`'s ink is this frame: its thumbnail's layer, the level its source's chain starts the layer at, its pool slot (−1: the thumbnail), live (1: its stroke and wet are bound). */\nfunction tierOf(s: BoardShared, id: number): [number, number, number, number] {\n const t = s.thumbOf.get(id);\n const r = s.rasters.has(id);\n // a board with no ink yet reads the empty layer (K6b); one with a raster and no layer, as before, layer 0 behind its slot\n // (K9 R1: one with a raster and no layer reads the empty layer — bare — unless a slot binds its raster; never layer 0, another board's)\n return [t?.layer ?? s.bare ?? 0, t?.base ?? 0, r ? s.pool.indexOf(id) : -1, s.live === id ? 1 : 0];\n}\n\n/**\n * The source board `id`'s record reads its ink's size and density from this frame: its raster while a pool slot or the live slot\n * binds it, else its thumbnail (cut from that raster — the same texels), else the EMPTY layer (K6b — no ink yet; K9 R1 — a raster\n * with no layer and no slot, drawn bare); undefined before the empty layer exists.\n */\nfunction inkOf(s: BoardShared, id: number): { readonly size: readonly [number, number]; readonly density: number } | undefined {\n const r = s.rasters.get(id);\n if (r !== undefined && (s.pool.includes(id) || s.live === id)) return r;\n return s.thumbOf.get(id) ?? (s.bare !== null ? BARE : undefined);\n}\n\nfunction concat(parts: readonly Float32Array[]): Float32Array {\n let n = 0;\n for (const p of parts) n += p.length;\n const out = new Float32Array(n);\n let o = 0;\n for (const p of parts) { out.set(p, o); o += p.length; }\n return out;\n}\n","// THE MARKER — pure (BOARD.md §5; D3t-a): the one pen of a board, in whatever pose it is in. Lying capped where a hand put\n// it down; taken up into the hand as the board comes into it (it slides from where it lies to the pointer, rises in an arc,\n// turns to a right hand's angle, its cap sliding back along the barrel to post on the end); in the hand at the pointer —\n// hovering, its shadow stands off the nib; pressed, they meet; leaning with the hand's speed across its axis — and, put\n// down, flying back to cap itself and lie down again. The eraser, when it is the tool in hand, rubs at the pointer while\n// the marker lies down. The bench's `poseOf` and its springs (lab/board.ts), number for number, as FLUX: `stepPen` advances\n// the springs toward what the hand is doing, `penPose` draws the pose they reach. At rest (every spring 0) the pose is\n// `boardRest`'s — the capped marker where the oracle's still draws it — byte for byte.\n\nimport { spring, settled } from \"@ice/desk/kit\";\nimport type { RGB } from \"@ice/desk\";\nimport { BOARD } from \"./theme\";\nimport type { BoardGeometry, WorldBox } from \"./board\";\nimport type { BoardEraser, BoardPen } from \"./layout\";\nimport { type TipName, TIPS } from \"./stroke\";\n\n/** A right hand holds a marker with its barrel rising away to the upper right (lab/board.ts). */\nexport const HAND_ANGLE = Math.atan2(-0.8, 0.6);\nconst clamp01 = (v: number): number => Math.min(1, Math.max(0, v));\nconst smooth = (a: number, b: number, x: number): number => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };\n\n/**\n * A board's pen as flux: `take` (0 lying … 1 in the hand), `shown` (present at the hand — over the melamine), `rub` (the eraser at\n * the hand), `press` (0 hovering … 1 on the board), each a spring with its velocity; `lean` (radians across the barrel) and the\n * hand's smoothed velocity (CSS px/s) it follows.\n */\nexport interface PenState {\n take: number; takeV: number;\n shown: number; shownV: number;\n rub: number; rubV: number;\n press: number; pressV: number;\n lean: number;\n vx: number; vy: number;\n}\nexport const penAtRest = (): PenState => ({ take: 0, takeV: 0, shown: 0, shownV: 0, rub: 0, rubV: 0, press: 0, pressV: 0, lean: 0, vx: 0, vy: 0 });\n\n/** What the hand is doing this frame, as the board's pen reads it. */\nexport interface PenInput {\n /** The pen is in hand: the board held and open (past 42 % of the pickup) — false on the desk and flying home. */\n readonly held: boolean;\n /** The eraser is the tool in hand (the marker lies down). */\n readonly erasing: boolean;\n /** The hand is over the melamine or laying a stroke: the pen (or the eraser) shows at it. */\n readonly over: boolean;\n /** A stroke is being laid: the nib meets the board. */\n readonly pressing: boolean;\n}\n\n/** The springs' numbers (lab/board.ts `step`): take 2.4 Hz critically damped, shown and rub 7 Hz, press 9 Hz ζ .85; the lean's decay and follow. */\nexport const PEN_SPRINGS = { take: [2.4, 1], shown: [7, 1], rub: [7, 1], press: [9, 0.85], leanDecay: 6, leanFollow: 12 } as const;\n\n/**\n * Advance the pen's flux by `dt` seconds toward what the hand is doing (lab/board.ts `step`, the pen's rows); `snap` sits every\n * spring at its target (a still). Returns true while anything still moves.\n */\nexport function stepPen(s: PenState, input: PenInput, dt: number, snap = false): boolean {\n const S = PEN_SPRINGS;\n const takeT = input.held && !input.erasing ? 1 : 0;\n const hand = input.held && input.over;\n const shownT = hand && !input.erasing ? 1 : 0;\n const rubT = hand && input.erasing ? 1 : 0;\n const pressT = input.held && input.pressing ? 1 : 0;\n let live = false;\n const run = (x: number, v: number, t: number, [hz, damp]: readonly [number, number]): [number, number] => {\n if (snap || dt <= 0) return snap ? [t, 0] : [x, v];\n const [nx, nv] = spring(x, v, t, hz, damp, dt);\n if (settled(nx, nv, t)) return [t, 0];\n live = true;\n return [nx, nv];\n };\n [s.take, s.takeV] = run(s.take, s.takeV, takeT, S.take);\n [s.shown, s.shownV] = run(s.shown, s.shownV, shownT, S.shown);\n [s.rub, s.rubV] = run(s.rub, s.rubV, rubT, S.rub);\n [s.press, s.pressV] = run(s.press, s.pressV, pressT, S.press);\n // the lean: the hand's velocity across the marker's axis, damped as the hand slows (half as much while it only hovers)\n if (snap) { s.vx = 0; s.vy = 0; s.lean = 0; return false; }\n if (dt > 0) {\n s.vx *= Math.exp(-dt * S.leanDecay);\n s.vy *= Math.exp(-dt * S.leanDecay);\n const across = (-s.vx * 0.8 - s.vy * 0.6) / 1400;\n const lean = Math.max(-1, Math.min(1, across)) * BOARD.pen.lean * (input.pressing ? 1 : 0.5);\n s.lean += (lean - s.lean) * (1 - Math.exp(-dt * S.leanFollow));\n if (Math.abs(lean - s.lean) > 1e-4) live = true;\n else s.lean = lean;\n }\n return live;\n}\n\n/** The hand moved: its velocity, CSS px/s, folded into the pen's (the bench's per-event smoothing, a frame at a time). */\nexport function followHand(s: PenState, dx: number, dy: number, dt: number): void {\n if (dt <= 0) return;\n const d = Math.min(0.1, Math.max(0.004, dt));\n s.vx += (dx / d - s.vx) * 0.35;\n s.vy += (dy / d - s.vy) * 0.35;\n}\n\n/** Where the marker lies on a board of `w × h`: its centre from the board's (× the hold's scale) and its angle — BOARD.md §5's rest. */\nexport const penRest = (w: number, h: number): { readonly x: number; readonly y: number; readonly angle: number } => ({ x: w * 0.16, y: h * 0.5 - BOARD.spec.frame - BOARD.pen.radius - 13, angle: -0.07 });\n\n/** The hand's world point kept on the melamine (lab/board.ts `handOf`); none seen: the board's centre. */\nexport function handOnMelamine(G: BoardGeometry, at: readonly [number, number] | null): readonly [number, number] {\n if (at === null) return [G.centre[0], G.centre[1]];\n return [Math.min(Math.max(at[0], G.centre[0] - G.inner[0]), G.centre[0] + G.inner[0]), Math.min(Math.max(at[1], G.centre[1] - G.inner[1]), G.centre[1] + G.inner[1])];\n}\n\n/**\n * THE marker's pose this frame between where it lies and the hand (lab/board.ts `poseOf`, number for number): the nib slides from\n * its resting place to the hand and turns to the hand's angle (plus the lean); it rises in an arc, its barrel tilting up from the\n * nib as a held pen does; its cap slides back along the barrel and posts on the end; present in the hand only where the hand is\n * over the board. The eraser at the hand while it rubs. And the world box both may paint, shadows and all.\n */\nexport function penPose(G: BoardGeometry, w: number, h: number, tip: TipName, ink: RGB, s: PenState, at: readonly [number, number] | null): { readonly pen: BoardPen; readonly eraser: BoardEraser | undefined; readonly box: WorldBox } {\n const P = BOARD.pen;\n const R = P.radius;\n const L = P.length;\n const e = clamp01(s.take);\n const r0 = penRest(w, h);\n const ar = r0.angle;\n const mid = [G.centre[0] + r0.x * G.scale, G.centre[1] + r0.y * G.scale] as const;\n const rest = [mid[0] - Math.cos(ar) * L * 0.5, mid[1] - Math.sin(ar) * L * 0.5] as const;\n const hand = e > 0 ? handOnMelamine(G, at) : rest;\n let da = HAND_ANGLE + s.lean - ar;\n da = Math.atan2(Math.sin(da), Math.cos(da));\n const gap = (1 - clamp01(s.press)) * P.hover;\n const pen: BoardPen = {\n x: rest[0] + (hand[0] - rest[0]) * e, y: rest[1] + (hand[1] - rest[1]) * e, angle: ar + da * e,\n height: R + (gap - R) * e + 34 * Math.sin(Math.PI * e), rise: P.rise * e,\n cap: smooth(0.3, 0.85, e), nib: TIPS[tip].half[1],\n presence: 1 + (clamp01(s.shown) - 1) * smooth(0.85, 1, e),\n ink,\n };\n const slope = Math.hypot(G.slope[0], G.slope[1]);\n const r = L * 1.3 + 60 + slope * (pen.height + L * pen.rise + 12);\n let box: WorldBox = { x0: pen.x - r, y0: pen.y - r, x1: pen.x + r, y1: pen.y + r };\n let eraser: BoardEraser | undefined;\n if (s.rub > 0.001) {\n const [x, y] = handOnMelamine(G, at);\n eraser = { x, y, height: gap, presence: clamp01(s.rub) };\n const re = 60 + slope * (gap + BOARD.block.felt + BOARD.block.wood + 8);\n box = { x0: Math.min(box.x0, x - re), y0: Math.min(box.y0, y - re), x1: Math.max(box.x1, x + re), y1: Math.max(box.y1, y + re) };\n }\n return { pen, eraser, box };\n}\n","// Assemble the board pass's programs from the host's shader text — the browser's generated module, a Node host's files\n// on disk; byte-identical either way. Four programs: the BOARD on the desk (the kit's view block, portal chain, card\n// primitives and mat light — kit/wgsl.ts, by name — then the felt's noise and the board's own), the STAMP that lays\n// the pen's footprints into a stroke, the INK that lays a finished stroke into the raster (and keeps the wet layer),\n// and the MIP that shrinks the raster for a board seen small.\n\nimport type { CardMaterial } from \"@ice/desk\";\nimport type { ComposeOptions } from \"@ice/desk/engine\";\nimport { kitWgsl, type ShaderText } from \"@ice/desk/kit\";\nimport { Board, BoardUniforms, InkUniforms, Stamp, StampUniforms } from \"./layout\";\n\nexport interface BoardShaders {\n readonly board: ComposeOptions; // the kit's view, portal, sdf, light + felt, board + board-pass\n readonly stamp: ComposeOptions; // the kit's sdf + felt + stamp\n readonly ink: ComposeOptions; // ink\n readonly mip: ComposeOptions; // mip\n}\n\n/** The board's own shader files (the kit's pieces come by name). */\nexport const BOARD_SHADER_FILES = {\n felt: \"board/felt.wgsl\",\n board: \"board/board.wgsl\",\n boardCard: \"board/board-card.wgsl\",\n boardPass: \"board/board-pass.wgsl\",\n stamp: \"board/stamp.wgsl\",\n ink: \"board/ink.wgsl\",\n mip: \"board/mip.wgsl\",\n} as const;\n\nexport function boardShaders(text: ShaderText): BoardShaders {\n const t = text(BOARD_SHADER_FILES);\n const felt = { label: \"board/felt.wgsl\", text: t.felt };\n return {\n board: kitWgsl([\"view\", \"portal\", \"sdf\", \"light\"], { structs: [BoardUniforms, Board], modules: [felt, { label: \"board/board.wgsl\", text: t.board }, { label: \"board/board-card.wgsl\", text: t.boardCard }], entry: { label: \"board/board-pass.wgsl\", text: t.boardPass } }, text),\n stamp: kitWgsl([\"sdf\"], { structs: [StampUniforms, Stamp], modules: [felt], entry: { label: \"board/stamp.wgsl\", text: t.stamp } }, text),\n ink: { structs: [InkUniforms], entry: { label: \"board/ink.wgsl\", text: t.ink } },\n mip: { entry: { label: \"board/mip.wgsl\", text: t.mip } },\n };\n}\n\n/**\n * The whiteboard's CARD MATERIAL (K7b, design-016 §6 K7): the flat-card pipeline draws a board with board-card.wgsl's quad and\n * fragment over the board pass's own records, knobs, samplers and thumbnail array (`BoardPass.cardResources`, in this order) —\n * every board drawn from its thumbnail (the card binds no pool and no live layers: its `board_ink` is the thumbnail's, its\n * stroke and wet none).\n */\nexport function boardCard(text: ShaderText): CardMaterial {\n return {\n shaders: () => {\n const t = text(BOARD_SHADER_FILES);\n return kitWgsl([\"view\", \"portal\", \"sdf\", \"light\"], { structs: [BoardUniforms, Board], modules: [{ label: \"board/felt.wgsl\", text: t.felt }, { label: \"board/board.wgsl\", text: t.board }], entry: { label: \"board/board-card.wgsl\", text: t.boardCard } }, text);\n },\n only: [\n \"fn board_ink(B: Board, uv: vec2f, lod: f32) -> vec4f { return board_thumb(B, uv, lod); } // the card binds no pool\",\n \"fn board_stroke(B: Board, uv: vec2f) -> f32 { return 0.0; } // …and no live layers: a board being written on is the pass's\",\n \"fn board_wet(B: Board, uv: vec2f) -> f32 { return 0.0; }\",\n ].join(\"\\n\"),\n bindings: [\n { wgsl: \"var<uniform> board_k: BoardUniforms\", entry: { stages: [\"fragment\"], buffer: \"uniform\" } },\n { wgsl: \"var<storage, read> boards: array<Board>\", entry: { stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" } },\n { wgsl: \"var board_gobo_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var board_noise_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var board_ink_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var board_thumbs: texture_2d_array<f32>\", entry: { stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" } },\n ],\n quad: \"board_quad\",\n fragInline: BOARD_FRAGMENT,\n };\n}\n\n/**\n * The board's fragment as the flat-card pipeline splices it (K7b): board-pass.wgsl's `fs`, statement for statement — its `in.idx`\n * the card's `slot`, its shade `cb`, its return the card's `c` — because shade_board reached through one more function compiles to\n * one LSB off on a pixel a scene (measured on the oracle): the card runs the very code the pass runs. `boardFsOf` is the pass's `fs`\n * the same statements make (test/card.test.ts holds board-pass.wgsl to it).\n */\nexport const BOARD_FRAGMENT = [\n \" let B = boards[slot];\",\n \" let zoom = max(u.cam.z, 1.0e-12);\",\n \" let dpr = max(u.cam.w, 1.0);\",\n \" let px = 1.0 / (zoom * dpr); // world per device px\",\n \" let css = 1.0 / zoom; // world per CSS px\",\n \" let p = in.clip.xy * px + u.cam.xy; // device px → world\",\n \" let cb = shade_board(B, u, board_k, p, px, css, in.clip.xy, gobo_tex, board_gobo_samp, noise_tex, board_noise_samp);\",\n \" if (cb.a < 0.002) { discard; }\",\n \" // Premultiplied: the presentation's opacity through the portal clip scales every channel.\",\n \" c = cb * (u.view.w * portal_cover(in.clip.xy / dpr, u.portals, u.clips, dpr));\",\n].join(\"\\n\");\n\n/** The pass's `fs` body BOARD_FRAGMENT's statements make — as board-pass.wgsl writes it (a test holds the two equal). */\nexport const boardFsOf = (fragment: string): string =>\n fragment.split(\"\\n\").map((l) => l.slice(4)\n .replace(\"let B = boards[slot];\", \"let B = boards[in.idx];\")\n .replace(\"let cb = shade_board(\", \"let c = shade_board(\")\n .replace(\"if (cb.a < 0.002)\", \"if (c.a < 0.002)\")\n .replace(\"c = cb * (\", \"return c * (\")).join(\"\\n\");\n","// The WHITEBOARD (BOARD.md) as a kind (kind.ts): the board pass behind the registry's door — a\n// thin adapter, the pass and its WGSL as they were. Stratum `things`: a board lies among the\n// desk's other things in the desk's own order (a note can sit on a board). Its `prepare` still\n// sends the queued stamps and the drying in submits of its own BEFORE the frame's (BOARD.md), and\n// takes no lamp — as the ground always called it. A spawned slot's pass copies the root's look\n// every frame (`tune` → the pass's `copy`).\n//\n// And its WORLD half (kinds/world.ts; D3w): `boardKind` — an entity of the board's widget type becomes a\n// `BoardInstance` through the prototype's own laws: `resolveBoard` on the rect and the flux (lift ← `Grab`,\n// the 12-unit rise and ×1.03 of BOARD.md; ring ← `Selected`; fade ← a ghost — a board never rises under the\n// pointer: BOARD.md's hover is the cursor's), the capped marker lying where a hand put it down (the bench's\n// `poseOf` at rest), `pickBoard` the mirror (the melamine `content`, the aluminium `frame`). Its INK is a\n// cache of its data children (board/data.ts — strokes and wipes as entities `ChildOf` the board, D-D5): the\n// kind's own state on each desk (`local()` → `BoardInk`) holds each board's raster on the root pass and\n// REPLAYS the children into it when the board is first met, when the children's stamp turns over (a stroke\n// laid, undone, redone, a remote peer's) or when the look changes. The materials and the markers' inks are\n// the product's (the theme gate): `theme()` takes them from the palette.\n\nimport { BoardPass, boardRung } from \"./board-pass\";\nimport { type BoardGeometry, type BoardLaw, DEFAULT_BOARD_LAW, pickBoard, quadOf, resolveBoard, surfaceSize } from \"./board\";\nimport { addStroke, BoardStroke, boardOps, feedStroke, MARKERS, type MarkerInk, strokePen, type StrokeRow, strokeSeed, type StrokeSpec } from \"./data\";\nimport type { BoardInstance } from \"./layout\";\nimport { followHand, penAtRest, penPose, type PenState, stepPen } from \"./pen\";\nimport { BOARD_SHADER_FILES, boardCard, boardShaders } from \"./shaders\";\nimport { type StrokeBuilder, TIP_NAMES, type TipName } from \"./stroke\";\nimport { type KindExtra, type KindPass, type KindProgram, type SlotContext, type Palette, type RGB, rgb, type ThemeName, type TokenRef, type KindHost, type KindLocal, type ObjectContext, type ObjectHit, type ObjectKind, rasterPriority, stringProp } from \"@ice/desk\";\nimport { type MarkFrame, type MatPass, type ShaderText, inking } from \"@ice/desk/kit\";\nimport { shaderText } from \"../shaders\";\nimport { BOARD } from \"./theme\";\nimport { ChildOf, type Entity, type HeldToolDef, type World } from \"@ice/core\";\n\n/** The whiteboard's kind name — its key in the registry and in every slot's `objects`. */\nexport const BOARD_KIND = \"board\";\n\nexport class BoardKind implements KindPass<BoardInstance> {\n /** The board pass itself: a host's door to the rasters (`ensure`, `lay`, `commit`, `replay`, `dry`) and the look (`look`, `chain`). */\n readonly pass: BoardPass;\n constructor(pass: BoardPass) { this.pass = pass; }\n\n spawn(mat: MatPass): BoardKind { return new BoardKind(this.pass.spawn(mat)); }\n\n tune(root: KindPass<BoardInstance>): void { if (root instanceof BoardKind) this.pass.copy(root.pass); }\n\n /** The pass's own `prepare`, argument for argument: the slot's camera, grid, clocks, the objects' presence, the light and the theme (its ring's colour) — and the records' keys (D6). */\n prepare(_encoder: GPUCommandEncoder, s: SlotContext, records: readonly BoardInstance[], extra?: KindExtra): number {\n // a record made without the desk's local carries its look's pen materials (K5b — the tray's specimen): they are its pass's\n const own = records.find((r) => r.materials !== undefined)?.materials;\n if (own !== undefined && this.pass.look !== own) this.pass.look = own;\n return this.pass.prepare(s.view, s.fadeIn, s.cfg, s.frame, records, s.present, s.light, s.theme, extra?.keys, s.target === \"hand\");\n }\n\n dropped(): number { return this.pass.dropped; }\n\n /** Records [first, end) — a board whose raster is missing draws nothing (the pass counts in the list it was handed). */\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void { this.pass.drawRange(pass, first, end); }\n cardResources() { return this.pass.cardResources(); }\n cardSlot(index: number): number { return this.pass.cardSlot(index); }\n records() { return this.pass.records; }\n\n dispose(): void { this.pass.dispose(); }\n}\n\n/** The whiteboard's program for a host's shader text: its passes made on the root's mat. */\nexport function boardProgram(text: ShaderText): KindProgram<BoardInstance> {\n return {\n name: BOARD_KIND,\n stratum: \"things\",\n card: boardCard(text),\n create: async (device, format, mat) => new BoardKind(await BoardPass.create(device, format, boardShaders(text), mat)),\n };\n}\n\n/** The whiteboard's silhouette for the desk's marks (D4a): its aluminium frame's outside as drawn, square to the mat. */\nexport function boardFrame(G: BoardGeometry): MarkFrame {\n return { cx: G.centre[0], cy: G.centre[1], hx: G.half[0], hy: G.half[1], angle: 0, r: G.radius };\n}\n\n// ---------------------------------------------------------------- the world half (D3w)\n\n/**\n * What the board's kind takes from the host's palette: its materials (BOARD.md — the melamine, the anodised frame, the\n * marker's barrel, the eraser's felt and wooden back) and the dry-erase markers by name, each an ink and the coverage one\n * pass lays. The product's (the theme gate), never the engine's.\n */\nexport interface BoardPalette extends Palette {\n readonly board?: { readonly surface: TokenRef; readonly frame: TokenRef; readonly barrel: TokenRef; readonly felt: TokenRef; readonly wood: TokenRef };\n readonly markers?: Readonly<Record<string, TokenRef & { readonly opacity: number }>>;\n}\n\n/** The board's look for a theme, parsed: the melamine and the frame a record takes, the pen's materials the pass takes, the markers' inks the replay takes, and each marker's CSS the held bar's swatch shows (by tool id). */\nexport interface BoardObjectLook {\n readonly surface: RGB;\n readonly metal: RGB;\n readonly pen: { readonly barrel: RGB; readonly felt: RGB; readonly wood: RGB };\n readonly markers: Readonly<Record<string, MarkerInk>>;\n readonly swatches: Readonly<Record<string, string>>;\n}\n\n// ---------------------------------------------------------------- the tools in hand (design-015 §8; D3t-a)\n\n/** A marker's tool id in the held bar (\"marker:blue\"); the eraser's is `ERASER_TOOL_ID`. */\nexport const markerToolId = (ink: string): string => `marker:${ink}`;\nexport const ERASER_TOOL_ID = \"eraser\";\n/** The ink a tool id names, or undefined (the eraser, anything else). */\nexport const inkOfTool = (id: string): string | undefined => (id.startsWith(\"marker:\") ? id.slice(7) : undefined);\n\n// a stroke in hand is the kit's question since K4a (kit/strokes.ts — the notebook asks it too); the board keeps its door\nexport { inking };\n\n/** Is there ink on board `e` — a stroke (the eraser's too: it may leave a ghost) after its last wipe? */\nexport function boardInked(world: World, e: Entity): boolean {\n let inked = false;\n for (const k of world.getReverse(e, ChildOf)) {\n const s = world.get(k, BoardStroke);\n if (s === undefined) continue;\n inked = s.tool !== \"wipe\";\n }\n return inked;\n}\n\nconst title = (s: string): string => `${s.charAt(0).toUpperCase()}${s.slice(1)}`;\n\n/**\n * The whiteboard's tools in hand (BOARD.md §5, *Marks on the Mat*'s contract: \"four markers, eraser, undo, redo\"; the tray merged\n * into the held bar, Q-o): the four markers (`1`–`4`) and the eraser (`e`, a toggle — chosen again, the marker it took over from\n * comes back) are MODES — core's `HeldTool`, the user's fact — whose cursor is none over the melamine (the pen draws itself);\n * undo and redo are the DOCUMENT's history (a stroke is one transaction, D-D5) and wait for a stroke in hand to land; on keys\n * alone, the tip (`t`: fine → bullet → chisel, the capped marker's durable `tip`) and the wipe (⌘⌫, one transaction — itself\n * undoable, as the bench's was). The pen's own state is written off the undo stack: ⌘Z undoes ink, never a pick of the pen.\n */\nexport const BOARD_TOOLS: readonly HeldToolDef[] = [\n ...MARKERS.map((ink, i): HeldToolDef => ({ id: markerToolId(ink), label: `${title(ink)} marker`, kind: \"mode\", keys: [String(i + 1)], hint: String(i + 1), glyph: \"pen\", cursor: \"none\" })),\n { id: ERASER_TOOL_ID, label: \"Eraser\", kind: \"mode\", keys: [\"e\"], hint: \"E\", glyph: \"eraser\", toggle: true, cursor: \"none\" },\n { id: \"undo\", label: \"Undo\", kind: \"action\", keys: [\"mod+z\"], hint: \"⌘Z\", glyph: \"undo\", run: (api) => { if (!inking(api.world)) api.undo(); } },\n { id: \"redo\", label: \"Redo\", kind: \"action\", keys: [\"mod+shift+z\", \"mod+y\"], hint: \"⇧⌘Z\", glyph: \"redo\", run: (api) => { if (!inking(api.world)) api.redo(); } },\n {\n id: \"tip\", label: \"Tip\", kind: \"action\", keys: [\"t\"], hint: \"T\", bar: false,\n run: (api) => {\n const cur = stringProp(api.props(), \"tip\", \"bullet\") as TipName;\n api.setProps({ tip: TIP_NAMES[(Math.max(TIP_NAMES.indexOf(cur), 0) + 1) % TIP_NAMES.length] }, { undoable: false });\n },\n },\n {\n id: \"wipe\", label: \"Wipe the board\", kind: \"action\", keys: [\"mod+Backspace\", \"mod+Delete\"], hint: \"⌘⌫\", bar: false,\n run: (api) => { if (!inking(api.world) && boardInked(api.world, api.entity)) api.transact((tx) => { addStroke(tx, api.entity, { tool: \"wipe\" }); }); },\n },\n];\n\n/**\n * A board at rest as the bench draws it (`BoardDesk.instances` + `poseOf` with no board open), all but its raster: THE\n * marker lying where a hand put it down — the pen's flux at rest (board/pen.ts: every hand term at e = 0, kept as the bench\n * computes them) —, the world rect the fragment may paint (the board, its shadow, the pen's box), the eye straight over it\n * (the parallax at rest).\n */\nexport function boardRest(G: BoardGeometry, w: number, h: number, tip: TipName, capInk: RGB, look: BoardObjectLook, law: BoardLaw = DEFAULT_BOARD_LAW): Omit<BoardInstance, \"id\"> {\n return boardPose(G, w, h, tip, capInk, look, penAtRest(), null, law);\n}\n\n/**\n * A board as drawn with its pen in whatever pose its flux has reached (D3t-a — board/pen.ts `penPose`): lying, taken up, in the\n * hand at `at` (a desk point), the eraser rubbing there; the quad grown to take in both. At rest it is `boardRest`, byte for byte.\n */\nexport function boardPose(G: BoardGeometry, w: number, h: number, tip: TipName, ink: RGB, look: BoardObjectLook, pen: PenState, at: readonly [number, number] | null, law: BoardLaw = DEFAULT_BOARD_LAW): Omit<BoardInstance, \"id\"> {\n const pose = penPose(G, w, h, tip, ink, pen, at);\n const par = [0, 0] as const;\n const k = BOARD.surface.parallax;\n return {\n geometry: G, surface: look.surface, metal: look.metal, quad: quadOf(G, pose.box, law), sheen: [par[0] * k * 5, -par[1] * k * 5], pen: pose.pen,\n ...(pose.eraser !== undefined ? { eraser: pose.eraser } : {}),\n };\n}\n\n/**\n * How far a board's drawing reaches past its rect, world units: the slab's shadow at full lift, or the resting pen's box\n * (it lies near the bottom edge and its box is wide), whichever is further; the held scale.\n */\nexport function boardReach(law: BoardLaw = DEFAULT_BOARD_LAW): number {\n const P = BOARD.pen;\n const top = law.lift.height + law.spec.thick;\n const shadow = law.shadow.slopeMax * top + 2.5 * (law.shadow.penumbra.sigma0 + law.shadow.penumbra.sigmaPerHeight * top);\n const pen = P.length * 1.3 + 60 + law.shadow.slopeMax * (P.radius + P.length * P.rise + 12);\n const held = (Math.max(law.spec.width, law.spec.height) * (law.lift.scale - 1)) / 2;\n return Math.max(shadow, pen) + held;\n}\n\n/** What the hand is doing over a board in hand this frame, as the pen driver (objects/pen.ts) reads the world: where (a desk point), over the melamine or not, laying a stroke or not, with which tool and ink, and the pointer on screen (its velocity leans the pen). */\nexport interface PenHand {\n readonly at: readonly [number, number] | null;\n readonly over: boolean;\n readonly pressing: boolean;\n readonly erasing: boolean;\n /** The ink in hand (the marker's, or the one it lies down in while the eraser rubs); absent = the capped marker's. */\n readonly ink?: string;\n /** The pointer on screen, CSS px, and the clock (ms) it was read at. */\n readonly screen?: readonly [number, number];\n readonly t?: number;\n}\n\n/** A still's pen (a pinned hand): its desk point, pressed or hovering, the eraser or the marker, the ink. */\nexport interface PenPin {\n readonly x: number;\n readonly y: number;\n readonly press?: boolean;\n readonly erase?: boolean;\n readonly ink?: string;\n}\n\n/**\n * The board's own state on one desk: each board's raster on the root pass, a cache of its strokes — and (D3t-a) what the hand\n * does to it in hand: the stroke laid LIVE into its stroke layer, committed WET and drying, its entity adopted when it lands\n * rather than replayed; the pen's flux and the hand it follows.\n */\nexport interface BoardInk extends KindLocal {\n /** When the kind is next live (K7a — `KindLocal.due`, declared: the six built-ins all say). */\n due(now: number): number;\n /**\n * The raster board `e` draws with (its id on the pass): made the first time, its children REPLAYED into it whenever\n * their stamp turned over or the look changed — unless the turnover is the stroke the hand just committed (adopted: the\n * raster holds it already, wet) —; a stroke in hand is laid again over a replay; a fading ghost keeps what it had. 0 before\n * the pass is here. `zd` — device px a world unit where it is drawn (zoom × dpr): a raster made now is made at its ZOOM\n * RUNG (K6a, `boardRung`); the pass's step raises it when the board grows on screen. K6b: a raster to MAKE (none held — never\n * made, or evicted — or its density raised) is asked of the desk's frame raster queue when the host has one, `px` (screen px\n * from the view's centre) its place: the board draws its old raster, its thumbnail, else its melamine bare until its turn.\n */\n raster(e: Entity, G: BoardGeometry, look: BoardObjectLook, ghost: boolean, zd?: number, px?: number): number;\n /** How many replays since the desk was made (a rig's witness). */\n replays(): number;\n /** Board `e`'s raster on the pass (`BoardPass.readInk` reads it — a rig's witness); undefined before it is met. */\n rasterOf(e: Entity): number | undefined;\n /** Board `e`'s residency (K6a — a rig's witness): its raster's density (null: evicted or not made), whether the pool binds it this frame, whether its thumbnail is cut. */\n residency(e: Entity): { readonly density: number | null; readonly bound: boolean; readonly thumb: boolean } | undefined;\n /**\n * The boards' residency in sum (K9 R5 — rig:scale's row): how many boards the desk has, how many were ever inked (replayed),\n * how many keep a far-LOD thumbnail (every inked board should, until the array's layer cap reclaims one — K9 R1), hold a raster,\n * are bound in the pool this frame; the thumbnail array's layers in use and capacity.\n */\n stats(): { readonly boards: number; readonly inked: number; readonly thumbed: number; readonly rastered: number; readonly bound: number; readonly layers: number; readonly capacity: number };\n /** The stroke in hand on `e`: the builder's stamps since the last call into the stroke layer (sent at the next prepare). */\n lay(e: Entity, builder: StrokeBuilder): void;\n /** The lift: the stroke in hand laid into the ink and marked WET; its entity (its cell's `points`) is adopted when it lands. */\n commit(e: Entity, points: string): void;\n /** A stroke in hand abandoned (or its transaction refused): its stamps dropped, the raster replayed from the children. */\n cancel(e: Entity): void;\n /** The stroke being laid on `e` — its ink (LINEAR) and whether it erases — for the record; undefined when none. */\n laying(e: Entity): { readonly color: RGB; readonly erase: boolean } | undefined;\n /** The hand over board `e` this frame (the pen driver's word). */\n hand(e: Entity, h: PenHand): void;\n /** Pin the hand for a still (`undefined` unpins): the pen sits where the pin says, its springs snapped. */\n pinPen(e: Entity, pin: PenPin | undefined): void;\n /** The pen's flux of board `e` (a rig's witness). */\n penOf(e: Entity): PenState | undefined;\n /** The world half's: the hand over `e` as the record reads it (the pin's, else the driver's), and the pen's flux. */\n handFor(e: Entity): { readonly hand: PenHand | undefined; readonly pen: PenState; readonly pinned: boolean };\n /** A pen still moving (the record says so): the next tick asks a frame. */\n moving(e: Entity): void;\n /**\n * A STILL's ink on board `e` (a rig's door — the oracle's `wet`/`live` board, D3t-a): after its children replayed, `wet` laid\n * LIVE and committed wet, then `live` mid-draw — its first `upto` samples in the stroke layer, the pen never lifted — each at the\n * seed of the op it would be. False before the board's raster is here.\n */\n sketch(e: Entity, s: { readonly wet?: StrokeSpec; readonly live?: StrokeSpec & { readonly upto: number } }): boolean;\n /** Hold the ink still (a still): no drying, no frame asked for a stroke in hand. */\n pinStill(on: boolean): void;\n}\n\ninterface BoardState {\n readonly id: number;\n /** The raster asked of the frame queue and not made yet (K6b): its surface, density and look; null = nothing asked. */\n want: { readonly surface: readonly [number, number]; readonly density: number; readonly look: BoardObjectLook } | null;\n /** The board's run for the queue, made once. */\n run: (() => \"done\" | \"wait\") | undefined;\n stamp: number;\n /** Replayed at least once — its ink has been on the device (K9 R5: `stats` counts these against the thumbnails kept). */\n inked: boolean;\n /** The density the pass's step asked its raster remade at (K6a — it grew on screen); undefined when none is owed. */\n raise: number | undefined;\n look: BoardObjectLook | null;\n /** The stroke in hand: its tool and builder (laid again over a replay). */\n live: { readonly builder: StrokeBuilder } | null;\n /** The committed stroke's `points` whose landing is adopted, not replayed. */\n adopt: string | null;\n pen: PenState;\n hand: PenHand | undefined;\n pin: PenPin | undefined;\n}\n\n/** The frame queue's name for the board's asks (K6b) — the kind's. */\nconst OWNER = \"board\";\n\n/** The board's `local()`: rasters by entity, released when the builder forgets a board. */\nexport function createBoardInk(host: KindHost): BoardInk {\n const boards = new Map<Entity, BoardState>();\n let next = 1;\n let replays = 0;\n let last = -1;\n let penMoving = false;\n let still = false;\n const passOf = (): BoardPass | undefined => { const k = host.pass(); return k instanceof BoardKind ? k.pass : undefined; };\n const stampOf = (e: Entity): number => host.children?.stamp(e) ?? 0;\n const drawn = host.drawn;\n // THE BUDGET (D6): a board's raster is a cache of its strokes — charged when made (its ink with its mips, its stroke and wet layers),\n // let go when the ledger evicts it (it replays from its children when next drawn: `stamp` −1), kept while the board is on screen\n const budget = host.budget;\n // THE FRAME QUEUE (K6b): a raster to make is asked there, made in its turn; the builder's door remakes the board's record then\n const queue = host.rasters;\n const remake = host.remake;\n const entityOf = new Map<string, Entity>();\n /** What has LANDED on each object, counted (D7 — `KindLocal.landed`): the held desk copy is made again when a desk object's moves. */\n const landedOf = new Map<Entity, number>();\n const land = (e: Entity): void => { landedOf.set(e, (landedOf.get(e) ?? 0) + 1); };\n const rasterBytes = (size: readonly [number, number]): number => Math.round(size[0] * size[1] * (4 * (4 / 3) + 1 + 1));\n /** The boards by their id on the pass (the step names boards by id). */\n const byId = new Map<number, Entity>();\n /** The far-LOD thumbnails' array (K6a): RESIDENT in the budget (K9 R2 — never evicted, outside the caches' room), charged at what its layers in use weigh, whenever that moves. */\n let thumbBytes = -1;\n const chargeThumbs = (pass: BoardPass): void => {\n if (budget === undefined || pass.thumbnailUsedBytes === thumbBytes) return;\n thumbBytes = pass.thumbnailUsedBytes;\n budget.reside(\"board\", \"thumbnails\", thumbBytes);\n };\n const state = (e: Entity): BoardState => {\n let st = boards.get(e);\n if (st === undefined) { st = { id: next++, want: null, run: undefined, stamp: -1, inked: false, raise: undefined, look: null, live: null, adopt: null, pen: penAtRest(), hand: undefined, pin: undefined }; boards.set(e, st); byId.set(st.id, e); }\n return st;\n };\n /** A raster just made charged to the budget — evicted, the RASTER goes and its thumbnail stays (replayed when next wanted) — else touched. */\n const charge = (e: Entity, st: BoardState, pass: BoardPass, made: boolean): void => {\n if (made && budget !== undefined) {\n const key = String(st.id);\n entityOf.set(key, e);\n const size = pass.sizeOf(st.id);\n budget.charge(\"board\", key, size === null ? 0 : rasterBytes(size), () => { passOf()?.evict(st.id); st.stamp = -1; entityOf.delete(key); });\n } else budget?.touch(\"board\", String(st.id));\n };\n /** Its strokes replayed into its raster — the stroke in hand laid again over them. */\n const replay = (e: Entity, st: BoardState, pass: BoardPass, look: BoardObjectLook): void => {\n pass.replay(st.id, boardOps(host.children?.rows(e, BoardStroke) ?? [], look.markers));\n land(e);\n st.inked = true;\n replays += 1;\n if (st.live !== null) pass.lay(st.id, st.live.builder.tool, st.live.builder.stamps());\n };\n /**\n * The queue's turn for board `e` (K6b): its raster made at the density it last asked and its strokes replayed into it, its record\n * remade (the frame that shows it is drawn). Nothing asked any more: done.\n */\n const run = (e: Entity): \"done\" | \"wait\" => {\n const st = boards.get(e);\n const pass = passOf();\n const want = st?.want ?? null;\n if (st === undefined || pass === undefined || want === null) return \"done\";\n st.want = null;\n st.raise = undefined;\n const made = pass.ensure(st.id, want.surface, want.density);\n charge(e, st, pass, made);\n replay(e, st, pass, want.look);\n st.stamp = stampOf(e);\n st.look = want.look;\n st.adopt = null;\n chargeThumbs(pass);\n remake?.(e);\n return \"done\";\n };\n return {\n raster(e, G, look, ghost, zd, px) {\n const pass = passOf();\n if (pass === undefined) return 0;\n const st = state(e);\n if (pass.look !== look.pen) pass.look = look.pen; // the pen's materials: the product's, set on the root (a spawned slot copies them)\n if (ghost) return st.id; // a board fading out keeps its ink: its children died with it\n const stamp = stampOf(e);\n // the density (K6a): the one the step asked for, else the raster's own, else the rung of where it is drawn now (the law's\n // 4 without a word — a bare host, the oracle)\n const density = st.raise ?? pass.densityOf(st.id) ?? (zd === undefined ? BOARD.ink.density : boardRung(zd * G.scale));\n const surface = surfaceSize(G);\n // a raster to MAKE (K6b) — none held, or its density raised — is the frame queue's: the board draws what it has meanwhile (its\n // old raster, its thumbnail, else its melamine bare) and the queue makes it and replays its strokes in its turn\n if (queue !== undefined && pass.makes(st.id, surface, density)) {\n st.want = { surface, density, look };\n const shows = pass.densityOf(st.id) !== null || pass.thumbed(st.id) ? \"magnified\" : \"nothing\";\n st.run ??= () => run(e);\n queue.ask(OWNER, e, rasterPriority(shows, px ?? 0), st.run);\n return st.id;\n }\n if (st.want !== null) { st.want = null; queue?.drop(OWNER, e); } // nothing to make any more\n st.raise = undefined;\n const made = pass.ensure(st.id, surface, density);\n charge(e, st, pass, made);\n if (made || stamp !== st.stamp || look !== st.look) {\n const rows: readonly StrokeRow[] = host.children?.rows(e, BoardStroke) ?? [];\n // the stroke the hand just committed has landed as its entity: the raster holds it already — WET — so it is adopted\n const landed = !made && look === st.look && st.adopt !== null && rows[rows.length - 1]?.points === st.adopt;\n st.adopt = null;\n if (!landed) replay(e, st, pass, look);\n st.stamp = stamp;\n st.look = look;\n }\n chargeThumbs(pass);\n return st.id;\n },\n lay(e, builder) {\n const st = state(e);\n st.live = { builder };\n const stamps = builder.pending();\n if (stamps.length > 0) passOf()?.lay(st.id, builder.tool, stamps);\n },\n commit(e, points) {\n const st = state(e);\n const live = st.live;\n st.live = null;\n if (live === null) return;\n const pass = passOf();\n const stamps = live.builder.pending();\n if (stamps.length > 0) pass?.lay(st.id, live.builder.tool, stamps);\n pass?.commit(st.id, live.builder.tool);\n st.adopt = points;\n },\n cancel(e) {\n const st = boards.get(e);\n if (st === undefined) return;\n st.live = null;\n st.adopt = null;\n passOf()?.cancel(st.id);\n st.stamp = -1; // replayed from the children at the next record\n },\n laying(e) {\n const b = boards.get(e)?.live?.builder;\n return b === undefined ? undefined : { color: b.tool.color, erase: b.tool.mode === \"erase\" };\n },\n hand(e, h) {\n const st = state(e);\n const prev = st.hand;\n if (prev?.screen !== undefined && h.screen !== undefined && prev.t !== undefined && h.t !== undefined) followHand(st.pen, h.screen[0] - prev.screen[0], h.screen[1] - prev.screen[1], (h.t - prev.t) / 1000);\n st.hand = h;\n },\n pinPen(e, pin) { state(e).pin = pin; penMoving = true; },\n penOf: (e) => boards.get(e)?.pen,\n handFor(e) {\n const st = state(e);\n const p = st.pin;\n if (p === undefined) return { hand: st.hand, pen: st.pen, pinned: false };\n const ink = p.ink ?? st.hand?.ink;\n return { hand: { at: [p.x, p.y], over: true, pressing: p.press === true, erasing: p.erase === true, ...(ink !== undefined ? { ink } : {}) }, pen: st.pen, pinned: true };\n },\n sketch(e, s) {\n const pass = passOf();\n const st = boards.get(e);\n const look = st?.look;\n if (pass === undefined || st === undefined || look === null || look === undefined || st.stamp === -1) return false;\n let n = host.children?.rows(e, BoardStroke).length ?? 0;\n const lay = (spec: StrokeSpec, upto?: number): StrokeBuilder | undefined => {\n const b = strokePen(spec, look.markers, spec.seed !== undefined && spec.seed >= 0 ? spec.seed : strokeSeed(n)); // the row's own seed (v4), else the position's\n if (b === undefined) return undefined;\n const points = spec.points ?? [];\n feedStroke(b, points, spec.times !== undefined && spec.times.length === points.length ? spec.times : null, spec.speed ?? 400, upto);\n pass.lay(st.id, b.tool, b.pending());\n n += 1;\n return b;\n };\n if (s.wet !== undefined) { const b = lay(s.wet); if (b !== undefined) pass.commit(st.id, b.tool); }\n if (s.live !== undefined) { const b = lay(s.live, s.live.upto); if (b !== undefined) st.live = { builder: b }; }\n return true;\n },\n pinStill(on) { still = on; },\n moving() { penMoving = true; },\n landed: (e) => landedOf.get(e) ?? 0,\n // K7a: next live now while the pen moves, a stroke is in hand, the ink dries, or the last frame's asks wait for their residency\n // step; never otherwise — a stroke laid, undone or a peer's arrives with a wake (the input, the document)\n due(now) {\n const pass = passOf();\n if (penMoving || pass?.stepOwed === true || (!still && pass?.wetting === true)) return now;\n if (!still) for (const st of boards.values()) if (st.live !== null) return now;\n return Number.POSITIVE_INFINITY;\n },\n tick(now) {\n const dt = last < 0 ? 0 : Math.min(Math.max((now - last) / 1000, 0), 0.25);\n last = now;\n const pass = passOf();\n if (!still) pass?.dry(dt); // fresh ink dries (the wet layer fades) on the frame's clock — a still holds it\n let want = penMoving || (!still && pass?.wetting === true);\n // the residency's frame boundary (K6a): the pool's slots freed for boards no frame asked for; a board grown on screen past\n // its raster's density is remade at its rung — its strokes replayed at its next record (a frame asked for now)\n for (const { id, density } of pass?.step() ?? []) {\n const e = byId.get(id);\n const st = e === undefined ? undefined : boards.get(e);\n if (st === undefined) continue;\n st.raise = density;\n st.stamp = -1;\n want = true;\n }\n penMoving = false;\n for (const [e, st] of boards) {\n if (st.live !== null && !still) want = true; // a stroke in hand: its stamps (a resting pen's bleed) go out every frame\n // a stroke laid or undone: a frame to replay in — for a board that is DRAWN (D6; the builder's word when it gives one): a\n // board off screen replays when it comes back (its record is made afresh then) and its stale stamp keeps nothing awake\n // (D-D3t-b.11's latent keep-awake)\n else if (st.stamp !== -1 && (drawn === undefined || drawn(e) !== undefined) && stampOf(e) !== st.stamp) want = true;\n }\n return want;\n },\n /** The budget's ask (D6; K6a): the thumbnails always; a board's raster while the pool binds it — drawn from it this frame. */\n keeps(key) {\n if (key === \"thumbnails\") return true;\n const e = entityOf.get(key);\n if (e === undefined) return false;\n return passOf()?.bound(Number(key)) ?? false;\n },\n forget(e) {\n const st = boards.get(e);\n if (st === undefined) return;\n queue?.drop(OWNER, e);\n const pass = passOf();\n pass?.release(st.id);\n budget?.release(\"board\", String(st.id));\n if (pass !== undefined) chargeThumbs(pass); // its thumbnail's layer given back: the resident charge follows (K9 R2)\n entityOf.delete(String(st.id));\n byId.delete(st.id);\n landedOf.delete(e);\n boards.delete(e);\n },\n dispose() {\n queue?.clear(OWNER);\n const pass = passOf();\n for (const st of boards.values()) { pass?.release(st.id); budget?.release(\"board\", String(st.id)); }\n budget?.release(\"board\", \"thumbnails\");\n thumbBytes = -1;\n boards.clear();\n entityOf.clear();\n },\n replays: () => replays,\n rasterOf: (e) => boards.get(e)?.id,\n residency(e) {\n const id = boards.get(e)?.id;\n const pass = passOf();\n return id === undefined || pass === undefined ? undefined : { density: pass.densityOf(id), bound: pass.bound(id), thumb: pass.thumbed(id) };\n },\n stats() {\n const pass = passOf();\n let inked = 0;\n let thumbed = 0;\n let rastered = 0;\n let bound = 0;\n for (const st of boards.values()) {\n if (st.inked) inked += 1;\n if (pass === undefined) continue;\n if (pass.thumbed(st.id)) thumbed += 1;\n if (pass.densityOf(st.id) !== null) rastered += 1;\n if (pass.bound(st.id)) bound += 1;\n }\n return { boards: boards.size, inked, thumbed, rastered, bound, layers: pass?.thumbnailLayers ?? 0, capacity: pass?.thumbnailCapacity ?? 0 };\n },\n };\n}\n\nexport interface BoardKindOptions {\n /** The host's shader text; the generated module unless a host says. */\n readonly text?: ShaderText;\n /** The board's numbers (theme.ts `BOARD`) — the engine's unless a host tweaks them. */\n readonly law?: BoardLaw;\n}\n\n/** The whiteboard's kind, whole (kinds/world.ts `ObjectKind`): the program, and the world half on the bench's laws. */\nexport function boardKind(opts: BoardKindOptions = {}): ObjectKind<BoardGeometry, BoardInstance, BoardObjectLook> {\n const law = opts.law ?? DEFAULT_BOARD_LAW;\n const program = boardProgram(opts.text ?? shaderText);\n const parse = (t: TokenRef | undefined): RGB | undefined => (t === undefined ? undefined : rgb(t.css));\n return {\n ...program,\n reach: boardReach(law),\n local: (host: KindHost): BoardInk => createBoardInk(host),\n // THE OPENING (design-015 §8, D4b): the board's face comes to the hand whole, flat under the pose's camera; its tools (D3t-a,\n // `BOARD_TOOLS` — the tray merged into the bar, Q-o) with the marker in the ink it lies in taken into the hand\n open: {\n extent: (c) => c.rect,\n tools: BOARD_TOOLS,\n tool: (props) => markerToolId(stringProp(props, \"cap\", \"black\")),\n swatches: (look) => (look as BoardObjectLook).swatches,\n },\n resolve(ctx: ObjectContext): BoardGeometry {\n const r = ctx.rect;\n return resolveBoard({ cx: r.cx, cy: r.cy, w: r.w, h: r.h }, { held: ctx.flux.lift, ring: ctx.flux.ring, fade: ctx.flux.fade }, ctx.lamp, law);\n },\n record(G: BoardGeometry, ctx: ObjectContext): BoardInstance {\n const look = ctx.look as BoardObjectLook | undefined;\n if (look === undefined) throw new Error(\"desk/board: the board's materials are the host's — the palette names no `board` (kinds/board.ts `BoardPalette`)\");\n const tipName = stringProp(ctx.props, \"tip\", \"bullet\") as TipName;\n const tip = TIP_NAMES.includes(tipName) ? tipName : \"bullet\";\n const capName = stringProp(ctx.props, \"cap\", \"black\");\n const colourOf = (name: string): RGB => (look.markers[name] ?? Object.values(look.markers)[0])?.color ?? look.metal;\n const ink = ctx.local as BoardInk | undefined;\n const v = ctx.view;\n const px = Math.hypot(ctx.rect.cx - (v.camX + v.width / (2 * v.zoom)), ctx.rect.cy - (v.camY + v.height / (2 * v.zoom))) * v.zoom; // its place in the frame queue (K6b)\n const id = ink?.raster(ctx.entity, G, look, ctx.flux.fade < 1, v.zoom * v.dpr, px) ?? 0;\n // on the desk the marker lies capped in the ink it was put down in (`cap`); IN HAND (D3t-a) it follows the hand — taken up\n // as the board opens, at the pointer over the melamine, pressed while a stroke is laid, laid down again flying home\n if (ink === undefined || ctx.held === undefined) {\n if (ink !== undefined) Object.assign(ink.handFor(ctx.entity).pen, penAtRest());\n // without the desk's local nobody sets the pass's pen materials: the record carries its look's (K5b — the tray's specimen)\n return { id, ...boardRest(G, ctx.rect.w, ctx.rect.h, tip, colourOf(capName), look, law), ...(ink === undefined ? { materials: look.pen } : {}) };\n }\n const { hand, pen, pinned } = ink.handFor(ctx.entity);\n const input = { held: ctx.held.open, erasing: hand?.erasing === true, over: hand?.over === true, pressing: hand?.pressing === true };\n if (stepPen(pen, input, ctx.dt, ctx.held.snap || pinned)) ink.moving(ctx.entity);\n const pose = boardPose(G, ctx.rect.w, ctx.rect.h, tip, colourOf(hand?.ink ?? capName), look, pen, hand?.at ?? null, law);\n const laying = ink.laying(ctx.entity);\n return { id, ...pose, ...(laying !== undefined ? { stroke: laying } : {}) };\n },\n hit(G: BoardGeometry, wx: number, wy: number): ObjectHit | null {\n const h = pickBoard(G, wx, wy);\n return h === \"surface\" ? \"content\" : h === \"frame\" ? \"frame\" : null;\n },\n frame: boardFrame,\n theme(palette: Palette, _name: ThemeName): BoardObjectLook {\n const p = palette as BoardPalette;\n const b = p.board;\n const surface = parse(b?.surface);\n const metal = parse(b?.frame);\n if (surface === undefined || metal === undefined) throw new Error(\"desk/board: the board's materials are the host's — the palette names no `board` (kinds/board.ts `BoardPalette`)\");\n const black: RGB = [0, 0, 0];\n return {\n surface, metal,\n pen: { barrel: parse(b?.barrel) ?? black, felt: parse(b?.felt) ?? black, wood: parse(b?.wood) ?? black },\n markers: Object.fromEntries(Object.entries(p.markers ?? {}).map(([name, m]) => [name, { color: rgb(m.css), opacity: m.opacity }])),\n swatches: Object.fromEntries(Object.entries(p.markers ?? {}).map(([name, m]) => [markerToolId(name), m.css])),\n };\n },\n };\n}\n","// THE WHITEBOARD IN HAND — its pen (BOARD.md §5; design-015 §8; D3t-a): the hand half of the board kind, the print's carry's\n// sibling (objects/carry.ts). It READS the world — the board in hand (core's `Held`), the tool in hand (`HeldTool`), the\n// local pointer through the pose the renderer drew (`HeldPointer`, mapped to the desk by the builder's `heldToWorld`), the\n// press that is the tool's (`HeldPress` \"tool\") and its buttons (a pen's eraser end erases too) — and drives the board kind's\n// own state (kinds/board.ts `BoardInk`): the hand it follows, the stroke laid LIVE. It WRITES exactly two things, each ONE\n// transaction deferred out of the frame (a reflector never writes — D-D2c.5): at the lift, the stroke — one `desk.stroke`\n// child of the board with its samples' times (board/data.ts), which the ink adopts rather than replays — and at the put-down,\n// the capped marker's ink (`cap`, off the undo stack) when the ink last used is another.\n//\n// A press on the melamine with a mode in hand begins a stroke at the next frame's pointer; every frame the pointer moved is a\n// move, a frame it did not is the pen RESTING (it bleeds); the frame the press is gone is the lift, at the pointer's last\n// point. The samples reach the pen as f32s — the same the cell stores — so the stamps laid live are the stamps a replay lays.\n// The pen is seeded with the next op's seed (`strokeSeed` of the board's children), as the replay seeds it. Put down while a\n// stroke is laid, the stroke lands first. Samples are a frame apart (the ingest folds a frame's moves into one — the\n// prototype's coalesced events are owed).\n\nimport { ChildOf, type Component, defineQuery, type Entity, guardedTransaction, heldEntity, HeldPointer, HeldPress, HeldTool, LocalPointer, Pointer, PointerButtons, PointerScreen, setWidgetProps, type World } from \"@ice/core\";\nimport { type BoardGeometry, toSurface } from \"./board\";\nimport { addStroke, BoardStroke, encodePoints, strokeSeed } from \"./data\";\nimport { ERASER_TOOL, markerTool, StrokeBuilder, TIP_NAMES, type TipName, TIPS } from \"./stroke\";\nimport { type BoardInk, type BoardObjectLook, ERASER_TOOL_ID, inkOfTool } from \"./kind\";\nimport { linear } from \"@ice/desk/kit\";\nimport { type TypingDocs, writable } from \"@ice/desk\";\n\nexport interface BoardPenOptions {\n readonly world: World;\n /** The document a stroke commits into — the facade's `engine.docs`. */\n readonly docs: TypingDocs;\n /** The board's props cell (its `cap`, its `tip`) — the object hands its own (D-D7-A.3); absent, the marker is black, the tip a bullet. */\n readonly props?: Component | undefined;\n /** The board kind's state on this desk (undefined before it is made). */\n readonly ink: () => BoardInk | undefined;\n /** The board kind's look for the theme in force (the markers' inks). */\n readonly look: () => BoardObjectLook | undefined;\n /** Is this entity a board (the desk's builder knows each entity's kind). */\n readonly isBoard: (e: Entity) => boolean;\n /** A point of the held object's own frame as a desk point, through the pose the last frame drew (the builder's). */\n readonly heldToWorld: (e: Entity, x: number, y: number) => readonly [number, number] | undefined;\n /** The geometry the board was drawn with in hand (the builder's). */\n readonly geometryOf: (e: Entity) => unknown;\n /** Where a transaction runs: out of the frame (a microtask) unless a test says. */\n readonly defer?: (fn: () => void) => void;\n}\n\nexport interface BoardPen {\n /** Nothing to follow (D7 #14): no board in hand, no stroke laid, no marker to lie down. */\n idle(): boolean;\n /** Once a frame, before the kinds' clocks: the hand onto the board in hand, its stroke laid, lifted, committed. */\n follow(now: number): void;\n /** The stroke in hand: its board and how many samples so far; null when none. */\n live(): { readonly board: Entity; readonly samples: number } | null;\n /** Strokes committed since creation (a rig's witness). */\n commits(): number;\n}\n\ninterface Stroke {\n readonly board: Entity;\n readonly pointer: Entity;\n readonly builder: StrokeBuilder;\n readonly t0: number;\n readonly points: [number, number][];\n readonly times: number[];\n readonly ink: string;\n readonly tip: TipName;\n readonly erase: boolean;\n /** The fibre seed the live pen laid with — STORED in the row (v4, D7 #13), so the replay lays the same stamps whatever lands before it. */\n readonly seed: number;\n}\n\nconst pointersQ = defineQuery([Pointer, LocalPointer, PointerScreen]);\nconst f32 = Math.fround;\n\nexport function createBoardPen(opts: BoardPenOptions): BoardPen {\n const { world, docs } = opts;\n const defer = opts.defer ?? ((fn: () => void) => queueMicrotask(fn));\n let stroke: Stroke | null = null;\n /** The board last in hand and the ink in hand then: at the put-down its marker lies down in it. */\n let last: { readonly board: Entity; ink: string } | null = null;\n let commits = 0;\n\n /** The capped marker's ink and tip, as the board's props hold them. */\n const propsOf = (b: Entity): { cap: string; tip: string } => {\n const v = opts.props === undefined ? undefined : (world.get(b, opts.props as never) as { cap?: string; tip?: string } | undefined);\n return { cap: v?.cap ?? \"black\", tip: v?.tip ?? \"bullet\" };\n };\n /** A desk point on board `b`'s melamine, as the cell stores it (world units from its top-left, f32). */\n const onMelamine = (G: BoardGeometry, at: readonly [number, number]): [number, number] => { const [x, y] = toSurface(G, at[0], at[1]); return [f32(x), f32(y)]; };\n\n /** The lift: the last sample, the stroke laid in WET, its ONE transaction out of the frame. */\n const lift = (s: Stroke, at: readonly [number, number] | undefined, now: number): void => {\n const ink = opts.ink();\n const G = opts.geometryOf(s.board) as BoardGeometry | undefined;\n const [x, y] = at !== undefined && G !== undefined ? onMelamine(G, at) : (s.points[s.points.length - 1] as [number, number]);\n const t = f32(now - s.t0);\n s.builder.end(x, y, t);\n s.points.push([x, y]);\n s.times.push(t);\n ink?.commit(s.board, encodePoints(s.points));\n const spec = { tool: \"marker\" as const, ink: s.ink, tip: s.tip, erase: s.erase, points: s.points, times: s.times, seed: s.seed };\n defer(() => {\n const session = writable(docs);\n let ok = false;\n if (session !== undefined && world.isAlive(s.board)) {\n try { guardedTransaction(session.store, world, (tx) => { addStroke(tx, s.board, spec); }); ok = true; } catch { ok = false; }\n }\n if (ok) commits += 1;\n else ink?.cancel(s.board); // refused (a read-only document, a board gone): the raster is its children's again\n });\n };\n\n /** The put-down: the marker lies down in the ink last used — the `cap`, off the undo stack, when it is another. */\n const layDown = (b: Entity, ink: string): void => {\n defer(() => {\n const session = writable(docs);\n if (session === undefined || !world.isAlive(b) || propsOf(b).cap === ink) return;\n try { setWidgetProps(session.store, world, b, { cap: ink }, { undoable: false }); } catch { /* refused (the prop's schema, the guard): the old cap stays */ }\n });\n };\n\n return {\n follow(now) {\n const held = heldEntity(world);\n const board = held !== undefined && world.isAlive(held) && opts.isBoard(held) ? held : undefined;\n if (last !== null && last.board !== board) {\n // the board was put down (or another taken up): the stroke in hand lands first, then the marker lies down\n if (stroke !== null && stroke.board === last.board) { lift(stroke, undefined, now); stroke = null; }\n layDown(last.board, last.ink);\n last = null;\n }\n if (stroke !== null && !world.isAlive(stroke.board)) { opts.ink()?.cancel(stroke.board); stroke = null; }\n if (board === undefined) return;\n const ink = opts.ink();\n const look = opts.look();\n if (ink === undefined || look === undefined) return;\n const held0 = world.get(board, HeldTool);\n const tool = { id: held0?.id ?? \"\", prev: held0?.prev ?? \"\" };\n const props = propsOf(board);\n const inHand = inkOfTool(tool.id) ?? inkOfTool(tool.prev) ?? props.cap;\n last = { board, ink: inHand };\n // the pointer: the one laying the stroke, else the local mouse\n let pointer: Entity | undefined;\n world.query(pointersQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (stroke !== null ? p === stroke.pointer : world.read(p, Pointer).device === \"mouse\" || world.get(p, HeldPress)?.kind === \"tool\") pointer = pointer ?? p;\n }\n });\n const hp = pointer !== undefined ? world.get(pointer, HeldPointer) : undefined;\n const at = hp !== undefined ? opts.heldToWorld(board, hp.x, hp.y) : undefined;\n const G = opts.geometryOf(board) as BoardGeometry | undefined;\n const buttons = pointer !== undefined ? (world.get(pointer, PointerButtons)?.buttons ?? 0) : 0;\n const pressing = pointer !== undefined && world.get(pointer, HeldPress)?.kind === \"tool\" && (buttons & (1 | 32)) !== 0;\n // the lift: the press is gone (released, cancelled) — the stroke lands at the pointer's last point\n if (stroke !== null && (!pressing || stroke.pointer !== pointer || stroke.board !== board)) { lift(stroke, at, now); stroke = null; }\n else if (stroke !== null && at !== undefined && G !== undefined) {\n // a frame of the stroke: a move, or — the pointer where it was — the pen resting (its bleed)\n const [x, y] = onMelamine(G, at);\n const t = f32(now - stroke.t0);\n const [px, py] = stroke.points[stroke.points.length - 1] as [number, number];\n if (x === px && y === py) stroke.builder.hold(t);\n else stroke.builder.move(x, y, t);\n stroke.points.push([x, y]);\n stroke.times.push(t);\n ink.lay(board, stroke.builder);\n } else if (stroke === null && pressing && pointer !== undefined && at !== undefined && G !== undefined) {\n // the press: the pen meets the melamine — the eraser if it is the tool in hand, or a pen's eraser end\n const erase = tool.id === ERASER_TOOL_ID || (buttons & 32) !== 0;\n const tip = (TIP_NAMES.includes(props.tip as TipName) ? props.tip : \"bullet\") as TipName;\n const m = look.markers[inHand] ?? Object.values(look.markers)[0];\n const pen = erase || m === undefined ? ERASER_TOOL : markerTool(linear(m.color), m.opacity, TIPS[tip]);\n const rows = world.getReverse(board, ChildOf).filter((k) => world.get(k, BoardStroke) !== undefined).length;\n const seed = strokeSeed(rows); // the next op's, as a replay of the rows so far would seed it — and the row will carry it\n const builder = new StrokeBuilder(pen, seed);\n const [x, y] = onMelamine(G, at);\n builder.begin(x, y, 0);\n stroke = { board, pointer, builder, t0: now, points: [[x, y]], times: [0], ink: inHand, tip, erase, seed };\n ink.lay(board, builder);\n }\n const screen = pointer !== undefined ? world.get(pointer, PointerScreen) : undefined;\n ink.hand(board, {\n at: at ?? null,\n over: hp?.part === \"content\" || stroke !== null,\n pressing: stroke !== null,\n erasing: stroke !== null ? stroke.erase : tool.id === ERASER_TOOL_ID,\n ink: inHand,\n ...(screen !== undefined ? { screen: [screen.x, screen.y] as const, t: now } : {}),\n });\n },\n idle: () => stroke === null && last === null && heldEntity(world) === undefined,\n live: () => (stroke === null ? null : { board: stroke.board, samples: stroke.points.length }),\n commits: () => commits,\n };\n}\n","// The WHITEBOARD (BOARD.md) as an OBJECT (design-015 §6; D3w): a melamine board in an aluminium frame,\n// lying square to the desk among its things. Durable props: the capped marker lying on it — its ink\n// (`cap`: the last marker it was written with, by name; the inks are the host's palette) and its tip.\n// What is WRITTEN on it is not a prop: its strokes and wipes are DATA CHILDREN, entities `ChildOf` the\n// board (board/data.ts, D-D5), and the raster the pass draws is a cache replayed from them (kinds/board.ts).\n// Things, movable, selectable, snapping both ways; RESIZABLE — the knobs the desk's marks draw on it (*Marks on the Mat*\n// Q-a/b: knobs only on the photo and the whiteboard) are core's resize handles, and its world half is drawn from its\n// rect, so a resized board is drawn at its new size and its ink replays into a raster of that size; a ROOT object (D-D18:\n// `interaction.drop: \"never\"` — no container takes it, whatever it accepts; let go over a mini mat's face it lies there).\n// Its held tools (D3t-a — the kind's `open.tools`): the four markers and the eraser (the tool in hand), undo and redo over its\n// strokes (the document's history), the tip and the wipe on keys; the prototype's tray is the held bar (Q-o).\n\nimport { p } from \"@ice/core\";\nimport { MARKERS, StrokePrefab } from \"./data\";\nimport { type BoardInk, type BoardObjectLook, boardKind } from \"./kind\";\nimport { DESK_OBJECT, defineObject } from \"@ice/desk\";\nimport { BOARD } from \"./theme\";\nimport { createBoardPen } from \"./board-pen\";\n\n/** The dry-erase markers a board is written with (BOARD.md §3) — names; the inks are the host's (board/data.ts). */\nexport { MARKERS, type MarkerName } from \"./data\";\n/** The marker's tips (board/stroke.ts `TIPS`). */\nexport const TIPS = [\"fine\", \"bullet\", \"chisel\"] as const;\n\n/** The board's durable type id. */\nexport const BOARD_TYPE = \"desk.board\";\n\nexport const Board = defineObject({\n type: BOARD_TYPE,\n version: 1,\n props: {\n cap: p.enum(MARKERS, { default: \"black\" }),\n tip: p.enum(TIPS, { default: \"bullet\" }),\n },\n size: { w: BOARD.spec.width, h: BOARD.spec.height },\n kind: boardKind(),\n // on the pegboard tray (design-017 §8): the whiteboard on a rail\n tray: { label: \"Whiteboard\", category: \"surfaces\", order: 1, hang: { w: 240, h: 160, accessory: \"rail\", pegs: [[-2.5, -0.5], [2.5, -0.5]] } },\n interaction: { selectable: true, movable: true, resizable: true, snap: \"both\", drop: \"never\" },\n // it lies on the desk by what it provides (K8a — `DESK_OBJECT`, the desk canvas's one key), as a plugin kind does\n provides: [DESK_OBJECT],\n // its strokes and wipes are its DATA (D3t-a): the catalog stamps, gates and migrates their prefab with the board's own\n data: [StrokePrefab],\n // the whiteboard in hand (D3t-a): its PEN — the hand onto the board kind's state, each stroke ONE transaction out of the frame (D-D7-A.3)\n drivers: (h) => createBoardPen({\n world: h.world, docs: h.docs, ink: () => h.local as BoardInk | undefined, look: () => h.look() as BoardObjectLook | undefined, isBoard: h.isKind,\n heldToWorld: h.heldToWorld, geometryOf: h.geometryOf, props: Board.groups[0]?.component,\n }),\n});\n","// The CALENDAR's numbers (CALENDAR.md) — one place. World units are CSS px at zoom 1: the sticky note\n// is 200 (a 3″ square), so a day's cell is sized to take one under its date: 240 wide, and in a\n// six-week month still 252 tall (the note's 200, turned a degree or two, under the 40 the date\n// prints in). The sheet is what those cells make — a desk pad of a blotter's size, 1760 × 1852.\n// The pad's build (board, block, tape), the roll the months before go into, the print, the hand,\n// the light and the springs follow; the colours are the host's (lab/theme.ts `CALENDAR_LOOK`).\n\nexport interface CalendarLaw {\n /** The sheet's bands, head to foot, and its margins. */\n readonly sheet: {\n /** Left and right, beside the grid (the week numbers print in the left one). */\n readonly margin: number;\n /** The cloth tape across the head: the sheets are bound under it. */\n readonly tape: number;\n /** Blank paper under the tape: where the roll of the months before lies. */\n readonly rollZone: number;\n /** The month's name and the two small months. */\n readonly title: number;\n /** The weekdays' row. */\n readonly weekdays: number;\n readonly foot: number;\n /** The pad's corners. */\n readonly radius: number;\n };\n readonly grid: {\n /** A day's width. */\n readonly cw: number;\n /** The grid's height: a month's rows share it (four, five or six). */\n readonly height: number;\n /** The rules between days, and the heavier one under the weekdays (world units). */\n readonly rule: number;\n readonly head: number;\n };\n /** The printed type (the product's stack, DESIGN.md §3: big is light, small is medium). */\n readonly print: {\n readonly numeral: { readonly size: number; readonly baseline: number; readonly pad: number; readonly weight: number };\n readonly title: { readonly size: number; readonly baseline: number; readonly weight: number; readonly year: number };\n readonly weekday: { readonly size: number; readonly tracking: number; readonly weight: number };\n readonly mini: { readonly size: number; readonly pitch: number; readonly col: number; readonly gap: number };\n readonly small: { readonly size: number; readonly weight: number };\n readonly moon: { readonly r: number; readonly inset: number };\n };\n /** The handwriting in the cells (paper/text.ts's hand, at a pen's size). */\n readonly hand: {\n readonly size: number;\n /** A line's pitch. */\n readonly pitch: number;\n /** The first line's top, from the cell's top (under the date). */\n readonly top: number;\n readonly pad: number;\n /** A timed line's time, × the pen's size. */\n readonly time: number;\n /** A band's height, and how far its ends rag. */\n readonly band: number;\n readonly rag: number;\n };\n /** A sticky note stuck to a day: the note's own side, and the gap it keeps from the cell's foot. */\n readonly note: { readonly size: number; readonly gap: number };\n /** The pad's build: the chipboard back, the sheets under the month (the months after), each sheet. */\n readonly pad: { readonly board: number; readonly block: number; readonly sheet: number };\n /**\n * The ROLL: a month rolled up goes into a roll of paper under the tape — an Archimedean spiral whose\n * turns thicken by `tau` each (paper's thickness, made visible), wound on a core so its outer radius\n * at rest is `rest`; `turns` of it are drawn (the rest is inside). The corner's tilt as a roll starts.\n */\n readonly roll: { readonly rest: number; readonly tau: number; readonly turns: number; readonly tilt: number; readonly peek: number };\n /** Carried, the pad rises this far. */\n readonly lift: number;\n /** Springs: [hz, damping]. */\n readonly springs: { readonly roll: readonly [number, number]; readonly lift: readonly [number, number]; readonly ring: readonly [number, number]; readonly peek: readonly [number, number] };\n /** The light: the sky's share, the lambert's cap, the dapple's share on paper and on cloth. */\n readonly light: { readonly ambient: number; readonly cap: number; readonly dapple: number; readonly clothDapple: number };\n /** The shadows: σ at contact, σ per unit of height, the cast's alpha, the contact's alpha and σ. */\n readonly shadow: { readonly sigma0: number; readonly perUnit: number; readonly alpha: number; readonly contact: number; readonly contactSigma: number; readonly slopeMax: number };\n /** The paper (the notebook's baked texture): fibre, mottle, tooth, cockle. */\n readonly paper: { readonly fibre: number; readonly mottle: number; readonly tooth: number; readonly cockle: number };\n readonly cloth: { readonly pitch: number; readonly relief: number; readonly sheen: readonly [number, number] };\n /** The selection ring around the pad (CSS px). */\n readonly ring: { readonly offset: number; readonly width: number };\n /** The eye (the notebook's desk eye). */\n readonly eye: { readonly k: number; readonly min: number };\n}\n\nexport const CALENDAR: CalendarLaw = {\n sheet: { margin: 40, tape: 56, rollZone: 64, title: 136, weekdays: 40, foot: 44, radius: 3 },\n grid: { cw: 240, height: 1512, rule: 0.9, head: 1.5 },\n print: {\n numeral: { size: 30, baseline: 34, pad: 13, weight: 300 },\n title: { size: 96, baseline: 102, weight: 300, year: 200 },\n weekday: { size: 13, tracking: 0.16, weight: 600 },\n mini: { size: 10.5, pitch: 15, col: 21, gap: 44 },\n small: { size: 11, weight: 500 },\n moon: { r: 5.5, inset: 17 },\n },\n hand: { size: 23, pitch: 30, top: 44, pad: 12, time: 0.82, band: 25, rag: 5 },\n note: { size: 200, gap: 6 },\n pad: { board: 2.2, block: 10, sheet: 0.22 },\n roll: { rest: 27, tau: 0.35, turns: 1.4, tilt: 0.42, peek: 105 },\n lift: 3,\n springs: { roll: [1.25, 0.92], lift: [2.2, 0.8], ring: [4, 1], peek: [3.2, 0.8] },\n light: { ambient: 0.46, cap: 1.28, dapple: 0.35, clothDapple: 1 },\n shadow: { sigma0: 1.4, perUnit: 0.3, alpha: 0.55, contact: 0.42, contactSigma: 1.6, slopeMax: 2.2 },\n paper: { fibre: 3 / 255, mottle: 4 / 255, tooth: 0.55, cockle: 0.3 },\n cloth: { pitch: 0.9, relief: 0.35, sheen: [14, 0.07] },\n ring: { offset: 5, width: 1.5 },\n eye: { k: 1.15, min: 1250 },\n};\n\n/** The sheet's size under a law. */\nexport const sheetSize = (law: CalendarLaw): { readonly W: number; readonly H: number } => {\n const s = law.sheet;\n return { W: 2 * s.margin + 7 * law.grid.cw, H: s.tape + s.rollZone + s.title + s.weekdays + law.grid.height + s.foot };\n};\n","// The MONTH — the calendar's arithmetic (CALENDAR.md §2). Pure: no Date in the hot path. A day is an\n// integer, its DAY NUMBER (days since 1970-01-01 on the proleptic Gregorian calendar, the civil date,\n// no time zone); a month is its grid of weeks as the sheet prints it — the rows it needs (four, five\n// or six), the cells before its first and after its last; a week has its ISO number; a day may hold\n// one of the Moon's four principal phases (Meeus, *Astronomical Algorithms* ch. 49, the periodic\n// terms to 1e-4 day — a printed calendar's accuracy). Only `today` and the phases' local days touch\n// the platform's clock and time zone, and each takes them as an argument where a test needs to pin them.\n\n/** A civil date: year, month 1–12, day 1–31. */\nexport interface Ymd { readonly y: number; readonly m: number; readonly d: number }\n\n/** Days since 1970-01-01 of a civil date (Hinnant's days_from_civil). */\nexport function dayNumber(y: number, m: number, d: number): number {\n const yy = m <= 2 ? y - 1 : y;\n const era = Math.floor(yy / 400);\n const yoe = yy - era * 400;\n const mp = (m + 9) % 12;\n const doy = Math.floor((153 * mp + 2) / 5) + d - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n return era * 146097 + doe - 719468;\n}\n\n/** The civil date of a day number (Hinnant's civil_from_days). */\nexport function civil(n: number): Ymd {\n const z = n + 719468;\n const era = Math.floor(z / 146097);\n const doe = z - era * 146097;\n const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);\n const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));\n const mp = Math.floor((5 * doy + 2) / 153);\n const d = doy - Math.floor((153 * mp + 2) / 5) + 1;\n const m = mp < 10 ? mp + 3 : mp - 9;\n return { y: yoe + era * 400 + (m <= 2 ? 1 : 0), m, d };\n}\n\n/** 0 = Sunday … 6 = Saturday (1970-01-01 was a Thursday). */\nexport const weekday = (n: number): number => (((n + 4) % 7) + 7) % 7;\n\nconst pad2 = (v: number) => (v < 10 ? `0${v}` : String(v));\n/** \"2026-09-24\". */\nexport const keyOf = (n: number): string => { const c = civil(n); return `${c.y}-${pad2(c.m)}-${pad2(c.d)}`; };\n/** The day number of a \"YYYY-MM-DD\" key. */\nexport function dayOfKey(key: string): number {\n const m = /^(-?\\d+)-(\\d{1,2})-(\\d{1,2})$/.exec(key);\n if (!m) throw new Error(`calendar: not a day key: ${key}`);\n return dayNumber(Number(m[1]), Number(m[2]), Number(m[3]));\n}\n\nexport const isLeap = (y: number): boolean => (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;\nexport const daysIn = (y: number, m: number): number => (m === 2 ? (isLeap(y) ? 29 : 28) : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1] as number);\n\n/** A month as one integer (y·12 + m − 1): the pad counts months with it. */\nexport const monthIndex = (y: number, m: number): number => y * 12 + (m - 1);\nexport const monthOf = (index: number): { readonly y: number; readonly m: number } => ({ y: Math.floor(index / 12), m: (((index % 12) + 12) % 12) + 1 });\n/** The month a day falls in, as its index. */\nexport const monthOfDay = (n: number): number => { const c = civil(n); return monthIndex(c.y, c.m); };\n\nexport const MONTH_NAMES = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"] as const;\n/** Sunday first; a sheet rotates them by its week's start. */\nexport const WEEKDAY_NAMES = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"] as const;\n\n/** A month's grid as the sheet prints it: whole weeks, from the week holding the 1st to the week holding the last day. */\nexport interface MonthGrid {\n readonly y: number;\n readonly m: number;\n readonly index: number;\n /** The weekday a row starts on: 0 Sunday, 1 Monday. */\n readonly weekStart: 0 | 1;\n /** The day number of the first cell (a day of the month before, unless the 1st starts the week). */\n readonly first: number;\n /** Weeks the month spans: 4 (a February that starts the week), 5 or 6. */\n readonly rows: number;\n /** Cells before the 1st. */\n readonly lead: number;\n readonly days: number;\n}\n\nexport function monthGrid(index: number, weekStart: 0 | 1): MonthGrid {\n const { y, m } = monthOf(index);\n const one = dayNumber(y, m, 1);\n const lead = (weekday(one) - weekStart + 7) % 7;\n const days = daysIn(y, m);\n return { y, m, index, weekStart, first: one - lead, rows: Math.ceil((lead + days) / 7), lead, days };\n}\n\n/** The day number in a grid's cell. */\nexport const cellDay = (g: MonthGrid, row: number, col: number): number => g.first + row * 7 + col;\n/** Does a day belong to the grid's own month (not a neighbour's day in its first or last row)? */\nexport const inMonth = (g: MonthGrid, n: number): boolean => n >= g.first + g.lead && n < g.first + g.lead + g.days;\n/** The row and column of a day in a grid (either may fall outside it). */\nexport const cellOf = (g: MonthGrid, n: number): { readonly row: number; readonly col: number } => ({ row: Math.floor((n - g.first) / 7), col: (((n - g.first) % 7) + 7) % 7 });\n/** Is a column a weekend (Saturday or Sunday) under this grid's week? */\nexport const isWeekendCol = (g: MonthGrid, col: number): boolean => { const wd = (col + g.weekStart) % 7; return wd === 0 || wd === 6; };\n\n/** ISO 8601 week number of a day (weeks start Monday; week 1 holds the year's first Thursday). */\nexport function isoWeek(n: number): number {\n const wd = (weekday(n) + 6) % 7; // Monday 0 … Sunday 6\n const thursday = n - wd + 3;\n const { y } = civil(thursday);\n return Math.floor((thursday - dayNumber(y, 1, 1)) / 7) + 1;\n}\n\n/** The local civil day of a moment (ms since the epoch) under the platform's time zone. */\nexport function localDay(ms: number): number {\n const t = new Date(ms);\n return dayNumber(t.getFullYear(), t.getMonth() + 1, t.getDate());\n}\n/** One formatter per IANA zone asked (a zone's rules are the platform's Intl data). */\nconst zoneFormats = new Map<string, Intl.DateTimeFormat>();\n/** The civil day of a moment in the IANA zone `zone` — the calendar's CLOCK SEAM (D7); absent, the platform's own (`localDay`). */\nexport function dayIn(ms: number, zone?: string): number {\n if (zone === undefined) return localDay(ms);\n let f = zoneFormats.get(zone);\n if (f === undefined) { f = new Intl.DateTimeFormat(\"en-US\", { timeZone: zone, year: \"numeric\", month: \"numeric\", day: \"numeric\" }); zoneFormats.set(zone, f); }\n let y = 0;\n let m = 0;\n let d = 0;\n for (const part of f.formatToParts(ms)) {\n if (part.type === \"year\") y = Number(part.value);\n else if (part.type === \"month\") m = Number(part.value);\n else if (part.type === \"day\") d = Number(part.value);\n }\n return dayNumber(y, m, d);\n}\n/** Today — the platform's clock and time zone unless the caller hands its own (a pad's clock seam, D7). */\nexport const today = (ms: number = Date.now(), zone?: string): number => dayIn(ms, zone);\n\n// ---------------------------------------------------------------- the Moon\n\n/** 0 new · 1 first quarter · 2 full · 3 last quarter. */\nexport type MoonPhase = 0 | 1 | 2 | 3;\nconst RAD = Math.PI / 180;\nconst SYNODIC = 29.530588861;\n\n/** The Julian Ephemeris Day of the principal phase `k` (an integer + 0, .25, .5 or .75 — Meeus 49.1 with its periodic terms). */\nexport function phaseJde(k: number): number {\n const T = k / 1236.85;\n const T2 = T * T;\n const T3 = T2 * T;\n const T4 = T3 * T;\n let jde = 2451550.09766 + SYNODIC * k + 0.00015437 * T2 - 0.00000015 * T3 + 0.00000000073 * T4;\n const E = 1 - 0.002516 * T - 0.0000074 * T2;\n const M = (2.5534 + 29.1053567 * k - 0.0000014 * T2 - 0.00000011 * T3) * RAD;\n const Mp = (201.5643 + 385.81693528 * k + 0.0107582 * T2 + 0.00001238 * T3 - 0.000000058 * T4) * RAD;\n const F = (160.7108 + 390.67050284 * k - 0.0016118 * T2 - 0.00000227 * T3 + 0.000000011 * T4) * RAD;\n const O = (124.7746 - 1.56375588 * k + 0.0020672 * T2 + 0.00000215 * T3) * RAD;\n const s = Math.sin;\n const frac = ((k % 1) + 1) % 1;\n if (frac < 0.01 || frac > 0.99 || Math.abs(frac - 0.5) < 0.01) {\n const full = Math.abs(frac - 0.5) < 0.01;\n const c = full\n ? [-0.40614, 0.17302, 0.01614, 0.01043, 0.00734, -0.00515, 0.00209, -0.00111, -0.00057, 0.00056, -0.00042, 0.00042, 0.00038, -0.00024, -0.00017]\n : [-0.4072, 0.17241, 0.01608, 0.01039, 0.00739, -0.00514, 0.00208, -0.00111, -0.00057, 0.00056, -0.00042, 0.00042, 0.00038, -0.00024, -0.00017];\n jde += (c[0] as number) * s(Mp) + (c[1] as number) * E * s(M) + (c[2] as number) * s(2 * Mp) + (c[3] as number) * s(2 * F)\n + (c[4] as number) * E * s(Mp - M) + (c[5] as number) * E * s(Mp + M) + (c[6] as number) * E * E * s(2 * M)\n + (c[7] as number) * s(Mp - 2 * F) + (c[8] as number) * s(Mp + 2 * F) + (c[9] as number) * E * s(2 * Mp + M)\n + (c[10] as number) * s(3 * Mp) + (c[11] as number) * E * s(M + 2 * F) + (c[12] as number) * E * s(M - 2 * F)\n + (c[13] as number) * E * s(2 * Mp - M) + (c[14] as number) * s(O);\n } else {\n jde += -0.62801 * s(Mp) + 0.17172 * E * s(M) - 0.01183 * E * s(Mp + M) + 0.00862 * s(2 * Mp) + 0.00804 * s(2 * F)\n + 0.00454 * E * s(Mp - M) + 0.00204 * E * E * s(2 * M) - 0.0018 * s(Mp - 2 * F) - 0.0007 * s(Mp + 2 * F)\n - 0.0004 * s(3 * Mp) - 0.00034 * E * s(2 * Mp - M) + 0.00032 * E * s(M + 2 * F) + 0.00032 * E * s(M - 2 * F)\n - 0.00028 * E * E * s(Mp + 2 * M) + 0.00027 * E * s(2 * Mp + M) - 0.00017 * s(O);\n const c = Math.cos;\n const W = 0.00306 - 0.00038 * E * c(M) + 0.00026 * c(Mp) - 0.00002 * c(Mp - M) + 0.00002 * c(Mp + M) + 0.00002 * c(2 * F);\n jde += frac < 0.5 ? W : -W;\n }\n return jde;\n}\n\n/** A Julian Day → ms since the epoch (ΔT, about a minute, is left in: it moves no phase across a midnight that matters here). */\nexport const jdToMs = (jd: number): number => (jd - 2440587.5) * 86400000;\n\n/**\n * The principal phases whose instant falls on a day of [n0, n1] (inclusive), each on the LOCAL day\n * `dayOf` gives it (the platform's time zone unless a test pins one).\n */\nexport function phasesBetween(n0: number, n1: number, dayOf: (ms: number) => number = localDay): Map<number, MoonPhase> {\n const out = new Map<number, MoonPhase>();\n // the lunation k nearest the start (2000-01-06 is k = 0), a quarter back to be safe\n const jd0 = n0 + 2440587.5;\n let k = Math.floor(((jd0 - 2451550.1) / SYNODIC) * 4) / 4 - 0.25;\n for (let i = 0; i < 400; i++, k += 0.25) {\n const day = dayOf(jdToMs(phaseJde(k)));\n if (day > n1) break;\n if (day >= n0) out.set(day, (Math.round((((k % 1) + 1) % 1) * 4) % 4) as MoonPhase);\n }\n return out;\n}\n","// The ROLL — how a month leaves the pad and comes back (CALENDAR.md §4). Pure; `calendar.wgsl`'s\n// `cal_roll` is the same arithmetic on the GPU (the moving sheet's grid is bent in its vertex\n// shader), this is its twin for the hit test and the tests.\n//\n// A sheet is bound under the tape at its head. Rolled up, it winds into a roll that sits ON the\n// pad and travels toward the tape, laying bare the month beneath; at the tape it joins the roll of\n// the months before, which lies there always (the past). Unrolled, the last month comes off that\n// roll and is laid back down over the one showing. The roll is an Archimedean spiral: the sheet's\n// part past the TANGENT LINE (where it leaves the pad) is wound on it, its free edge innermost, each\n// turn `tau` thinner than the last, round a core sized so a whole sheet wound is exactly the roll at\n// rest — a month rolling up arrives as the roll it joins. Rolled from a corner, the tangent line\n// starts tilted (the corner lifts first) and straightens as the roll goes on.\n//\n// Sheet coordinates: x across (0 … W), s down the sheet from the tape's edge (0 … L); z up from the\n// sheet's own face. d is how far past the tangent line a point is (along the line's normal, toward\n// the free edge): d ≤ 0 lies flat, d > 0 is wound — the outer turn nearest the line.\n\nexport interface RollState {\n /** Where the tangent line crosses x = `px`, from the tape's edge (L = nothing wound). */\n readonly a: number;\n /** The line's tilt (radians): negative lifts the right-hand corner first, positive the left. */\n readonly alpha: number;\n readonly px: number;\n /** The core's radius, and how much thinner each turn is. */\n readonly r0: number;\n readonly tau: number;\n /** The sheet's free length (the tape's edge to its foot). */\n readonly L: number;\n}\n\nexport interface RollPoint {\n /** Sheet x, s and height above the sheet's face. */\n readonly x: number;\n readonly s: number;\n readonly z: number;\n /** The FRONT face's normal (the printed side): up when flat, toward the roll's axis when wound. */\n readonly nx: number;\n readonly ns: number;\n readonly nz: number;\n /** How far round the spiral (radians); 0 flat. */\n readonly phi: number;\n}\n\n/** The core that makes a whole sheet wound (tangent line at `rest`) a roll of radius `rest`. */\nexport function coreOf(rest: number, tau: number, L: number): number {\n return Math.sqrt(Math.max(rest * rest - (tau * Math.max(L - rest, 0)) / Math.PI, 1));\n}\n\n/** The radius of the roll where the wound length is D. */\nexport const radiusOf = (r0: number, tau: number, D: number): number => Math.sqrt(r0 * r0 + (tau * Math.max(D, 0)) / Math.PI);\n\n/** The roll's outer radius and its axis's place, at x (a tilted roll is a little fatter at its lifted end). */\nexport function rollAt(R: RollState, x: number): { readonly radius: number; readonly wound: number } {\n const sa = Math.sin(R.alpha);\n const ca = Math.cos(R.alpha);\n const wound = Math.max((x - R.px) * -sa + (R.L - R.a) * ca, 0);\n return { radius: radiusOf(R.r0, R.tau, wound), wound };\n}\n\n/** A sheet point (x, s) as the roll bends it. */\nexport function rollPoint(R: RollState, x: number, s: number): RollPoint {\n const sa = Math.sin(R.alpha);\n const ca = Math.cos(R.alpha);\n const d = (x - R.px) * -sa + (s - R.a) * ca;\n if (d <= 0) return { x, s, z: 0, nx: 0, ns: 0, nz: 1, phi: 0 };\n // the wound length of this fibre (to the sheet's foot), and the roll's radius there\n const D = Math.max((x - R.px) * -sa + (R.L - R.a) * ca, d);\n const Rr = radiusOf(R.r0, R.tau, D);\n // φ(d): Rφ − τφ²/4π = d (the arc length of the spiral from the tangent point)\n const phi = R.tau > 1e-6 ? ((2 * Math.PI) / R.tau) * (Rr - Math.sqrt(Math.max(Rr * Rr - (R.tau * d) / Math.PI, 0))) : d / Rr;\n const rho = Rr - (R.tau * phi) / (2 * Math.PI);\n // the line's normal toward the free edge, in (x, s)\n const nx = -sa;\n const ns = ca;\n const bx = x - d * nx;\n const bs = s - d * ns;\n const sp = Math.sin(phi);\n const cp = Math.cos(phi);\n return { x: bx + nx * rho * sp, s: bs + ns * rho * sp, z: Rr - rho * cp, nx: -nx * sp, ns: -ns * sp, nz: cp, phi };\n}\n\n/**\n * The roll for a sheet a fraction `p` of the way up (0 flat … 1 at rest against the tape), with a\n * corner's tilt `tilt0` that straightens over the first third, pivoting at the grabbed side.\n */\nexport function rollState(p: number, law: { readonly rest: number; readonly tau: number }, L: number, W: number, tilt0: number): RollState {\n const q = Math.min(Math.max(p, 0), 1);\n const a = L - q * (L - law.rest);\n const k = Math.min(Math.max(q / 0.34, 0), 1);\n const alpha = tilt0 * (1 - k * k * (3 - 2 * k));\n return { a, alpha, px: tilt0 < 0 ? W : 0, r0: coreOf(law.rest, law.tau, L), tau: law.tau, L };\n}\n\n/** Where the tangent line lies at x (the flat part's end, along s). */\nexport const tangentAt = (R: RollState, x: number): number => R.a + (x - R.px) * Math.tan(R.alpha);\n","// The PAD — the calendar as a thing on the desk (CALENDAR.md §4): its build and its static mesh. Pure.\n//\n// Pad coordinates: centred, x across, y DOWN the pad (the tape at −H/2), z up off the desk. From\n// the bottom: a chipboard back (`board`), the block of the months to come (its sheets' edges on the\n// sides), the month showing on top — the BASE sheet, one quad printed by the shader — and across the\n// head the cloth TAPE they are bound under, wrapped over the top edge. Lying on the pad under the\n// tape, always, the ROLL of the months before (roll.ts: the spiral of a whole sheet wound, at rest\n// against the tape). The sheet in motion is not here: it is a fine grid bent by the roll on the GPU\n// (`movingGrid`). The mesh uses the notebook's vertex (16 floats) and writer; its uv are SHEET\n// coordinates in world units (x from the left edge, y from the head), so the print, the paper and the\n// weave are laid the same way on every face.\n\nimport type { CalendarLaw } from \"./law\";\nimport { sheetSize } from \"./law\";\nimport { type BuiltMesh, FLAG_TWO_SIDED, type MeshWriter } from \"@ice/desk/kit\";\nimport { rollPoint, rollState } from \"./roll\";\n\n/** The materials, by the number a vertex carries. */\nexport const CMAT = { base: 0, moving: 1, past: 2, edge: 3, board: 4, tape: 5 } as const;\n\nexport interface PadFrame {\n readonly W: number;\n readonly H: number;\n /** The tape's depth down the head, and the sheet's free length below it. */\n readonly T: number;\n readonly L: number;\n /** The board's top, the pad's face (the base sheet), the moving sheet's face, the tape's top. */\n readonly zb: number;\n readonly zt: number;\n readonly zm: number;\n readonly zTape: number;\n /** The past roll's radius, and how much of its spiral is drawn (radians). */\n readonly rest: number;\n readonly turns: number;\n}\n\nexport function padFrame(law: CalendarLaw): PadFrame {\n const { W, H } = sheetSize(law);\n const T = law.sheet.tape;\n const zb = law.pad.board;\n const zt = zb + law.pad.block * law.pad.sheet;\n return { W, H, T, L: H - T, zb, zt, zm: zt + law.pad.sheet, zTape: zt + 0.5, rest: law.roll.rest, turns: law.roll.turns * 2 * Math.PI };\n}\n\n/** A sheet point (x from the left edge, s down from the tape's edge) → pad coordinates. */\nexport const padOf = (F: PadFrame, sx: number, s: number, z: number): readonly [number, number, number] => [sx - F.W / 2, -F.H / 2 + F.T + s, z];\n\n/**\n * The pad's static mesh: the board's and the block's sides, the base sheet, the tape, the past roll.\n * Rebuilt only when the law changes; the pad moves by its matrix.\n */\nexport function buildPad(m: MeshWriter, F: PadFrame, law: CalendarLaw): BuiltMesh & { readonly sheetFirst: number; readonly rollFirst: number } {\n m.reset();\n const { W, H, T, zb, zt, zm, zTape } = F;\n const x0 = -W / 2;\n const x1 = W / 2;\n const y0 = -H / 2;\n const y1 = H / 2;\n // a face: four corners (counter-clockwise seen from outside), its normal, its uv at each corner, material\n const face = (p: readonly (readonly [number, number, number])[], n: readonly [number, number, number], uv: readonly (readonly [number, number])[], mat: number, flags = 0, ao = 1) => {\n const i = p.map((q, k) => m.vert(q[0], q[1], q[2], n[0], n[1], n[2], (uv[k] as readonly [number, number])[0], (uv[k] as readonly [number, number])[1], mat, 0, flags, ao, 1, 1));\n m.quad(i[0] as number, i[1] as number, i[2] as number, i[3] as number);\n };\n // ---- the board's sides (chipboard), and the block's (the months to come, edge on)\n const sides = (za: number, zc: number, mat: number, skipHead: boolean) => {\n face([[x0, y1, za], [x1, y1, za], [x1, y1, zc], [x0, y1, zc]], [0, 1, 0], [[0, za], [W, za], [W, zc], [0, zc]], mat); // the foot\n face([[x1, y1, za], [x1, y0, za], [x1, y0, zc], [x1, y1, zc]], [1, 0, 0], [[H, za], [0, za], [0, zc], [H, zc]], mat); // the right\n face([[x0, y0, za], [x0, y1, za], [x0, y1, zc], [x0, y0, zc]], [-1, 0, 0], [[0, za], [H, za], [H, zc], [0, zc]], mat); // the left\n if (!skipHead) face([[x1, y0, za], [x0, y0, za], [x0, y0, zc], [x1, y0, zc]], [0, -1, 0], [[W, za], [0, za], [0, zc], [W, zc]], mat);\n };\n sides(0, zb, CMAT.board, false);\n sides(zb, zt, CMAT.edge, true);\n // ---- the tape: its face, its lip over the sheets, the head it wraps, its ends\n face([[x0, y0, zTape], [x1, y0, zTape], [x1, y0 + T, zTape], [x0, y0 + T, zTape]], [0, 0, 1], [[0, 0], [W, 0], [W, T], [0, T]], CMAT.tape);\n face([[x0, y0 + T, zTape], [x1, y0 + T, zTape], [x1, y0 + T, zt], [x0, y0 + T, zt]], [0, 1, 0], [[0, T], [W, T], [W, T + zTape - zt], [0, T + zTape - zt]], CMAT.tape);\n face([[x1, y0, 0], [x0, y0, 0], [x0, y0, zTape], [x1, y0, zTape]], [0, -1, 0], [[W, -zTape], [0, -zTape], [0, 0], [W, 0]], CMAT.tape);\n face([[x1, y0 + T, 0], [x1, y0, 0], [x1, y0, zTape], [x1, y0 + T, zTape]], [1, 0, 0], [[W + T, 0], [W, 0], [W, zTape], [W + T, zTape]], CMAT.tape);\n face([[x0, y0, 0], [x0, y0 + T, 0], [x0, y0 + T, zTape], [x0, y0, zTape]], [-1, 0, 0], [[0, 0], [T, 0], [T, zTape], [0, zTape]], CMAT.tape);\n // ---- the PAPER from here on (its own shader): the base sheet — the month on the pad, from under the tape's edge to the foot\n const sheetFirst = m.ni;\n face([[x0, y0 + T, zt], [x1, y0 + T, zt], [x1, y1, zt], [x0, y1, zt]], [0, 0, 1], [[0, T], [W, T], [W, H], [0, H]], CMAT.base);\n // ---- the past roll: the flat of the months rolled up, then their spiral — its outer turns (the rest is inside)\n const rollFirst = m.ni;\n const R = rollState(1, law.roll, F.L, W, 0);\n const rows: number[] = [];\n rows.push(0, R.a);\n const steps = Math.ceil((F.turns / (2 * Math.PI)) * 72);\n for (let i = 1; i <= steps; i++) {\n const phi = (F.turns * i) / steps;\n const Rr = F.rest;\n rows.push(R.a + Rr * phi - (R.tau * phi * phi) / (4 * Math.PI));\n }\n const first = m.nv;\n for (const s of rows) {\n for (const sx of [0, W]) {\n const q = rollPoint(R, sx, s);\n const [px, py, pz] = padOf(F, q.x, q.s, zm + q.z);\n m.vert(px, py, pz, q.nx, q.ns, q.nz, q.x, T + s, CMAT.past, 0, FLAG_TWO_SIDED, 1, 1, 1);\n }\n }\n m.gridQuads(first, 2, rows.length);\n return { vertices: m.v, indices: m.ix, vcount: m.nv, icount: m.ni, min: [m.min[0], m.min[1], m.min[2]], max: [m.max[0], m.max[1], m.max[2]], sheetFirst, rollFirst };\n}\n\n/** The moving sheet's grid: (u, v) in [0, 1]², `cols` × `rows` quads; the vertex shader lays it on the sheet and rolls it. */\nexport function movingGrid(cols: number, rows: number): { readonly vertices: Float32Array<ArrayBuffer>; readonly indices: Uint32Array<ArrayBuffer> } {\n const vertices = new Float32Array((cols + 1) * (rows + 1) * 2);\n let o = 0;\n for (let j = 0; j <= rows; j++) for (let i = 0; i <= cols; i++) { vertices[o++] = i / cols; vertices[o++] = j / rows; }\n const indices = new Uint32Array(cols * rows * 6);\n let k = 0;\n for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) {\n const a = j * (cols + 1) + i;\n const b = a + 1;\n const c = a + cols + 2;\n const d = a + cols + 1;\n indices[k++] = a; indices[k++] = b; indices[k++] = c; indices[k++] = a; indices[k++] = c; indices[k++] = d;\n }\n return { vertices, indices };\n}\n","// A month's SHEET — where everything on it goes (CALENDAR.md §3). Pure. Sheet coordinates are world\n// units from the sheet's top-left corner, y down the pad: the tape covers the head, the roll of the\n// months before lies under it, then the month's name, the weekdays, the grid, the foot. The grid's\n// height is fixed and a month's rows share it — four, five or six weeks, taller cells in a shorter\n// month (the \"dynamic\" layout a system calendar has, printed). A cell holds its date at the top\n// left, the week's bands in lanes under it, the day's lines, and — at its foot — the sticky note\n// stuck to that day, if one is.\n\nimport type { CalendarLaw } from \"./law\";\nimport { sheetSize } from \"./law\";\nimport { cellDay, type MonthGrid } from \"./month\";\n\nexport interface Box { readonly x: number; readonly y: number; readonly w: number; readonly h: number }\n\nexport interface SheetLayout {\n readonly W: number;\n readonly H: number;\n readonly grid: MonthGrid;\n /** The grid's top-left, a cell's size. */\n readonly x0: number;\n readonly y0: number;\n readonly cw: number;\n readonly ch: number;\n readonly rows: number;\n /** Where the title band and the weekday row start. */\n readonly titleY: number;\n readonly weekdaysY: number;\n}\n\nexport function sheetOf(g: MonthGrid, law: CalendarLaw): SheetLayout {\n const { W, H } = sheetSize(law);\n const s = law.sheet;\n const titleY = s.tape + s.rollZone;\n const weekdaysY = titleY + s.title;\n const y0 = weekdaysY + s.weekdays;\n return { W, H, grid: g, x0: s.margin, y0, cw: law.grid.cw, ch: law.grid.height / g.rows, rows: g.rows, titleY, weekdaysY };\n}\n\nexport const cellBox = (L: SheetLayout, row: number, col: number): Box => ({ x: L.x0 + col * L.cw, y: L.y0 + row * L.ch, w: L.cw, h: L.ch });\n\n/** The cell under a sheet point, with its day — or null off the grid. */\nexport function cellAt(L: SheetLayout, x: number, y: number): { readonly row: number; readonly col: number; readonly day: number } | null {\n const col = Math.floor((x - L.x0) / L.cw);\n const row = Math.floor((y - L.y0) / L.ch);\n if (col < 0 || col > 6 || row < 0 || row >= L.rows) return null;\n return { row, col, day: cellDay(L.grid, row, col) };\n}\n\n/** A day's cell on this sheet (a neighbour month's day in the first or last row counts), or null. */\nexport function dayBox(L: SheetLayout, day: number): Box | null {\n const i = day - L.grid.first;\n if (i < 0 || i >= L.rows * 7) return null;\n return cellBox(L, Math.floor(i / 7), i % 7);\n}\n\n/** Where a sticky note stuck to a day sits: centred across the cell, its foot `gap` above the cell's. */\nexport function noteSlot(L: SheetLayout, row: number, col: number, law: CalendarLaw): { readonly x: number; readonly y: number } {\n const b = cellBox(L, row, col);\n return { x: b.x + b.w / 2, y: b.y + b.h - law.note.gap - law.note.size / 2 };\n}\n\n/** How many lines of writing a cell holds (bands included) — fewer when a note hangs at its foot. */\nexport function lineCapacity(L: SheetLayout, law: CalendarLaw, noted: boolean): number {\n const h = law.hand;\n const bottom = noted ? L.ch - law.note.gap - law.note.size - 2 : L.ch - 8;\n return Math.max(0, Math.floor((bottom - h.top) / h.pitch));\n}\n\n/** The i-th line's box in a cell (a band's lane or a day's line). */\nexport function lineBox(L: SheetLayout, row: number, col: number, i: number, law: CalendarLaw): Box {\n const b = cellBox(L, row, col);\n const h = law.hand;\n return { x: b.x + h.pad, y: b.y + h.top + i * h.pitch, w: b.w - 2 * h.pad, h: h.pitch };\n}\n\n/** A band's box in its week row: from its first column to its last, in its lane. */\nexport function bandBox(L: SheetLayout, row: number, col0: number, col1: number, lane: number, law: CalendarLaw): Box {\n const h = law.hand;\n const y = L.y0 + row * L.ch + h.top + lane * h.pitch + (h.pitch - h.band) / 2;\n return { x: L.x0 + col0 * L.cw + 5, y, w: (col1 - col0 + 1) * L.cw - 10, h: h.band };\n}\n","// The desk calendar's DATA (design-015 §5.1, D-D5; D3w) — what is written on a pad and what is stuck to it are\n// ENTITIES, durable children of the pad (`ChildOf`, never members of the desk's paint order):\n//\n// - an EVENT `desk.event { start, end, text, seeds, ink }` — a line on a day, or a band across a run of days: its\n// first and last day as ISO day keys (YYYY-MM-DD, legible to an agent — the prototype held day numbers), its\n// writing and its hand's seeds (the note's encoding, D-D2c.2: base64 LE u32 per UTF-16 unit), and its ink by name\n// (a pen for a line, a highlighter for a band — the prototype's `CalEvent.ink`; the colours are the host's);\n// - a PIN `desk.pin { day }` — a note stuck to a day: a child of the pad with a durable relation `desk.pins` to the\n// note (a reified edge, the wire's precedent: strata's relations carry no data, and the day is the pin's).\n//\n// D3t-c writes both: the pen's sessions spawn and edit events (objects/calendar-writing.ts), the hand sticks and unsticks\n// notes (objects/calendar-hand.ts); here the model, its transactions for a test or an agent, where a pinned note lies\n// (`daySlot` — the lab's `slotOf`), an event as the print takes it (`calEventOf`) and the user's selection on a pad\n// (`PadSelection`, runtime). The pin's edge is DEPENDENT: a pin dies with its note.\n\nimport { ChildOf, defineComponent, definePrefab, defineRelation, type Entity, field, type GuardedTx, init, type World } from \"@ice/core\";\nimport { decodeSeeds } from \"@ice/desk/kit\";\nimport type { CalEvent } from \"./events\";\nimport { CALENDAR, type CalendarLaw } from \"./law\";\nimport { dayOfKey, keyOf, monthGrid, monthOfDay } from \"./month\";\nimport { padFrame } from \"./pad\";\nimport { noteSlot, sheetOf } from \"./sheet\";\n\n/** A pad's event: a line on a day or a band across days (`start` … `end`, inclusive ISO day keys). */\nexport const CalendarEvent = defineComponent(\"desk.event\", {\n start: field(\"string\", { default: \"\" }),\n end: field(\"string\", { default: \"\" }),\n text: field(\"string\", { default: \"\" }),\n seeds: field(\"string\", { default: \"\" }),\n ink: field(\"string\", { default: \"felt\" }),\n});\nexport const EVENT_TYPE = \"desk.event\";\nexport const EventPrefab = definePrefab(EVENT_TYPE, {\n store: \"durable\",\n version: 1,\n components: [init(CalendarEvent, { start: \"\", end: \"\", text: \"\", seeds: \"\", ink: \"felt\" })],\n relations: [ChildOf],\n});\n\n/** A note stuck to a day of a pad: the pin's day (ISO key); its note by the `PinsNote` edge. */\nexport const NotePin = defineComponent(\"desk.pin\", { day: field(\"string\", { default: \"\" }) });\n/**\n * pin → the note it holds (a reified edge: the day is the pin's cell). DEPENDENT (D3t-c — core's `defineRelation({ dependent })`):\n * the pin dies with its note in the same transaction (a stuck note deleted leaves no pin behind; one ⌘Z brings both back).\n */\nexport const PinsNote = defineRelation(\"desk.pins\", { arity: \"one\", dependent: true });\n\n/** The notes stuck to a pad, with their days (its pins' edges) — what rides with it, what goes with its months. */\nexport function pinnedNotes(world: World, pad: Entity): { readonly pin: Entity; readonly note: Entity; readonly day: string }[] {\n if (!world.isAlive(pad)) return [];\n const out: { pin: Entity; note: Entity; day: string }[] = [];\n for (const k of world.getReverse(pad, ChildOf)) {\n const p = world.get(k, NotePin);\n if (p === undefined) continue;\n const note = world.getRelation(k, PinsNote);\n if (note !== undefined && world.isAlive(note)) out.push({ pin: k, note, day: p.day ?? \"\" });\n }\n return out;\n}\nexport const PIN_TYPE = \"desk.pin\";\nexport const PinPrefab = definePrefab(PIN_TYPE, {\n store: \"durable\",\n version: 1,\n components: [init(NotePin, { day: \"\" })],\n relations: [ChildOf, PinsNote],\n});\n\n/**\n * Runtime, on a pad: the USER's selection on it (D3t-c) — a run of days (`anchor` … `focus`, day keys; \"\" none) or one entry\n * (`entry`, an event child; 0 none) — and `home`, bumped by the held bar's today (the hand then rolls home and selects today).\n * The user's fact, as `Selected` is: never in the document, a peer's selection its own. Its writers: the calendar's hand\n * (objects/calendar-hand.ts, host/calendar-input.ts) and the today tool's bump.\n */\nexport const PadSelection = defineComponent(\"desk.padSelection\", {\n anchor: field(\"string\", { default: \"\" }),\n focus: field(\"string\", { default: \"\" }),\n entry: field(\"eid\", { default: 0 as Entity }),\n home: field(\"u32\", { default: 0 }),\n});\n\n/** An event as an author states one. */\nexport interface EventSpec {\n readonly start: string;\n readonly end?: string;\n readonly text?: string;\n readonly seeds?: string;\n readonly ink?: string;\n}\n\n/** Write an event on a pad — one entity, the pad's newest child — inside the caller's transaction. */\nexport function addEvent(tx: GuardedTx, pad: Entity, s: EventSpec): Entity {\n const e = tx.spawnPrefab(EventPrefab, [init(CalendarEvent, { start: s.start, end: s.end ?? s.start, text: s.text ?? \"\", seeds: s.seeds ?? \"\", ink: s.ink ?? \"felt\" })]);\n tx.setRelation(e, ChildOf, pad);\n return e;\n}\n\n/** Stick a note to a day of a pad — the pin a child of the pad, its edge to the note — inside the caller's transaction. */\nexport function pinNote(tx: GuardedTx, pad: Entity, note: Entity, day: string): Entity {\n const e = tx.spawnPrefab(PinPrefab, [init(NotePin, { day })]);\n tx.setRelation(e, ChildOf, pad);\n tx.setRelation(e, PinsNote, note);\n return e;\n}\n\n/** A month index as its key (\"2026-09\"). */\nexport function monthKeyOf(m: number): string {\n const y = Math.floor(m / 12);\n return `${y}-${String(m - y * 12 + 1).padStart(2, \"0\")}`;\n}\n\n/** A month key (YYYY-MM) as the law's month index; undefined when it is not one. */\nexport function monthOfKey(key: string): number | undefined {\n const m = /^(\\d{4})-(\\d{2})$/.exec(key);\n if (m === null) return undefined;\n const month = Number(m[2]);\n return month >= 1 && month <= 12 ? Number(m[1]) * 12 + (month - 1) : undefined;\n}\n\n/**\n * Where a note stuck to `day` lies on a pad centred at (cx, cy) — its day's slot on the month that day is in (the\n * lab's `slotOf`; the oracle's `pinnedAt`), world units. Throws for a day off its month's sheet.\n */\nexport function daySlot(cx: number, cy: number, day: string, weekStart: 0 | 1 = 1, law: CalendarLaw = CALENDAR): { readonly x: number; readonly y: number } {\n const F = padFrame(law);\n const n = dayOfKey(day);\n if (!Number.isFinite(n) || keyOf(n) !== day) throw new Error(`desk/calendar: \"${day}\" is not a day (YYYY-MM-DD)`);\n const L = sheetOf(monthGrid(monthOfDay(n), weekStart), law);\n const k = n - L.grid.first;\n if (k < 0 || k >= L.rows * 7) throw new Error(`desk/calendar: ${day} is not on its month's sheet`);\n const s = noteSlot(L, Math.floor(k / 7), k % 7, law);\n return { x: cx - F.W / 2 + s.x, y: cy - F.H / 2 + s.y };\n}\n\n/** An event's cell as a reader takes it (a tolerant reader: a string field strata hands back as null reads as its default). */\nexport interface EventRow {\n readonly start: string | null;\n readonly end: string | null;\n readonly text: string | null;\n readonly seeds: string | null;\n readonly ink: string | null;\n}\n\n/** A day key's day number, or undefined when it is not one (YYYY-MM-DD, a real day). */\nexport function dayOr(key: string): number | undefined {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(key)) return undefined;\n const n = dayOfKey(key);\n return keyOf(n) === key ? n : undefined;\n}\n\n/** A string's 32-bit FNV-1a, as a number (an entry's own seed, its content's key). */\nfunction fnv32(s: string): number {\n let h = 0x811c9dc5 >>> 0;\n for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }\n return h | 0;\n}\n\n/**\n * An event entity as the PRINT takes it (calendar/events.ts `CalEvent`, the prototype's): its days as day numbers, its text and\n * its hand's seeds decoded, and two numbers the prototype kept on the event and the world does not (D-D3t-c.2): its own `seed`\n * — the band's wobble, the hand of a glyph with no stored seed — made from what the entry IS (its days and its ink, so it holds\n * still while the entry is written), identical on every peer; and its `rev`, a hash of its whole cell (a cell edited redraws\n * the tiles over it). Null for a cell whose days are not days.\n */\nexport function calEventOf(entity: Entity, row: EventRow): CalEvent | null {\n const startKey = row.start ?? \"\";\n const start = dayOr(startKey);\n const end = dayOr(row.end === null || row.end === \"\" ? startKey : row.end);\n if (start === undefined || end === undefined) return null;\n const text = row.text ?? \"\";\n const ink = row.ink ?? \"felt\";\n const stored = row.seeds ?? \"\";\n return {\n id: entity as number, start: Math.min(start, end), end: Math.max(start, end), text, seeds: decodeSeeds(stored),\n seed: fnv32(`${startKey}|${row.end ?? \"\"}|${ink}`), ink, rev: fnv32(`${text}\\u0000${stored}\\u0000${ink}\\u0000${startKey}\\u0000${row.end ?? \"\"}`) >>> 0,\n };\n}\n","// The PRINT's tiles (CALENDAR.md §6) — a sheet is 1760 × 1852 world units and must read crisply from a\n// glance at the whole desk to a date filling the screen, so its ink is not one raster but a PYRAMID\n// of tiles: level ℓ is drawn at 0.25·√2^ℓ texels a unit (√2 rungs, the sticky note's ladder), each\n// tile 256² texels of the sheet plus a 2-texel gutter (so a tile's bilinear edge reads its\n// neighbour's ink, not black). The shader asks for the level at or above the screen's density and\n// falls back a rung at a time to one that is resident; the coarse levels (the whole sheet in a few\n// tiles) are always kept for the sheets in play, so nothing is ever blank — only soft for a frame.\n// A tile nothing is printed in is marked empty and never drawn or stored. Pure bookkeeping: which\n// tiles a view needs, their rectangles, the page table the shader reads, a least-recently-used\n// cache of texture layers keyed by what the tile shows.\n\n/** A tile's texels of sheet, and its gutter each side. */\nexport const TILE = 256;\nexport const GUTTER = 2;\nexport const TILE_TEX = TILE + 2 * GUTTER;\n/** 0.25 … 8 texels a unit. */\nexport const LEVELS = 11;\n/** The coarsest levels kept resident for every sheet in play (the fallbacks). */\nexport const BASE_LEVELS = 3;\n/** Page-table entries: a layer, or one of these. */\nexport const MISSING = -1;\nexport const EMPTY = -2;\n\nexport const bandOf = (level: number): number => 2 ** (level / 2) / 4; // exact on the even rungs (the shader's `exp2` too)\n\n/** The level for a density (texels wanted per unit): the rung at or above it. */\nexport function levelFor(density: number): number {\n const l = Math.ceil(2 * Math.log2(Math.max(density, 1e-6) / 0.25) - 1e-6);\n return Math.min(Math.max(l, 0), LEVELS - 1);\n}\n\n/** Each level's tile counts across and down a sheet, and where its entries start in the page table. */\nexport interface TileGrid {\n readonly W: number;\n readonly H: number;\n readonly nx: readonly number[];\n readonly ny: readonly number[];\n readonly offset: readonly number[];\n /** Entries in one sheet's page table. */\n readonly count: number;\n}\n\nexport function tileGrid(W: number, H: number): TileGrid {\n const nx: number[] = [];\n const ny: number[] = [];\n const offset: number[] = [];\n let count = 0;\n for (let l = 0; l < LEVELS; l++) {\n const b = bandOf(l);\n nx.push(Math.ceil((W * b) / TILE)); ny.push(Math.ceil((H * b) / TILE));\n offset.push(count);\n count += (nx[l] as number) * (ny[l] as number);\n }\n return { W, H, nx, ny, offset, count };\n}\n\n/** A tile's rectangle on the sheet (its content, without the gutter), sheet units. */\nexport function tileRect(level: number, tx: number, ty: number): { readonly x: number; readonly y: number; readonly w: number; readonly h: number } {\n const size = TILE / bandOf(level);\n return { x: tx * size, y: ty * size, w: size, h: size };\n}\n\n/** The tiles of a level that a sheet rectangle touches (clamped to the sheet). */\nexport function tilesIn(g: TileGrid, level: number, x0: number, y0: number, x1: number, y1: number): Array<readonly [number, number]> {\n const size = TILE / bandOf(level);\n const nx = g.nx[level] as number;\n const ny = g.ny[level] as number;\n const a = Math.max(Math.floor(x0 / size), 0);\n const b = Math.min(Math.floor(x1 / size), nx - 1);\n const c = Math.max(Math.floor(y0 / size), 0);\n const d = Math.min(Math.floor(y1 / size), ny - 1);\n const out: Array<readonly [number, number]> = [];\n for (let ty = c; ty <= d; ty++) for (let tx = a; tx <= b; tx++) out.push([tx, ty]);\n return out;\n}\n\n/** A tile's page-table index within its sheet's table. */\nexport const entryOf = (g: TileGrid, level: number, tx: number, ty: number): number => (g.offset[level] as number) + ty * (g.nx[level] as number) + tx;\n\ninterface Resident { key: string; content: string; layer: number; used: number }\n\n/**\n * The texture layers the tiles live in: `layers` of them, handed out by key (which sheet, level and\n * tile) and CONTENT (what the tile shows — the keys of the cells under it); a tile whose content moved\n * is stale and draws again. When the layers run out, the one used longest ago that this frame has not\n * touched is given up.\n */\nexport class TileCache {\n readonly layers: number;\n private readonly byKey = new Map<string, Resident>();\n private readonly byLayer: (Resident | null)[];\n private frame = 0;\n constructor(layers: number) { this.layers = layers; this.byLayer = Array.from({ length: layers }, () => null); }\n\n /** A new frame: what it touches is protected from eviction until the next. */\n tick(): void { this.frame += 1; }\n\n /** The layer holding this tile with this content, or null (absent, or stale). Touches it. */\n get(key: string, content: string): number | null {\n const r = this.byKey.get(key);\n if (!r || r.content !== content) return null;\n r.used = this.frame;\n return r.layer;\n }\n\n /** Is a stale copy of the tile resident (it may be shown until the fresh one is drawn)? */\n stale(key: string): number | null {\n const r = this.byKey.get(key);\n if (!r) return null;\n r.used = this.frame;\n return r.layer;\n }\n\n /**\n * A layer for this tile (its old one, a free one, or the least-recently-used one not touched this\n * frame), and the key of the tile it evicted (a page table pointing at it must forget it); null when\n * every layer is in use this frame.\n */\n put(key: string, content: string): { readonly layer: number; readonly evicted: string | null } | null {\n const old = this.byKey.get(key);\n if (old) { old.content = content; old.used = this.frame; return { layer: old.layer, evicted: null }; }\n let best = -1;\n let bestUsed = Number.POSITIVE_INFINITY;\n for (let i = 0; i < this.layers; i++) {\n const r = this.byLayer[i];\n if (!r) { best = i; break; }\n if (r.used < this.frame && r.used < bestUsed) { best = i; bestUsed = r.used; }\n }\n if (best < 0) return null;\n const prev = this.byLayer[best];\n if (prev) this.byKey.delete(prev.key);\n const r: Resident = { key, content, layer: best, used: this.frame };\n this.byLayer[best] = r;\n this.byKey.set(key, r);\n return { layer: best, evicted: prev ? prev.key : null };\n }\n\n /** Forget every tile whose key starts with `prefix` (a calendar gone, a style changed). */\n drop(prefix: string): void {\n for (const [k, r] of this.byKey) if (k.startsWith(prefix)) { this.byKey.delete(k); this.byLayer[r.layer] = null; }\n }\n\n get size(): number { return this.byKey.size; }\n}\n","// The calendar pass's GPU records, declared once (`defineStruct`). `CalUniforms` is the pass's knobs,\n// the desk eye and the print's tile pyramid (its counts per level); `CalPad` is one calendar: its\n// placement, its lamp, its build, the roll of the sheet in motion, the two sheets in play (the one\n// on the pad — BASE — and the one rolling — MOVING: their grids, their tile tables), the marks the\n// host draws on the sheet (the days selected, the entry selected, the caret, the newest glyph's wipe,\n// the day a note would stick to) and its palette. The camera, the light and the gobo arrive through\n// the mat's block (`MatUniforms`), as for the notebook — the pad is lit like the mat it lies on.\n\nimport { defineStruct } from \"@ice/desk/engine\";\nimport type { RGB } from \"@ice/desk\";\nimport type { CalendarLaw } from \"./law\";\nimport { GUTTER, LEVELS, TILE, TILE_TEX, type TileGrid } from \"./tiles\";\n\nexport const CalUniforms = defineStruct(\"CalUniforms\", [\n [\"eye\", \"vec4f\"], // the desk eye: foot x, y (world), height (world), zoom\n [\"view\", \"vec4f\"], // viewport w, h (CSS px), the depth range's near and far\n [\"light\", \"vec4f\"], // the sky's share, the lambert's cap, the dapple's share on paper, on cloth\n [\"shadow\", \"vec4f\"], // σ at contact, σ per unit of height, the cast's alpha on the mat, the contact's alpha\n [\"shadow2\", \"vec4f\"], // the contact's σ, unused, unused, dpr\n [\"paper\", \"vec4f\"], // fibre, mottle, tooth, cockle\n [\"cloth\", \"vec4f\"], // the weave's pitch, its relief, the sheen's exponent and strength\n [\"castCol\", \"vec4f\"], // what a shadow is made of on this ground\n [\"select\", \"vec4f\"], // the ring's colour, its width (CSS px)\n [\"ring\", \"vec4f\"], // the ring's offset (CSS px), the debug bits, the rule's width, the heading rule's width (world)\n [\"alpha\", \"vec4f\"], // the rules, the heading rule, the weekend's wash, a neighbour month's wash\n [\"tiles\", \"vec4f\"], // entries in one sheet's table, a tile's texels, its gutter, its texture's side\n [\"tileNx\", \"array<vec4f, 3>\"], // tiles across a sheet, by level (11)\n [\"tileNy\", \"array<vec4f, 3>\"], // tiles down\n [\"tileOff\", \"array<vec4f, 3>\"], // where a level's entries start in a sheet's table\n] as const);\n\nexport const CalPad = defineStruct(\"CalPad\", [\n [\"model\", \"mat4x4f\"], // pad → world\n [\"inv\", \"mat4x4f\"], // world → pad\n [\"lamp\", \"vec4f\"], // the unit direction to the lamp (world), unused\n [\"size\", \"vec4f\"], // the sheet's W, H; the tape's depth T; the free length L = H − T\n [\"z\", \"vec4f\"], // the board's top, the pad's face (the base sheet), the moving sheet's face, the tape's top\n [\"roll\", \"vec4f\"], // the moving sheet: its tangent line's a, tilt α, pivot x; the core's radius\n [\"roll2\", \"vec4f\"], // τ (a turn's thinning), the turns drawn (radians), a sheet is moving (0/1), the past roll's radius\n [\"gridA\", \"vec4f\"], // the BASE sheet's grid: x0, y0, a cell's w, h\n [\"gridB\", \"vec4f\"], // … its rows, its weekend columns (a bit mask), the cells before the 1st, the month's days\n [\"gridC\", \"vec4f\"], // the MOVING sheet's grid, the same\n [\"gridD\", \"vec4f\"],\n [\"slots\", \"vec4f\"], // the base's and the moving sheet's tile tables (−1 = none), the sheet the marks are on (0 base, 1 moving), the ring's presence\n [\"sel\", \"array<vec4f, 6>\"], // the days selected: up to six boxes (a range, a box a week), x0 y0 x1 y1 on the sheet\n [\"mark\", \"vec4f\"], // the entry selected: its box\n [\"drop\", \"vec4f\"], // the day a note held over the pad would stick to\n [\"caret\", \"vec4f\"], // the pen's caret: x, top, bottom, its width (0 = hidden)\n [\"wipe\", \"vec4f\"], // the newest glyph's box\n [\"wipe2\", \"vec4f\"], // its progress (0 … 1; ≥ 1 = none), a seed, the lift, how many of `sel` are boxes\n [\"recv\", \"vec4f\"], // the mat's rect this pad darkens (world)\n [\"col0\", \"vec4f\"], [\"col1\", \"vec4f\"], [\"col2\", \"vec4f\"], [\"col3\", \"vec4f\"], [\"col4\", \"vec4f\"],\n [\"col5\", \"vec4f\"], [\"col6\", \"vec4f\"], [\"col7\", \"vec4f\"], [\"col8\", \"vec4f\"],\n] as const);\n\nexport const MAX_CALENDARS = 4;\n/** Two sheets in play per calendar: its base's table and its moving sheet's. */\nexport const TABLE_SLOTS = MAX_CALENDARS * 2;\n\n/** A calendar's colours, as the pass takes them (lab/theme.ts `calendarLook`). */\nexport interface CalendarColours {\n readonly paper: RGB; readonly ink: RGB; readonly muted: RGB; readonly weekend: RGB; readonly hot: RGB;\n readonly chipboard: RGB; readonly cloth: RGB; readonly foil: RGB;\n /** The pen the caret is drawn in. */\n readonly pen: RGB;\n}\n\nconst pad4 = (a: readonly number[], n: number): number[] => { const o = a.slice(0, n); while (o.length < n) o.push(0); return o; };\n\n/** The pass's knobs by name. */\nexport function calUniformValues(law: CalendarLaw, eye: { eye: number[]; view: number[] }, dpr: number, cast: RGB, select: RGB, alpha: { readonly rule: number; readonly head: number; readonly weekend: number; readonly outside: number }, grid: TileGrid, debug: number) {\n return {\n eye: eye.eye, view: eye.view,\n light: [law.light.ambient, law.light.cap, law.light.dapple, law.light.clothDapple],\n shadow: [law.shadow.sigma0, law.shadow.perUnit, law.shadow.alpha, law.shadow.contact],\n shadow2: [law.shadow.contactSigma, 0, 0, dpr],\n paper: [law.paper.fibre, law.paper.mottle, law.paper.tooth, law.paper.cockle],\n cloth: [law.cloth.pitch, law.cloth.relief, law.cloth.sheen[0], law.cloth.sheen[1]],\n castCol: [...cast, 1],\n select: [...select, law.ring.width],\n ring: [law.ring.offset, debug, law.grid.rule, law.grid.head],\n alpha: [alpha.rule, alpha.head, alpha.weekend, alpha.outside],\n tiles: [grid.count, TILE, GUTTER, TILE_TEX],\n tileNx: pad4(grid.nx, 12), tileNy: pad4(grid.ny, 12), tileOff: pad4(grid.offset, 12),\n };\n}\n\nvoid LEVELS;\n","// The CALENDAR pass — desk pads drawn beneath everything else on the desk (CALENDAR.md §6). Like the\n// notebook's, it draws into its own LAYER (4× multisampled colour + depth, then resolved): the pads'\n// meshes (the sheet in motion bent by the roll in its vertex shader), then the mat under each (its\n// shadow, its contact, its ring) wherever the pad does not cover it. Unlike the notebook's, the layer\n// is not laid over the frame afterwards: the host renders it first (`renderLayer`, its own command\n// buffer) and the ground lays it on the mat inside its own pass, right after the field\n// (`underlay()` — ground.ts `underlays`), so the cards, the notes, the boards and the notebooks all lie\n// ON the calendar: a sticky note stuck to a day is drawn over its paper by the paper pass, casting on it.\n//\n// As a kind of the desk's registry (kinds/calendar.ts; design-015 D3r-b) the layer is recorded into the\n// frame's own encoder after the mat's wind (`layer`) and laid as the pads stratum's one run (`composite`)\n// — the underlay's own draw, where the underlay lay: right after the mat, beneath everything else.\n//\n// The print is a pyramid of tiles (tiles.ts) in a texture array; the host draws them (Canvas 2D) and\n// hands them over with `uploadTile`, and writes each sheet's page table with `writeTable`. The pads'\n// shadows are analytic (a slab on the mat, a roll on the paper): no shadow map is drawn.\n\nimport { bindGroup, bindLayout, storageBuffer, uniformBuffer, compile, compose } from \"@ice/desk/engine\";\nimport type { RenderTarget, RGB } from \"@ice/desk\";\nimport { type FadeIn, type View, type MatConfig, type MatFrame, MatUniforms, type MatPass, DAY_LIGHT, type MatLight, type DeskEye, eyeValues, project, NbBook, NbUniforms, type BuiltMesh, VERTEX_BYTES, inverseOf, matrixOf, type Rigid, worldBounds, PAPER_TEX, paperTexture, generateMips, mipCount, sentBytes, writeChanged, attachmentOf, BoxTargets, layerCompositeLayout } from \"@ice/desk/kit\";\nimport type { CalendarLaw } from \"./law\";\nimport { CalPad, type CalendarColours, CalUniforms, calUniformValues, MAX_CALENDARS, TABLE_SLOTS } from \"./layout\";\nimport { movingGrid, type PadFrame } from \"./pad\";\nimport type { RollState } from \"./roll\";\nimport type { CalendarShaders } from \"./shaders\";\nimport { MISSING, TILE_TEX, type TileGrid } from \"./tiles\";\n\nconst SAMPLES = 4;\nconst BLEND_PREMUL: GPUBlendState = {\n color: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n alpha: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n};\n/** The moving sheet's grid: fine enough down the sheet that a turn of the roll is ~40 facets. */\nconst GRID_COLS = 96;\nconst GRID_ROWS = 220;\n\n/** A box on a sheet, x0 y0 x1 y1 (sheet units); absent = none. */\nexport type SheetBox = readonly [number, number, number, number];\n\n/** One sheet in play: where its grid is printed and which rows and days it has, and its tile table. */\nexport interface SheetDraw {\n readonly x0: number; readonly y0: number; readonly cw: number; readonly ch: number;\n readonly rows: number;\n /** Bit c set: column c is a weekend. */\n readonly weekends: number;\n readonly lead: number;\n readonly days: number;\n /** Its page table's slot (0 … TABLE_SLOTS − 1). */\n readonly slot: number;\n}\n\n/** One calendar as the pass draws it this frame. */\nexport interface CalendarDraw {\n readonly id: number;\n readonly frame: PadFrame;\n /** The pad's static mesh (pad.ts `buildPad`: its solid parts, then from `sheetFirst` its paper), and its version — the upload's key. */\n readonly mesh: BuiltMesh & { readonly sheetFirst: number; readonly rollFirst: number };\n readonly version: number;\n readonly rigid: Rigid;\n /** The unit direction toward the lamp (world). */\n readonly lamp: readonly [number, number, number];\n readonly lift: number;\n /** The ring's presence, 0 … 1. */\n readonly ring: number;\n readonly base: SheetDraw;\n /** The sheet in motion and its roll, or none. */\n readonly moving: SheetDraw | null;\n readonly roll: RollState | null;\n /** Which sheet the host's marks are on: 0 the base, 1 the moving sheet. */\n readonly marksOn: 0 | 1;\n readonly sel: readonly SheetBox[];\n readonly mark: SheetBox | null;\n readonly drop: SheetBox | null;\n /** The caret: x, top, bottom, width — or none. */\n readonly caret: readonly [number, number, number, number] | null;\n /** The newest glyph's box and its progress (0 … 1). */\n readonly wipe: { readonly box: SheetBox; readonly t: number } | null;\n readonly colours: CalendarColours;\n /** The look's print presences — the pass's fallback where no host set its own (a record made without the desk's local: a tray specimen, K5a). */\n readonly alpha?: { readonly rule: number; readonly head: number; readonly weekend: number; readonly outside: number };\n}\n\ninterface PadBuffers { vb: GPUBuffer; ib: GPUBuffer; vcap: number; icap: number; version: number; icount: number; sheetFirst: number; rollFirst: number; seen: number }\n\n/**\n * What one RENDER TARGET keeps between its prepares (D7) — as the notebook's (notebook/pass.ts `NbTarget`): the layer's targets at its\n * size, the pads' meshes it drew, its frame count, this prepare's pads, their screen extent and scissor, its stats; the held desk\n * copy's apart from the frame's, so a held frame's two prepares never undo each other.\n */\ninterface CalTarget {\n /** The layer's targets at the pads' screen box (K7a, kit/layer.ts `BoxTargets`). */\n readonly layer: BoxTargets;\n readonly buffers: Map<number, PadBuffers>;\n /** Turns over whenever one of this target's meshes is uploaded (K7a: a layer drawn from other meshes is drawn again). */\n meshGen: number;\n list: CalendarDraw[];\n frameNo: number;\n screen: { x0: number; y0: number; x1: number; y1: number } | null;\n scissor: readonly [number, number, number, number] | null;\n stats: CalendarStats;\n}\n\nconst calTarget = (layer: BoxTargets): CalTarget => ({ layer, buffers: new Map(), meshGen: 0, list: [], frameNo: 0, screen: null, scissor: null, stats: { calendars: 0, moving: 0 } });\n\n/** The tiles' stand-in before the first tile: one texel, one layer. */\nconst noTiles = (device: GPUDevice): GPUTexture => device.createTexture({ label: \"calendar/print tiles (none yet)\", size: [1, 1, 1], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING });\n\nfunction dropTarget(t: CalTarget): void {\n for (const b of t.buffers.values()) { b.vb.destroy(); b.ib.destroy(); }\n t.buffers.clear();\n t.layer.dispose();\n}\n\nexport interface CalendarStats { readonly calendars: number; readonly moving: number }\n\nexport class CalendarPass {\n readonly name = \"calendar/pads\";\n /** Tile layers in the print's texture array. */\n readonly layers: number;\n private readonly device: GPUDevice;\n private readonly mat: MatPass;\n private readonly knobs = CalUniforms.alloc(1);\n private readonly records = CalPad.alloc(MAX_CALENDARS);\n /** What the GPU holds of the records: a prefix is written only when it changed (K4a). */\n private readonly recordsSent = sentBytes(CalPad.size * MAX_CALENDARS);\n private readonly knobBuf: GPUBuffer;\n /** What the GPU holds of the knobs: they are written only when they change (K4a — a standing value costs a frame nothing). */\n private readonly knobsSent = sentBytes(CalUniforms.size);\n private readonly recordBuf: GPUBuffer;\n private tableBuf: GPUBuffer;\n private readonly layoutMain: GPUBindGroupLayout;\n private readonly layoutComp: GPUBindGroupLayout;\n private readonly facePipe: GPURenderPipeline;\n private readonly sheetPipe: GPURenderPipeline;\n private readonly solidPipe: GPURenderPipeline;\n private readonly movingPipe: GPURenderPipeline;\n private readonly recvPipe: GPURenderPipeline;\n private readonly compPipe: GPURenderPipeline;\n private readonly goboSampler: GPUSampler;\n private readonly noiseSampler: GPUSampler;\n private readonly tileSampler: GPUSampler;\n private readonly paperSampler: GPUSampler;\n /** The print tiles: a placeholder until the first tile is laid (K6a — a desk with no calendar holds none of their 41 MB). */\n private tileTex: GPUTexture;\n private tilesReady = false;\n /** When a pad was last drawn: its layer targets are let go once none was for a while (the kind's tick — K6a, D-K6a.3). */\n private drawnAt = Number.NEGATIVE_INFINITY;\n private readonly paperTex: GPUTexture;\n private readonly gridVb: GPUBuffer;\n private readonly gridIb: GPUBuffer;\n private readonly gridCount: number;\n private mainGroup!: GPUBindGroup;\n private boundAssets = -1;\n /**\n * The pass whose PRINT this one samples — its own, or (K5b) the root's: a slot that made its own calendar pass (the tray's specimen)\n * reads the root's tile texture and page tables, where the desk's pads print (their local writes the root pass), never a copy.\n */\n private print: CalendarPass = this;\n private boundTiles: GPUTexture | null = null;\n private boundTable: GPUBuffer | null = null;\n /** The frame's target (the canvas; the hand) and the held desk copy's, apart (D7) — `t` the one this prepare is for (`use`). */\n private readonly frameT: CalTarget;\n private copyT: CalTarget | null = null;\n private t: CalTarget;\n private tableCount = 0;\n /** The records the last prepare turned away at the pass's cap — not drawn; the ground reports them (`GroundStats.dropped`, D7). */\n dropped = 0;\n /** Profiling switches: 2 no print or paper detail · 4 no gobo · 8 no rolls' shade · 16 no layer on the mat · 32 no marks · 64 no tiles · 128 no mat under it · 256 no moving sheet · 512 flat colour. */\n debug = 0;\n /**\n * Turns over at every pass-wide resource a layer reads changing (K7a) — a tile, a page table, the main group made again: with the\n * target's meshes' generation, the silhouette's key, what the pass lists and the box — and by CONTENT the knobs, the records and the\n * slot's view block — what a target's layer is laid again by, undrawn (`BoxTargets.holds`).\n */\n private gen = 0;\n private readonly sig = new Float64Array(8);\n private readonly read: Uint8Array[] = [];\n /** Layers drawn and laid again undrawn since the pass was made (a witness). */\n private layerDraws = 0;\n private layerKept = 0;\n\n private constructor(device: GPUDevice, mat: MatPass, layers: number, pipes: { layoutMain: GPUBindGroupLayout; layoutComp: GPUBindGroupLayout; face: GPURenderPipeline; sheet: GPURenderPipeline; solid: GPURenderPipeline; moving: GPURenderPipeline; recv: GPURenderPipeline; comp: GPURenderPipeline }) {\n this.device = device; this.mat = mat; this.layers = layers;\n this.layoutMain = pipes.layoutMain; this.layoutComp = pipes.layoutComp;\n this.facePipe = pipes.face; this.sheetPipe = pipes.sheet; this.solidPipe = pipes.solid; this.movingPipe = pipes.moving; this.recvPipe = pipes.recv; this.compPipe = pipes.comp;\n this.frameT = calTarget(new BoxTargets(device, \"calendar\", this.layoutComp, SAMPLES, mat.view));\n this.t = this.frameT;\n this.knobBuf = uniformBuffer(device, CalUniforms.size, \"calendar/knobs\");\n this.recordBuf = storageBuffer(device, CalPad.size * MAX_CALENDARS, \"calendar/pads\");\n this.tableBuf = device.createBuffer({ label: \"calendar/tile tables\", size: 16, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });\n this.goboSampler = device.createSampler({ label: \"calendar/gobo\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" });\n this.noiseSampler = device.createSampler({ label: \"calendar/noise\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\" });\n this.tileSampler = device.createSampler({ label: \"calendar/tiles\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" });\n this.tileTex = noTiles(device);\n this.paperTex = device.createTexture({ label: \"calendar/paper\", size: [PAPER_TEX, PAPER_TEX], format: \"rgba8unorm\", mipLevelCount: mipCount(PAPER_TEX, PAPER_TEX), usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });\n device.queue.writeTexture({ texture: this.paperTex }, paperTexture(), { bytesPerRow: PAPER_TEX * 4 }, [PAPER_TEX, PAPER_TEX, 1]);\n generateMips(device, this.paperTex);\n this.paperSampler = device.createSampler({ label: \"calendar/paper\", magFilter: \"linear\", minFilter: \"linear\", mipmapFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\", maxAnisotropy: 8 });\n const g = movingGrid(GRID_COLS, GRID_ROWS);\n this.gridVb = device.createBuffer({ label: \"calendar/moving grid\", size: g.vertices.byteLength, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });\n this.gridIb = device.createBuffer({ label: \"calendar/moving grid indices\", size: g.indices.byteLength, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST });\n device.queue.writeBuffer(this.gridVb, 0, g.vertices);\n device.queue.writeBuffer(this.gridIb, 0, g.indices);\n this.gridCount = g.indices.length;\n this.rebind();\n }\n\n static async create(device: GPUDevice, format: GPUTextureFormat, src: CalendarShaders, mat: MatPass, layers = 160): Promise<CalendarPass> {\n const layoutMain = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 2, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n { binding: 3, stages: [\"fragment\"], texture: \"float\" },\n { binding: 4, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 5, stages: [\"fragment\"], texture: \"float\" },\n { binding: 6, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 7, stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" },\n { binding: 8, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 9, stages: [\"fragment\"], buffer: \"read-only-storage\" },\n { binding: 10, stages: [\"fragment\"], texture: \"float\" },\n { binding: 11, stages: [\"fragment\"], sampler: \"filtering\" },\n ], \"calendar/main\");\n // the layer, its box's origin (K7a — kit/layer.ts `BoxTargets`: the composite reads a pixel's texel at the pixel less it) and the\n // slot's view block — the composite lays the layer through the slot's portal chain (design-018 §4: the kit's contract, as one)\n const layoutComp = layerCompositeLayout(device, \"calendar/composite\");\n const module = await compile(device, compose(src.program));\n const compModule = await compile(device, compose(src.composite));\n const vertexLayout: GPUVertexBufferLayout = {\n arrayStride: VERTEX_BYTES,\n attributes: [\n { shaderLocation: 0, offset: 0, format: \"float32x3\" },\n { shaderLocation: 1, offset: 12, format: \"float32x3\" },\n { shaderLocation: 2, offset: 24, format: \"float32x2\" },\n { shaderLocation: 3, offset: 32, format: \"float32x4\" },\n { shaderLocation: 4, offset: 48, format: \"float32x2\" },\n { shaderLocation: 5, offset: 56, format: \"float32x2\" },\n ],\n };\n const mainLayout = device.createPipelineLayout({ bindGroupLayouts: [layoutMain] });\n const depthStencil: GPUDepthStencilState = { format: \"depth24plus\", depthWriteEnabled: true, depthCompare: \"less\" };\n const [face, sheet, solid, moving, recv, comp] = await Promise.all([\n device.createRenderPipelineAsync({\n label: \"calendar/face\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_pad\", buffers: [vertexLayout] },\n fragment: { module, entryPoint: \"fs_face\", targets: [{ format: \"rgba8unorm\" }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil, multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"calendar/paper\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_pad\", buffers: [vertexLayout] },\n fragment: { module, entryPoint: \"fs_sheet\", targets: [{ format: \"rgba8unorm\" }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil, multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"calendar/solid\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_pad\", buffers: [vertexLayout] },\n fragment: { module, entryPoint: \"fs_solid\", targets: [{ format: \"rgba8unorm\" }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil, multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"calendar/moving\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_moving\", buffers: [{ arrayStride: 8, attributes: [{ shaderLocation: 0, offset: 0, format: \"float32x2\" }] }] },\n fragment: { module, entryPoint: \"fs_sheet\", targets: [{ format: \"rgba8unorm\" }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil, multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"calendar/mat\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_recv\" },\n fragment: { module, entryPoint: \"fs_recv\", targets: [{ format: \"rgba8unorm\", blend: BLEND_PREMUL }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil: { format: \"depth24plus\", depthWriteEnabled: false, depthCompare: \"less\" },\n multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"calendar/composite\", layout: device.createPipelineLayout({ bindGroupLayouts: [layoutComp] }),\n vertex: { module: compModule, entryPoint: \"vs\" },\n fragment: { module: compModule, entryPoint: \"fs\", targets: [{ format, blend: BLEND_PREMUL }] },\n primitive: { topology: \"triangle-list\" },\n }),\n ]);\n return new CalendarPass(device, mat, layers, { layoutMain, layoutComp, face, sheet, solid, moving, recv, comp });\n }\n\n private rebind(): void {\n const p = this.print;\n if (this.boundAssets === this.mat.assetVersion && this.boundTiles === p.tileTex && this.boundTable === p.tableBuf) return;\n this.mainGroup = bindGroup(this.device, this.layoutMain, [\n this.mat.view, this.knobBuf, this.recordBuf, this.mat.silhouette, this.goboSampler, this.mat.noiseTexture.createView(), this.noiseSampler,\n p.tileTex.createView({ dimension: \"2d-array\" }), this.tileSampler, p.tableBuf, this.paperTex.createView(), this.paperSampler,\n ], \"calendar/main\");\n this.boundAssets = this.mat.assetVersion;\n this.boundTiles = p.tileTex;\n this.boundTable = p.tableBuf;\n this.gen += 1;\n }\n\n /** Sample `root`'s print — its tiles and page tables — rather than this pass's own (K5b: the tray's specimen reads the desk's print). */\n sharePrintOf(root: CalendarPass): void {\n if (this.print === root) return;\n this.print = root;\n this.rebind();\n }\n\n /** Size the page tables for a sheet's tile grid (every table the same); re-makes the buffer, all entries missing. */\n private fitTables(grid: TileGrid): void {\n if (this.tableCount === grid.count) return;\n this.tableBuf.destroy();\n this.tableBuf = this.device.createBuffer({ label: \"calendar/tile tables\", size: grid.count * TABLE_SLOTS * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });\n this.device.queue.writeBuffer(this.tableBuf, 0, new Int32Array(grid.count * TABLE_SLOTS).fill(MISSING));\n this.tableCount = grid.count;\n this.boundAssets = -1;\n this.rebind();\n }\n\n /**\n * The page tables let go (the desk has no pad — K7a, found by rig:stress: 227 KB of tables stood after the last pad left, the\n * calendar kind over its 1 MB \"none on the desk\" line): the 16-byte stand-in again; the next sheet's grid makes them afresh.\n */\n releaseTables(): void {\n if (this.tableCount === 0) return;\n this.tableBuf.destroy();\n this.tableBuf = this.device.createBuffer({ label: \"calendar/tile tables\", size: 16, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });\n this.tableCount = 0;\n this.boundAssets = -1;\n this.rebind();\n }\n\n /** A sheet's page table (a layer per tile, or MISSING / EMPTY), into its slot. */\n writeTable(slot: number, grid: TileGrid, table: Int32Array): void {\n this.fitTables(grid);\n this.device.queue.writeBuffer(this.tableBuf, slot * grid.count * 4, table.buffer, table.byteOffset, grid.count * 4);\n this.gen += 1;\n }\n\n /** The tiles' texture, made on the first tile laid (K6a). */\n private tiles(): GPUTexture {\n if (!this.tilesReady) {\n this.tileTex.destroy();\n this.tileTex = this.device.createTexture({ label: \"calendar/print tiles\", size: [TILE_TEX, TILE_TEX, this.layers], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });\n this.tilesReady = true;\n this.boundAssets = -1;\n this.rebind();\n }\n return this.tileTex;\n }\n\n /** What the tiles hold on the device: 0 before the first tile and after `releaseTiles`. */\n get tileBytes(): number { return this.tilesReady ? this.layers * TILE_TEX * TILE_TEX * 4 : 0; }\n\n /** The tiles let go (the desk has no pad): the placeholder again; the kind's tile cache starts afresh. */\n releaseTiles(): void {\n if (!this.tilesReady) return;\n this.tileTex.destroy();\n this.tileTex = noTiles(this.device);\n this.tilesReady = false;\n this.boundAssets = -1;\n this.rebind();\n }\n\n /** A tile's raster (the host's canvas, TILE_TEX², straight alpha) into its layer. */\n uploadTile(layer: number, source: HTMLCanvasElement | OffscreenCanvas): void {\n this.device.queue.copyExternalImageToTexture({ source, origin: { x: 0, y: 0 } }, { texture: this.tiles(), origin: { x: 0, y: 0, z: layer }, premultipliedAlpha: false }, [TILE_TEX, TILE_TEX]);\n this.gen += 1;\n }\n\n /** A tile's COMMITTED raster (RGBA bytes, TILE_TEX² × 4, straight alpha, row 0 at the top) into its layer — a host with no canvas (the Node oracle; D3t-c). */\n writeTileBytes(layer: number, bytes: Uint8Array<ArrayBuffer>): void {\n if (bytes.byteLength !== TILE_TEX * TILE_TEX * 4) throw new Error(`calendar: a tile is ${TILE_TEX}² RGBA (${TILE_TEX * TILE_TEX * 4} bytes), not ${bytes.byteLength}`);\n this.device.queue.writeTexture({ texture: this.tiles(), origin: { x: 0, y: 0, z: layer } }, bytes, { bytesPerRow: TILE_TEX * 4, rowsPerImage: TILE_TEX }, [TILE_TEX, TILE_TEX, 1]);\n this.gen += 1;\n }\n\n\n /** Was a pad drawn within the last `ms`? */\n drawnWithin(ms: number): boolean { return performance.now() - this.drawnAt < ms; }\n /** When the layer was last drawn (`performance.now()`; -Infinity before the first) — the kind's registered wake lets it go LAYER_IDLE_MS after (K7a). */\n get lastDrawn(): number { return this.drawnAt; }\n\n /** Is the frame's layer made? */\n get layerMade(): boolean { return this.frameT.layer.made; }\n /** The layers drawn and the ones laid again undrawn (nothing they are drawn from moved) since the pass was made (K7a). */\n get layerFrames(): { readonly drawn: number; readonly kept: number } { return { drawn: this.layerDraws, kept: this.layerKept }; }\n\n /**\n * Every mesh on the device given back — the frame's and the held copy's (K7a: the desk has none of this kind's objects left, and\n * no prepare will come to sweep the ones it no longer lists).\n */\n releaseMeshes(): void {\n for (const t of [this.frameT, this.copyT]) {\n if (t === null) continue;\n for (const b of t.buffers.values()) { b.vb.destroy(); b.ib.destroy(); }\n t.buffers.clear();\n }\n }\n\n /** The frame's layer targets let go (no pad drawn for a while, or none on the desk): made again at the next pad drawn. */\n releaseLayer(): void { this.frameT.layer.release(); }\n\n private upload(d: CalendarDraw): PadBuffers {\n let b = this.t.buffers.get(d.id);\n const vbytes = d.mesh.vcount * VERTEX_BYTES;\n const ibytes = d.mesh.icount * 4;\n if (!b || b.vcap < vbytes || b.icap < ibytes) {\n b?.vb.destroy(); b?.ib.destroy();\n const vcap = Math.max(vbytes, 4096);\n const icap = Math.max(ibytes, 4096);\n b = {\n vb: this.device.createBuffer({ label: `calendar/${d.id} vertices`, size: (vcap + 3) & ~3, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }),\n ib: this.device.createBuffer({ label: `calendar/${d.id} indices`, size: (icap + 3) & ~3, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST }),\n vcap, icap, version: -1, icount: 0, sheetFirst: 0, rollFirst: 0, seen: 0,\n };\n this.t.buffers.set(d.id, b);\n }\n if (b.version !== d.version) {\n this.device.queue.writeBuffer(b.vb, 0, d.mesh.vertices.buffer, d.mesh.vertices.byteOffset, vbytes);\n this.device.queue.writeBuffer(b.ib, 0, d.mesh.indices.buffer, d.mesh.indices.byteOffset, ibytes);\n b.version = d.version; b.icount = d.mesh.icount; b.sheetFirst = d.mesh.sheetFirst; b.rollFirst = d.mesh.rollFirst;\n this.t.meshGen += 1;\n }\n b.seen = this.t.frameNo;\n return b;\n }\n\n /**\n * This frame's calendars: the mat's block, the knobs and the eye, each pad's record (placement, lamp,\n * roll, sheets, marks, palette), its mesh. Returns how many will draw.\n */\n // biome-ignore lint/style/useDefaultParameterLast: the prototype's signature, moved verbatim — dropping the default would change what an explicit `undefined` means (design-015 D1)\n prepare(view: View & { readonly dpr: number }, fadeIn: FadeIn, cfg: MatConfig, frame: MatFrame | undefined, light: MatLight = DAY_LIGHT, eye: DeskEye, law: CalendarLaw, grid: TileGrid, colours: { readonly cast: RGB; readonly select: RGB; readonly alpha: { readonly rule: number; readonly head: number; readonly weekend: number; readonly outside: number } }, calendars: readonly CalendarDraw[]): number {\n this.fitTables(grid);\n this.rebind();\n this.t.frameNo += 1;\n const reach = (d: CalendarDraw) => 3 * (law.shadow.sigma0 + law.shadow.perUnit * (d.frame.zTape + d.lift)) + 2.2 * (d.frame.zTape + d.lift) + (law.ring.offset + law.ring.width * 2 + 2) / Math.max(eye.zoom, 1e-6);\n const onScreen = (d: CalendarDraw): boolean => {\n const wb = worldBounds(d.rigid, [-d.frame.W / 2, -d.frame.H / 2, 0], [d.frame.W / 2, d.frame.H / 2, d.frame.zm + 2 * d.frame.rest + 4]);\n const pad = reach(d);\n let x0 = Number.POSITIVE_INFINITY;\n let y0 = Number.POSITIVE_INFINITY;\n let x1 = Number.NEGATIVE_INFINITY;\n let y1 = Number.NEGATIVE_INFINITY;\n for (let c = 0; c < 8; c++) { const [qx, qy] = project(eye, c & 1 ? wb.hi[0] + pad : wb.lo[0] - pad, c & 2 ? wb.hi[1] + pad : wb.lo[1] - pad, c & 4 ? wb.hi[2] : wb.lo[2]); x0 = Math.min(x0, qx); y0 = Math.min(y0, qy); x1 = Math.max(x1, qx); y1 = Math.max(y1, qy); }\n return x1 >= 0 && y1 >= 0 && x0 <= eye.vw && y0 <= eye.vh;\n };\n const shown = calendars.filter(onScreen);\n this.dropped = Math.max(0, shown.length - MAX_CALENDARS);\n this.t.list = shown.slice(0, MAX_CALENDARS) as CalendarDraw[];\n const n = this.t.list.length;\n let sx0 = Number.POSITIVE_INFINITY;\n let sy0 = Number.POSITIVE_INFINITY;\n let sx1 = Number.NEGATIVE_INFINITY;\n let sy1 = Number.NEGATIVE_INFINITY;\n let moving = 0;\n const box = (b: SheetBox | null | undefined): number[] => (b ? [b[0], b[1], b[2], b[3]] : [0, 0, 0, 0]);\n for (let i = 0; i < n; i++) {\n const d = this.t.list[i] as CalendarDraw;\n this.upload(d);\n const F = d.frame;\n const wb = worldBounds(d.rigid, [-F.W / 2, -F.H / 2, 0], [F.W / 2, F.H / 2, F.zm + 2 * F.rest + 4]);\n const r = reach(d);\n const L = d.lamp;\n let rx0 = wb.lo[0];\n let ry0 = wb.lo[1];\n let rx1 = wb.hi[0];\n let ry1 = wb.hi[1];\n for (const [px, py] of [[wb.lo[0], wb.lo[1]], [wb.hi[0], wb.hi[1]]] as const) {\n const gx = px - (L[0] * (F.zTape + d.lift)) / Math.max(L[2], 1e-3);\n const gy = py - (L[1] * (F.zTape + d.lift)) / Math.max(L[2], 1e-3);\n rx0 = Math.min(rx0, gx); ry0 = Math.min(ry0, gy); rx1 = Math.max(rx1, gx); ry1 = Math.max(ry1, gy);\n }\n rx0 -= r; ry0 -= r; rx1 += r; ry1 += r;\n for (let c = 0; c < 8; c++) {\n const [qx, qy] = project(eye, c & 1 ? wb.hi[0] : wb.lo[0], c & 2 ? wb.hi[1] : wb.lo[1], c & 4 ? wb.hi[2] : wb.lo[2]);\n sx0 = Math.min(sx0, qx); sy0 = Math.min(sy0, qy); sx1 = Math.max(sx1, qx); sy1 = Math.max(sy1, qy);\n }\n for (const [qx, qy] of [[rx0, ry0], [rx1, ry1]] as const) { const [a, b] = project(eye, qx, qy, 0); sx0 = Math.min(sx0, a); sy0 = Math.min(sy0, b); sx1 = Math.max(sx1, a); sy1 = Math.max(sy1, b); }\n const R = d.roll;\n if (d.moving && R) moving += 1;\n const sheet = (s: SheetDraw | null) => s ? [[s.x0, s.y0, s.cw, s.ch], [s.rows, s.weekends, s.lead, s.days]] : [[0, 0, 1, 1], [0, 0, 0, 0]];\n const [gA, gB] = sheet(d.base);\n const [gC, gD] = sheet(d.moving);\n const c = d.colours;\n const sel: number[] = [];\n for (let k = 0; k < 6; k++) sel.push(...box(d.sel[k]));\n this.records.set({\n model: matrixOf(d.rigid), inv: matrixOf(inverseOf(d.rigid)),\n lamp: [L[0], L[1], L[2], 0],\n size: [F.W, F.H, F.T, F.L],\n z: [F.zb, F.zt, F.zm, F.zTape],\n roll: R ? [R.a, R.alpha, R.px, R.r0] : [F.L, 0, 0, 1],\n roll2: [R ? R.tau : 0, F.turns, d.moving && R ? 1 : 0, F.rest],\n gridA: gA as number[], gridB: gB as number[], gridC: gC as number[], gridD: gD as number[],\n slots: [d.base.slot, d.moving ? d.moving.slot : -1, d.marksOn, d.ring],\n sel, mark: box(d.mark), drop: box(d.drop),\n caret: d.caret ? [...d.caret] : [0, 0, 0, 0],\n wipe: box(d.wipe?.box), wipe2: [d.wipe ? d.wipe.t : 1, d.id, d.lift, Math.min(d.sel.length, 6)],\n recv: [rx0, ry0, rx1, ry1],\n col0: [...c.paper, 1], col1: [...c.ink, 1], col2: [...c.muted, 1], col3: [...c.weekend, 1], col4: [...c.hot, 1],\n col5: [...c.chipboard, 1], col6: [...c.cloth, 1], col7: [...c.foil, 1], col8: [...c.pen, 1],\n }, i);\n }\n if (n > 0) writeChanged(this.device.queue, this.recordBuf, this.records, this.recordsSent, n);\n for (const [id, b] of this.t.buffers) if (b.seen !== this.t.frameNo) { b.vb.destroy(); b.ib.destroy(); this.t.buffers.delete(id); }\n this.t.screen = n > 0 ? { x0: sx0, y0: sy0, x1: sx1, y1: sy1 } : null;\n // the knobs, with the layer's box origin (K7a): a fragment's position is the box's, and what samples by it adds the origin back\n const at = this.boxOf(attachmentOf(view), view.dpr);\n const knobs = calUniformValues(law, eyeValues(eye), view.dpr, colours.cast, colours.select, colours.alpha, grid, this.debug);\n this.knobs.set({ ...knobs, shadow2: [knobs.shadow2[0] as number, at?.[0] ?? 0, at?.[1] ?? 0, knobs.shadow2[3] as number] });\n writeChanged(this.device.queue, this.knobBuf, this.knobs, this.knobsSent);\n this.t.stats = { calendars: n, moving };\n return n;\n }\n\n get drawn(): CalendarStats { return this.t.stats; }\n\n /** The render target the next prepare, layer and composite are for (D7): the frame's, or the held desk copy's — made on first use. */\n use(target: RenderTarget): void {\n if (target === \"copy\" && this.copyT === null) this.copyT = calTarget(new BoxTargets(this.device, \"calendar\", this.layoutComp, SAMPLES, this.mat.view));\n this.t = target === \"copy\" && this.copyT !== null ? this.copyT : this.frameT;\n }\n\n /** The hold is over: the desk copy's target gives its layer and meshes back (D7). */\n endHold(): void {\n if (this.copyT) dropTarget(this.copyT);\n this.copyT = null;\n this.t = this.frameT;\n }\n\n /** The pads' screen box on an attachment of `size` device px, clamped to it — the layer's scissor and the composite's; null when none shows. */\n private boxOf(size: { readonly w: number; readonly h: number }, dpr: number): readonly [number, number, number, number] | null {\n if (this.t.list.length === 0 || !this.t.screen) return null;\n const W = Math.max(1, size.w);\n const H = Math.max(1, size.h);\n const x0 = Math.max(0, Math.floor(this.t.screen.x0 * dpr) - 2);\n const y0 = Math.max(0, Math.floor(this.t.screen.y0 * dpr) - 2);\n const x1 = Math.min(W, Math.ceil(this.t.screen.x1 * dpr) + 2);\n const y1 = Math.min(H, Math.ceil(this.t.screen.y1 * dpr) + 2);\n return x1 <= x0 || y1 <= y0 ? null : [x0, y0, x1, y1];\n }\n\n /** The pads' screen box of the last layer, device px [x, y, w, h] — what the composite paints at most; null: no layer to lay. */\n get screenBox(): readonly [number, number, number, number] | null { return this.t.scissor; }\n\n /** Draw the prepared pads into the layer (its own command buffer — submit it before the ground's). */\n renderLayer(size: { readonly w: number; readonly h: number }, dpr: number): void {\n this.t.scissor = null;\n if (!this.boxOf(size, dpr)) return;\n const watch = this.t.frameNo < 4;\n if (watch) this.device.pushErrorScope(\"validation\");\n const enc = this.device.createCommandEncoder({ label: \"calendar\" });\n this.layer(enc, size, dpr);\n this.device.queue.submit([enc.finish()]);\n if (watch) void this.device.popErrorScope().then((e) => { if (e) console.error(`calendar pass: ${e.message}`); });\n }\n\n /**\n * Record the prepared pads into their LAYER, into `encoder` — ahead of the pass it is laid in: the host's own command buffer\n * (`renderLayer`), or the desk's frame, after the mat's wind (the calendar a kind of its registry — kinds/calendar.ts). Draw order:\n * the sheet in motion, the faces, the past roll, the solid, the mat under each. `size`: the attachment's device px. Returns\n * whether there is a layer to lay (its box: `screenBox`).\n */\n layer(encoder: GPUCommandEncoder, size: { readonly w: number; readonly h: number }, dpr: number): boolean {\n this.t.scissor = null;\n const at = this.boxOf(size, dpr);\n if (!at) return false;\n this.drawnAt = performance.now();\n const [x0, y0, x1, y1] = at;\n // into the targets at the pads' screen box (K7a — kit/layer.ts `BoxTargets`), on the attachment's pixel grid — or, when nothing\n // it was drawn from moved since (the pass's resources, the meshes, the silhouette, what it lists, the box; by content this\n // target's knobs and records and the slot's view block: the camera, the clocks, the lamp), that layer laid again undrawn (K7a)\n this.t.layer.fit(at, size);\n const sig = this.sig;\n const view = this.mat.viewBytes;\n // (the pass's resources — and, a specimen sampling the desk's print (K5b `sharePrintOf`), the print's too: a tile or a page table\n // written there is this layer's input; both counts only rise, so their sum moves when either does)\n sig[0] = this.print === this ? this.gen : this.gen + this.print.gen; sig[1] = this.t.meshGen; sig[2] = view === undefined ? Number.NaN : (this.mat.silhouetteKey ?? Number.NaN);\n sig[3] = this.t.list.length; sig[4] = x0; sig[5] = y0; sig[6] = x1; sig[7] = y1;\n const read = this.read;\n read.length = 0;\n read.push(this.knobs.view(), this.records.view(this.t.list.length));\n if (view !== undefined) read.push(view);\n if (this.t.layer.holds(sig, read)) {\n this.layerKept += 1;\n this.t.scissor = [x0, y0, x1 - x0, y1 - y0];\n return true;\n }\n this.layerDraws += 1;\n const pass = this.t.layer.begin(encoder, \"calendar/layer\", size, at);\n pass.setBindGroup(0, this.mainGroup);\n // the sheet in motion first: the month it lies over is then skipped by the depth test, never shaded under it\n if (!(this.debug & 256)) {\n pass.setPipeline(this.movingPipe);\n pass.setVertexBuffer(0, this.gridVb);\n pass.setIndexBuffer(this.gridIb, \"uint32\");\n this.t.list.forEach((d, i) => { if (d.moving && d.roll) pass.drawIndexed(this.gridCount, 1, 0, 0, i); });\n }\n const range = (pipe: GPURenderPipeline, from: (b: PadBuffers) => number, to: (b: PadBuffers) => number) => {\n pass.setPipeline(pipe);\n this.t.list.forEach((d, i) => {\n const b = this.t.buffers.get(d.id);\n if (!b || to(b) <= from(b)) return;\n pass.setVertexBuffer(0, b.vb);\n pass.setIndexBuffer(b.ib, \"uint32\");\n pass.drawIndexed(to(b) - from(b), 1, from(b), 0, i);\n });\n };\n range(this.facePipe, (b) => b.sheetFirst, (b) => b.rollFirst);\n range(this.sheetPipe, (b) => b.rollFirst, (b) => b.icount);\n range(this.solidPipe, () => 0, (b) => b.sheetFirst);\n if (!(this.debug & 128)) { pass.setPipeline(this.recvPipe); for (let i = 0; i < this.t.list.length; i++) pass.draw(6, 1, 0, i); }\n pass.end();\n this.t.layer.drew(sig, read);\n this.t.scissor = [x0, y0, x1 - x0, y1 - y0];\n return true;\n }\n\n /**\n * Lay the last layer over what `pass` holds — premultiplied, one fullscreen triangle — scissored to `scissor` (the pads' box, or\n * a part of it a host narrows it to). Nothing without a layer, or with the debug bit 16 (no layer on the mat). `underlay()` is\n * the same draw for a host that lays it through the ground's `underlays`.\n */\n composite(pass: GPURenderPassEncoder, scissor: readonly [number, number, number, number] | null = this.t.scissor): void {\n const group = this.t.layer.compGroup;\n if (!this.t.scissor || !scissor || !group || (this.debug & 16)) return;\n pass.setScissorRect(scissor[0], scissor[1], scissor[2], scissor[3]);\n pass.setPipeline(this.compPipe);\n pass.setBindGroup(0, group);\n pass.draw(3);\n }\n\n /** The layer laid on the mat, for the ground to draw inside its own pass (ground.ts `underlays`). */\n underlay(): { draw(pass: GPURenderPassEncoder): void } | null {\n const sc = this.t.scissor;\n const group = this.t.layer.compGroup;\n if (!sc || !group || (this.debug & 16)) return null;\n return {\n draw: (pass) => {\n pass.setScissorRect(sc[0], sc[1], sc[2], sc[3]);\n pass.setPipeline(this.compPipe);\n pass.setBindGroup(0, group);\n pass.draw(3);\n },\n };\n }\n\n dispose(): void {\n dropTarget(this.frameT);\n if (this.copyT) dropTarget(this.copyT);\n this.tileTex.destroy(); this.paperTex.destroy(); this.gridVb.destroy(); this.gridIb.destroy();\n this.knobBuf.destroy(); this.recordBuf.destroy(); this.tableBuf.destroy();\n }\n}\n","// The EVENTS — what is written on the calendar, and where on a sheet each line goes (CALENDAR.md §5).\n// Pure. An event is a line of handwriting on a day, or a highlighter's band across several: its days\n// (day numbers, inclusive), its text as written, each glyph's own seed (the hand, carried through\n// edits as the sticky note's are), its ink. A time at the head of the text (\"9:30 dentist\", \"3pm\n// call\") makes it a TIMED event: a day sorts its lines as a system calendar's month view does —\n// the bands first, in lanes that hold across the week, then the day's untimed lines in the order\n// they were written, then the timed ones by their time.\n\n/** One entry on the calendar. */\nexport interface CalEvent {\n readonly id: number;\n /** First and last day (day numbers, inclusive); equal for a one-day line. */\n start: number;\n end: number;\n text: string;\n /** Each glyph's seed — its hand (paper/text.ts `carrySeeds`). */\n seeds: number[];\n seed: number;\n /** The pen (a line) or the highlighter (a band) — the host's names; the law never reads them. */\n ink: string;\n /** Bumped on every edit: part of the raster's key. */\n rev: number;\n}\n\nexport const isSpan = (e: CalEvent): boolean => e.end > e.start;\n\n/**\n * A time at the head of an entry: `9:30`, `14:00`, `9am`, `9.30pm`, `3 pm`, `12a` — hours and minutes,\n * or an hour with am/pm. A bare number is not a time (\"3 apples\"). Returns minutes after midnight\n * and how many characters it took (with the space after it), or null.\n */\nexport function parseTime(text: string): { readonly minutes: number; readonly len: number } | null {\n const m = /^\\s*(\\d{1,2})(?:[:.](\\d{2}))?\\s*(am|pm|a\\.m\\.|p\\.m\\.|a|p)?(?=\\s|$)\\s*/i.exec(text);\n if (!m) return null;\n const hasMin = m[2] !== undefined;\n const ap = m[3]?.toLowerCase().replace(/\\./g, \"\");\n if (!hasMin && !ap) return null;\n let h = Number(m[1]);\n const min = hasMin ? Number(m[2]) : 0;\n if (min > 59) return null;\n if (ap) {\n if (h < 1 || h > 12) return null;\n const pm = ap.startsWith(\"p\");\n h = (h % 12) + (pm ? 12 : 0);\n } else if (h > 23) return null;\n return { minutes: h * 60 + min, len: m[0].length };\n}\n\n/** An event's time, or null (an all-day line). */\nexport const timeOf = (e: CalEvent): number | null => (isSpan(e) ? null : parseTime(e.text)?.minutes ?? null);\n\n/** The order of a day's one-day lines: untimed first (as written, by id), then timed by the clock. */\nexport function compareLines(a: CalEvent, b: CalEvent): number {\n const ta = timeOf(a);\n const tb = timeOf(b);\n if (ta === null && tb === null) return a.id - b.id;\n if (ta === null) return -1;\n if (tb === null) return 1;\n return ta - tb || a.id - b.id;\n}\n\n/** One week's piece of a band: the columns it covers in that row, its lane, whether the event starts or ends in it. */\nexport interface SpanSeg {\n readonly event: CalEvent;\n readonly row: number;\n readonly col0: number;\n readonly col1: number;\n readonly lane: number;\n readonly head: boolean;\n readonly tail: boolean;\n}\n\n/** A day's lines as its cell writes them (an entry may take two lines: `layoutMonth`'s `size`). */\nexport interface CellLines {\n readonly day: number;\n /** Lines the week's bands take at the top of this cell (their lanes through it). */\n readonly lanes: number;\n /** The one-day lines, sorted; those that fit and those that do not. */\n readonly shown: readonly CalEvent[];\n readonly hidden: number;\n}\n\n/**\n * Lay a grid's weeks out: every band cut into its week rows and given a lane that holds across the row\n * (sorted by start, the longer first; the first lane free for all its columns), and every day's one-day\n * lines. `capacity(day, lanes)` says how many lines a cell has in all (the host knows the cell's height\n * and whether a note hangs in it); `size(e)` how many a one-day entry takes (its writing wraps).\n */\nexport function layoutMonth(events: readonly CalEvent[], first: number, rows: number, capacity: (day: number, lanes: number) => number, size: (e: CalEvent) => number = () => 1): { readonly spans: readonly SpanSeg[]; readonly cells: readonly CellLines[] } {\n const last = first + rows * 7 - 1;\n const spans: SpanSeg[] = [];\n const laneAt = new Map<number, number>(); // day → lanes its bands take\n const bands = events.filter((e) => isSpan(e) && e.end >= first && e.start <= last)\n .sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start) || a.id - b.id);\n for (let r = 0; r < rows; r++) {\n const w0 = first + r * 7;\n const w1 = w0 + 6;\n const taken: boolean[][] = []; // lane → the week's 7 columns\n for (const e of bands) {\n if (e.end < w0 || e.start > w1) continue;\n const c0 = Math.max(e.start, w0) - w0;\n const c1 = Math.min(e.end, w1) - w0;\n let lane = 0;\n for (; ; lane++) {\n let row = taken[lane];\n if (row === undefined) { row = [false, false, false, false, false, false, false]; taken[lane] = row; }\n let free = true;\n for (let c = c0; c <= c1; c++) if (row[c]) { free = false; break; }\n if (free) { for (let c = c0; c <= c1; c++) row[c] = true; break; }\n }\n spans.push({ event: e, row: r, col0: c0, col1: c1, lane, head: e.start >= w0, tail: e.end <= w1 });\n for (let c = c0; c <= c1; c++) laneAt.set(w0 + c, Math.max(laneAt.get(w0 + c) ?? 0, lane + 1));\n }\n }\n const byDay = new Map<number, CalEvent[]>();\n for (const e of events) {\n if (isSpan(e) || e.start < first || e.start > last) continue;\n let list = byDay.get(e.start);\n if (!list) { list = []; byDay.set(e.start, list); }\n list.push(e);\n }\n const cells: CellLines[] = [];\n for (let n = first; n <= last; n++) {\n const lanes = laneAt.get(n) ?? 0;\n const list = (byDay.get(n) ?? []).sort(compareLines);\n const room = Math.max(0, capacity(n, lanes) - lanes);\n // lines as they come while they fit; a cell that cannot show them all gives its last line to the count (\"+2 more\")\n let used = 0;\n let fit = 0;\n const total = list.reduce((a, e) => a + size(e), 0);\n const limit = total <= room ? room : room - 1;\n while (fit < list.length && used + size(list[fit] as CalEvent) <= limit) { used += size(list[fit] as CalEvent); fit += 1; }\n cells.push({ day: n, lanes, shown: list.slice(0, fit), hidden: list.length - fit });\n }\n return { spans, cells };\n}\n","// The calendar's PRINT and HAND (CALENDAR.md §2–§3; D3t-c) — everything on a month's sheet that is ink, as a display\n// list, and the Canvas 2D that draws any rectangle of it at any density: the prototype's lab/calendar-print.ts, moved\n// whole. The grid's rules and the weekend's tint are the shader's (crisp at every zoom, free); this is the type — the\n// month's name in the product's face, light (DESIGN.md §3: big is light, small is medium), the weekdays as eyebrows,\n// each date, the two small months, the week numbers, the Moon's phases, the colophon — and the hand: each event a line\n// of the sticky note's handwriting (paper/text.ts, each glyph its own seed), a band of highlighter across a run of days,\n// today's date ringed by a marker, a past date ticked off in pencil.\n//\n// DOM-free as a contract (design-015 §3): the items DRAW into a 2D context they are handed (the host's — desk/host/print.ts,\n// an OffscreenCanvas), the type is MEASURED by the host (`measure`), and the hand's face is named, never loaded, here. The\n// tile driver (calendar/printing.ts) asks for rectangles; nothing here knows about tiles, textures or the GPU.\n\nimport type { CalendarLaw } from \"./law\";\nimport { type CalEvent, isSpan, layoutMonth, parseTime } from \"./events\";\nimport { cellDay, inMonth, isoWeek, isWeekendCol, MONTH_NAMES, monthGrid, type MonthGrid, type MoonPhase, WEEKDAY_NAMES } from \"./month\";\nimport { bandBox, type Box, cellBox, lineBox, lineCapacity, type SheetLayout } from \"./sheet\";\nimport { type PrintFace, hashHand, type HandLaw, type HandLayout, type HandMetrics, layoutText } from \"@ice/desk/kit\";\n\n/** A 2D context the print draws into — the browser's (a canvas's or an OffscreenCanvas's); a TYPE, never a touch of the DOM. */\nexport type PrintContext = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\n/** The print's colours as CSS (the product's — `vf-theme.ts` `calendarPrint`): straight colour + alpha, drawn onto a clear canvas. */\nexport interface PrintLook {\n /** The dates, the month's name. */\n readonly ink: string;\n /** The year, the eyebrows, the weekend's dates, the small print. */\n readonly muted: string;\n /** A neighbour month's date: the ink at this alpha. */\n readonly faint: number;\n /** Today's ring. */\n readonly hot: string;\n /** A past day's tick. */\n readonly pencil: string;\n readonly pens: Readonly<Record<string, string>>;\n readonly highlighters: Readonly<Record<string, string>>;\n /** The alpha a highlighter lays down (the shader multiplies it into the paper). */\n readonly highlight: number;\n}\n\nexport const SANS = 'system-ui, -apple-system, \"Helvetica Neue\", sans-serif';\nexport const MONO = 'ui-monospace, \"SF Mono\", SFMono-Regular, Menlo, monospace';\nconst font = (weight: number, size: number, family = SANS): string => `${weight} ${size}px ${family}`;\nconst handFont = (face: PrintFace, px: number): string => `${face.weight} ${px}px \"${face.family}\"`;\n\n/** One thing printed or written: its bounds on the sheet, the cells it belongs to, and how to draw it (in sheet coordinates). */\nexport interface PrintItem {\n readonly x0: number;\n readonly y0: number;\n readonly x1: number;\n readonly y1: number;\n draw(ctx: PrintContext): void;\n}\n\n/** Where an event's writing landed: the editor places its caret by it, the pointer picks by it. */\nexport interface EventLine {\n readonly event: CalEvent;\n readonly day: number;\n /** The line's (or the band segment's) box on the sheet. */\n readonly box: Box;\n /** The hand's layout and the sheet point its origin is at (a timed line's layout starts after its time). */\n readonly layout: HandLayout;\n readonly ox: number;\n readonly oy: number;\n readonly band: boolean;\n}\n\nexport interface SheetPrint {\n readonly sheet: SheetLayout;\n readonly items: readonly PrintItem[];\n /** What each cell holds, as a key: a tile over a cell whose key moved is drawn again. Index row·7 + col; the last is the sheet's own print. */\n readonly keys: readonly string[];\n readonly lines: readonly EventLine[];\n /** Days whose count of lines did not fit (\"+2 more\"). */\n readonly hidden: ReadonlyMap<number, number>;\n}\n\nexport interface PrintInputs {\n readonly law: CalendarLaw;\n readonly look: PrintLook;\n readonly sheet: SheetLayout;\n readonly events: readonly CalEvent[];\n /** Days with a sticky note stuck to them (their cells keep the foot clear). */\n readonly noted: ReadonlySet<number>;\n readonly today: number;\n readonly moons: ReadonlyMap<number, MoonPhase>;\n readonly face: PrintFace;\n readonly metrics: HandMetrics;\n /** The sticky note's hand (theme.ts `HAND`): its jitter and wander; the size is the calendar's. */\n readonly hand: HandLaw;\n readonly measure: (font: string, text: string) => number;\n /** Tick the past days off in pencil. */\n readonly ticks: boolean;\n /** A key of everything above that is not per cell (the face, the look, the law's print): part of every cell's key. */\n readonly style: string;\n /** The entry being written: printed whole, its time not set apart, so the pen's caret maps one to one (−1 = none). */\n readonly plain?: number;\n}\n\n// ---------------------------------------------------------------- the hand, and the marks a hand makes\n\n/** A line of the hand, laid out once per (text, seeds, width) — the raster draws exactly these glyphs. */\nfunction handLine(text: string, seeds: readonly number[], seed: number, width: number, size: number, inp: PrintInputs): HandLayout {\n const law: HandLaw = { ...inp.hand, size, lineHeight: inp.law.hand.pitch / size, pad: 0 };\n return layoutText(text, { w: width, h: inp.law.hand.pitch * 2 }, law, inp.metrics, seed, seeds);\n}\n\nfunction drawHand(ctx: PrintContext, L: HandLayout, ox: number, oy: number, face: PrintFace, color: string, alpha = 1, bleed = 0.3): void {\n ctx.font = handFont(face, L.em);\n ctx.textBaseline = \"alphabetic\";\n ctx.textAlign = \"left\";\n ctx.fillStyle = color;\n ctx.strokeStyle = color;\n ctx.lineJoin = \"round\";\n ctx.lineCap = \"round\";\n for (const g of L.glyphs) {\n ctx.save();\n ctx.translate(ox + g.x, oy + g.y);\n ctx.rotate(g.rot);\n ctx.scale(g.scale, g.scale);\n if (bleed > 0) { ctx.globalAlpha = alpha * g.press * 0.4; ctx.lineWidth = bleed / g.scale; ctx.strokeText(g.ch, 0, 0); }\n ctx.globalAlpha = alpha * g.press;\n ctx.fillText(g.ch, 0, 0);\n ctx.restore();\n }\n ctx.globalAlpha = 1;\n}\n\n/** A seeded wobble: a few slow sines, deterministic. */\nfunction wobble(seed: number): (t: number) => number {\n const [a, b, c, d] = hashHand(seed, 71);\n return (t) => 0.55 * Math.sin(t * 2 + a * 6.28) + 0.3 * Math.sin(t * 3.1 + b * 6.28) + 0.15 * Math.sin(t * 5.3 + c * 6.28) + (d - 0.5) * 0.2;\n}\n\n/** Today's ring: a marker's loop round the date, a little off round, overshooting where it closes. */\nfunction ring(cx: number, cy: number, rx: number, ry: number, seed: number, color: string, width: number): PrintItem {\n const w = wobble(seed);\n const [r0, r1] = hashHand(seed, 5);\n const tilt = -0.2 + r0 * 0.18;\n const start = -2.3 + r1 * 0.5;\n const span = Math.PI * 2 + 0.42;\n return {\n x0: cx - rx - 8, y0: cy - ry - 8, x1: cx + rx + 8, y1: cy + ry + 8,\n draw(ctx) {\n ctx.save();\n ctx.strokeStyle = color;\n ctx.lineCap = \"round\";\n ctx.lineJoin = \"round\";\n // the marker's stroke: its width swells in the middle of the loop and thins where it lifts off\n const n = 64;\n let px = 0;\n let py = 0;\n for (let i = 0; i <= n; i++) {\n const t = start + (span * i) / n;\n const k = 1 + 0.045 * w(t) + 0.03 * (i / n);\n const ex = Math.cos(t) * rx * k;\n const ey = Math.sin(t) * ry * k;\n const x = cx + ex * Math.cos(tilt) - ey * Math.sin(tilt);\n const y = cy + ex * Math.sin(tilt) + ey * Math.cos(tilt);\n if (i > 0) {\n const f = i / n;\n ctx.globalAlpha = 0.88 * Math.min(1, f * 7, (1 - f) * 5 + 0.25);\n ctx.lineWidth = width * (0.75 + 0.35 * Math.sin(Math.PI * f));\n ctx.beginPath();\n ctx.moveTo(px, py);\n ctx.lineTo(x, y);\n ctx.stroke();\n }\n px = x;\n py = y;\n }\n ctx.restore();\n },\n };\n}\n\n/** A pencil's tick through a past date: one quick stroke, a little curved, lighter where it starts and ends. */\nfunction tick(x0: number, y0: number, x1: number, y1: number, seed: number, color: string): PrintItem {\n const [a, b] = hashHand(seed, 13);\n const bow = (a - 0.5) * 5;\n const dx = x1 - x0;\n const dy = y1 - y0;\n const len = Math.hypot(dx, dy) || 1;\n const nx = -dy / len;\n const ny = dx / len;\n return {\n x0: Math.min(x0, x1) - 6, y0: Math.min(y0, y1) - 6, x1: Math.max(x0, x1) + 6, y1: Math.max(y0, y1) + 6,\n draw(ctx) {\n ctx.save();\n ctx.strokeStyle = color;\n ctx.lineCap = \"round\";\n const n = 14;\n let px = x0;\n let py = y0;\n for (let i = 1; i <= n; i++) {\n const t = i / n;\n const s = Math.sin(Math.PI * t);\n const x = x0 + dx * t + nx * bow * s;\n const y = y0 + dy * t + ny * bow * s;\n ctx.globalAlpha = 0.5 + 0.5 * Math.min(1, s * 2.2);\n ctx.lineWidth = 1.35 + 0.35 * s + (b - 0.5) * 0.2;\n ctx.beginPath();\n ctx.moveTo(px, py);\n ctx.lineTo(x, y);\n ctx.stroke();\n px = x;\n py = y;\n }\n ctx.restore();\n },\n };\n}\n\n/** A highlighter's pass over a run of days: a chisel's flat stroke, its ends cut on the slant and ragged, a little uneven along it. */\nfunction band(b: Box, seed: number, color: string, alpha: number, rag: number, head: boolean, tail: boolean): PrintItem {\n const w = wobble(seed);\n const [r0, r1] = hashHand(seed, 29);\n return {\n x0: b.x - rag - 2, y0: b.y - 3, x1: b.x + b.w + rag + 2, y1: b.y + b.h + 3,\n draw(ctx) {\n ctx.save();\n ctx.fillStyle = color;\n ctx.globalAlpha = alpha;\n const top: [number, number][] = [];\n const bot: [number, number][] = [];\n const n = Math.max(8, Math.round(b.w / 14));\n const slant = 4 + r0 * 3;\n for (let i = 0; i <= n; i++) {\n const t = i / n;\n const x = b.x + b.w * t;\n const e = 1.1 * w(x * 0.03);\n top.push([x, b.y + e * 0.8]);\n bot.push([x, b.y + b.h + e * 0.7 + 0.6 * w(x * 0.05 + 3)]);\n }\n const t0 = top[0] as [number, number];\n const tn = top[n] as [number, number];\n const b0 = bot[0] as [number, number];\n const bn = bot[n] as [number, number];\n ctx.beginPath();\n // the head: cut on the chisel's slant (a continuation from the week before is cut square — it runs on)\n const hx = head ? rag * (0.4 + r1 * 0.6) : 0;\n ctx.moveTo(t0[0] + hx + slant * 0.5, t0[1]);\n for (const [x, y] of top) if (x > b.x + hx + slant * 0.5) ctx.lineTo(x, y);\n const tx = tail ? rag * (0.3 + r0 * 0.7) : 0;\n ctx.lineTo(b.x + b.w + tx, tn[1]);\n ctx.lineTo(b.x + b.w + tx - slant, bn[1]);\n for (let i = n; i >= 0; i--) { const [x, y] = bot[i] as [number, number]; if (x < b.x + b.w + tx - slant && x > b.x + hx - slant * 0.5) ctx.lineTo(x, y); }\n ctx.lineTo(b.x + hx - slant * 0.5, b0[1]);\n ctx.closePath();\n ctx.fill();\n // the second pass a highlighter leaves where the stroke started (the tip rests a moment)\n if (head) { ctx.globalAlpha = alpha * 0.35; ctx.fillRect(b.x + hx - slant * 0.3, b.y + 1, 6 + r1 * 4, b.h - 2); }\n ctx.restore();\n },\n };\n}\n\n/** The Moon's phase as printed: new filled, full an outline, the quarters half-filled (the lit side as the northern sky shows it). */\nfunction moon(cx: number, cy: number, r: number, phase: MoonPhase, color: string): PrintItem {\n return {\n x0: cx - r - 2, y0: cy - r - 2, x1: cx + r + 2, y1: cy + r + 2,\n draw(ctx) {\n ctx.save();\n ctx.strokeStyle = color;\n ctx.fillStyle = color;\n ctx.lineWidth = 0.9;\n ctx.beginPath();\n ctx.arc(cx, cy, r, 0, Math.PI * 2);\n if (phase === 0) ctx.fill();\n else ctx.stroke();\n if (phase === 1 || phase === 3) {\n // first quarter: the right half lit (drawn as the dark left half filled); last: the left lit\n ctx.beginPath();\n ctx.arc(cx, cy, r, Math.PI / 2, (Math.PI * 3) / 2, phase === 3);\n ctx.closePath();\n ctx.fill();\n }\n ctx.restore();\n },\n };\n}\n\nfunction text(x: number, y: number, s: string, f: string, color: string, opts: { align?: \"left\" | \"right\" | \"center\"; alpha?: number; tracking?: number; size: number; width: number }): PrintItem {\n const align = opts.align ?? \"left\";\n const x0 = align === \"left\" ? x : align === \"right\" ? x - opts.width : x - opts.width / 2;\n return {\n x0: x0 - 2, y0: y - opts.size, x1: x0 + opts.width + 2, y1: y + opts.size * 0.35,\n draw(ctx) {\n ctx.font = f;\n ctx.fillStyle = color;\n ctx.globalAlpha = opts.alpha ?? 1;\n ctx.textAlign = align;\n ctx.textBaseline = \"alphabetic\";\n if (opts.tracking) ctx.letterSpacing = `${opts.tracking}px`;\n ctx.fillText(s, x, y);\n if (opts.tracking) ctx.letterSpacing = \"0px\";\n ctx.globalAlpha = 1;\n },\n };\n}\n\n// ---------------------------------------------------------------- the sheet\n\n/** Everything inked on one month's sheet. */\nexport function printSheet(inp: PrintInputs): SheetPrint {\n const { law, look, sheet: L } = inp;\n const g = L.grid;\n const P = law.print;\n const Hd = law.hand;\n const items: PrintItem[] = [];\n const cellItems: string[][] = Array.from({ length: L.rows * 7 }, () => []);\n const sheetKey: string[] = [`${g.index}:${g.weekStart}:${L.rows}:${inp.style}`];\n const lines: EventLine[] = [];\n const hiddenMap = new Map<number, number>();\n const measure = inp.measure;\n\n // ---- the month's name, the year beside it in a lighter weight\n const tf = font(P.title.weight, P.title.size);\n const yf = font(P.title.year, P.title.size);\n const name = MONTH_NAMES[g.m - 1] as string;\n const nameW = measure(tf, name);\n const ty = L.titleY + P.title.baseline;\n items.push(text(L.x0, ty, name, tf, look.ink, { size: P.title.size, width: nameW }));\n const year = String(g.y);\n items.push(text(L.x0 + nameW + P.title.size * 0.28, ty, year, yf, look.muted, { size: P.title.size, width: measure(yf, year) }));\n\n // ---- the foil stamped on the tape: the year, and what the pad is (the tape's shader lays its foil where this prints)\n {\n const ff = font(650, 12.5);\n const track = 3.2;\n const ty0 = law.sheet.tape / 2 + 4.5;\n const yr = String(g.y);\n const what = \"MONTHLY\";\n items.push(text(L.x0, ty0, yr, ff, look.ink, { size: 12.5, width: measure(ff, yr) + yr.length * track, tracking: track }));\n items.push(text(L.W - law.sheet.margin, ty0, what, ff, look.ink, { align: \"right\", size: 12.5, width: measure(ff, what) + what.length * track, tracking: track }));\n }\n\n // ---- the two small months at the title's right: the one before and the one after\n const mf = font(500, P.mini.size);\n const mh = font(650, P.mini.size * 0.92);\n const miniW = 7 * P.mini.col;\n const minis = [g.index - 1, g.index + 1];\n minis.forEach((mi, k) => {\n const mg = monthGrid(mi, g.weekStart);\n const right = L.W - law.sheet.margin - (1 - k) * (miniW + P.mini.gap);\n const left = right - miniW;\n const top = L.titleY + 26;\n const label = (MONTH_NAMES[mg.m - 1] as string).toUpperCase() + (mg.y !== g.y ? ` ${mg.y}` : \"\");\n items.push(text(left, top, label, mh, look.muted, { size: P.mini.size, width: measure(mh, label) + label.length * 1.4, tracking: 1.4 }));\n for (let c = 0; c < 7; c++) {\n const wd = (c + g.weekStart) % 7;\n const initial = (WEEKDAY_NAMES[wd] as string)[0] as string;\n items.push(text(left + (c + 1) * P.mini.col - 4, top + P.mini.pitch + 3, initial, mf, look.muted, { align: \"right\", size: P.mini.size, width: P.mini.size, alpha: 0.7 }));\n }\n for (let d = 1; d <= mg.days; d++) {\n const i = mg.lead + d - 1;\n const r = Math.floor(i / 7);\n const c = i % 7;\n const s = String(d);\n items.push(text(left + (c + 1) * P.mini.col - 4, top + P.mini.pitch * (r + 2) + 4, s, mf, isWeekendCol(mg, c) ? look.muted : look.ink, { align: \"right\", size: P.mini.size, width: measure(mf, s), alpha: 0.82 }));\n }\n sheetKey.push(`m${mi}`);\n });\n\n // ---- the weekdays, as eyebrows over their columns\n const wf = font(P.weekday.weight, P.weekday.size);\n const track = P.weekday.size * P.weekday.tracking;\n for (let c = 0; c < 7; c++) {\n const wd = (c + g.weekStart) % 7;\n const s = (WEEKDAY_NAMES[wd] as string).toUpperCase();\n const weekend = wd === 0 || wd === 6;\n items.push(text(L.x0 + c * L.cw + P.numeral.pad, L.weekdaysY + law.sheet.weekdays - 13, s, wf, weekend ? look.muted : look.ink, { size: P.weekday.size, width: measure(wf, s) + s.length * track, tracking: track, alpha: weekend ? 0.8 : 0.72 }));\n }\n\n // ---- the week numbers in the left margin (a Monday week's ISO number)\n if (g.weekStart === 1) {\n const kf = font(500, P.small.size - 1, MONO);\n for (let r = 0; r < L.rows; r++) {\n const s = String(isoWeek(cellDay(g, r, 0)));\n items.push(text(L.x0 - 9, L.y0 + r * L.ch + P.numeral.baseline - 4, s, kf, look.muted, { align: \"right\", size: P.small.size, width: measure(kf, s), alpha: 0.55 }));\n }\n }\n\n // ---- the colophon at the foot: the Moon's legend, the month's number\n {\n const ff = font(500, P.small.size - 1, MONO);\n const fy = L.H - law.sheet.foot / 2 + 4;\n const s = `${String(g.m).padStart(2, \"0\")} / ${g.y}`;\n items.push(text(L.W - law.sheet.margin, fy, s, ff, look.muted, { align: \"right\", size: P.small.size, width: measure(ff, s), alpha: 0.6 }));\n const lf = font(500, P.small.size - 1);\n let lx = L.x0;\n for (const [ph, label] of [[0, \"new moon\"], [1, \"first quarter\"], [2, \"full moon\"], [3, \"last quarter\"]] as const) {\n items.push(moon(lx + 5, fy - 4, 4.2, ph, look.muted));\n items.push(text(lx + 15, fy, label, lf, look.muted, { size: P.small.size, width: measure(lf, label), alpha: 0.6 }));\n lx += 15 + measure(lf, label) + 22;\n }\n }\n\n // ---- the days\n const nf = font(P.numeral.weight, P.numeral.size);\n // each one-day entry's writing, laid out once: the time small and apart, what it is wrapping under itself (two lines at most)\n const hands = new Map<number, { t: HandLayout | null; tw: number; r: HandLayout; n: number }>();\n const lineW = L.cw - 2 * Hd.pad;\n for (const e of inp.events) {\n if (isSpan(e) || e.start < g.first || e.start >= g.first + g.rows * 7) continue;\n const t = e.id === inp.plain ? null : parseTime(e.text);\n const Lt = t ? handLine(e.text.slice(0, t.len).trimEnd(), e.seeds.slice(0, t.len), e.seed, lineW, Hd.size * Hd.time, inp) : null;\n const tw = Lt ? (Lt.lines[0]?.width ?? 0) + Hd.size * 0.3 : 0;\n const Lr = handLine(t ? e.text.slice(t.len) : e.text, t ? e.seeds.slice(t.len) : e.seeds, e.seed + 1, Math.max(lineW - tw, 20), Hd.size, inp);\n hands.set(e.id, { t: Lt, tw, r: Lr, n: Math.min(Math.max(Lr.lines.length, 1), 2) });\n }\n const layout = layoutMonth(inp.events, g.first, g.rows, (day, lanes) => Math.max(lineCapacity(L, law, inp.noted.has(day)), lanes), (e) => hands.get(e.id)?.n ?? 1);\n const pens = (name: string): string => look.pens[name] ?? (look.pens.felt as string);\n for (let r = 0; r < L.rows; r++) {\n for (let c = 0; c < 7; c++) {\n const day = cellDay(g, r, c);\n const own = inMonth(g, day);\n const b = cellBox(L, r, c);\n const key = cellItems[r * 7 + c] as string[];\n const s = String(civilDay(day));\n const nx = b.x + P.numeral.pad;\n const ny = b.y + P.numeral.baseline;\n const nw = measure(nf, s);\n const weekend = isWeekendCol(g, c);\n items.push(text(nx, ny, s, nf, weekend ? look.muted : look.ink, { size: P.numeral.size, width: nw, alpha: own ? 1 : look.faint }));\n key.push(`${day}:${own ? 1 : 0}`);\n if (!own) continue;\n const ph = inp.moons.get(day);\n if (ph !== undefined) { items.push(moon(b.x + b.w - P.moon.inset, b.y + P.moon.inset + 2, P.moon.r, ph, look.muted)); key.push(`moon${ph}`); }\n if (day === inp.today) {\n const cap = P.numeral.size * 0.72;\n items.push(ring(nx + nw / 2, ny - cap / 2, nw / 2 + 12, cap / 2 + 10, day * 7 + 3, look.hot, 2.3));\n key.push(\"today\");\n } else if (inp.ticks && day < inp.today) {\n const cap = P.numeral.size * 0.72;\n items.push(tick(nx - 4, ny + 3, nx + nw + 4, ny - cap - 3, day * 13 + 1, look.pencil));\n key.push(\"past\");\n }\n if (inp.noted.has(day)) key.push(\"note\");\n }\n }\n // the bands: a highlighter across the run, the title written on its first day in each week\n for (const seg of layout.spans) {\n const e = seg.event;\n const bb = bandBox(L, seg.row, seg.col0, seg.col1, seg.lane, law);\n items.push(band(bb, e.seed + seg.row * 31, look.highlighters[e.ink] ?? (Object.values(look.highlighters)[0] as string), look.highlight, Hd.rag, seg.head, seg.tail));\n const Lh = handLine(e.text, e.seeds, e.seed, bb.w - 14, Hd.size * 0.92, inp);\n // the layout's origin is its top-left: its first baseline sits `ascent` below it\n const ox = bb.x + 8;\n const oy = bb.y + bb.h * 0.5 + Lh.ascent * 0.36 - Lh.ascent;\n items.push(clipHand(Lh, ox, oy, { x: bb.x, y: bb.y - 8, w: bb.w, h: bb.h + 16 }, inp.face, pens(\"felt\")));\n lines.push({ event: e, day: g.first + seg.row * 7 + seg.col0, box: bb, layout: Lh, ox, oy, band: true });\n for (let cc = seg.col0; cc <= seg.col1; cc++) (cellItems[seg.row * 7 + cc] as string[]).push(`b${e.id}.${e.rev}.${seg.lane}.${seg.head ? 1 : 0}${seg.tail ? 1 : 0}`);\n }\n // each day's lines: the time small and a shade lighter, then what it is\n for (const cell of layout.cells) {\n const i = cell.day - g.first;\n const r = Math.floor(i / 7);\n const c = i % 7;\n if (!inMonth(g, cell.day)) continue;\n const key = cellItems[r * 7 + c] as string[];\n let at = cell.lanes;\n for (const e of cell.shown) {\n const h = hands.get(e.id) as { t: HandLayout | null; tw: number; r: HandLayout; n: number };\n const lb = lineBox(L, r, c, at, law);\n const box = { x: lb.x, y: lb.y, w: lb.w, h: lb.h * h.n };\n const color = pens(e.ink);\n if (h.t) items.push(clipHand(h.t, lb.x, lb.y + Hd.pitch * 0.74 - h.t.ascent, { x: lb.x, y: lb.y - 6, w: lb.w + 4, h: lb.h + 10 }, inp.face, color, 0.66, 1));\n const ox = lb.x + h.tw;\n const oy = lb.y + Hd.pitch * 0.74 - h.r.ascent;\n items.push(clipHand(h.r, ox, oy, { x: lb.x, y: lb.y - 6, w: lb.w + 4, h: box.h + 10 }, inp.face, color, 1, h.n));\n lines.push({ event: e, day: cell.day, box, layout: h.r, ox, oy, band: false });\n key.push(`e${e.id}.${e.rev}.${at}`);\n at += h.n;\n }\n if (cell.hidden > 0) {\n const lb = lineBox(L, r, c, at, law);\n const s = `+${cell.hidden} more`;\n const sf = font(P.small.size >= 11 ? 600 : 500, P.small.size + 1);\n items.push(text(lb.x, lb.y + Hd.pitch * 0.66, s, sf, look.muted, { size: P.small.size + 1, width: measure(sf, s) }));\n hiddenMap.set(cell.day, cell.hidden);\n key.push(`+${cell.hidden}`);\n }\n }\n const keys = cellItems.map((k) => `${sheetKey[0]}|${k.join(\",\")}`);\n keys.push(sheetKey.join(\",\"));\n return { sheet: L, items, keys, lines, hidden: hiddenMap };\n}\n\n/** The day of the month of a day number, without building the whole civil date twice. */\nconst civilDay = (n: number): number => {\n const z = n + 719468;\n const era = Math.floor(z / 146097);\n const doe = z - era * 146097;\n const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);\n const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));\n const mp = Math.floor((5 * doy + 2) / 153);\n return doy - Math.floor((153 * mp + 2) / 5) + 1;\n};\n\n/**\n * Writing, clipped to its box: `keep` lines of it; where there is more than that, the last kept line\n * fades out over its last few units — the pen ran on past the cell — rather than stopping short.\n */\nfunction clipHand(Lh: HandLayout, ox: number, oy: number, clip: Box, face: PrintFace, color: string, alpha = 1, keep = 1): PrintItem {\n const right = clip.x + clip.w;\n const more = Lh.lines.length > keep;\n const kept: HandLayout = more ? { ...Lh, glyphs: Lh.glyphs.filter((gl) => gl.line < keep) } : Lh;\n return {\n x0: clip.x - 2, y0: clip.y - 2, x1: clip.x + clip.w + 2, y1: clip.y + clip.h + 2,\n draw(ctx) {\n ctx.save();\n ctx.beginPath();\n ctx.rect(clip.x, clip.y, clip.w, clip.h);\n ctx.clip();\n drawHand(ctx, kept, ox, oy, face, color, alpha);\n if (more) {\n const last = Lh.lines[keep - 1];\n const end = Math.min(ox + (last?.width ?? 0), right);\n const y = oy + (last?.y ?? 0);\n ctx.globalCompositeOperation = \"destination-out\";\n const grad = ctx.createLinearGradient(end - 26, 0, end, 0);\n grad.addColorStop(0, \"transparent\");\n grad.addColorStop(1, \"black\");\n ctx.fillStyle = grad;\n ctx.fillRect(end - 26, y - Lh.ascent - 4, 30, Lh.ascent + Lh.descent + 8);\n }\n ctx.restore();\n },\n };\n}\n\n/** Is an event drawn on this sheet at all (a band may start or end off it)? */\nexport const onSheet = (e: CalEvent, g: MonthGrid): boolean => e.end >= g.first && e.start < g.first + g.rows * 7 && (isSpan(e) || inMonth(g, e.start));\n\n// ---------------------------------------------------------------- the raster\n\n/**\n * Draw the rectangle [x, y, w, h] of a sheet (sheet units) into `ctx`, `band` texels a unit, onto a\n * clear canvas: the items it overlaps, in order. The canvas's alpha is the ink's presence.\n */\nexport function drawRegion(ctx: PrintContext, print: SheetPrint, x: number, y: number, w: number, h: number, band: number): number {\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n ctx.setTransform(band, 0, 0, band, -x * band, -y * band);\n let n = 0;\n for (const it of print.items) {\n if (it.x1 < x || it.x0 > x + w || it.y1 < y || it.y0 > y + h) continue;\n it.draw(ctx);\n n += 1;\n }\n ctx.setTransform(1, 0, 0, 1, 0, 0);\n return n;\n}\n\n/** Does anything print in the rectangle? (An empty tile is never drawn nor stored.) */\nexport function anyIn(print: SheetPrint, x: number, y: number, w: number, h: number): boolean {\n for (const it of print.items) if (!(it.x1 < x || it.x0 > x + w || it.y1 < y || it.y0 > y + h)) return true;\n return false;\n}\n","// The PRINT'S TILES at work (CALENDAR.md §6; D3t-c) — the prototype's tile scheduling (lab/calendar.ts `tableFor` ·\n// `contentOf` · `tileSheet` · `forget`), moved as a driver the calendar kind's local runs once a frame: a sheet in play\n// keeps the coarse levels resident for the whole sheet and the view's level (and the one under it) for what is in view,\n// each tile keyed by WHAT IT SHOWS (the keys of the cells under it), so an entry written redraws only the tiles over its\n// cell. A tile nothing is printed in is marked empty and costs nothing; out of the frame's budget a stale copy may stand in\n// for a frame, else the shader falls back a rung. The tiles are a CACHE of the print, and the print a function of the\n// events: nothing here is a fact.\n//\n// DOM-free: the raster is the host's seam (`PrintRaster` — desk/host/print.ts draws a rectangle of a print on an\n// OffscreenCanvas and measures the type), the pass takes what it hands back. The Node oracle has no raster: it PINS a\n// sheet's committed tiles (`pin` — the fixture's bytes, one level), and a sheet pinned so is never drawn live.\n\nimport type { PrintRaster, TileSource } from \"@ice/desk/kit\";\nimport { anyIn, type SheetPrint } from \"./print\";\nimport { BASE_LEVELS, bandOf, EMPTY, entryOf, GUTTER, MISSING, TileCache, type TileGrid, tileRect, tilesIn } from \"./tiles\";\n\n/** What the driver asks of the calendar's pass: its layers, a tile uploaded or written, a page table written. */\nexport interface PrintPass {\n readonly layers: number;\n uploadTile(layer: number, source: TileSource): void;\n writeTileBytes(layer: number, bytes: Uint8Array<ArrayBuffer>): void;\n writeTable(slot: number, grid: TileGrid, table: Int32Array): void;\n}\n\n/** A sheet's committed tiles (a fixture): one level's tiles by `tx:ty`, RGBA TILE_TEX² each, and the ones nothing prints in. */\nexport interface PinnedSheet {\n readonly level: number;\n readonly tiles: ReadonlyMap<string, Uint8Array<ArrayBuffer>>;\n readonly empty: ReadonlySet<string>;\n}\n\n/** A sheet rectangle in view (sheet units). */\nexport interface SheetView { readonly x0: number; readonly y0: number; readonly x1: number; readonly y1: number }\n\n/** A string's 32-bit FNV-1a, as a tile's content key. */\nexport function fnv(s: string): string {\n let h = 0x811c9dc5 >>> 0;\n for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }\n return `${h.toString(36)}:${s.length}`;\n}\n\n/** What a tile of a print shows — the keys of the cells under it and the sheet's own. */\nexport function contentOf(print: SheetPrint, x: number, y: number, w: number, h: number): string {\n const L = print.sheet;\n let s = print.keys[print.keys.length - 1] as string;\n const c0 = Math.max(0, Math.floor((x - L.x0) / L.cw));\n const c1 = Math.min(6, Math.floor((x + w - L.x0) / L.cw));\n const r0 = Math.max(0, Math.floor((y - L.y0) / L.ch));\n const r1 = Math.min(L.rows - 1, Math.floor((y + h - L.y0) / L.ch));\n if (x + w >= L.x0 && x <= L.x0 + 7 * L.cw && y + h >= L.y0 && y <= L.y0 + L.rows * L.ch) {\n for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) s += `|${print.keys[r * 7 + c]}`;\n }\n return fnv(s);\n}\n\nexport interface PrintTilesOptions {\n readonly grid: TileGrid;\n /** The clock the frame's budget runs on (ms). */\n readonly now?: () => number;\n /** The most raster a frame spends, ms (a tile is ~0.3–1 ms): the rest come on the frames after. */\n readonly budgetMs?: number;\n}\n\n/** The tile driver of one desk's pads: the layers' cache, each slot's page table, the frame's budget. */\nexport class PrintTiles {\n readonly grid: TileGrid;\n private readonly now: () => number;\n private readonly budgetMs: number;\n private cache: TileCache | null = null;\n private readonly tables = new Map<number, { owner: string; table: Int32Array; dirty: boolean }>();\n private t0 = 0;\n /** Tiles the last frame left waiting, by sheet slot — a pad's own, so a pad forgotten takes its waiting tiles with it (D7). */\n private readonly pendingBy = new Map<number, number>();\n private starvedN = 0;\n private drawnN = 0;\n\n constructor(opts: PrintTilesOptions) {\n this.grid = opts.grid;\n this.now = opts.now ?? (() => Date.now());\n this.budgetMs = opts.budgetMs ?? 6;\n }\n\n /** Tiles still to draw after the last frame (the desk asks for another). */\n pending(): number { let n = 0; for (const k of this.pendingBy.values()) n += k; return n; }\n /** Tiles drawn since the driver was made (a witness). */\n drawn(): number { return this.drawnN; }\n /** Tiles the last frame wanted and no layer could hold (every one in use by that frame) — a witness. */\n starved(): number { return this.starvedN; }\n /** Resident tiles. */\n resident(): number { return this.cache?.size ?? 0; }\n\n private cacheOf(pass: PrintPass): TileCache {\n this.cache ??= new TileCache(pass.layers);\n return this.cache;\n }\n\n /** A new frame: its budget starts now; what it touches is kept from eviction until the next. */\n begin(pass: PrintPass): void {\n this.cacheOf(pass).tick();\n this.pendingBy.clear();\n this.starvedN = 0;\n this.t0 = this.now();\n }\n\n /** A sheet's page table in `slot`, owned by (pad, month): made again (all missing) when the owner changes. */\n private tableFor(slot: number, owner: string): { owner: string; table: Int32Array; dirty: boolean } {\n let t = this.tables.get(slot);\n if (t === undefined || t.owner !== owner) { t = { owner, table: new Int32Array(this.grid.count).fill(MISSING), dirty: true }; this.tables.set(slot, t); }\n return t;\n }\n\n /**\n * Bring a sheet's tiles up to date for this frame: the coarse levels for the whole sheet, the view's level (and the one\n * under it) for what is in view — resident ones kept, empty ones marked, the rest drawn (the view's centre first) within the\n * frame's budget. `owner` names the sheet (`${pad}:${month}`); a sheet with no print yet (its face loading) keeps its table.\n */\n sheet(pass: PrintPass, raster: PrintRaster<SheetPrint>, owner: string, slot: number, print: SheetPrint, view: SheetView, level: number, rungs: 1 | 2 = 2): void {\n const cache = this.cacheOf(pass);\n const T = this.tableFor(slot, owner);\n const want: { l: number; tx: number; ty: number; d: number }[] = [];\n for (let l = 0; l < BASE_LEVELS; l++) for (const [tx, ty] of tilesIn(this.grid, l, 0, 0, this.grid.W, this.grid.H)) want.push({ l, tx, ty, d: -1 });\n const cx = (view.x0 + view.x1) / 2;\n const cy = (view.y0 + view.y1) / 2;\n for (let l = Math.max(BASE_LEVELS, level - rungs + 1); l <= level; l++) {\n for (const [tx, ty] of tilesIn(this.grid, l, view.x0, view.y0, view.x1, view.y1)) {\n const r = tileRect(l, tx, ty);\n want.push({ l, tx, ty, d: (l === level ? 0 : 1e9) + Math.hypot(r.x + r.w / 2 - cx, r.y + r.h / 2 - cy) });\n }\n }\n want.sort((a, b) => a.d - b.d);\n for (const t of want) {\n const r = tileRect(t.l, t.tx, t.ty);\n const g = GUTTER / bandOf(t.l);\n const content = contentOf(print, r.x - g, r.y - g, r.w + 2 * g, r.h + 2 * g);\n const key = `${owner}:${t.l}:${t.tx}:${t.ty}`;\n const e = entryOf(this.grid, t.l, t.tx, t.ty);\n const have = cache.get(key, content);\n if (have !== null) { if (T.table[e] !== have) { T.table[e] = have; T.dirty = true; } continue; }\n if (!anyIn(print, r.x - g, r.y - g, r.w + 2 * g, r.h + 2 * g)) { if (T.table[e] !== EMPTY) { T.table[e] = EMPTY; T.dirty = true; } continue; }\n if (this.now() - this.t0 > this.budgetMs) {\n // out of time: a stale copy may stand in for a frame; else it waits, its level's fallback showing\n const v = cache.stale(key) ?? MISSING;\n if (T.table[e] !== v) { T.table[e] = v; T.dirty = true; }\n this.pendingBy.set(slot, (this.pendingBy.get(slot) ?? 0) + 1);\n continue;\n }\n // every layer in use by this very frame: the tile STARVES (its level's fallback shows) — not pending, so a view that wants more\n // tiles than the layers hold does not keep the desk awake redrawing them (the prototype's did); a frame that moves retries it\n const put = cache.put(key, content);\n if (put === null) { this.starvedN += 1; continue; }\n if (put.evicted !== null) this.forget(put.evicted);\n const band = bandOf(t.l);\n pass.uploadTile(put.layer, raster.tile(print, r.x - g, r.y - g, (r.w + 2 * g), (r.h + 2 * g), band));\n this.drawnN += 1;\n T.table[e] = put.layer;\n T.dirty = true;\n }\n }\n\n /**\n * A sheet's COMMITTED tiles (a still's — the Node oracle's, a rig's pin): its table names the fixture's level alone (the rest\n * missing: the shader falls back to it from any density), each tile written once into a layer of its own. The table is the\n * pinned sheet's EXACTLY: a pin under an owner that pinned another sheet before (the oracle's pad 1 in September, scene after\n * scene) keeps none of that sheet's entries — a blank pin is a blank sheet.\n */\n pin(pass: PrintPass, owner: string, slot: number, pinned: PinnedSheet): void {\n const cache = this.cacheOf(pass);\n const T = this.tableFor(slot, `pin:${owner}`);\n const named = new Set<number>();\n for (const at of [...pinned.tiles.keys(), ...pinned.empty]) {\n const [tx, ty] = at.split(\":\").map(Number) as [number, number];\n named.add(entryOf(this.grid, pinned.level, tx, ty));\n }\n for (let e = 0; e < T.table.length; e++) if (!named.has(e) && T.table[e] !== MISSING) { T.table[e] = MISSING; T.dirty = true; }\n for (const [at, bytes] of pinned.tiles) {\n const [tx, ty] = at.split(\":\").map(Number) as [number, number];\n const key = `pin:${owner}:${pinned.level}:${tx}:${ty}`;\n const e = entryOf(this.grid, pinned.level, tx, ty);\n let layer = cache.get(key, \"pin\");\n if (layer === null) {\n const put = cache.put(key, \"pin\");\n if (put === null) continue;\n if (put.evicted !== null) this.forget(put.evicted);\n pass.writeTileBytes(put.layer, bytes);\n layer = put.layer;\n }\n if (T.table[e] !== layer) { T.table[e] = layer; T.dirty = true; }\n }\n for (const at of pinned.empty) {\n const [tx, ty] = at.split(\":\").map(Number) as [number, number];\n const e = entryOf(this.grid, pinned.level, tx, ty);\n if (T.table[e] !== EMPTY) { T.table[e] = EMPTY; T.dirty = true; }\n }\n }\n\n /** The frame's page tables that moved, into the pass. */\n end(pass: PrintPass): void {\n for (const [slot, t] of this.tables) if (t.dirty) { pass.writeTable(slot, this.grid, t.table); t.dirty = false; }\n }\n\n /** A tile gave up its layer: every table pointing at it forgets it (the shader falls back a level). */\n private forget(key: string): void {\n const parts = key.split(\":\");\n const pin = parts[0] === \"pin\";\n const at = pin ? 1 : 0;\n const owner = `${pin ? \"pin:\" : \"\"}${parts[at]}:${parts[at + 1]}`;\n const e = entryOf(this.grid, Number(parts[at + 2]), Number(parts[at + 3]), Number(parts[at + 4]));\n for (const [, t] of this.tables) if (t.owner === owner && (t.table[e] as number) >= 0) { t.table[e] = MISSING; t.dirty = true; }\n }\n\n /** A pad gone: its tiles, its tables and its waiting tiles (by its slots) forgotten. */\n drop(pad: number, slots: readonly number[]): void {\n this.cache?.drop(`${pad}:`);\n this.cache?.drop(`pin:${pad}:`);\n for (const s of slots) this.pendingBy.delete(s);\n for (const s of slots) { const t = this.tables.get(s); if (t !== undefined) { t.owner = \"\"; t.table.fill(MISSING); t.dirty = true; } }\n }\n}\n\n","// THE MONTH'S TURN at work (CALENDAR.md §4; D3t-c) — the prototype's `Turn`, `startTurn`, the pointer's roll and `step`\n// (lab/calendar.ts), pure: a month rolls UP from its foot into the roll under the tape (the next laid bare beneath it), or the last\n// month comes DOWN off the roll over the one showing. A turn runs on `roll [1.25 Hz, 0.92]` toward 1 (rolled) or 0 (flat); a hand\n// drives it (the sheet under the finger), and let go it decides — a click takes the whole month, a flick goes where it was\n// flicked, else past a third it goes and short of it falls back. The corner LIFTS (the peek) while the pointer is near it.\n//\n// The DOCUMENT holds the month (`desk.calendar.month`); the turn is FLUX. The pad shows the month it has laid bare (`shown`) and\n// rolls toward the document's — a month turned by the bar, the keys, today, a peer, one after another, quicker the further it is.\n// A month turned BY HAND ends where the document does not know yet: it is `pending` (the hand commits it — ONE transaction, off\n// the undo stack, D-D3t-c.5) and the pad holds it until the document says so.\n\nimport type { CalendarLaw } from \"./law\";\nimport type { PadFrame } from \"./pad\";\nimport { rollState, type RollState } from \"./roll\";\nimport { spring } from \"@ice/desk/kit\";\n\n/** A turn in flight. */\nexport interface Turn {\n readonly dir: 1 | -1;\n /** How far the moving sheet is rolled: 0 flat on the pad … 1 in the roll at rest. */\n p: number;\n v: number;\n target: 0 | 1;\n /** The corner's tilt it started with. */\n readonly tilt: number;\n /** The hand on it: the sheet point under the finger (`s` from under the tape), its velocity, whether it moved. */\n drag: { lastS: number; lastT: number; vs: number; moved: boolean } | null;\n /** A quick run (several months to go): the spring's frequency multiplied. */\n fast: number;\n /** A HAND's turn (its end a month the document does not know yet), not one toward the document's month. */\n readonly hand: boolean;\n}\n\n/** One pad's turning, the local's own. */\nexport interface PadRoll {\n /** The month laid bare (null until the pad is first seen: it shows the document's then). */\n shown: number | null;\n turn: Turn | null;\n peek: number;\n peekV: number;\n peekOn: boolean;\n /** A hand's finished roll asked of the document, not yet there — held until the document SPEAKS (its month moves, to this or elsewhere). */\n pending: number | null;\n /** A hand's roll finished (the hand commits `shown`); cleared by whoever drains it. */\n rolled: boolean;\n /** The document's month as last seen. */\n durable: number | null;\n /** The document's month as `stepRoll` last heard it (a move from it is the document speaking — D7 #3). */\n heard: number | null;\n}\n\nexport const newRoll = (): PadRoll => ({ shown: null, turn: null, peek: 0, peekV: 0, peekOn: false, pending: null, rolled: false, durable: null, heard: null });\n\nconst clamp01 = (v: number): number => Math.min(1, Math.max(0, v));\n\n/** The sheets in play for a pad: the month on it and the one in motion, the roll's line — the prototype's `sheetsOf`. */\nexport function rollSheets(r: PadRoll, durable: number, law: CalendarLaw, F: PadFrame): { readonly shown: number; readonly base: number; readonly moving: number | null; readonly roll: RollState | null; readonly marksOn: 0 | 1; readonly turning: boolean } {\n if (r.shown === null) r.shown = durable;\n r.durable = durable;\n const shown = r.shown;\n const rollOf = (p: number, tilt: number): RollState => rollState(p, { rest: law.roll.rest + 0.6, tau: law.roll.tau }, F.L, F.W, tilt);\n const t = r.turn;\n if (t !== null) {\n const roll = rollOf(t.p, t.tilt);\n return t.dir === 1 ? { shown, base: shown + 1, moving: shown, roll, marksOn: 1, turning: true } : { shown, base: shown, moving: shown - 1, roll, marksOn: 0, turning: true };\n }\n if (r.peek > 1e-3) return { shown, base: shown + 1, moving: shown, roll: rollOf((r.peek * law.roll.peek) / (F.L - law.roll.rest), -law.roll.tilt), marksOn: 1, turning: false };\n return { shown, base: shown, moving: null, roll: null, marksOn: 0, turning: false };\n}\n\n/** The month the pad rolls toward: a hand's pending one, else the document's. */\nexport const targetOf = (r: PadRoll): number | null => r.pending ?? r.durable;\n\n/** Start a turn: up (`dir` 1, from the corner's lift) or down (−1, the last month off the roll). False while one runs. */\nexport function startTurn(r: PadRoll, dir: 1 | -1, tilt: number, law: CalendarLaw, F: PadFrame, opts: { readonly hand?: boolean; readonly fast?: number; readonly drag?: { readonly s: number; readonly now: number } } = {}): boolean {\n if (r.turn !== null || r.shown === null) return false;\n const p0 = dir === 1 ? (r.peek * law.roll.peek) / (F.L - law.roll.rest) : 1;\n r.turn = {\n dir, p: p0, v: 0, target: dir === 1 ? 1 : 0, tilt: dir === 1 ? (r.peek > 0.05 ? -law.roll.tilt : tilt) : 0,\n drag: opts.drag === undefined ? null : { lastS: opts.drag.s, lastT: opts.drag.now, vs: 0, moved: false },\n fast: opts.fast ?? 1, hand: opts.hand === true,\n };\n r.peek = 0;\n r.peekV = 0;\n r.peekOn = false;\n return true;\n}\n\n/** A hand takes the sheet in motion mid-turn (the prototype's press on `moving`). */\nexport function grabMoving(r: PadRoll, s: number, now: number): boolean {\n const t = r.turn;\n if (t === null || t.drag !== null) return false;\n t.drag = { lastS: s, lastT: now, vs: 0, moved: false };\n return true;\n}\n\n/** The finger at `s` (the sheet point under it, from under the tape): the moving sheet follows it; `moved` once it has. */\nexport function dragTo(r: PadRoll, s: number, now: number, moved: boolean, law: CalendarLaw, F: PadFrame): void {\n const t = r.turn;\n if (t === null || t.drag === null) return;\n const d = t.drag;\n if (moved) d.moved = true;\n // the velocity follows the finger's MOVES (a frame it stands still is no sample — the pause before a release must read as a pause)\n if (s !== d.lastS) {\n const dt = Math.max((now - d.lastT) / 1000, 1e-3);\n d.vs = d.vs * 0.6 + ((s - d.lastS) / dt) * 0.4;\n d.lastS = s;\n d.lastT = now;\n }\n t.p = clamp01((F.L - s) / (F.L - law.roll.rest));\n t.v = 0;\n}\n\n/** Let go: a click takes the whole month (or brings it); a flick goes where it was flicked; else past a third it goes, short of it it falls back. */\nexport function letGo(r: PadRoll, now: number, law: CalendarLaw, F: PadFrame, cancel = false): void {\n const t = r.turn;\n if (t === null || t.drag === null) return;\n const d = t.drag;\n t.drag = null;\n // a hand that stopped before letting go threw nothing: the flick fades over the pause\n const vs = d.vs * Math.exp(-((now - d.lastT) / 1000) / 0.08);\n if (!d.moved && !cancel) t.target = t.dir === 1 ? 1 : 0;\n else if (vs < -260) t.target = 1;\n else if (vs > 260) t.target = 0;\n else t.target = t.dir === 1 ? (t.p > 0.3 ? 1 : 0) : t.p < 0.7 ? 0 : 1;\n t.v = -vs / Math.max(F.L - law.roll.rest, 1);\n}\n\n/**\n * Advance a pad's turning by `dt` seconds toward the document's month `durable`: the corner's peek, the turn's spring, its end (a\n * month rolled away or back — a hand's is `pending` and `rolled`), the next turn toward the target. True while anything moves.\n */\nexport function stepRoll(r: PadRoll, durable: number, dt: number, law: CalendarLaw, F: PadFrame): boolean {\n if (r.shown === null) r.shown = durable;\n r.durable = durable;\n // A hand's month is held only until the DOCUMENT speaks: its own word (the hand's commit landed) or another's (a peer's roll\n // won the race, LWW) — either way the pad follows the document from here. Held until the document echoed it EXACTLY, a lost\n // race left `pending` forever, and `targetOf` shadowed every later month the document took (D7 #3).\n const spoke = r.heard !== null && durable !== r.heard;\n r.heard = durable;\n if (r.pending !== null && (durable === r.pending || spoke)) r.pending = null;\n let live = false;\n const peekT = r.peekOn && r.turn === null ? 1 : 0;\n [r.peek, r.peekV] = spring(r.peek, r.peekV, peekT, law.springs.peek[0], law.springs.peek[1], dt);\n if (Math.abs(r.peek - peekT) < 1e-3 && Math.abs(r.peekV) < 1e-2) { r.peek = peekT; r.peekV = 0; } else live = true;\n const t = r.turn;\n if (t !== null) {\n live = true;\n if (t.drag === null) {\n [t.p, t.v] = spring(t.p, t.v, t.target, law.springs.roll[0] * t.fast, law.springs.roll[1], dt);\n if (Math.abs(t.p - t.target) < 2e-3 && Math.abs(t.v) < 0.02) {\n // the turn is over: a month rolled away (or back), or the sheet let go of\n const done = (t.dir === 1 && t.target === 1) || (t.dir === -1 && t.target === 0);\n if (done) {\n r.shown = (r.shown as number) + t.dir;\n if (t.hand) { r.pending = r.shown === durable ? null : r.shown; r.rolled = r.pending !== null; }\n }\n r.turn = null;\n const target = targetOf(r) as number;\n if (r.shown !== target) startToward(r, target, law, F, 1.6);\n }\n }\n } else {\n const target = targetOf(r);\n if (target !== null && r.shown !== target) { startToward(r, target, law, F, 1); live = true; }\n }\n return live;\n}\n\n/** A turn toward `target`, one month of the way, quicker the further it has to go. */\nfunction startToward(r: PadRoll, target: number, law: CalendarLaw, F: PadFrame, base: number): void {\n const n = Math.abs(target - (r.shown as number));\n const dir: 1 | -1 = target > (r.shown as number) ? 1 : -1;\n startTurn(r, dir, dir === 1 ? -law.roll.tilt * 0.6 : 0, law, F, { fast: base + Math.min(n - 1, 6) * 0.5 });\n}\n","// Assemble the calendar pass's programs from the host's shader text — the browser's generated module, a Node host's files on\n// disk; byte-identical either way. The pad is the notebook's paper and cloth under the same colour chain: the kit's view\n// block, the mat's light and the 3D kit (kit/wgsl.ts `book`), then the calendar's own records, module and entry; its layer\n// is laid by the kit's composite.\n\nimport type { ComposeOptions } from \"@ice/desk/engine\";\nimport { layerComposite, kitWgsl, type ShaderText } from \"@ice/desk/kit\";\nimport { CalPad, CalUniforms } from \"./layout\";\n\n/** The calendar's own shader files (the kit's pieces come by name). */\nexport const CALENDAR_SHADER_FILES = { calendar: \"calendar/calendar.wgsl\", pass: \"calendar/calendar-pass.wgsl\" } as const;\n\nexport interface CalendarShaders {\n readonly program: ComposeOptions; // the kit's view · light · book + calendar, calendar-pass\n readonly composite: ComposeOptions; // the kit's layer composite\n}\n\nexport function calendarShaders(text: ShaderText): CalendarShaders {\n const t = text(CALENDAR_SHADER_FILES);\n return {\n program: kitWgsl([\"view\", \"light\", \"book\"], {\n structs: [CalUniforms, CalPad],\n modules: [{ label: \"calendar/calendar.wgsl\", text: t.calendar }],\n entry: { label: \"calendar/calendar-pass.wgsl\", text: t.pass },\n }, text),\n composite: layerComposite(text),\n };\n}\n","// The DESK CALENDAR (CALENDAR.md) as a kind (kind.ts): the pad beneath everything behind the registry's\n// door — a thin adapter, the pass and its WGSL as they were. Stratum `pads`, registered `composite`: the\n// pass renders every pad into a layer of its own in `prepare` — the sheet in motion, the faces, the past\n// roll, the solid, the mat under each (the prototype's `renderLayer` order) — recorded into the frame's\n// encoder after the mat's wind, and its one run lays that layer on the mat before the sheets and the\n// things (the prototype laid it as a host's `underlays` entry), so every note, board and notebook lies ON\n// the calendar. The desk eye is the slot's view's; the law and the print's presences are the host's (the\n// presences are the product's look). The PRINT is the host's too: its tiles are a Canvas 2D raster the\n// host hands the pass (`kind.pass.uploadTile`, `writeTable`) — a pad whose tables name no tile shows its\n// paper and its ruled grid (MISSING = −1). ROOT ONLY (D-D18): a spawned slot's pass draws nothing.\n//\n// And its WORLD half (kinds/world.ts; D3w): `calendarKind` — a pad becomes a `CalendarDraw` as the lab's `reset`\n// + `pose` + `renderLayer` make one: its shown month and week start durable, a still's roll or peek a FLUX pin\n// on the kind's own state (never a Grab), its lift the builder's (Grab: CALENDAR.md's 3 units, through the desk\n// eye), its ring the selection's, fading with a ghost (the lab's `ring × (1 − fade)`; the pad itself stays whole\n// until it is gone — its delete). Its page tables' slots and its id are the kind's, per pad. Its hit unprojects the\n// desk point at the pad's face through the SAME desk eye the pass draws with: at rest a pad answers its TAPE\n// (`frame` — a press carries it, a tap selects it) and the roll's handles (D3t-c: the roll, the corner, the foot, the\n// sheet in motion — parts); its paper is not taken (a miss — the press falls through to the mat and pans, the lab's\n// \"not taken\"; a click there is the days', read at event time); in hand the whole sheet is the pen's `content`. Its\n// events and pins are data children (calendar/data.ts). The colours and the print's presences are the product's\n// (`theme()`; the presences set on the root pass by the kind's local — the theme gate).\n//\n// AT WORK (D3t-c): the local (`createPads`) also keeps each pad's PRINT (calendar/print.ts, from its events — tiles\n// through calendar/printing.ts and the host's raster), its months TURNING toward the document's month\n// (calendar/turn.ts), the MARKS the hand puts on it (days, a line, the caret, a drop — drawn on the sheet as the\n// marks' brackets), a DRAFT line, and the notes stuck to it that go with its months (`veils` — not drawn, never picked).\n\nimport type { Entity, HeldToolApi } from \"@ice/core\";\nimport { calEventOf, CalendarEvent, dayOr, monthKeyOf, monthOfKey, NotePin, PadSelection, PinsNote } from \"./data\";\nimport type { CalEvent } from \"./events\";\nimport { padFrame, buildPad } from \"./pad\";\nimport { CALENDAR, type CalendarLaw } from \"./law\";\nimport type { CalendarColours } from \"./layout\";\nimport { dayIn, isWeekendCol, monthGrid, monthOfDay, phasesBetween, today as todayOf } from \"./month\";\nimport { type CalendarDraw, CalendarPass, type SheetBox, type SheetDraw } from \"./pass\";\nimport { anyIn, type EventLine, onSheet, type PrintLook, printSheet, type SheetPrint } from \"./print\";\nimport { type PinnedSheet, PrintTiles } from \"./printing\";\nimport { rollAt, rollState, type RollState, tangentAt } from \"./roll\";\nimport { dragTo, grabMoving, letGo, newRoll, type PadRoll, rollSheets, startTurn, stepRoll } from \"./turn\";\nimport { CALENDAR_SHADER_FILES, calendarShaders } from \"./shaders\";\nimport { cellAt, dayBox, noteSlot, sheetOf } from \"./sheet\";\nimport { bandOf, GUTTER, levelFor, TILE_TEX, type TileGrid, tileGrid, tileRect, tilesIn } from \"./tiles\";\nimport { caretAt, glyphBox, type HandLaw, HAND, type MatPass, type MarkFrame, type DeskEye, eyeOf, project, unproject, MeshWriter, lampDir, type Rigid, rigidOf, type ShaderText, LayeredKind, LAYER_IDLE_MS, PRINT_RASTER } from \"@ice/desk/kit\";\nimport { type KindPass, type KindProgram, type SlotContext, MAT_COLORS, type Palette, type RGB, rgb, type ThemeName, type TokenRef, type KindHost, type KindLocal, numberProp, type ObjectContext, type ObjectHit, type ObjectKind, stringProp } from \"@ice/desk\";\nimport { shaderText } from \"../shaders\";\n\n/** The desk calendar's kind name — its key in the registry and in every slot's `objects`. */\nexport const CALENDAR_KIND = \"calendar\";\n\n/** The print's presences over the paper: the day rules, the heading rule, the weekend's wash, a neighbour month's wash. */\nexport interface CalendarAlpha { readonly rule: number; readonly head: number; readonly weekend: number; readonly outside: number }\n\n/** No print: what the knobs carry while no pad draws (a host sets `alpha` before one does). */\nconst NO_ALPHA: CalendarAlpha = { rule: 0, head: 0, weekend: 0, outside: 0 };\n\nexport class CalendarKind extends LayeredKind<CalendarDraw, CalendarPass> {\n /** The calendar's law — the pad's size, its roll, its eye, its shadow: the host's; `CALENDAR` until one says. */\n law: CalendarLaw = CALENDAR;\n /** The print's presences — the PRODUCT's look (CALENDAR.md §4): a host sets them before a pad draws. */\n alpha: CalendarAlpha | null = null;\n /** The tile grid of the law's sheet (tiles.ts) — the page tables' shape, the host's `writeTable` names the same. */\n private tiles: { readonly law: CalendarLaw; readonly grid: TileGrid } | null = null;\n\n /** The tile grid the pass's page tables have for the law in force — the one a host hands `kind.pass.writeTable`. */\n get grid(): TileGrid {\n if (this.tiles?.law !== this.law) { const F = padFrame(this.law); this.tiles = { law: this.law, grid: tileGrid(F.W, F.H) }; }\n return this.tiles.grid;\n }\n\n /** Root only (D-D18): a spawned slot's pass — a mini mat's inside, a flight's departed desk — holds nothing and draws nothing. */\n spawn(_mat: MatPass): CalendarKind { return new CalendarKind(null); }\n\n /**\n * A slot's own pass of this kind takes the ROOT's host-set state before it prepares (its law and the print's presences): a spawned pass draws nothing, but a\n * slot that made its own from the program — the tray's specimen (design-017 §8, K5a) — draws with the desk's, and reads the desk's PRINT (K5b).\n */\n tune(root: KindPass<unknown>): void {\n if (!(root instanceof CalendarKind) || root === this) return;\n this.law = root.law;\n this.alpha = root.alpha;\n // …and its PRINT (K5b): the pads' local prints into the root pass, so a specimen drawn with it samples the root's tiles\n if (this.pass !== null && root.pass !== null) this.pass.sharePrintOf(root.pass);\n }\n\n /** The pass's own `prepare`, as the prototype's lab called it: the slot's camera, grid, clocks and light, the desk eye over the slot's view, the law, the tile grid, the colours. */\n protected prepareOwn(pass: CalendarPass, s: SlotContext, records: readonly CalendarDraw[]): number {\n // the host's presences, else a record's own look's (made without the desk's local — a tray specimen, K5a): never none\n const alpha = this.alpha ?? records.find((r) => r.alpha !== undefined)?.alpha ?? null;\n if (records.length > 0 && !alpha) throw new Error(\"calendar: the print's presences are the host's look — set the kind's `alpha` before a pad draws\");\n const v = s.view;\n const eye = eyeOf({ x: v.camX, y: v.camY, zoom: v.zoom }, { width: v.width, height: v.height }, this.law.eye);\n return pass.prepare(v, s.fadeIn, s.cfg, s.frame, s.light, eye, this.law, this.grid, { cast: MAT_COLORS.cast, select: s.select, alpha: alpha ?? NO_ALPHA }, records);\n }\n}\n\n/** The desk calendar's program for a host's shader text: its pass made on the root's mat; its pads one composite run, the first stratum. */\nexport function calendarProgram(text: ShaderText): KindProgram<CalendarDraw> {\n return {\n name: CALENDAR_KIND,\n stratum: \"pads\",\n composite: true,\n create: async (device, format, mat) => new CalendarKind(await CalendarPass.create(device, format, calendarShaders(text), mat)),\n };\n}\n\n// ---------------------------------------------------------------- the world half (D3w)\n\n/**\n * What the calendar's kind takes from the host's palette (CALENDAR.md §4): the paper and the print's inks, the\n * chipboard, the tapes by name (cloth and foil), the print's presences; the pens a caret is drawn in are the note's\n * (`pens`, kinds/paper.ts `PaperPalette`).\n */\nexport interface CalendarPalette extends Palette {\n readonly calendars?: {\n readonly paper: TokenRef; readonly ink: TokenRef; readonly muted: TokenRef; readonly weekend: TokenRef; readonly hot: TokenRef; readonly chipboard: TokenRef;\n readonly tapes: Readonly<Record<string, { readonly cloth: TokenRef; readonly foil: TokenRef }>>;\n /** The presences; `faint` (a neighbour month's date) and `highlight` (a highlighter's dye) are the PRINT's (D3t-c). */\n readonly alpha: CalendarAlpha & { readonly faint?: number; readonly highlight?: number };\n /** The PRINT's inks (D3t-c): the pencil a past day is ticked in, the highlighters a run of days is banded in. */\n readonly pencil?: TokenRef;\n readonly highlighters?: Readonly<Record<string, TokenRef>>;\n };\n readonly pens?: Readonly<Record<string, TokenRef>>;\n}\n\n/** A pencil's tick lies at this presence (CALENDAR.md §2: graphite through a past date, lighter than the ink). */\nconst PENCIL_ALPHA = 0.55;\n/** A colour as the print's Canvas 2D takes it, with a presence — the fixture's `calendarPrint` spelling, byte for byte. */\nconst cssOf = (c: RGB, a = 1): string => `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${a})`;\n\n/** The calendar's look for a theme, parsed. */\nexport interface CalendarObjectLook {\n readonly paper: RGB; readonly ink: RGB; readonly muted: RGB; readonly weekend: RGB; readonly hot: RGB; readonly chipboard: RGB;\n readonly tapes: Readonly<Record<string, { readonly cloth: RGB; readonly foil: RGB }>>;\n readonly pens: Readonly<Record<string, RGB>>;\n readonly alpha: CalendarAlpha;\n /** The PRINT's inks as the raster takes them (D3t-c) — absent when the palette names no pencil or highlighters. */\n readonly print?: PrintLook;\n}\n\n/** A pad's still, pinned on the kind's own state (a FLUX pin): a month rolling (`dir` +1 up, −1 down, `p` of the way, the roll's tilt) or the corner's peek. */\nexport interface PadPose {\n readonly roll?: { readonly dir: 1 | -1; readonly p: number; readonly tilt?: number };\n readonly peek?: number;\n}\n\n/** A pad as the builder resolved it: what its record draws and its hit reads (the same eye the pass draws with). */\nexport interface CalendarGeometry {\n readonly shown: number;\n readonly weekStart: 0 | 1;\n readonly base: number;\n readonly moving: number | null;\n readonly roll: RollState | null;\n readonly marksOn: 0 | 1;\n readonly rigid: Rigid;\n readonly lamp: readonly [number, number, number];\n readonly lift: number;\n readonly ring: number;\n readonly eye: DeskEye;\n readonly cx: number;\n readonly cy: number;\n /** In hand (D4b's `ctx.held`): the whole sheet is the pen's surface (`content`), never a miss (D3t-c). */\n readonly held: boolean;\n /** A month in motion (a turn — not the corner's peek): the sheet in motion is what a press takes. */\n readonly turning: boolean;\n}\n\n/** The parts of a pad (the prototype's `CalendarHit`): where a point lands on its sheet, the day and the line there. */\nexport type CalendarPartName = \"tape\" | \"roll\" | \"moving\" | \"corner\" | \"foot\" | \"day\" | \"entry\" | \"sheet\";\nexport interface CalendarPart {\n readonly part: CalendarPartName;\n /** The sheet point: x from its left edge, y from its head (world units). */\n readonly sx: number;\n readonly sy: number;\n /** The day under it (a neighbour month's day in the first or last row counts) — on `day` and `entry`. */\n readonly day?: number;\n /** The line there, as the print laid it — on `entry`. */\n readonly line?: EventLine;\n}\n\n/**\n * What a desk point lands on, on a pad as resolved (the prototype's `hit`, through the SAME desk eye the pass draws with, at the\n * face's height): the tape; mid-turn the sheet in motion (within the roll's reach of its tangent line) or the sheet beneath; at\n * rest the roll under the tape, the corner, the foot, a line of writing (the print's own boxes — a band a little taller), a day,\n * or the sheet's paper. Null off the pad. The print is the month shown's (`lines` — none in Node: no lines are hit).\n */\nexport function partAt(G: CalendarGeometry, wx: number, wy: number, lines: readonly EventLine[] = [], law: CalendarLaw = CALENDAR): CalendarPart | null {\n const F = padFrame(law);\n const [px, py] = unproject(G.eye, wx, wy, F.zt + G.lift);\n const sx = px - G.cx + F.W / 2;\n const sy = py - G.cy + F.H / 2;\n if (sx < 0 || sy < 0 || sx > F.W || sy > F.H) return null;\n if (sy < F.T) return { part: \"tape\", sx, sy };\n const s = sy - F.T;\n if (G.turning && G.roll !== null) {\n const R = rollAt(G.roll, sx).radius;\n const a = tangentAt(G.roll, sx);\n return { part: Math.abs(s - a) < R * 1.4 + 6 ? \"moving\" : \"sheet\", sx, sy };\n }\n if (s < 2 * law.roll.rest + 6) return { part: \"roll\", sx, sy };\n if (F.W - sx + (F.H - sy) < 150) return { part: \"corner\", sx, sy };\n if (F.H - sy < law.sheet.foot) return { part: \"foot\", sx, sy };\n const L = sheetOf(monthGrid(G.shown, G.weekStart), law);\n const cell = cellAt(L, sx, sy);\n if (cell === null) return { part: \"sheet\", sx, sy };\n const line = lines.find((l) => !l.band && sx >= l.box.x && sx <= l.box.x + l.box.w && sy >= l.box.y && sy <= l.box.y + l.box.h)\n ?? lines.find((l) => l.band && sx >= l.box.x && sx <= l.box.x + l.box.w && sy >= l.box.y - 3 && sy <= l.box.y + l.box.h + 3);\n if (line !== undefined) return { part: \"entry\", sx, sy, day: cell.day, line };\n return { part: \"day\", sx, sy, day: cell.day };\n}\n\n/** The sheet point (x from its left edge, y from its head) under a desk point, at the pad's face through the eye — unclamped (a finger may leave the pad). */\nexport function sheetPoint(G: CalendarGeometry, wx: number, wy: number, law: CalendarLaw = CALENDAR): { readonly sx: number; readonly sy: number } {\n const F = padFrame(law);\n const [px, py] = unproject(G.eye, wx, wy, F.zt + G.lift);\n return { sx: px - G.cx + F.W / 2, sy: py - G.cy + F.H / 2 };\n}\n\n/** A pad's sheet point (x from its left, y from its head, `z` up) on the screen, CSS px — through the eye the pad was drawn with. */\nexport function sheetOnScreen(G: CalendarGeometry, sx: number, sy: number, z?: number, law: CalendarLaw = CALENDAR): readonly [number, number] {\n const F = padFrame(law);\n return project(G.eye, G.cx - F.W / 2 + sx, G.cy - F.H / 2 + sy, (z ?? F.zt) + G.lift);\n}\n\n/** A day's cell on the month a pad shows (sheet units) — a neighbour month's day in the first or last row counts — or null. */\nexport function sheetDayBox(G: CalendarGeometry, day: number, law: CalendarLaw = CALENDAR): { readonly x: number; readonly y: number; readonly w: number; readonly h: number } | null {\n return dayBox(sheetOf(monthGrid(G.shown, G.weekStart), law), day);\n}\n\n/** A run of days, an entry, a caret: what the calendar's hand says is marked on a pad (the driver's — objects/calendar-hand.ts). */\nexport interface PadMarks {\n /** The days selected, first to last (day numbers). */\n readonly days?: readonly [number, number];\n /** The entry selected — an event entity's id, or the draft's (−1). */\n readonly entry?: number;\n /** The day a note held over the pad would stick to. */\n readonly drop?: number;\n /** The entry being WRITTEN (the editor on it): printed whole, its time not set apart, the caret at `index` (`on`: the blink). */\n readonly writing?: { readonly entry: number; readonly index: number; readonly on: boolean };\n /** The newest glyph being written and how far the pen's wipe has come over it (0 … 1 — the hand's clock). */\n readonly wipe?: { readonly entry: number; readonly index: number; readonly t: number };\n}\n\n/** An entry being written that the world does not hold yet (a new line: it is spawned when its session ends — D-D3t-c.4). */\nexport interface PadDraft {\n readonly start: number;\n readonly end: number;\n readonly text: string;\n readonly seeds: readonly number[];\n readonly ink: string;\n}\n\n/** The draft's id in a print (never an entity's). */\nexport const DRAFT_ID = -1;\n\n/** The calendar's own state on one desk: each pad's id and page-table slots, its pinned still, its print and marks; the print's presences on the root pass. */\nexport interface Pads extends KindLocal {\n /** When the kind is next live (K7a — `KindLocal.due`, declared: the six built-ins all say). */\n due(now: number): number;\n pin(e: Entity, pose: PadPose | undefined): void;\n /** The world half's: the pad's id, its slot pair (its base sheet's table is 2k, its moving sheet's 2k + 1) and its pin. */\n state(e: Entity): { readonly id: number; readonly slot: number; readonly pose: PadPose | undefined };\n /** The world half's: the print's presences on the root pass (the product's look). */\n alpha(a: CalendarAlpha): void;\n /** A pad's events as its data children hold them. */\n events(e: Entity): readonly { readonly start: string | null; readonly end: string | null; readonly text: string | null; readonly ink: string | null }[];\n // ---- D3t-c: the print, the marks, the pen\n /** The day the print calls today: the pinned one (a still's), else the clock's. */\n today(): number;\n /** Pin today (a day key) for stills and rigs — null gives it back to the clock. */\n pinToday(key: string | null): void;\n /**\n * Pin the ZONE a day is reckoned in (an IANA name) — today's, and the Moon's phases' local days on the print — for stills and rigs:\n * the committed prints were drawn in one zone, and a scene that holds a live print to them pins it (D7). Null: the pad's own.\n */\n pinZone(zone: string | null): void;\n /** The past days ticked off in pencil (CALENDAR.md Q-4; on by default). */\n ticks(on?: boolean): boolean;\n /** A pad's entries as the print takes them — its events by entity, and the draft being written. */\n entries(e: Entity): readonly CalEvent[];\n /** Month `month`'s print on pad `e` as the last frame laid it (its lines: where each entry landed), or undefined — no raster, or not laid. */\n printOf(e: Entity, month: number): SheetPrint | undefined;\n /** A month's COMMITTED tiles on pad `e` (a still's, a rig's pin): drawn instead of the live print; null takes them back. */\n pinPrint(e: Entity, month: number, sheet: PinnedSheet | null): void;\n /** What the calendar's hand marks on pad `e` this frame (undefined: nothing). */\n mark(e: Entity, marks: PadMarks | undefined): void;\n marksOf(e: Entity): PadMarks | undefined;\n /** The entry being written that the world does not hold yet (null: none). */\n draft(e: Entity, d: PadDraft | null): void;\n draftOf(e: Entity): PadDraft | null;\n /** The print's tiles: resident, still to draw, drawn since the desk began. */\n tiles(): { readonly resident: number; readonly pending: number; readonly drawn: number; readonly starved: number };\n /** The desk's raster reads a live sheet back as a fixture would hold it (level `level`'s tiles, RGBA) — a rig's door; undefined without a raster. */\n readSheet(e: Entity, month: number, level: number): { readonly tiles: ReadonlyMap<string, Uint8Array<ArrayBuffer>>; readonly empty: ReadonlySet<string> } | undefined;\n // ---- D3t-c: the month's turn (calendar/turn.ts) — flux toward the document's month\n /** The sheets in play for pad `e` whose document month is `durable` (the kind's `resolve`): the month laid bare, the one in motion. */\n sheets(e: Entity, durable: number): ReturnType<typeof rollSheets>;\n /** A pad's turning as it stands (a witness): the month laid bare, the turn in flight, the corner's lift, a hand's roll pending. */\n rollOf(e: Entity): { readonly shown: number | null; readonly turn: { readonly dir: 1 | -1; readonly p: number; readonly target: 0 | 1; readonly held: boolean; readonly hand: boolean } | null; readonly peek: number; readonly pending: number | null } | undefined;\n /** The corner lifts while the pointer is near the foot or the corner (the next month shows under it). */\n peek(e: Entity, on: boolean): void;\n /** A hand takes a sheet by `part` (the foot or the corner: up; the roll: down; the sheet in motion) at sheet point (sx, s from under the tape). False when it cannot. */\n grab(e: Entity, part: \"foot\" | \"corner\" | \"roll\" | \"moving\", sx: number, s: number, now: number): boolean;\n /** The finger at `s`: the moving sheet follows it. */\n dragTo(e: Entity, s: number, now: number, moved: boolean): void;\n /** Let go (or the press was cancelled): the turn decides. */\n letGo(e: Entity, now: number, cancel?: boolean): void;\n /** The hands' finished rolls since the last drain — each a month the document should now hold (the hand commits it). */\n rolled(): readonly { readonly e: Entity; readonly month: number }[];\n /** A hand's finished roll waits for `rolled` to drain it (K7a): the hand is not idle, the kind is due, until it is committed. */\n rollOwed(): boolean;\n /** A hand's roll the document REFUSED (read-only, a pad gone): the pad rolls back to the document's month. A landed roll is released by the roll itself, once the document speaks (turn.ts, D7 #3). */\n unroll(e: Entity): void;\n /** A pad is on this desk (D7 #14): the hand's peek follows the pointer while one is — the hand is idle only while neither the pointer nor the camera moved (K7a). */\n busy(): boolean;\n /** The notes stuck to its pads that go with their months (D3t-c): not drawn, never picked (`KindLocal.veils`). */\n veils(): ReadonlySet<Entity>;\n /** Draw a pad's print and its marks for this frame (the kind's `record`): the sheets' tiles brought up, the marks' boxes. */\n draw(e: Entity, G: CalendarGeometry, view: ObjectContext[\"view\"], print: PrintLook | undefined): Pick<CalendarDraw, \"sel\" | \"mark\" | \"drop\" | \"caret\" | \"wipe\">;\n}\n\ninterface PadState {\n readonly id: number;\n readonly slot: number;\n pose: PadPose | undefined;\n readonly pinned: Map<number, PinnedSheet>;\n marks: PadMarks | undefined;\n draft: PadDraft | null;\n /** Its months turning (calendar/turn.ts) — flux toward the document's month. */\n readonly roll: PadRoll;\n /** The notes stuck to it that go with its months this frame (not drawn, never picked — `veils`). */\n hidden: ReadonlySet<Entity>;\n}\n\nconst NO_MARKS: Pick<CalendarDraw, \"sel\" | \"mark\" | \"drop\" | \"caret\" | \"wipe\"> = { sel: [], mark: null, drop: null, caret: null, wipe: null };\n\n/** The calendar's `local()`: ids from 1, slot pairs from the lowest free (the pass's tables hold `MAX_CALENDARS` pads); the print's driver. */\nexport function createPads(host: KindHost, opts: { readonly law?: CalendarLaw; readonly now?: () => number; readonly zone?: string; readonly hand?: HandLaw } = {}): Pads {\n // the print raster — a SERVICE its DOM half lends (K8a, `PRINT_RASTER`: the host's hand), none in Node (the oracle pins its tiles)\n const printer = host.use?.(PRINT_RASTER);\n const law = opts.law ?? CALENDAR;\n const clock = opts.now ?? (() => Date.now());\n const hand = opts.hand ?? HAND;\n const F = padFrame(law);\n const pads = new Map<Entity, PadState>();\n const free: number[] = [];\n let nextId = 1;\n let nextSlot = 0;\n let woke = false;\n let todayPin: number | null = null;\n let zonePin: string | null = null;\n /** The day the print last called today, and when the wall clock is next asked whether it turned over (D7). */\n let dayShown: number | null = null;\n let dayCheckAt = Number.NEGATIVE_INFINITY;\n /** A month turning at the last tick (its spring on the frame's clock): the kind is due every frame until it lands (K7a). */\n let rolling = false;\n let ticksOn = true;\n let tiles: PrintTiles | null = null;\n let begun = false;\n let lastTick: number | null = null;\n const prints = new Map<string, { key: string; print: SheetPrint }>();\n /** What has LANDED on each object, counted (D7 — `KindLocal.landed`): the held desk copy is made again when a desk object's moves. */\n const landedOf = new Map<Entity, number>();\n const land = (e: Entity): void => { landedOf.set(e, (landedOf.get(e) ?? 0) + 1); };\n // A pad's state is MADE by the draw path only — `sheets`, `draw`, `pin` (a scene's pose), `pinPrint`, the kind's record — and\n // answered to every other door for a pad it knows (`pads.get`): a mark, a draft, a peek or a grab on a pad already forgotten\n // (its delete, its cull) must not re-acquire a slot against MAX_CALENDARS (D7 #10 — the hand marks a pad it saw last frame,\n // the writing drafts on one). A pad culled mid-draft shows its draft again at the next keystroke, not before: the price\n const state = (e: Entity): PadState => {\n let st = pads.get(e);\n if (st === undefined) { free.sort((a, b) => a - b); st = { id: nextId++, slot: free.shift() ?? nextSlot++, pose: undefined, pinned: new Map(), marks: undefined, draft: null, roll: newRoll(), hidden: new Set() }; pads.set(e, st); }\n return st;\n };\n const passOf = (): CalendarPass | undefined => { const k = host.pass(); return k instanceof CalendarKind ? (k.pass ?? undefined) : undefined; };\n const tilesOf = (pass: CalendarPass): PrintTiles => { tiles ??= new PrintTiles({ grid: tileGrid(F.W, F.H), now: clock }); if (!begun) { tiles.begin(pass); begun = true; } return tiles; };\n // THE BUDGET (D6): the print's tile layers are one fixed texture the pass owns, LRU among themselves (tiles.ts `TileCache`) —\n // charged as resident and kept once it is MADE (K6a: at the first tile, never for a desk with no pad), let go with the last pad\n let charged = 0;\n const chargeTiles = (): void => {\n if (host.budget === undefined) return;\n const pass = passOf();\n if (pass === undefined) return;\n const bytes = pass.tileBytes;\n if (bytes === charged) return;\n if (bytes === 0) host.budget.release(\"calendar\", \"print tiles\");\n else host.budget.charge(\"calendar\", \"print tiles\", bytes, () => {});\n charged = bytes;\n };\n // THE CLOCK SEAM (D7): today and the Moon's local days on the pad's own wall clock (`now`) in its zone — the platform's unless the\n // host says (`zone`) or a still pins them (`pinToday`, `pinZone`)\n const zoneNow = (): string | undefined => zonePin ?? opts.zone;\n const todayNow = (): number => todayPin ?? todayOf(clock(), zoneNow());\n /**\n * When the wall clock next turns the day over (K7a — the kind's registered wake, instead of asking the clock once a second): the\n * first second after `from` whose day in the pad's zone is not `from`'s — hour by hour (a DST day is 23 or 25), then halved to\n * the second. A pinned today never turns.\n */\n const nextTurn = (from: number): number => {\n if (todayPin !== null) return Number.POSITIVE_INFINITY;\n const zone = zoneNow();\n const d0 = todayOf(from, zone);\n let lo = from;\n let hi = from + 3_600_000;\n for (let i = 0; i < 26 && todayOf(hi, zone) === d0; i++) { lo = hi; hi += 3_600_000; }\n while (hi - lo > 1000) { const mid = Math.floor((lo + hi) / 2); if (todayOf(mid, zone) === d0) lo = mid; else hi = mid; }\n return hi;\n };\n const entriesOf = (e: Entity): CalEvent[] => {\n const out: CalEvent[] = [];\n for (const { entity, value } of host.children?.entries?.(e, CalendarEvent) ?? []) { const ev = calEventOf(entity, value); if (ev !== null) out.push(ev); }\n const d = pads.get(e)?.draft ?? null;\n if (d !== null) out.push({ id: DRAFT_ID, start: Math.min(d.start, d.end), end: Math.max(d.start, d.end), text: d.text, seeds: [...d.seeds], seed: 0, ink: d.ink, rev: d.text.length });\n return out;\n };\n /** Month `month`'s print on pad `e` — built again only when what it shows changed (the prototype's `printOf`). */\n const printFor = (e: Entity, st: PadState, month: number, weekStart: 0 | 1, look: PrintLook, writing: number): SheetPrint | undefined => {\n const raster = printer;\n const h = raster?.hand();\n if (raster === undefined || h === undefined) return undefined;\n const L = sheetOf(monthGrid(month, weekStart), law);\n const g = L.grid;\n const last = g.first + g.rows * 7 - 1;\n const events = entriesOf(e).filter((ev) => onSheet(ev, g));\n const noted: number[] = [];\n for (const p of host.children?.rows(e, NotePin) ?? []) { const d = dayOr(p.day ?? \"\"); if (d !== undefined && d >= g.first && d <= last && monthOfDay(d) === month) noted.push(d); }\n noted.sort((a, b) => a - b);\n const today = todayNow();\n const style = `${h.face.family}:${h.face.weight}:${raster.version()}:${ticksOn ? 1 : 0}:${lookKey(look)}`;\n const zone = zoneNow();\n const key = `${events.map((ev) => `${ev.id}.${ev.rev}.${ev.start}.${ev.end}`).join(\",\")}|${weekStart}|${noted.join(\",\")}|${today}|${zone ?? \"\"}|${style}|${writing}`;\n const id = `${st.id}:${month}`;\n const hit = prints.get(id);\n if (hit !== undefined && hit.key === key) return hit.print;\n const print = printSheet({\n law, look, sheet: L, events, noted: new Set(noted), today, moons: phasesBetween(g.first, last, (ms) => dayIn(ms, zone)),\n face: h.face, metrics: h.metrics, hand, measure: (f, t) => raster.measure(f, t), ticks: ticksOn, style, plain: writing,\n });\n prints.set(id, { key, print });\n return print;\n };\n /**\n * The notes stuck to pad `e` that go with its months this frame (the prototype's `syncNotes`, each note at its day's slot): a note\n * whose month is not laid bare; mid-turn, one on the sheet in motion once the roll has reached it, one on the sheet beneath until\n * the roll has laid it bare (Q-7: a note steps out of sight as the roll reaches it — it is not wound into the paper).\n */\n const hiddenOf = (e: Entity, G: CalendarGeometry): ReadonlySet<Entity> => {\n const out = new Set<Entity>();\n const ch = host.children;\n if (ch?.entries === undefined || ch.target === undefined) return out;\n for (const { entity: pin, value } of ch.entries(e, NotePin)) {\n const note = ch.target(pin, PinsNote);\n const day = dayOr(value.day ?? \"\");\n if (note === undefined || day === undefined) continue;\n const m = monthOfDay(day);\n let show = m === G.base && G.moving === null;\n const R = G.roll;\n if (G.moving !== null && R !== null && (m === G.moving || m === G.base)) {\n const L = sheetOf(monthGrid(m, G.weekStart), law);\n const k = day - L.grid.first;\n const slot = noteSlot(L, Math.floor(k / 7), k % 7, law);\n const h = (law.note.size / 2) * 1.05;\n const corners: readonly (readonly [number, number])[] = [[slot.x - h, slot.y - h], [slot.x + h, slot.y - h], [slot.x - h, slot.y + h], [slot.x + h, slot.y + h]];\n show = m === G.moving\n ? corners.every(([x, y]) => y - F.T < tangentAt(R, x) - rollAt(R, x).radius * 1.1)\n : corners.every(([x, y]) => y - F.T > tangentAt(R, x) + rollAt(R, x).radius * 1.25);\n }\n if (!show) out.add(note);\n }\n return out;\n };\n let veilsCache: ReadonlySet<Entity> | null = null;\n /** The marks' boxes on the sheet they are on (the base at rest and rolling down, the moving sheet rolling up). */\n const marksOn = (st: PadState, month: number, weekStart: 0 | 1, print: SheetPrint | undefined): Pick<CalendarDraw, \"sel\" | \"mark\" | \"drop\" | \"caret\" | \"wipe\"> => {\n const m = st.marks;\n if (m === undefined) return NO_MARKS;\n const L = sheetOf(monthGrid(month, weekStart), law);\n const sel: SheetBox[] = [];\n if (m.days !== undefined) {\n const [a, b] = m.days[0] <= m.days[1] ? m.days : [m.days[1], m.days[0]];\n for (let d = a; d <= b;) {\n const b0 = dayBox(L, d);\n const col = (((d - L.grid.first) % 7) + 7) % 7;\n const endD = Math.min(b, d + (6 - col));\n const b1 = dayBox(L, endD);\n if (b0 !== null && b1 !== null) sel.push([b0.x + 3, b0.y + 3, b1.x + b1.w - 3, b1.y + b1.h - 3]);\n d = endD + 1;\n if (sel.length >= 6) break;\n }\n }\n let mark: SheetBox | null = null;\n let caret: CalendarDraw[\"caret\"] = null;\n let wipe: CalendarDraw[\"wipe\"] = null;\n const line = (id: number): EventLine | undefined => print?.lines.find((l) => l.event.id === id);\n const selected = m.writing?.entry ?? m.entry;\n if (selected !== undefined) {\n const l = line(selected);\n if (l !== undefined) mark = [l.box.x - 5, l.box.y - 1, l.box.x + l.box.w + 5, l.box.y + l.box.h + 2];\n const w = m.writing;\n if (l !== undefined && w !== undefined) {\n const n = l.layout.positions.length / 2 - 1;\n const cp = caretAt(l.layout, Math.min(Math.max(w.index, 0), n));\n if (w.on) caret = [l.ox + cp.x, l.oy + cp.y - cp.above * 0.8, l.oy + cp.y + cp.below * 0.6, 1.3];\n const wp = m.wipe;\n if (wp !== undefined && wp.entry === selected && wp.t < 1) {\n const gl = l.layout.glyphs.find((q) => q.index === wp.index);\n if (gl !== undefined) { const gb = glyphBox(l.layout, gl); wipe = { box: [l.ox + gb.x0, l.oy + gb.y0, l.ox + gb.x1, l.oy + gb.y1], t: Math.max(wp.t, 0) }; }\n }\n }\n }\n let drop: SheetBox | null = null;\n if (m.drop !== undefined) { const b = dayBox(L, m.drop); if (b !== null) drop = [b.x + 2, b.y + 2, b.x + b.w - 2, b.y + b.h - 2]; }\n return { sel, mark, drop, caret, wipe };\n };\n return {\n pin(e, pose) { state(e).pose = pose; woke = true; }, // a scene's pose, pinned before its first draw (the oracle's, a test's): the draw path's own setup\n sheets: (e, durable) => rollSheets(state(e).roll, durable, law, F),\n rollOf(e) {\n const st = pads.get(e);\n if (st === undefined) return undefined;\n const r = st.roll;\n const t = r.turn;\n return { shown: r.shown, turn: t === null ? null : { dir: t.dir, p: t.p, target: t.target, held: t.drag !== null, hand: t.hand }, peek: r.peek, pending: r.pending };\n },\n peek(e, on) { const r = pads.get(e)?.roll; if (r !== undefined && r.peekOn !== on) { r.peekOn = on; woke = true; } },\n grab(e, part, sx, s, now) {\n const r = pads.get(e)?.roll;\n if (r === undefined) return false;\n let ok: boolean;\n if (part === \"moving\") ok = grabMoving(r, s, now);\n else if (part === \"roll\") ok = startTurn(r, -1, 0, law, F, { hand: true, drag: { s, now } });\n else {\n const tilt = part === \"corner\" || sx > F.W * 0.78 ? -law.roll.tilt : sx < F.W * 0.22 ? law.roll.tilt : 0;\n ok = startTurn(r, 1, tilt, law, F, { hand: true, drag: { s, now } });\n }\n if (ok) woke = true;\n return ok;\n },\n dragTo(e, s, now, moved) { const st = pads.get(e); if (st === undefined) return; dragTo(st.roll, s, now, moved, law, F); woke = true; },\n letGo(e, now, cancel) { const st = pads.get(e); if (st === undefined) return; letGo(st.roll, now, law, F, cancel); woke = true; },\n rollOwed() {\n for (const st of pads.values()) if (st.roll.rolled && st.roll.shown !== null) return true;\n return false;\n },\n rolled() {\n const out: { e: Entity; month: number }[] = [];\n for (const [e, st] of pads) if (st.roll.rolled && st.roll.shown !== null) { st.roll.rolled = false; out.push({ e, month: st.roll.shown }); }\n return out;\n },\n unroll(e) { const st = pads.get(e); if (st === undefined) return; st.roll.pending = null; woke = true; },\n busy: () => pads.size > 0,\n state,\n alpha(a) { const k = host.pass(); if (k instanceof CalendarKind && k.alpha !== a) k.alpha = a; },\n events: (e) => host.children?.rows(e, CalendarEvent) ?? [],\n today: todayNow,\n // a pin is its own frame, never a turn of the day: the next look at the wall clock starts afresh\n pinToday(key) { todayPin = key === null ? null : (dayOr(key) ?? null); dayShown = null; dayCheckAt = Number.NEGATIVE_INFINITY; woke = true; },\n pinZone(zone) { zonePin = zone; dayShown = null; dayCheckAt = Number.NEGATIVE_INFINITY; woke = true; },\n ticks(on) { if (on !== undefined && on !== ticksOn) { ticksOn = on; woke = true; } return ticksOn; },\n entries: (e) => entriesOf(e),\n printOf: (e, month) => { const st = pads.get(e); return st === undefined ? undefined : prints.get(`${st.id}:${month}`)?.print; },\n pinPrint(e, month, sheet) { const st = state(e); if (sheet === null) st.pinned.delete(month); else st.pinned.set(month, sheet); woke = true; },\n mark(e, marks) { const st = pads.get(e); if (st !== undefined && !sameMarks(st.marks, marks)) { st.marks = marks; woke = true; } },\n marksOf: (e) => pads.get(e)?.marks,\n draft(e, d) { const st = pads.get(e); if (st !== undefined && st.draft !== d) { st.draft = d; woke = true; } },\n draftOf: (e) => pads.get(e)?.draft ?? null,\n tiles: () => ({ resident: tiles?.resident() ?? 0, pending: tiles?.pending() ?? 0, drawn: tiles?.drawn() ?? 0, starved: tiles?.starved() ?? 0 }),\n readSheet(e, month, level) {\n const st = pads.get(e);\n const print = st === undefined ? undefined : prints.get(`${st.id}:${month}`)?.print;\n const raster = printer;\n if (print === undefined || raster === undefined) return undefined;\n const out = new Map<string, Uint8Array<ArrayBuffer>>();\n const empty = new Set<string>();\n const grid = tileGrid(F.W, F.H);\n for (const [tx, ty] of tilesIn(grid, level, 0, 0, F.W, F.H)) {\n const r = tileRect(level, tx, ty);\n const g = GUTTER / bandOf(level);\n if (!anyIn(print, r.x - g, r.y - g, r.w + 2 * g, r.h + 2 * g)) { empty.add(`${tx}:${ty}`); continue; }\n out.set(`${tx}:${ty}`, raster.bytes(print, r.x - g, r.y - g, r.w + 2 * g, r.h + 2 * g, bandOf(level)));\n }\n return { tiles: out, empty };\n },\n veils() {\n if (veilsCache === null) { const all = new Set<Entity>(); for (const st of pads.values()) for (const n of st.hidden) all.add(n); veilsCache = all; }\n return veilsCache;\n },\n draw(e, G, view, look) {\n const st = state(e);\n // the notes stuck to it that go with its months (before the things are drawn: the pads paint first)\n const hidden = hiddenOf(e, G);\n if (hidden.size !== st.hidden.size || [...hidden].some((n) => !st.hidden.has(n))) { st.hidden = hidden; veilsCache = null; }\n const writing = st.marks?.writing?.entry ?? Number.NaN;\n const markMonth = G.marksOn === 1 && G.moving !== null ? G.moving : G.base;\n const pass = passOf();\n let markPrint: SheetPrint | undefined;\n const sheets: [number, number][] = [[G.base, st.slot * 2]];\n if (G.moving !== null) sheets.push([G.moving, st.slot * 2 + 1]);\n for (const [month, slot] of sheets) {\n const pinned = st.pinned.get(month);\n if (pass !== undefined && pinned !== undefined) { const t = tilesOf(pass); t.pin(pass, `${st.id}:${month}`, slot, pinned); t.end(pass); continue; }\n const print = look === undefined ? undefined : printFor(e, st, month, G.weekStart, look, month === markMonth ? writing : Number.NaN);\n if (month === markMonth) markPrint = print;\n if (pass === undefined || print === undefined || printer === undefined) continue;\n // the sheet in view (sheet units) and the rung the screen wants — the moving sheet a rung softer, as the prototype drew it\n const x0 = view.camX - (G.cx - F.W / 2);\n const y0 = view.camY - (G.cy - F.H / 2);\n const x1 = x0 + view.width / view.zoom;\n const y1 = y0 + view.height / view.zoom;\n if (x1 < 0 || y1 < 0 || x0 > F.W || y0 > F.H) continue;\n const level = levelFor(view.zoom * view.dpr);\n const t = tilesOf(pass);\n const tiles0 = t.drawn();\n t.sheet(pass, printer, `${st.id}:${month}`, slot, print, { x0, y0, x1, y1 }, month === G.base ? level : Math.max(level - 1, 0), G.moving === null ? 2 : 1);\n if (t.drawn() !== tiles0) land(e);\n t.end(pass);\n }\n return marksOn(st, markMonth, G.weekStart, markPrint);\n },\n /** The budget's ask (D6): the tile texture is the pass's, fixed — always kept. */\n keeps: () => true,\n landed: (e) => landedOf.get(e) ?? 0,\n // K7a: next live now while a month turns, a pad drew with tiles still to print, or a pin, a peek, a drag asked; when its layer is\n // made, LAYER_IDLE_MS after it was last drawn; the day's turn at the wall clock's next midnight in the pad's zone — never sooner\n due(now) {\n if (woke || rolling || (begun && (tiles?.pending() ?? 0) > 0)) return now;\n for (const st of pads.values()) if (st.roll.rolled && st.roll.shown !== null) return now; // a finished roll for the hand to commit\n if (pads.size === 0) return Number.POSITIVE_INFINITY;\n const own = passOf();\n const release = own?.layerMade === true ? own.lastDrawn + LAYER_IDLE_MS : Number.POSITIVE_INFINITY;\n return Math.min(release, now + Math.max(0, dayCheckAt - clock()));\n },\n tick(now) {\n // tiles still to draw are a reason for a frame only while a pad DREW since the last tick: a pad culled (the builder resolves\n // nothing off-screen) or gone leaves its count standing, and a count no frame will ever lower kept the desk awake (D7)\n const drew = begun;\n begun = false;\n chargeTiles();\n // the layer's targets (K6a, D-K6a.3): made at the first pad drawn, let go once none was for LAYER_IDLE_MS\n const own = passOf();\n if (own?.layerMade && !own.drawnWithin(LAYER_IDLE_MS)) own.releaseLayer();\n // the months turning (their springs on the frame's clock); tiles still to draw: another frame (the marks' clocks — the\n // caret's blink, the wipe — are the hand's: it marks anew)\n const dt = lastTick === null ? 0 : Math.min(Math.max((now - lastTick) / 1000, 0), 0.1);\n lastTick = now;\n let turning = false;\n for (const st of pads.values()) if (st.roll.durable !== null && st.pose === undefined && stepRoll(st.roll, st.roll.durable, dt, law, F)) turning = true;\n rolling = turning;\n // the day turns over (D7): today's ring and its ticks — an unrolled pad's month too — move at midnight; the wall clock is asked\n // when the day next turns (K7a — `nextTurn`, the kind's registered wake; it was once a second), and a pinned today never turns\n let turned = false;\n const wall = clock();\n if (wall >= dayCheckAt) {\n dayCheckAt = nextTurn(wall);\n const d = todayNow();\n turned = dayShown !== null && d !== dayShown;\n dayShown = d;\n }\n const w = woke || turning || turned || (drew && (tiles?.pending() ?? 0) > 0);\n woke = false;\n return w;\n },\n forget(e) {\n const st = pads.get(e);\n if (st === undefined) return;\n free.push(st.slot);\n pads.delete(e);\n landedOf.delete(e);\n if (st.hidden.size > 0) veilsCache = null;\n tiles?.drop(st.id, [st.slot * 2, st.slot * 2 + 1]);\n for (const k of [...prints.keys()]) if (k.startsWith(`${st.id}:`)) prints.delete(k);\n // no pad on the desk (K6a): the tiles, the layer and (K7a) the page tables and meshes go — the next pad starts afresh\n if (pads.size === 0) { const pass = passOf(); pass?.releaseTiles(); pass?.releaseLayer(); pass?.releaseTables(); pass?.releaseMeshes(); tiles = null; }\n },\n dispose() { pads.clear(); prints.clear(); },\n };\n}\n\n/** Two marks the same (the local wakes only when they moved). */\nfunction sameMarks(a: PadMarks | undefined, b: PadMarks | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/** The print look as a key (a changed look is a changed print). */\nconst lookKeys = new WeakMap<PrintLook, string>();\nfunction lookKey(look: PrintLook): string {\n let k = lookKeys.get(look);\n if (k === undefined) { k = JSON.stringify(look); lookKeys.set(look, k); }\n return k;\n}\n\n/** A sheet as the pass draws it (the oracle's `sheetDrawOf`): where its grid is printed, its rows, weekends and days, its table's slot. */\nexport function sheetDraw(month: number, weekStart: 0 | 1, slot: number, law: CalendarLaw = CALENDAR): SheetDraw {\n const L = sheetOf(monthGrid(month, weekStart), law);\n const g = L.grid;\n let weekends = 0;\n for (let col = 0; col < 7; col++) if (isWeekendCol(g, col)) weekends |= 1 << col;\n return { x0: L.x0, y0: L.y0, cw: L.cw, ch: L.ch, rows: L.rows, weekends, lead: g.lead, days: g.days, slot };\n}\n\n/** How far a pad's drawing reaches past its sheet, world units: its lift through the eye and its shadow (the pad lies low), the ring's offset. */\nexport function calendarReach(law: CalendarLaw = CALENDAR): number {\n const F = padFrame(law);\n const h = F.zTape + law.lift;\n return law.shadow.slopeMax * h + 3 * (law.shadow.sigma0 + law.shadow.perUnit * h) + law.ring.offset + 8;\n}\n\n/**\n * A desk calendar's silhouette for the desk's marks (D4a — the brackets, a member's ticks, the tape): its sheet's footprint\n * on the mat, square to it, about the pad's centre, with the sheet's corner. The height's parallax aside, as the print's;\n * the oracle's marks read the same function (oracle/frame.mjs).\n */\nexport function calendarFrame(cx: number, cy: number, law: CalendarLaw = CALENDAR): MarkFrame {\n const F = padFrame(law);\n return { cx, cy, hx: F.W / 2, hy: F.H / 2, angle: 0, r: law.sheet.radius };\n}\n\n/** The bar's ‹ › (D3t-c): the pad's month one on or back — its durable `month`, ONE transaction off the undo stack (a roll is not an edit). */\nfunction turnBy(api: HeldToolApi, d: 1 | -1): void {\n // a pad with no month chosen steps from the platform's month (the bar has no word from the pad's clock; a still spawns its month)\n const m = monthOfKey(stringProp(api.props(), \"month\", \"\")) ?? monthOfDay(todayOf());\n api.setProps({ month: monthKeyOf(m + d) }, { undoable: false });\n}\n\n/** The bar's today (D3t-c): the hand rolls the pad home and selects today — asked through the pad's selection (`home` bumped). */\nfunction homeOf(api: HeldToolApi): void {\n const cur = api.world.get(api.entity, PadSelection);\n if (cur === undefined) api.world.addComponent(api.entity, PadSelection, { anchor: \"\", focus: \"\", entry: 0 as Entity, home: 1 });\n else api.world.edit(api.entity).set(PadSelection, { ...cur, home: (cur.home ?? 0) + 1 });\n}\n\nexport interface CalendarKindOptions {\n readonly text?: ShaderText;\n /** The calendar's numbers (calendar/law.ts `CALENDAR`) — the engine's unless a host tweaks them. */\n readonly law?: CalendarLaw;\n}\n\n/** The desk calendar's kind, whole (kinds/world.ts `ObjectKind`): the program, and the world half on the lab's own pad. */\nexport function calendarKind(opts: CalendarKindOptions = {}): ObjectKind<CalendarGeometry, CalendarDraw, CalendarObjectLook> {\n const law = opts.law ?? CALENDAR;\n const program = calendarProgram(opts.text ?? shaderText);\n const F = padFrame(law);\n const mesh = buildPad(new MeshWriter(2048, 8192), F, law);\n const roll = (p: number, tilt: number): RollState => rollState(p, { rest: law.roll.rest + 0.6, tau: law.roll.tau }, F.L, F.W, tilt);\n return {\n ...program,\n reach: calendarReach(law),\n // its entries and its pins are cells of its data children (D3t-c): a line typed, a peer's edit, a note stuck — the builder wakes\n reads: { components: [CalendarEvent, NotePin] },\n local: (host: KindHost): Pads => createPads(host, { law }),\n // THE OPENING (design-015 §8, D4b — Q-q): the month comes to the hand laid bare, flat under the pose's camera (the notes stuck\n // to it ride along, as when the pad is carried). Its tools, LIVE on D3t-a's seam (D3t-c): ‹ › turn the month — its durable\n // `month`, ONE transaction off the undo stack (D-D3t-c.5; the kind's local rolls the sheet there) —, today asks the hand to roll\n // home and select today (`PadSelection.home`, the user's fact), and the PEN is the tool in hand: a press on the month is its\n // (the days selected, a line written, a sheet rolled by hand — never a tap that puts the pad down)\n open: {\n extent: (c) => c.rect,\n tools: [\n { id: \"month:-1\", label: \"Previous month\", kind: \"action\", keys: [\"ArrowLeft\", \"PageUp\", \"[\"], hint: \"←\", glyph: \"chevron-left\", run: (api) => turnBy(api, -1) },\n { id: \"month:1\", label: \"Next month\", kind: \"action\", keys: [\"ArrowRight\", \"PageDown\", \"]\"], hint: \"→\", glyph: \"chevron\", run: (api) => turnBy(api, 1) },\n { id: \"today\", label: \"Today\", kind: \"action\", keys: [\"t\"], hint: \"T\", glyph: \"today\", run: (api) => homeOf(api) },\n { id: \"pen\", label: \"The pen\", kind: \"mode\", keys: [\"p\"], hint: \"P\", glyph: \"pen\" },\n ],\n tool: () => \"pen\",\n },\n resolve(ctx: ObjectContext): CalendarGeometry {\n const pads = ctx.local as Pads | undefined;\n const pose = pads?.state(ctx.entity).pose;\n // no month chosen (the default ''): the month of the pad's today (its clock seam — a still's pinned day), never a literal (D7)\n const shown = monthOfKey(stringProp(ctx.props, \"month\", \"\")) ?? monthOfDay(pads?.today() ?? todayOf());\n const weekStart: 0 | 1 = numberProp(ctx.props, \"weekStart\", 1) === 0 ? 0 : 1;\n let sh: { base: number; moving: number | null; roll: RollState | null; marksOn: 0 | 1 } = { base: shown, moving: null, roll: null, marksOn: 0 };\n const r = pose?.roll;\n let laid = shown;\n let turning = r !== undefined;\n if (r !== undefined) sh = r.dir === 1 ? { base: shown + 1, moving: shown, roll: roll(r.p, r.tilt ?? 0), marksOn: 1 } : { base: shown, moving: shown - 1, roll: roll(r.p, r.tilt ?? 0), marksOn: 0 };\n else if ((pose?.peek ?? 0) > 1e-3) sh = { base: shown + 1, moving: shown, roll: roll(((pose?.peek ?? 0) * law.roll.peek) / (F.L - law.roll.rest), -law.roll.tilt), marksOn: 1 };\n else if (pads !== undefined && pose === undefined) {\n // the months turning (D3t-c): the pad shows the month it has laid bare and rolls toward the document's\n const t = pads.sheets(ctx.entity, shown);\n laid = t.shown;\n turning = t.turning;\n sh = { base: t.base, moving: t.moving, roll: t.roll, marksOn: t.marksOn };\n }\n const lift = law.lift * ctx.flux.lift;\n const v = ctx.view;\n return {\n shown: laid, weekStart, ...sh, rigid: rigidOf({ cx: ctx.rect.cx, cy: ctx.rect.cy, angle: 0, lift, tiltX: 0, tiltY: 0, zc: 0 }),\n lamp: lampDir(ctx.lamp, ctx.rect.cx, ctx.rect.cy, law.shadow.slopeMax), lift, ring: ctx.flux.ring * ctx.flux.fade,\n eye: eyeOf({ x: v.camX, y: v.camY, zoom: v.zoom }, { width: v.width, height: v.height }, law.eye), cx: ctx.rect.cx, cy: ctx.rect.cy,\n held: ctx.held !== undefined, turning,\n };\n },\n record(G: CalendarGeometry, ctx: ObjectContext): CalendarDraw {\n const look = ctx.look as CalendarObjectLook | undefined;\n const tapes = look?.tapes ?? {};\n const tape = tapes[stringProp(ctx.props, \"tape\", \"\")] ?? Object.values(tapes)[0];\n const pen = look?.pens[stringProp(ctx.props, \"pen\", \"\")] ?? Object.values(look?.pens ?? {})[0];\n if (look === undefined || tape === undefined || pen === undefined) throw new Error(\"desk/calendar: the pad's colours are the host's — the palette names no `calendars` (or no `pens`) (kinds/calendar.ts `CalendarPalette`)\");\n const pads = ctx.local as Pads | undefined;\n pads?.alpha(look.alpha);\n const st = pads?.state(ctx.entity) ?? { id: 1, slot: 0 };\n const colours: CalendarColours = { paper: look.paper, ink: look.ink, muted: look.muted, weekend: look.weekend, hot: look.hot, chipboard: look.chipboard, cloth: tape.cloth, foil: tape.foil, pen };\n // the print (D3t-c): the sheets' tiles brought up to date from the events; the hand's marks on the sheet they are on\n const marks = pads?.draw(ctx.entity, G, ctx.view, look.print) ?? { sel: [], mark: null, drop: null, caret: null, wipe: null };\n return {\n id: st.id, frame: F, mesh, version: 1, rigid: G.rigid, lamp: G.lamp, lift: G.lift, ring: G.ring,\n base: sheetDraw(G.base, G.weekStart, st.slot * 2, law), moving: G.moving !== null ? sheetDraw(G.moving, G.weekStart, st.slot * 2 + 1, law) : null, roll: G.roll, marksOn: G.marksOn,\n ...marks, colours,\n // without the desk's local nobody sets the pass's presences: the record carries its look's\n ...(pads === undefined ? { alpha: look.alpha } : {}),\n };\n },\n hit(G: CalendarGeometry, wx: number, wy: number): ObjectHit | null {\n // the desk point unprojected at the pad's face (its top sheet, lifted) through the eye. At rest the tape is the pad's (a press\n // carries it, a tap selects it) and the ROLL's handles are parts (the roll under the tape, the corner, the foot, the sheet in\n // motion — a press there rolls, never pans, D3t-c); its paper is not taken — a drag there pans the desk, a click is the days'\n // (host/calendar-input.ts reads it at event time). In hand the whole sheet is the pen's surface (`content`: a press there is\n // the tool's, D3t-a) and the tape the pad's frame.\n const at = partAt(G, wx, wy, [], law);\n if (at === null) return null;\n if (at.part === \"tape\") return \"frame\";\n if (G.held) return \"content\";\n return at.part === \"roll\" || at.part === \"corner\" || at.part === \"foot\" || at.part === \"moving\" ? at.part : null;\n },\n frame: (G: CalendarGeometry): MarkFrame => calendarFrame(G.cx, G.cy, law),\n theme(palette: Palette, _name: ThemeName): CalendarObjectLook {\n const p = palette as CalendarPalette;\n const c = p.calendars;\n const pens = Object.fromEntries(Object.entries(p.pens ?? {}).map(([k, t]) => [k, rgb(t.css)]));\n if (c === undefined) return { paper: [0, 0, 0], ink: [0, 0, 0], muted: [0, 0, 0], weekend: [0, 0, 0], hot: [0, 0, 0], chipboard: [0, 0, 0], tapes: {}, pens, alpha: { rule: 0, head: 0, weekend: 0, outside: 0 } };\n // the print's inks (D3t-c): the fixture's `calendarPrint` from the same tokens — the pens a line is written in, the pencil, the highlighters\n const print: PrintLook | undefined = c.pencil === undefined || c.highlighters === undefined ? undefined : {\n ink: cssOf(rgb(c.ink.css)), muted: cssOf(rgb(c.muted.css)), faint: c.alpha.faint ?? 0.26, hot: cssOf(rgb(c.hot.css)), pencil: cssOf(rgb(c.pencil.css), PENCIL_ALPHA),\n pens: Object.fromEntries(Object.entries(p.pens ?? {}).map(([k, t]) => [k, cssOf(rgb(t.css))])),\n highlighters: Object.fromEntries(Object.entries(c.highlighters).map(([k, t]) => [k, cssOf(rgb(t.css))])), highlight: c.alpha.highlight ?? 0.62,\n };\n const alpha: CalendarAlpha = { rule: c.alpha.rule, head: c.alpha.head, weekend: c.alpha.weekend, outside: c.alpha.outside };\n return {\n paper: rgb(c.paper.css), ink: rgb(c.ink.css), muted: rgb(c.muted.css), weekend: rgb(c.weekend.css), hot: rgb(c.hot.css), chipboard: rgb(c.chipboard.css),\n tapes: Object.fromEntries(Object.entries(c.tapes).map(([k, t]) => [k, { cloth: rgb(t.cloth.css), foil: rgb(t.foil.css) }])), pens, alpha: c.alpha,\n ...(print !== undefined ? { print } : {}),\n };\n },\n };\n}\n","// THE DESK CALENDAR AT WORK — its hand (CALENDAR.md §5; D3t-c): the world half of the calendar's interaction, the whiteboard pen's\n// sibling (objects/pen.ts). Once a frame, before the kinds' clocks, it READS the world — each pad's selection (`PadSelection`, the\n// user's fact), the entry being written (objects/calendar-writing.ts) and the editor's caret (host/calendar-input.ts) — and hands\n// the calendar kind's local what to MARK on each pad this frame (`Pads.mark`: the days selected, the entry, the caret's blink, the\n// newest glyph's wipe). It WRITES only as an op would, each out of the frame (a reflector never writes — D-D2c.5): the bar's today\n// (`home` bumped) rolls the pad home — its month, ONE transaction, off the undo stack (D-D3t-c.5) — and selects today.\n\nimport { Active, Camera, Captures, ChildOf, type CommitIntent, defineQuery, Down, DownPart, type Entity, Grab, type GuardedTx, heldEntity, HeldPointer, HeldPress, LocalPointer, Pointer, PointerButtons, PointerPart, PointerScreen, PointerVersion, PointerWorld, Position, PrefabId, setWidgetProps, Size, TouchesExact, TransformTween, Watches, type World } from \"@ice/core\";\nimport { dayOr, daySlot, monthKeyOf, NotePin, PadSelection, pinNote, PinsNote } from \"./data\";\nimport { CALENDAR, type CalendarLaw } from \"./law\";\nimport { keyOf, monthOfDay } from \"./month\";\nimport { padFrame } from \"./pad\";\nimport { type CalendarGeometry, DRAFT_ID, type PadMarks, type Pads, partAt, sheetPoint } from \"./kind\";\nimport type { CalendarWriting } from \"./writing\";\nimport { type TypingDocs, writable } from \"@ice/desk\";\n\nexport interface CalendarHandOptions {\n readonly world: World;\n readonly docs: TypingDocs;\n readonly pads: () => Pads | undefined;\n readonly writing: CalendarWriting;\n /** The editor's caret on the line being written — its index and when its blink restarted (the hand's clock) — and the newest glyph's wipe. */\n readonly caret: () => { readonly index: number; readonly t0: number; readonly wipe: { readonly index: number; readonly t0: number } | null } | null;\n /** The caret's blink, ms (530). */\n readonly blinkMs?: number;\n /** The newest glyph's wipe, ms (the hand's 110). */\n readonly wipeMs?: number;\n /** Where a transaction runs: out of the frame (a microtask) unless a test says. */\n readonly defer?: (fn: () => void) => void;\n /** The builder's word on a pad — its geometry as drawn, the hand's frame, the held pose (the roll by hand reads them; absent: no hands). */\n readonly geometryOf?: (e: Entity) => unknown;\n readonly hand?: () => { readonly entity: Entity; readonly landing: boolean; readonly frame: { readonly cx: number; readonly cy: number; readonly s: number } } | undefined;\n readonly heldToWorld?: (e: Entity, x: number, y: number) => readonly [number, number] | undefined;\n readonly isPad?: (e: Entity) => boolean;\n /** Is this entity a sticky note (it may be stuck to a day)? Absent: nothing sticks. */\n readonly isNote?: (e: Entity) => boolean;\n /** The glide into a day's slot, ms (the prototype's 3.2 Hz spring, as a tween). */\n readonly glideMs?: number;\n readonly law?: CalendarLaw;\n}\n\nexport interface CalendarHand {\n /** Once a frame, before the kinds' clocks: the marks on every pad; the bar's today acted on. */\n follow(now: number): void;\n /** Nothing to follow (D7 #14): no pad on the desk, nothing in hand, no press, no selection, no note carried, no glide owed. */\n idle(): boolean;\n /** Leave the document's commit door (the landing's extender). */\n dispose(): void;\n}\n\nconst selectionsQ = defineQuery([PadSelection]);\n/** The objects being carried (core's move rider). */\nconst grabbedQ = defineQuery([Grab, Position, Size]);\n/** The frame's objects (the pads a note may be dropped on). */\nconst framedQ = defineQuery([PrefabId, Position, Size, Active]);\n/** Core's recognizers that began on a PART (their capture and their down) — a press on a pad's roll at rest. */\nconst partPressQ = defineQuery([Down, DownPart]);\nconst pointersQ = defineQuery([Pointer, LocalPointer, PointerScreen]);\n/** The parts a hand rolls a month by. */\nconst ROLL_PARTS = new Set([\"foot\", \"corner\", \"roll\", \"moving\"]);\ntype RollPart = \"foot\" | \"corner\" | \"roll\" | \"moving\";\n/** A press moved this far (CSS px) is a drag: its release decides by the third or the flick, never as a click. */\nconst MOVED_PX = 4;\n\n\nexport function createCalendarHand(opts: CalendarHandOptions): CalendarHand {\n const { world, docs } = opts;\n const law = opts.law ?? CALENDAR;\n const F = padFrame(law);\n /** The hands on a pad's roll, by pointer: the pad, where the press began (CSS px). */\n const hands = new Map<Entity, { readonly pad: Entity; readonly x0: number; readonly y0: number }>();\n /** The pads whose corner the pointer lifted last frame. */\n let peeked = new Set<Entity>();\n /**\n * The pointer's input and the camera as the last `follow` saw them (K7a — registered wakes): the peek follows the pointer over a\n * pad, so a pad on the desk needs the hand only when either moved since — never every frame (D7 #14's crutch, which kept a\n * desk with a calendar awake forever).\n */\n let seenPointer = -1;\n let seenCamera = -1;\n const G = (e: Entity): CalendarGeometry | undefined => opts.geometryOf?.(e) as CalendarGeometry | undefined;\n /** A pointer's desk point: at rest the world's; in hand through the pose the renderer drew (as core maps `HeldPointer`). */\n const deskOf = (p: Entity, pad: Entity): readonly [number, number] | undefined => {\n if (heldEntity(world) === pad) {\n const hp = world.get(p, HeldPointer);\n return hp === undefined ? undefined : opts.heldToWorld?.(pad, hp.x, hp.y);\n }\n const w = world.get(p, PointerWorld);\n return w === undefined ? undefined : [w.x, w.y];\n };\n /** The presses on a pad's roll this frame, by pointer: at rest core's recognizers on a roll part; in hand the pen's press, its part where it began. */\n const pressesNow = (): Map<Entity, { pad: Entity; part: RollPart; x: number; y: number }> => {\n const out = new Map<Entity, { pad: Entity; part: RollPart; x: number; y: number }>();\n world.query(partPressQ).each((b) => {\n for (const r of b) {\n const rec = b.entity(r);\n const part = world.read(rec, DownPart).part ?? \"\";\n const pad = world.getRelation(rec, Captures);\n const p = world.getRelations(rec, Watches)[0];\n if (!ROLL_PARTS.has(part) || pad === undefined || p === undefined || opts.isPad?.(pad) !== true) continue;\n if (((world.get(p, PointerButtons)?.buttons ?? 0) & 1) === 0 || out.has(p)) continue;\n const d = world.read(rec, Down);\n out.set(p, { pad, part: part as RollPart, x: d.x, y: d.y });\n }\n });\n const held = heldEntity(world);\n if (held !== undefined && opts.isPad?.(held) === true) {\n world.query(pointersQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n const pr = world.get(p, HeldPress);\n if (pr === undefined || pr.kind !== \"tool\" || ((world.get(p, PointerButtons)?.buttons ?? 0) & 1) === 0 || out.has(p)) continue;\n const known = hands.get(p);\n if (known !== undefined) { out.set(p, { pad: held, part: \"moving\", x: known.x0, y: known.y0 }); continue; }\n // where the press BEGAN (its screen point, through the hand's frame): a roll part starts a roll; the days are the DOM half's\n const h = opts.hand?.();\n const g = G(held);\n if (h === undefined || h.entity !== held || g === undefined) continue;\n const at = opts.heldToWorld?.(held, (pr.x - h.frame.cx) / h.frame.s, (pr.y - h.frame.cy) / h.frame.s);\n const part = at === undefined ? null : partAt(g, at[0], at[1], [], law);\n if (part !== null && ROLL_PARTS.has(part.part)) out.set(p, { pad: held, part: part.part as RollPart, x: pr.x, y: pr.y });\n }\n });\n }\n return out;\n };\n /** The hands on the pads' rolls: a press takes the sheet, the finger drags it, the release lets it decide. */\n const rollByHand = (pads: Pads, now: number): void => {\n const presses = pressesNow();\n for (const [p, pr] of presses) {\n const g = G(pr.pad);\n const at = deskOf(p, pr.pad);\n if (g === undefined || at === undefined) continue;\n const { sx, sy } = sheetPoint(g, at[0], at[1], law);\n const s = sy - F.T;\n const screen = world.get(p, PointerScreen);\n const moved = screen !== undefined && Math.hypot(screen.x - pr.x, screen.y - pr.y) > MOVED_PX;\n if (!hands.has(p)) {\n if (pads.grab(pr.pad, pr.part, sx, s, now)) hands.set(p, { pad: pr.pad, x0: pr.x, y0: pr.y });\n continue;\n }\n pads.dragTo(pr.pad, s, now, moved);\n }\n for (const [p, h] of [...hands]) if (!presses.has(p)) { pads.letGo(h.pad, now); hands.delete(p); }\n };\n /** The corner lifts under a pointer near the foot or the corner (not pressed): at rest the pick's part, in hand the pad's own. */\n const peekUnder = (pads: Pads): void => {\n const now = new Set<Entity>();\n const held = heldEntity(world);\n world.query(pointersQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n // (pressed or not: a pressed hand on the foot is a turn, and a turn lets the corner down itself)\n if (world.read(p, Pointer).device !== \"mouse\") continue;\n if (held !== undefined) {\n if (opts.isPad?.(held) !== true) continue;\n const at = deskOf(p, held);\n const g = G(held);\n const part = at === undefined || g === undefined ? null : partAt(g, at[0], at[1], [], law);\n if (part !== null && (part.part === \"foot\" || part.part === \"corner\")) now.add(held);\n continue;\n }\n const pad = world.getRelation(p, TouchesExact);\n const part = world.get(p, PointerPart)?.part ?? \"\";\n if (pad !== undefined && opts.isPad?.(pad) === true && (part === \"foot\" || part === \"corner\")) now.add(pad);\n }\n });\n for (const pad of now) pads.peek(pad, true);\n for (const pad of peeked) if (!now.has(pad)) pads.peek(pad, false);\n peeked = now;\n };\n // ---- the notes stuck to days\n const glideMs = opts.glideMs ?? 320;\n /** The pin holding a note: the pin, its pad, its day (a note is stuck to one day at most). */\n const pinOf = (note: Entity): { readonly pin: Entity; readonly pad: Entity; readonly day: string } | undefined => {\n for (const pin of world.getReverse(note, PinsNote)) {\n const pad = world.getRelation(pin, ChildOf);\n const v = world.get(pin, NotePin);\n if (pad !== undefined && v !== undefined) return { pin, pad, day: v.day ?? \"\" };\n }\n return undefined;\n };\n /** The pad and the day a note's centre is over — a day of the month laid bare, on a pad at rest (the prototype's `dropTarget`). */\n const dropTarget = (note: Entity): { readonly pad: Entity; readonly day: number } | undefined => {\n const p = world.get(note, Position);\n const z = world.get(note, Size);\n if (p === undefined || z === undefined) return undefined;\n return dropTargetAt(note, p.x + z.w / 2, p.y + z.h / 2);\n };\n /** The pad and the day a point (a note's centre) is over — a day of the month laid bare, on a pad at rest. */\n const dropTargetAt = (note: Entity, cx: number, cy: number): { readonly pad: Entity; readonly day: number } | undefined => {\n let best: { pad: Entity; day: number } | undefined;\n world.query(framedQ).each((b) => {\n for (const r of b) {\n const pad = b.entity(r);\n if (pad === note || opts.isPad?.(pad) !== true || world.has(pad, Grab)) continue;\n const g = G(pad);\n if (g === undefined || g.turning) continue;\n const part = partAt(g, cx, cy, [], law);\n if (part === null || part.day === undefined || monthOfDay(part.day) !== g.shown) continue;\n best = { pad, day: part.day };\n }\n });\n return best;\n };\n /** The notes carried by themselves this frame (not riding their carried pad) and the day each would stick to, shown on its pad. */\n const dropMarks = (): Map<Entity, number> => {\n const drops = new Map<Entity, number>();\n if (opts.isNote === undefined) return drops;\n world.query(grabbedQ).each((b) => {\n for (const r of b) {\n const note = b.entity(r);\n if (!opts.isNote?.(note)) continue;\n const held = pinOf(note);\n if (held !== undefined && world.has(held.pad, Grab)) continue; // riding its carried pad: it goes where the pad goes\n const t = dropTarget(note);\n if (t !== undefined) drops.set(t.pad, t.day);\n }\n });\n return drops;\n };\n /** The glides owed after a landing: the note drawn from where it was let go while the document already holds its slot. */\n const glides: { readonly note: Entity; readonly from: { readonly x: number; readonly y: number }; readonly to: { readonly x: number; readonly y: number } }[] = [];\n /**\n * THE LANDING (D7 #2): core's move intent for a note, inside ITS transaction (the facade's `extendCommits`) — let go over a day\n * of a month laid bare, the note is STUCK: its old pin (if any) destroyed, its pin on the day, the note at the day's slot; let go\n * over no day (or consumed into a container), UNSTUCK: its pin destroyed. Nothing is written while the note is carried: Esc\n * restores the note and commits nothing, so the pin outlives a cancelled carry; and the whole drop — the move, the pins, the\n * slot — is ONE undo step. A note riding its carried pad is the pad's move to carry (core's riders), not this hand's.\n */\n const landing = (intent: CommitIntent, tx: GuardedTx): void => {\n if (opts.isNote === undefined || (intent.kind !== \"move\" && intent.kind !== \"consume\")) return;\n for (const w of intent.writes) {\n if (w.component !== Position || !opts.isNote(w.entity) || !world.isAlive(w.entity)) continue;\n const note = w.entity;\n const held = pinOf(note);\n if (held !== undefined && world.has(held.pad, Grab)) continue;\n const at = w.value as { readonly x: number; readonly y: number };\n const z = world.get(note, Size);\n const t = intent.kind === \"move\" && z !== undefined ? dropTargetAt(note, at.x + z.w / 2, at.y + z.h / 2) : undefined;\n if (t === undefined) {\n if (held !== undefined && world.isAlive(held.pin)) tx.destroy(held.pin);\n continue;\n }\n const day = keyOf(t.day);\n if (held !== undefined && held.pad === t.pad && held.day === day) continue; // let go on its own day: nothing to do\n const pp = world.get(t.pad, Position);\n const pz = world.get(t.pad, Size);\n if (pp === undefined || pz === undefined || z === undefined) continue;\n const weekStart = (((G(t.pad)?.weekStart) ?? 1) === 0 ? 0 : 1) as 0 | 1;\n let slot: { x: number; y: number };\n try { slot = daySlot(pp.x + pz.w / 2, pp.y + pz.h / 2, day, weekStart, law); } catch { continue; }\n const to = { x: slot.x - z.w / 2, y: slot.y - z.h / 2 };\n if (held !== undefined && world.isAlive(held.pin)) tx.destroy(held.pin);\n pinNote(tx, t.pad, note, day);\n tx.edit(note).set(Position, to);\n if (glideMs > 0 && (at.x !== to.x || at.y !== to.y)) glides.push({ note, from: { x: at.x, y: at.y }, to });\n }\n if (glides.length > 0) defer(glide);\n };\n /** After the landing's transaction: the note is drawn from where it was let go, a tween being its claim (ops.arrange's way). */\n const glide = (): void => {\n const session = writable(docs);\n for (const g of glides.splice(0)) {\n if (session === undefined || !world.isAlive(g.note)) continue;\n world.addComponent(g.note, TransformTween, { toX: g.to.x, toY: g.to.y, durationMs: glideMs, elapsedMs: 0 });\n session.liveWriter.set(g.note, Position, g.from);\n }\n };\n const leaveDoor = docs.extendCommits?.(landing);\n\n /**\n * A hand's finished roll: the document's month follows it — ONE transaction, off the undo stack; refused, the pad rolls back\n * to the document's month. The pad's hold on the month (`pending`) is NOT released here on a landed commit (D7 #3, corrected by\n * gate:landing): the kinds' `tick` runs before the draw path refreshes the roll's `durable`, so a release at the commit left one\n * frame in which the target fell back to the OLD month and a turn back began (the part under the tape read `moving`). The\n * release is the roll's own (calendar/turn.ts): the document SPEAKS — its month moves, to the hand's or, a race lost, to a\n * peer's — and the hold ends; a landed month moves it at the next sync, a lost race moves it at least once either way.\n */\n const commitRolls = (pads: Pads): void => {\n for (const { e, month } of pads.rolled()) {\n defer(() => {\n const session = writable(docs);\n let ok = false;\n if (session !== undefined && world.isAlive(e)) {\n try { setWidgetProps(session.store, world, e, { month: monthKeyOf(month) }, { undoable: false }); ok = true; } catch { ok = false; }\n }\n if (!ok) pads.unroll(e);\n });\n }\n };\n const defer = opts.defer ?? ((fn: () => void) => queueMicrotask(fn));\n const blinkMs = opts.blinkMs ?? 530;\n const wipeMs = opts.wipeMs ?? 110;\n /** The pads marked last frame (a pad whose selection went is given back its bare sheet). */\n let marked = new Set<Entity>();\n /** Each pad's `home` as last seen: a bump is the bar's today. */\n const homes = new Map<Entity, number>();\n\n /** Roll a pad home and select today: its month (one transaction, off the undo stack) and its days. */\n const goHome = (pad: Entity): void => {\n const pads = opts.pads();\n if (pads === undefined) return;\n const today = pads.today();\n const key = keyOf(today);\n const month = monthKeyOf(monthOfDay(today));\n defer(() => {\n if (!world.isAlive(pad)) return;\n const cur = world.get(pad, PadSelection);\n if (cur !== undefined) world.edit(pad).set(PadSelection, { ...cur, anchor: key, focus: key, entry: 0 as Entity });\n const session = writable(docs);\n if (session === undefined) return;\n try { setWidgetProps(session.store, world, pad, { month }, { undoable: false }); } catch { /* refused (the prop's schema, the guard): the month stays */ }\n });\n };\n\n return {\n follow(now) {\n seenPointer = world.resourceStamp(PointerVersion);\n seenCamera = world.resourceStamp(Camera);\n const pads = opts.pads();\n if (pads === undefined) return;\n if (opts.isPad !== undefined) { rollByHand(pads, now); peekUnder(pads); }\n commitRolls(pads);\n const drops = dropMarks();\n const next = new Set<Entity>();\n const w = opts.writing.current();\n world.query(selectionsQ).each((b) => {\n for (const r of b) {\n const pad = b.entity(r);\n const sel = world.read(pad, PadSelection);\n const seen = homes.get(pad);\n if (sel.home !== (seen ?? 0)) goHome(pad);\n homes.set(pad, sel.home);\n const a = dayOr(sel.anchor ?? \"\");\n const f = dayOr(sel.focus ?? \"\");\n const entry = sel.entry as number;\n const marks: { -readonly [K in keyof PadMarks]: PadMarks[K] } = {};\n if (a !== undefined && f !== undefined) marks.days = [Math.min(a, f), Math.max(a, f)];\n if (entry !== 0 && world.isAlive(sel.entry)) marks.entry = entry;\n const drop = drops.get(pad);\n if (drop !== undefined) { marks.drop = drop; drops.delete(pad); }\n pads.mark(pad, Object.keys(marks).length > 0 ? marks : undefined);\n next.add(pad);\n }\n });\n // a note carried over a pad with no selection: the day it would stick to\n for (const [pad, day] of drops) { pads.mark(pad, { drop: day }); next.add(pad); }\n // the line being written: its caret (the blink on the hand's clock), its newest glyph's wipe\n if (w !== null) {\n const id = w.draft !== null ? DRAFT_ID : ((w.entry as number | null) ?? DRAFT_ID);\n const c = opts.caret();\n const base = pads.marksOf(w.pad) ?? {};\n const on = c === null ? true : Math.floor(Math.max(0, now - c.t0) / blinkMs) % 2 === 0;\n const wipe = c?.wipe !== null && c?.wipe !== undefined && now - c.wipe.t0 < wipeMs ? { entry: id, index: c.wipe.index, t: Math.max(0, (now - c.wipe.t0) / wipeMs) } : undefined;\n const { days: _days, ...rest } = base;\n pads.mark(w.pad, { ...rest, entry: id, writing: { entry: id, index: c?.index ?? w.draft?.text.length ?? 0, on }, ...(wipe !== undefined ? { wipe } : {}) });\n next.add(w.pad);\n }\n for (const pad of marked) if (!next.has(pad)) pads.mark(pad, undefined);\n marked = next;\n for (const pad of [...homes.keys()]) if (!world.isAlive(pad) || !world.has(pad, PadSelection)) homes.delete(pad);\n },\n idle() {\n if (heldEntity(world) !== undefined || hands.size > 0 || peeked.size > 0 || marked.size > 0 || homes.size > 0 || glides.length > 0) return false;\n const pads = opts.pads();\n if (pads?.rollOwed() === true) return false; // a roll finished: the hand commits it (K7a — once asked every frame)\n if (pads?.busy() === true && (world.resourceStamp(PointerVersion) !== seenPointer || world.resourceStamp(Camera) !== seenCamera)) return false;\n if (world.firstOf(selectionsQ) !== undefined || world.firstOf(grabbedQ) !== undefined) return false;\n let pressed = false;\n world.query(pointersQ).each((b) => { for (const r of b) if (((world.get(b.entity(r), PointerButtons)?.buttons ?? 0) & 1) !== 0) pressed = true; });\n return !pressed;\n },\n dispose() {\n leaveDoor?.();\n glides.length = 0;\n },\n };\n}\n","// WRITING ON THE CALENDAR IS A GESTURE (CALENDAR.md §5; design-015 §6.1; D3t-c) — an entry's text through the note's text stack:\n// the ONE editor (host/editor.ts, lent to the calendar), typing as a gesture (objects/typing.ts's law, on an event's cell). The\n// world half, as typing.ts is the note's:\n//\n// - an EXISTING entry: `beginEntry` stamps the runtime `Editing` claim on its EVENT entity — core's `makeDefaultMayDiverge` reads it\n// as a gesture claim — so its cell (`desk.event` — the days, the text, the hand's seeds, the ink: ONE cell, text and seeds one\n// conflict group by construction, D-D3t-c.1) is written LIVE through the guarded live writer on every keystroke, the seeds\n// carried (`carrySeeds`); the SESSION's end (`commit` — the editor's: ⏎, blur, 1 s without input) is ONE undoable transaction,\n// unless it nets to nothing (the text and the hand as the session found them: no transaction, the cell put back exactly); an entry\n// written down to nothing is taken off the pad in that one transaction;\n// - a NEW line is a DRAFT (D-D3t-c.4): the calendar's own state (the kind's local prints it), never an empty entity in the document\n// — its session's end SPAWNS it, text and seeds and days and ink, as ONE transaction (`addEvent`), and the writing goes on on the\n// entity it became; a draft that nets to nothing spawns nothing.\n//\n// `cancel` (the editor's Esc — \"esc takes it back\", CALENDAR.md §5) puts the session back: a draft gone, an entry's cell as the\n// session found it, no transaction. ⌘Z undoes a SESSION, never a keystroke. Collaboration is strata's claimed-cell rule, as a note's.\n\nimport { type DocSession, Editing, type Entity, guardedTransaction, type World } from \"@ice/core\";\nimport { addEvent, CalendarEvent, type EventRow } from \"./data\";\nimport { keyOf } from \"./month\";\nimport type { PadDraft, Pads } from \"./kind\";\nimport { decodeSeeds, encodeSeeds, freshSeed, carrySeeds } from \"@ice/desk/kit\";\nimport { type TypingDocs, writable } from \"@ice/desk\";\n\nexport interface CalendarWritingOptions {\n readonly world: World;\n readonly docs: TypingDocs;\n /** The calendar kind's state on this desk (the draft is printed through it). */\n readonly pads: () => Pads | undefined;\n /** A fresh seed for a glyph just written (`Math.random` unless a test says). */\n readonly fresh?: () => number;\n}\n\n/** What is being written: its pad, and the entry (an event entity) or the draft (a new line not yet in the document). */\nexport interface WritingTarget {\n readonly pad: Entity;\n readonly entry: Entity | null;\n readonly draft: PadDraft | null;\n}\n\nexport interface CalendarWriting {\n current(): WritingTarget | null;\n /** A NEW line on days `start` … `end` of `pad`, in `ink` — a draft until its session ends. False for a dead pad. */\n beginNew(pad: Entity, start: number, end: number, ink: string): boolean;\n /** Write into an existing entry (the `Editing` claim on it). False for a dead entry or one not of `pad`. */\n beginEntry(pad: Entity, entry: Entity): boolean;\n /** The platform's value (a line: a newline is a space): the draft's text, or the entry's cell written LIVE; the inserted run, or null. */\n input(value: string): { readonly from: number; readonly to: number } | null;\n /** The text as it stands (the draft's, or the entry's live cell). */\n text(): string;\n /** A session is open: text written and not yet committed. */\n open(): boolean;\n /** End the SESSION — ONE transaction (the draft spawned, the cell committed, an emptied entry removed) or none; the writing stays on. */\n commit(): boolean;\n /** Take the session back — a draft gone, an entry's cell as found — and end the writing. */\n cancel(): void;\n /** End the writing: commit, then lift the claim. */\n end(): void;\n /** Transactions committed since creation (a rig's witness). */\n commits(): number;\n}\n\ntype Cell = { readonly start: string; readonly end: string; readonly text: string; readonly seeds: string; readonly ink: string };\n\nconst cellOf = (row: EventRow | undefined): Cell | undefined => (row === undefined ? undefined : { start: row.start ?? \"\", end: row.end ?? \"\", text: row.text ?? \"\", seeds: row.seeds ?? \"\", ink: row.ink ?? \"felt\" });\n/** A line of writing: no newlines (a paste's become spaces). */\nconst oneLine = (v: string): string => v.replace(/\\r?\\n/g, \" \");\n\nexport function createCalendarWriting(opts: CalendarWritingOptions): CalendarWriting {\n const { world, docs } = opts;\n const fresh = opts.fresh ?? freshSeed;\n let target: { pad: Entity; entry: Entity | null; draft: PadDraft | null } | null = null;\n /** The entry's cell as the session found it (before its first live write). */\n let start: Cell | undefined;\n let open = false;\n let commits = 0;\n\n const alive = (e: Entity | null | undefined): e is Entity => e !== null && e !== undefined && world.isAlive(e);\n const read = (e: Entity): Cell | undefined => cellOf(world.get(e, CalendarEvent) as EventRow | undefined);\n const live = (session: Pick<DocSession, \"store\" | \"liveWriter\"> | undefined, e: Entity, c: Cell): void => {\n if (session !== undefined) session.liveWriter.set(e, CalendarEvent, { ...c });\n else world.edit(e).set(CalendarEvent, { ...c });\n };\n const setDraft = (d: PadDraft | null): void => { if (target !== null) { target.draft = d; opts.pads()?.draft(target.pad, d); } };\n const lift = (e: Entity | null): void => { if (alive(e) && world.hasTag(e, Editing)) world.removeTag(e, Editing); };\n\n const commit = (): boolean => {\n const t = target;\n if (t === null || !open) return false;\n open = false;\n const session = writable(docs);\n if (t.draft !== null) {\n // a NEW line: spawned now, whole — or nothing, if nothing was written\n const d = t.draft;\n if (d.text.trim().length === 0 || session === undefined || !alive(t.pad)) { setDraft(null); return false; }\n let made: Entity | undefined;\n try {\n guardedTransaction(session.store, world, (tx) => { made = addEvent(tx, t.pad, { start: keyOf(d.start), end: keyOf(d.end), text: d.text, seeds: encodeSeeds(d.seeds), ink: d.ink }); });\n } catch { made = undefined; }\n setDraft(null);\n if (made === undefined || !world.isAlive(made)) { t.entry = null; return false; }\n commits += 1;\n // the writing goes on, on the entry it became\n t.entry = made;\n world.addTag(made, Editing);\n start = undefined;\n return true;\n }\n const e = t.entry;\n const from = start;\n start = undefined;\n if (!alive(e) || session === undefined) return false;\n const cur = read(e);\n if (cur === undefined) return false;\n // NETS TO NOTHING — the text and the hand as the session found them: no transaction, the cell put back exactly\n if (from !== undefined && from.text === cur.text && from.seeds === cur.seeds) return false;\n if (from !== undefined && from.text === cur.text) { live(session, e, from); return false; }\n try {\n guardedTransaction(session.store, world, (tx) => {\n // an entry written down to nothing leaves the pad (the prototype's `commit`: \"kept if anything was written, gone if not\")\n if (cur.text.trim().length === 0) tx.destroy(e);\n else tx.edit(e).set(CalendarEvent, { ...cur });\n });\n } catch { return false; }\n commits += 1;\n return true;\n };\n\n const end = (): void => {\n const t = target;\n commit();\n target = null;\n open = false;\n start = undefined;\n if (t !== null) { lift(t.entry); if (t.draft !== null) opts.pads()?.draft(t.pad, null); }\n };\n\n return {\n current: () => (target === null ? null : { pad: target.pad, entry: alive(target.entry) ? target.entry : null, draft: target.draft }),\n beginNew(pad, s, e, ink) {\n if (target !== null) end();\n if (!alive(pad)) return false;\n if (docs.current() !== undefined && writable(docs) === undefined) return false; // a read-only document: no line begins on it\n target = { pad, entry: null, draft: null };\n setDraft({ start: Math.min(s, e), end: Math.max(s, e), text: \"\", seeds: [], ink });\n open = false;\n start = undefined;\n return true;\n },\n beginEntry(pad, entry) {\n if (target !== null && target.entry === entry) return true;\n if (target !== null) end();\n if (!alive(pad) || !alive(entry) || read(entry) === undefined) return false;\n if (docs.current() !== undefined && writable(docs) === undefined) return false; // a read-only document: its lines are read, not written\n world.addTag(entry, Editing);\n target = { pad, entry, draft: null };\n open = false;\n start = undefined;\n return true;\n },\n input(value) {\n const t = target;\n if (t === null) return null;\n const v = oneLine(value);\n if (t.draft !== null) {\n const d = t.draft;\n if (d.text === v) return null;\n const carried = carrySeeds(d.text, d.seeds, v, fresh);\n setDraft({ ...d, text: v, seeds: carried.seeds });\n open = true;\n return { from: carried.from, to: carried.to };\n }\n const e = t.entry;\n if (!alive(e)) return null;\n const cur = read(e);\n if (cur === undefined || cur.text === v) return null;\n const carried = carrySeeds(cur.text, decodeSeeds(cur.seeds), v, fresh);\n if (!open) start = cur;\n live(docs.current(), e, { ...cur, text: v, seeds: encodeSeeds(carried.seeds) });\n open = true;\n return { from: carried.from, to: carried.to };\n },\n text() {\n const t = target;\n if (t === null) return \"\";\n if (t.draft !== null) return t.draft.text;\n return alive(t.entry) ? (read(t.entry)?.text ?? \"\") : \"\";\n },\n open: () => open,\n commit,\n cancel() {\n const t = target;\n if (t === null) return;\n if (t.draft !== null) setDraft(null);\n else if (alive(t.entry) && open && start !== undefined) live(docs.current(), t.entry, start); // back as the session found it: it reconverges, no transaction\n open = false;\n start = undefined;\n lift(t.entry);\n target = null;\n },\n end,\n commits: () => commits,\n };\n}\n","// THE DAYS AND THE PEN — the calendar's DOM half (CALENDAR.md §5; D3t-c), leasing the desk's ONE editor for its day line (K8a). A day\n// is chosen, and a line begun, at EVENT TIME — the focus that makes typing write must be taken in the event (design-007 §2; a\n// phone's keyboard opens only so, D-D2c.6) — so the clicks on a pad's paper are read here, on the container, at rest and in hand:\n//\n// - a CLICK on a day selects it (⇧ stretches the selection over a run) and lends the ONE editor to the calendar, so the keys are\n// the days' (the keymap cedes to the editor's claim): ⏎ or just typing writes a line on it, the arrows walk the days (over a\n// month's edge the pad follows), t goes home, PageUp/PageDown/[/] turn the month, Esc lets go; a click on a LINE selects it (⌫\n// takes it off — one transaction; ⏎ writes into it); ⌘Z/⇧⌘Z are the document's;\n// - a DOUBLE-CLICK on a day writes a line on it (on the run, if the day is in the one selected), on a line writes into it with the\n// caret where it was pointed; a day under 150 px on screen is PICKED UP first (*Marks on the Mat*: picking it up replaces the\n// prototype's lean-in to the week) — the pen begins at once and the editor rides the pad into the hand;\n// - writing: ⏎ keeps the line, Esc takes it back (\"esc takes it back\"), a blur keeps it, 1 s without input ends a session.\n//\n// At rest a pad's paper is a MISS for the interaction stack (a drag there pans the desk — D-D3w.7), so a click there is the days'\n// only when nothing above it was hit (the pointer's exact hit is empty); in hand the point is mapped through the pose the renderer\n// drew (the builder's `heldToWorld`, as core maps `HeldPointer`). The world half is objects/calendar-writing.ts (the sessions) and\n// the `PadSelection` fact this writes; objects/calendar-hand.ts marks it on the pad each frame.\n\nimport { Active, Camera, CanvasSurface, defineQuery, type Entity, GestureSettings, guardedTransaction, HeldIntent, heldEntity, LocalPointer, Pointer, Position, PrefabId, setWidgetProps, Size, TouchesExact, trayOpen, type WidgetType, type World } from \"@ice/core\";\nimport { dayOr, monthKeyOf, PadSelection } from \"../data\";\nimport { isSpan } from \"../events\";\nimport { CALENDAR, type CalendarLaw } from \"../law\";\nimport { inMonth, keyOf, monthGrid, monthOfDay } from \"../month\";\nimport type { EventLine } from \"../print\";\nimport { dayBox, sheetOf } from \"../sheet\";\nimport { type CalendarGeometry, type CalendarObjectLook, type CalendarPart, DRAFT_ID, partAt, sheetOnScreen } from \"../kind\";\nimport type { CalendarDriver } from \"../object\";\nimport { type TypingDocs, writable } from \"@ice/desk\";\nimport type { DeskEditor, EditorLease } from \"@ice/desk/kit\";\n\n/** The desk calendar's text part's name (K8a) — a day's line: what the editor's lease carries while the calendar holds it. */\nexport const CALENDAR_LINE = \"calendar.line\";\n\nexport interface CalendarInputOptions {\n readonly container: HTMLElement;\n readonly world: World;\n /** The builder's word on a pad: its geometry as drawn, the hand's frame, the held pose (host/layer.ts hands the builder). */\n readonly geometryOf: (e: Entity) => unknown;\n readonly hand: () => { readonly entity: Entity; readonly landing: boolean; readonly frame: { readonly cx: number; readonly cy: number; readonly s: number } } | undefined;\n readonly heldToWorld: (e: Entity, x: number, y: number) => readonly [number, number] | undefined;\n readonly editor: DeskEditor;\n /** The calendar's driver (`CalendarDriver`, D-D7-A.3): this is the CALENDAR's DOM half, which the calendar declares (K4b) — the host hands it the calendar's own and it joins it; none, no input. */\n readonly driver: CalendarDriver | undefined;\n /** The calendar object (its compiled widget type — its first group is a pad's props: its month, its week start). */\n readonly object: WidgetType;\n readonly docs: TypingDocs;\n /** The calendar's look as the desk composed it (the highlighters a band is drawn in). */\n readonly look: () => unknown;\n readonly law?: CalendarLaw;\n /** The hand's clock (the caret's blink, the wipe): `performance.now` unless a test says. */\n readonly now?: () => number;\n readonly wake: () => void;\n}\n\nexport interface CalendarInput {\n /** The caret on the line being written — its index, its blink's restart, the newest glyph's wipe — for the hand's marks. */\n caret(): { readonly index: number; readonly t0: number; readonly wipe: { readonly index: number; readonly t0: number } | null } | null;\n /** Select days on a pad (a rig's door, the keys' own path): a run from `anchor` to `focus`; lends the editor. */\n selectDays(pad: Entity, anchor: number, focus: number): void;\n /** Select an entry on a pad; lends the editor. */\n selectEntry(pad: Entity, entry: Entity): void;\n /** Let go of the selection (and the editor). */\n clear(): void;\n /** Begin writing a new line on the selected days (the ⏎'s path); true when it began. */\n write(): boolean;\n /** Write into an entry, the caret at `index` (the end by default). */\n edit(pad: Entity, entry: Entity, index?: number): boolean;\n /** What a client point lands on — the pad and its part — as a click would read it (a rig's door). */\n partAtClient(clientX: number, clientY: number): { readonly pad: Entity; readonly part: CalendarPart } | null;\n dispose(): void;\n}\n\nconst padsQ = defineQuery([PrefabId, Position, Size, Active]);\nconst pointersQ = defineQuery([Pointer, LocalPointer]);\n\n/** The caret index nearest a sheet point on a line — where a tap puts the pen (the prototype's `caretIndexAt`). */\nexport function caretIndexAt(line: EventLine, sx: number, sy: number): number {\n const L = line.layout;\n const t = line.event.text;\n const n = L.positions.length / 2 - 1;\n const off = t.length - n; // a timed line's layout starts after its time\n let best = t.length;\n let score = Number.POSITIVE_INFINITY;\n for (let i = 0; i <= n; i++) {\n const px = line.ox + (L.positions[2 * i] as number);\n const py = line.oy + (L.positions[2 * i + 1] as number);\n const s = Math.abs(py - L.ascent * 0.4 - sy) * 3 + Math.abs(px - sx);\n if (s < score) { score = s; best = i + off; }\n }\n return Math.max(0, Math.min(best, t.length));\n}\n\nexport function createCalendarInput(opts: CalendarInputOptions): CalendarInput | undefined {\n const cal = opts.driver;\n if (cal === undefined) return undefined; // no calendar kind on this desk: no days, no pen\n const { container, world, editor } = opts;\n const { writing, pads, isPad } = cal;\n const look = (): CalendarObjectLook | undefined => opts.look() as CalendarObjectLook | undefined;\n /** The pad's props as the world holds them (its pen, its month, its week start). */\n const propsOf = (e: Entity): Readonly<Record<string, unknown>> => (world.isAlive(e) ? ((world.get(e, opts.object.groups[0]?.component as never) as Record<string, unknown> | undefined) ?? {}) : {});\n /** Write a pad's props (its month) — ONE transaction, off the undo stack: a roll is not an edit (D-D3t-c.5). */\n const setProps = (e: Entity, props: Readonly<Record<string, unknown>>): void => {\n const session = writable(opts.docs);\n if (session === undefined || !world.isAlive(e)) return;\n try { setWidgetProps(session.store, world, e, props, { undoable: false }); } catch { /* refused (the prop's schema, the guard): the month stays */ }\n };\n const law = opts.law ?? CALENDAR;\n const clock = opts.now ?? (() => performance.now());\n /** The pad the editor is lent for (its days, its line), or null. */\n let pad: Entity | null = null;\n let caretIndex = 0;\n let caretT0 = 0;\n let wipe: { index: number; t0: number } | null = null;\n /** The press in flight: where it began, and the run lent when it did (the press's blur lets the days go before its click). */\n let down: { id: number; type: string; x: number; y: number; lent: { readonly pad: Entity; readonly anchor: string } | null } | null = null;\n\n const G = (e: Entity): CalendarGeometry | undefined => opts.geometryOf(e) as CalendarGeometry | undefined;\n const selOf = (e: Entity) => (world.isAlive(e) ? world.get(e, PadSelection) : undefined);\n const setSel = (e: Entity, sel: { anchor?: string; focus?: string; entry?: Entity }): void => {\n const cur = world.get(e, PadSelection);\n const next = { anchor: sel.anchor ?? \"\", focus: sel.focus ?? \"\", entry: sel.entry ?? (0 as Entity), home: cur?.home ?? 0 };\n if (cur === undefined) world.addComponent(e, PadSelection, next);\n else if (cur.anchor !== next.anchor || cur.focus !== next.focus || cur.entry !== next.entry) world.edit(e).set(PadSelection, next);\n opts.wake();\n };\n const dropSel = (e: Entity): void => { if (world.isAlive(e) && world.has(e, PadSelection)) world.removeComponent(e, PadSelection); opts.wake(); };\n const printLines = (e: Entity): readonly EventLine[] => { const g = G(e); return g === undefined ? [] : (pads()?.printOf(e, g.shown)?.lines ?? []); };\n const runOf = (e: Entity): readonly [number, number] | null => {\n const s = selOf(e);\n const a = dayOr(s?.anchor ?? \"\");\n const f = dayOr(s?.focus ?? \"\");\n return a === undefined || f === undefined ? null : [Math.min(a, f), Math.max(a, f)];\n };\n const monthOfPad = (e: Entity): number | undefined => G(e)?.shown;\n /** Turn a pad to a month: its durable month, one transaction off the undo stack (the local rolls it there). */\n const turnTo = (e: Entity, month: number): void => { if (monthOfPad(e) !== month) setProps(e, { month: monthKeyOf(month) }); };\n\n // ---- the lease: the ONE editor's keys and value while the calendar holds it\n const lease: EditorLease = {\n part: CALENDAR_LINE,\n label: \"write on the calendar\",\n value: () => (writing.current() !== null ? writing.text() : \"\"),\n input(value) {\n const e = pad;\n if (e === null) return;\n if (writing.current() === null) {\n // just typing on a selected day writes a line on it — the key already in the field (a space alone writes nothing)\n if (value.trim().length === 0) { editor.element.value = \"\"; return; }\n if (!beginOnRun(e)) { editor.element.value = \"\"; return; }\n }\n const r = writing.input(value);\n caretIndex = editor.element.selectionStart;\n caretT0 = clock();\n if (r !== null) {\n const ch = value[r.from];\n wipe = r.to - r.from === 1 && ch !== undefined && ch !== \" \" ? { index: r.from, t0: clock() } : null;\n }\n },\n keydown(ev) {\n const e = pad;\n if (e === null) return false;\n const k = ev.key;\n const mod = ev.metaKey || ev.ctrlKey;\n const w = writing.current();\n if (w !== null) {\n if (k === \"Enter\") { finishWriting(true); return true; }\n if (k === \"Escape\") { finishWriting(false); return true; }\n return false; // the line's own keys: the platform's (its caret, its undo while focused — D-D2c.9)\n }\n // the document's history through the facade's doors (historyStep: the tween retarget, the read-only posture — D7 #9)\n if (mod && (k === \"z\" || k === \"Z\")) { if (ev.shiftKey) opts.docs.redo?.(); else opts.docs.undo?.(); return true; }\n if (mod || ev.altKey) return false;\n if (k === \"Escape\") { clear(); return true; }\n if (k === \"t\" || k === \"T\") { goToday(e); return true; }\n if (k === \"PageDown\" || k === \"]\") { const m = monthOfPad(e); if (m !== undefined) turnTo(e, m + 1); return true; }\n if (k === \"PageUp\" || k === \"[\") { const m = monthOfPad(e); if (m !== undefined) turnTo(e, m - 1); return true; }\n const s = selOf(e);\n const entry = s !== undefined && s.entry !== (0 as Entity) && world.isAlive(s.entry) ? s.entry : null;\n if (entry !== null) {\n if (k === \"Backspace\" || k === \"Delete\") { removeEntry(e, entry); return true; }\n if (k === \"Enter\") { edit(e, entry); return true; }\n return k.length !== 1; // a printable key on a selected line writes nothing (the prototype's), and is swallowed by `input`\n }\n const run = runOf(e);\n if (run !== null) {\n const move = k === \"ArrowRight\" ? 1 : k === \"ArrowLeft\" ? -1 : k === \"ArrowDown\" ? 7 : k === \"ArrowUp\" ? -7 : 0;\n if (move !== 0) {\n const f = (dayOr(s?.focus ?? \"\") ?? run[1]) + move;\n if (ev.shiftKey) setSel(e, { anchor: s?.anchor ?? keyOf(f), focus: keyOf(f) });\n else setSel(e, { anchor: keyOf(f), focus: keyOf(f) });\n // over a month's edge the pad follows\n turnTo(e, monthOfDay(f));\n return true;\n }\n if (k === \"Enter\") { write(); return true; }\n if (k === \"Backspace\" || k === \"Delete\") return true;\n }\n return false;\n },\n caret(index) { caretIndex = index; caretT0 = clock(); },\n place() {\n const e = pad;\n const g = e === null ? undefined : G(e);\n if (e === null || g === undefined) return null;\n const w = writing.current();\n let box: { x: number; y: number; w: number; h: number } | null = null;\n if (w !== null) {\n const id = w.draft !== null ? DRAFT_ID : (w.entry as number | null) ?? DRAFT_ID;\n const l = printLines(e).find((q) => q.event.id === id);\n if (l !== undefined) box = { x: l.box.x, y: l.box.y, w: l.box.w, h: law.hand.pitch };\n }\n if (box === null) {\n const run = runOf(e);\n const b = run === null ? null : dayBox(sheetOf(monthGrid(g.shown, g.weekStart), law), run[0]);\n box = b === null ? null : { x: b.x + law.hand.pad, y: b.y + law.hand.top, w: b.w - 2 * law.hand.pad, h: law.hand.pitch };\n }\n if (box === null) return null;\n const [x0, y0] = sheetOnScreen(g, box.x, box.y, undefined, law);\n const [x1, y1] = sheetOnScreen(g, box.x + box.w, box.y + box.h, undefined, law);\n const h = Math.max(1, y1 - y0);\n return { x: x0, y: y0, w: Math.max(1, x1 - x0), h, fontPx: law.hand.size * (h / box.h) };\n },\n idle() { writing.commit(); },\n ended() {\n // a blur (a press anywhere else) keeps the line being written and lets go of the days: the keys go back to the desk\n const e = pad;\n if (writing.current() !== null) writing.end();\n pad = null;\n wipe = null;\n if (e !== null) dropSel(e);\n },\n };\n\n const lendFor = (e: Entity): void => {\n if (pad !== null && pad !== e) editor.release(lease); // another pad's days let go (the lease's end drops them)\n pad = e;\n editor.lend(lease);\n caretT0 = clock();\n };\n /** A new line on the selected run (a band across several days, in the next highlighter; a line in the pad's pen). */\n const beginOnRun = (e: Entity): boolean => {\n const run = runOf(e);\n if (run === null) return false;\n const [a, b] = run;\n const g = G(e);\n if (g !== undefined && a === b && !inMonth(monthGrid(g.shown, g.weekStart), a)) { turnTo(e, monthOfDay(a)); return false; }\n let ink: string;\n if (b > a) {\n const names = Object.keys(look()?.print?.highlighters ?? {});\n const spans = (pads()?.entries(e) ?? []).filter((ev) => ev.id !== DRAFT_ID && isSpan(ev)).length;\n ink = names.length > 0 ? (names[spans % names.length] as string) : \"yellow\";\n } else ink = String(propsOf(e).pen ?? \"felt\");\n if (!writing.beginNew(e, a, b, ink)) return false;\n setSel(e, {});\n // too small to write on: the pad comes to the hand first (the editor rides it)\n pickUpIfSmall(e);\n return true;\n };\n const pickUpIfSmall = (e: Entity): void => {\n if (heldEntity(world) === e) return;\n const cam = world.getResource(Camera);\n if (cam === undefined || law.grid.cw * cam.zoom >= 150) return;\n const prev = world.getResource(HeldIntent);\n world.setResource(HeldIntent, { kind: \"open\", target: e, epoch: (prev?.epoch ?? 0) + 1 });\n };\n const finishWriting = (keep: boolean): void => {\n const w = writing.current();\n if (w === null) return;\n if (keep) writing.commit();\n const entry = writing.current()?.entry ?? null;\n if (keep) writing.end();\n else writing.cancel();\n wipe = null;\n // kept: the line is selected; taken back: the day it was on\n if (keep && entry !== null && world.isAlive(entry)) setSel(w.pad, { entry });\n else if (w.draft !== null) setSel(w.pad, { anchor: keyOf(w.draft.start), focus: keyOf(w.draft.end) });\n else if (w.entry !== null && world.isAlive(w.entry)) setSel(w.pad, { entry: w.entry });\n editor.element.value = \"\";\n };\n const removeEntry = (e: Entity, entry: Entity): void => {\n const s = writable(opts.docs);\n if (s === undefined) return;\n try { guardedTransaction(s.store, opts.world, (tx) => { tx.destroy(entry); }); } catch { return; }\n setSel(e, {});\n opts.wake();\n };\n const goToday = (e: Entity): void => {\n const today = pads()?.today();\n if (today === undefined) return;\n setSel(e, { anchor: keyOf(today), focus: keyOf(today) });\n turnTo(e, monthOfDay(today));\n };\n const clear = (): void => {\n const e = pad;\n if (writing.current() !== null) writing.end();\n editor.release(lease);\n if (e !== null) dropSel(e);\n pad = null;\n };\n const write = (): boolean => {\n const e = pad;\n if (e === null) return false;\n if (!beginOnRun(e)) return false;\n editor.element.value = \"\";\n caretIndex = 0;\n caretT0 = clock();\n opts.wake();\n return true;\n };\n const edit = (e: Entity, entry: Entity, index?: number): boolean => {\n lendFor(e);\n if (!writing.beginEntry(e, entry)) return false;\n setSel(e, { entry });\n const v = writing.text();\n editor.element.value = v;\n const i = Math.max(0, Math.min(index ?? v.length, v.length));\n editor.element.setSelectionRange(i, i);\n caretIndex = i;\n caretT0 = clock();\n pickUpIfSmall(e);\n opts.wake();\n return true;\n };\n\n // ---- where a client point lands\n const partAtClient = (clientX: number, clientY: number): { pad: Entity; part: CalendarPart } | null => {\n const r = container.getBoundingClientRect();\n const px = clientX - r.left;\n const py = clientY - r.top;\n const held = heldEntity(world);\n if (held !== undefined) {\n // in hand: through the pose the last frame drew — the pad in hand, or nothing (the desk behind is soft)\n const h = opts.hand();\n if (h === undefined || h.entity !== held || h.landing || !isPad(held)) return null;\n const at = opts.heldToWorld(held, (px - h.frame.cx) / h.frame.s, (py - h.frame.cy) / h.frame.s);\n const g = G(held);\n if (at === undefined || g === undefined) return null;\n const part = partAt(g, at[0], at[1], printLines(held), law);\n return part === null ? null : { pad: held, part };\n }\n const cam = world.getResource(Camera);\n if (cam === undefined) return null;\n const wx = cam.x + px / cam.zoom;\n const wy = cam.y + py / cam.zoom;\n let best: { pad: Entity; part: CalendarPart } | null = null;\n world.query(padsQ).each((b) => {\n for (const row of b) {\n const e = b.entity(row);\n if (!isPad(e)) continue;\n const g = G(e);\n if (g === undefined) continue;\n const part = partAt(g, wx, wy, printLines(e), law);\n if (part !== null) best = { pad: e, part };\n }\n });\n return best;\n };\n /** Whether the interaction stack's exact hit for this pointer is empty (nothing above the paper took the click). */\n const bareUnder = (type: string, id: number): boolean => {\n const pid = type === \"touch\" ? `touch:${id}` : \"mouse\";\n let bare = true;\n world.query(pointersQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (world.read(p, Pointer).id !== pid) continue;\n const hit = world.getRelation(p, TouchesExact);\n if (hit !== undefined && !world.hasTag(hit, CanvasSurface)) bare = false; // the bare mat is the canvas surface\n }\n });\n return bare;\n };\n\n const onDown = (ev: PointerEvent): void => {\n const anchor = pad === null || runOf(pad) === null ? null : (selOf(pad)?.anchor ?? null);\n const lent = pad !== null && anchor !== null ? { pad, anchor } : null;\n down = ev.isPrimary && ev.button === 0 ? { id: ev.pointerId, type: ev.pointerType, x: ev.clientX, y: ev.clientY, lent } : null;\n };\n const tapOn = (ev: MouseEvent): { pad: Entity; part: CalendarPart } | null => {\n const d = down;\n if (d === null || ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.altKey) return null;\n const slop = world.getResource(GestureSettings)?.dragSlopPx ?? 10;\n if (Math.hypot(ev.clientX - d.x, ev.clientY - d.y) > slop) return null;\n // the pegboard drawer out: the desk is inert (design-017 §4) — `bareUnder` calls the canvas bare, so it cannot be the guard here;\n // a click on a specimen over a pad under the drawer selects no day and begins no writing (K9 law #1)\n if (trayOpen(world)) return null;\n const held = heldEntity(world);\n if (held === undefined && !bareUnder(d.type, d.id)) return null;\n return partAtClient(ev.clientX, ev.clientY);\n };\n const onClick = (ev: MouseEvent): void => {\n // the run lent when the press began: the press moved the focus off the editor, and that blur (`ended`) let the days go\n const lent = down?.lent ?? null;\n const hit = tapOn(ev);\n down = ev.detail >= 2 ? down : null;\n if (hit === null) return;\n const { pad: e, part } = hit;\n if (part.part === \"day\" && part.day !== undefined) {\n if (ev.shiftKey && lent !== null && lent.pad === e) setSel(e, { anchor: lent.anchor, focus: keyOf(part.day) });\n else setSel(e, { anchor: keyOf(part.day), focus: keyOf(part.day) });\n lendFor(e);\n return;\n }\n if (part.part === \"entry\" && part.line !== undefined) {\n if (writing.current()?.entry === (part.line.event.id as Entity)) return; // a click inside the line being written: the platform moves the caret\n if (part.line.event.id === DRAFT_ID) return;\n setSel(e, { entry: part.line.event.id as Entity });\n lendFor(e);\n return;\n }\n if (part.part === \"sheet\" && pad === e) clear();\n };\n const onDbl = (ev: MouseEvent): void => {\n const hit = tapOn(ev);\n down = null;\n if (hit === null) return;\n const { pad: e, part } = hit;\n if (part.part === \"entry\" && part.line !== undefined && part.line.event.id !== DRAFT_ID) {\n edit(e, part.line.event.id as Entity, caretIndexAt(part.line, part.sx, part.sy));\n return;\n }\n if (part.part === \"day\" && part.day !== undefined) {\n const run = runOf(e);\n const inRun = run !== null && part.day >= run[0] && part.day <= run[1];\n if (!inRun) setSel(e, { anchor: keyOf(part.day), focus: keyOf(part.day) });\n lendFor(e);\n write();\n }\n };\n container.addEventListener(\"pointerdown\", onDown, { capture: true });\n container.addEventListener(\"click\", onClick, { capture: true });\n container.addEventListener(\"dblclick\", onDbl, { capture: true });\n\n const input: CalendarInput = {\n caret: () => (writing.current() === null ? null : { index: caretIndex, t0: caretT0, wipe }),\n selectDays(e, anchor, focus) { setSel(e, { anchor: keyOf(anchor), focus: keyOf(focus) }); lendFor(e); },\n selectEntry(e, entry) { setSel(e, { entry }); lendFor(e); },\n clear,\n write,\n edit,\n partAtClient,\n dispose() {\n container.removeEventListener(\"pointerdown\", onDown, { capture: true });\n container.removeEventListener(\"click\", onClick, { capture: true });\n container.removeEventListener(\"dblclick\", onDbl, { capture: true });\n editor.release(lease);\n if (cal.input === input) cal.input = undefined;\n },\n };\n cal.input = input; // the driver's hand reads this half's caret; the driver disposes it\n return input;\n}\n","// The calendar's PRINT RASTER in the browser (CALENDAR.md §6; D3t-c) — the host half of calendar/printing.ts's seam: the\n// prototype's `tileCanvas` and `measureCtx` (lab/calendar.ts). One OffscreenCanvas the size of a tile (TILE_TEX², the gutter\n// in) is reused for every tile the driver draws; the print's type is measured on a context of its own; the HAND is the\n// note's — its face and its metrics come from the desk's text raster (desk/host/ink.ts, the faces the app hands in), so the\n// calendar writes in the very Caveat a note does and waits, blank, while it loads.\n\nimport { type HandMetrics, type TextRaster, type PrintFace, type PrintRaster, PEN_FACES } from \"@ice/desk/kit\";\nimport { drawRegion, type SheetPrint } from \"../print\";\nimport { TILE_TEX } from \"../tiles\";\n\nexport interface PrintRasterOptions {\n /** The desk's text raster: the hand's face and its metrics (the note's). */\n readonly text: TextRaster;\n /** The hand's face by name (`PEN_FACES` — the note's Caveat unless a host says). */\n readonly face?: string;\n}\n\nexport function printRaster(opts: PrintRasterOptions): PrintRaster<SheetPrint> {\n const faceName = opts.face ?? \"caveat\";\n const spec = PEN_FACES[faceName] ?? { family: \"Caveat\", weight: 500 };\n const face: PrintFace = { family: spec.family, weight: spec.weight };\n let canvas: OffscreenCanvas | null = null;\n let ctx: OffscreenCanvasRenderingContext2D | null = null;\n let measurer: OffscreenCanvasRenderingContext2D | null = null;\n const context = (): OffscreenCanvasRenderingContext2D => {\n if (ctx === null) {\n canvas = new OffscreenCanvas(TILE_TEX, TILE_TEX);\n // the CPU raster (as the note's ink): a GPU-backed 2D canvas rasterised the same tile differently run to run (seen by the\n // print check — 6 tiles of a sheet a few bytes apart), so the committed print could not be held to the live one\n ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n if (ctx === null) throw new Error(\"desk/print: no 2d context on an OffscreenCanvas\");\n }\n return ctx;\n };\n const widths = new Map<string, number>();\n return {\n hand() {\n const metrics: HandMetrics | undefined = opts.text.metrics(faceName);\n return metrics === undefined ? undefined : { face, metrics };\n },\n version: () => opts.text.version(),\n measure(font, s) {\n const key = `${font}\\u0000${s}`;\n let w = widths.get(key);\n if (w === undefined) {\n measurer ??= new OffscreenCanvas(8, 8).getContext(\"2d\");\n if (measurer === null) throw new Error(\"desk/print: no 2d context to measure with\");\n measurer.font = font;\n w = measurer.measureText(s).width;\n widths.set(key, w);\n }\n return w;\n },\n tile(print: SheetPrint, x, y, w, h, band) {\n const g = context();\n drawRegion(g, print, x, y, w, h, band);\n return g.canvas;\n },\n bytes(print: SheetPrint, x, y, w, h, band) {\n const g = context();\n drawRegion(g, print, x, y, w, h, band);\n const img = g.getImageData(0, 0, TILE_TEX, TILE_TEX);\n return new Uint8Array(img.data.buffer.slice(0));\n },\n };\n}\n","// The DESK CALENDAR (CALENDAR.md) as an OBJECT (design-015 §6; D3w): a pad of the notebook's paper under a cloth\n// tape, lying beneath everything (stratum `pads`). Durable props: the MONTH it shows (YYYY-MM), its week start\n// (1 Monday, 0 Sunday), its tape and the pen its caret is drawn in, by name (the colours are the host's). What is\n// WRITTEN on it and what is STUCK to it are data children (calendar/data.ts): its events `desk.event`, its pins\n// `desk.pin` (a note stuck to a day; D3t-c writes both, and the notes stuck to it ride with it — its `riders`).\n// Its rect is the sheet (1760 × 1852 at the law's cell); movable by its tape, selectable; a ROOT object (D-D18:\n// `interaction.drop: \"never\"` — no container takes it, whatever it accepts).\n\nimport { type Entity, p } from \"@ice/core\";\nimport { EventPrefab, PinPrefab, pinnedNotes } from \"./data\";\nimport { CALENDAR } from \"./law\";\nimport { padFrame } from \"./pad\";\nimport { type CalendarPart, calendarKind, type Pads } from \"./kind\";\nimport { DESK_OBJECT, type KindDriver, defineObject, PINNABLE } from \"@ice/desk\";\nimport { type CalendarHand, createCalendarHand } from \"./hand\";\nimport { type CalendarWriting, createCalendarWriting } from \"./writing\";\nimport { PENS, PRINT_RASTER, service, TEXT_RASTER } from \"@ice/desk/kit\";\nimport { CALENDAR_LINE, createCalendarInput } from \"./host/input\";\nimport { printRaster } from \"./host/print\";\n\n/** The tapes a pad is bound with (CALENDAR.md §4) — names; the cloths and foils are the host's. */\nexport const TAPES = [\"ink\", \"tobacco\", \"kraft\"] as const;\nexport type TapeName = (typeof TAPES)[number];\n\n/** The desk calendar's durable type id. */\nexport const CALENDAR_TYPE = \"desk.calendar\";\n\nconst PAD = padFrame(CALENDAR);\n\n/**\n * What sticks to a day (D3t-c): an object that PROVIDES `PINNABLE` (K8a — the note does; a plugin kind may), asked of the host by that\n * key (`KindDriverHost.provides`) — never by another kind's name: a desk where nothing provides it lends no predicate, and the pad\n * pins nothing.\n */\nexport { PINNABLE } from \"@ice/desk\";\n\nexport const Calendar = defineObject({\n type: CALENDAR_TYPE,\n version: 1,\n props: {\n // '' — no month chosen: the pad shows the month of its today (the calendar's clock seam, D7) until a roll writes one\n month: p.string({ default: \"\" }),\n weekStart: p.number({ default: 1 }),\n tape: p.enum(TAPES, { default: \"ink\" }),\n pen: p.enum(PENS, { default: \"felt\" }),\n },\n size: { w: PAD.W, h: PAD.H },\n kind: calendarKind(),\n // on the pegboard tray (design-017 §8): the pad on a hook\n // …printing the month of its today through its own print (K5b — `local`: `month` '' follows the clock); one taken is this month's too\n tray: { label: \"Calendar\", category: \"paper\", order: 3, local: true, hang: { w: 152, h: 160, accessory: \"hook\", pegs: [[0, -0.5]] } },\n interaction: { selectable: true, movable: true, resizable: false, snap: \"both\", drop: \"never\" },\n // it lies on the desk by what it provides (K8a — `DESK_OBJECT`, the desk canvas's one key), as a plugin kind does\n provides: [DESK_OBJECT],\n // its entries and its pins are its DATA (D3t-a's door, D3t-c): the catalog stamps, gates and migrates their prefabs with the pad's own\n data: [EventPrefab, PinPrefab],\n // the notes stuck to it RIDE with it (D3t-c — core's `riders`): carried by its tape, they move with it and land in its transaction\n riders: (world, pad) => pinnedNotes(world, pad).map((p) => p.note),\n // the desk calendar at work (D3t-c): its WRITING (the sessions the ONE editor is lent to) and its HAND (the marks, the rolls, the\n // notes' landing) — its DOM half (the days and the pen at event time) is the host's and joins through `input` (D-D7-A.3)\n drivers: (h): CalendarDriver => {\n const pads = (): Pads | undefined => h.local as Pads | undefined;\n const writing = createCalendarWriting({ world: h.world, docs: h.docs, pads });\n const isNote = h.provides(PINNABLE);\n const driver: CalendarDriver = {\n writing,\n pads,\n isPad: h.isKind,\n input: undefined,\n hand: createCalendarHand({\n world: h.world, docs: h.docs, pads, writing, caret: () => driver.input?.caret() ?? null,\n geometryOf: h.geometryOf, hand: h.hand, heldToWorld: h.heldToWorld, isPad: h.isKind, ...(isNote !== undefined ? { isNote } : {}),\n }),\n follow: (now) => driver.hand.follow(now),\n idle: () => driver.hand.idle(),\n dispose: () => { driver.hand.dispose(); driver.input?.dispose(); driver.input = undefined; },\n };\n return driver;\n },\n // its DOM HALF (K4b — declared, never found by type): its PRINT raster, lent to its world half before its local (the tiles in\n // the host's hand, D3t-c — none without a text raster: the oracle pins committed tiles), and its days and its pen at event time\n // (host/calendar-input.ts), mounted over the desk's ONE editor, which it leases (K8a: every desk has one)\n host: {\n lend: (h) => { const text = h.use(TEXT_RASTER); return text === undefined ? [] : [service(PRINT_RASTER, printRaster({ text }))]; },\n // its TEXT PART (K8a): a day's line — leased by its own half at event time (a day selected), never routed a tap by the desk\n text: () => [{ part: CALENDAR_LINE }],\n mount: (h) => {\n createCalendarInput({\n container: h.container, world: h.world, object: h.object, driver: h.driver as CalendarDriver | undefined, editor: h.editor, docs: h.docs,\n geometryOf: h.geometryOf, hand: h.hand, heldToWorld: h.heldToWorld, look: h.look, wake: h.wake,\n });\n },\n },\n});\n\n/** The calendar's DOM half as its driver sees it (host/calendar-input.ts implements it): the caret on the line being written, the part under a client point, the selection's doors. */\nexport interface CalendarInputDoors {\n caret(): { readonly index: number; readonly t0: number; readonly wipe: { readonly index: number; readonly t0: number } | null } | null;\n partAtClient(x: number, y: number): { readonly pad: Entity; readonly part: CalendarPart } | null;\n selectDays(pad: Entity, anchor: number, focus: number): void;\n selectEntry(pad: Entity, entry: Entity): void;\n clear(): void;\n dispose(): void;\n}\n\n/** The calendar's driver (`driversOf(Calendar)`): its writing, its hand, its pads, its membership — and the DOM half that joins it. */\nexport interface CalendarDriver extends KindDriver {\n readonly writing: CalendarWriting;\n readonly hand: CalendarHand;\n readonly pads: () => Pads | undefined;\n readonly isPad: (e: Entity) => boolean;\n /** The DOM half, once the host has made it (the days and the pen at event time); the hand reads its caret. */\n input: CalendarInputDoors | undefined;\n}\n","// The NOTEBOOK's law — every number the 3D notebook is made of (NOTEBOOK.md), with\n// where it came from. Pure: no GPU, no colour (the colours are the host's —\n// lab/theme.ts `NOTEBOOK_LOOK`, by token, the one law the theme gate keeps).\n//\n// World units are the desk's: a CSS px at zoom 1 (the note's scale — theme.ts\n// PAPER.size 200 = 3″, so one unit ≈ 0.38 mm and this A6-ish book is 180 × 252).\n// Axes: x right, y down the screen, z up off the mat, toward the eye.\n\nimport { PHYSICS } from \"@ice/desk/kit\";\n\nexport interface NotebookLaw {\n /** The case: the cover's width × height, a board's thickness, its fore-edge corner radius. */\n readonly cover: { readonly width: number; readonly height: number; readonly board: number; readonly radius: number };\n /** The text block: sheets and their thickness; the squares (the case's overhang past the pages); the joint (the gap between the spine and the first page when closed); a page's fore-edge corner radius. */\n readonly block: { readonly sheets: number; readonly sheet: number; readonly square: number; readonly joint: number; readonly radius: number };\n /** The quarter binding: the spine band's width on the face; the spine's bulge when closed. */\n readonly spine: { readonly band: number; readonly bulge: number };\n /**\n * The GUTTER, open: every sheet is bound at one line and rises from it to its own height in the\n * stack. A sheet leaves the binding at `entry0 + entryPer · rise` radians (at most `entryMax`) and\n * bends flat — so a thick stack climbs steeply out of the valley and a thin one barely dips, and\n * the upper sheets' fore-edges are drawn in toward the gutter more than the lower ones' (the fan\n * a real open notebook shows). `dip` is the least a page falls into the valley even when its\n * stack is thin (the binding pulls every page down).\n */\n readonly gutter: { readonly entry0: number; readonly entryPer: number; readonly entryMax: number; readonly dip: number };\n /**\n * The desk EYE: the camera stays top-down, but what rises off the mat is seen from a point above\n * the view's centre, so a lifted book grows and a standing cover keystones — the desk plane\n * itself maps exactly as the ortho camera maps it. The eye stands `k` view-diagonals up (a fixed\n * field of view when zoomed out), never nearer than `min` world units (the perspective of a book\n * held close stays a book's, not a fish-eye's).\n */\n readonly eye: { readonly k: number; readonly min: number };\n /** The lamp's shading: the sky's share where the lamp is blocked or faced away, and how far a face turned toward it may brighten over a flat one. */\n readonly light: { readonly ambient: number; readonly cap: number };\n /**\n * The SHADOW — the desk's one law (the note's, PAPER.shadow, and the photo's): a penumbra σ at\n * contact that grows per unit of height between the caster and the receiver; its darkness on\n * the mat; the slope's cap (a book far from the lamp keeps a finite shadow). Plus a CONTACT term\n * (ambient occlusion where the case meets the mat) that lets go as the book rises.\n */\n readonly shadow: {\n readonly sigma0: number; readonly perUnit: number; readonly alpha: number; readonly slopeMax: number;\n readonly contact: { readonly sigma: number; readonly alpha: number; readonly reach: number };\n };\n /** How much of the leaves' dapple a page takes (1 = the mat's own) — the palm must not blind the writing. */\n readonly dapple: { readonly page: number; readonly cover: number };\n /** The lift: a held book rises `held` units and tilts into its motion (radians per unit of CSS px/s, capped). Opening, it rises `open` units while the cover stands, and settles as it lands. Under the pointer a closed book rises `hover` — an invitation to pick it up. */\n readonly lift: { readonly held: number; readonly open: number; readonly hover: number; readonly tiltPer: number; readonly tiltMax: number };\n /** The springs (Hz, damping ratio): the cover's swing, a sheet's root and its free edge, the lift, the tilt, the corner's peek, the ring. */\n readonly springs: {\n readonly cover: readonly [number, number]; readonly root: readonly [number, number]; readonly edge: readonly [number, number];\n readonly lift: readonly [number, number]; readonly tilt: readonly [number, number]; readonly peek: readonly [number, number];\n readonly ring: readonly [number, number];\n };\n /** A sheet's bend: how its angle travels from the root to the free edge (1 = a circular arc; more = the edge curls most). */\n readonly bend: number;\n /** The corner's peek on hover: the free edge's lift (rad) and the twist that keeps it to one corner; the zone that invites it (units from the corner). */\n readonly peek: { readonly angle: number; readonly twist: number; readonly zone: number };\n /** A page's outer share that turns it on a click (the rest of the page is for the pen). */\n readonly turnZone: number;\n /** The flutter as a book lands open: the first sheets' kick (rad/s), falling off by sheet. */\n readonly flutter: { readonly kick: number; readonly sheets: number };\n /** The paper: fibre and mottle (±/255), the tooth's relief, the cockle (units), the ruling (units). */\n readonly paper: { readonly fibre: number; readonly mottle: number; readonly tooth: number; readonly cockle: number; readonly pitch: number; readonly dot: number; readonly margin: number };\n /** The cloth: the weave's pitch (units), its relief, the sheen (blinn exponent, strength). */\n readonly cloth: { readonly pitch: number; readonly relief: number; readonly sheen: readonly [number, number] };\n /** The selection ring on the mat around a selected book: offset from the footprint, width (CSS px). */\n readonly ring: { readonly offset: number; readonly width: number };\n}\n\nexport const NOTEBOOK: NotebookLaw = {\n cover: { width: 180, height: 252, board: 2.4, radius: 8 },\n block: { sheets: 64, sheet: 0.19, square: 3.2, joint: 5, radius: 5.5 },\n spine: { band: 30, bulge: 2.6 },\n gutter: { entry0: 0.32, entryPer: 0.055, entryMax: 1.2, dip: 2.2 },\n eye: { k: 1.15, min: 1250 },\n light: { ambient: 0.46, cap: 1.28 },\n // PAPER.shadow's slope cap and contact σ; the growth is the photo's (0.36/unit, not the note's 0.75 — a\n // standing cover is 180 up, and at the note's rate its shadow would blur into the mat)\n shadow: { sigma0: 1.4, perUnit: 0.3, alpha: 0.55, slopeMax: PHYSICS.shadow.slopeMax, contact: { sigma: 1.3, alpha: 0.45, reach: 3 } },\n dapple: { page: 0.35, cover: 1 },\n lift: { held: 30, open: 20, hover: 3.5, tiltPer: 0.00011, tiltMax: 0.11 },\n springs: {\n cover: [1.12, 0.74], root: [1.9, 0.78], edge: [2.6, 0.62],\n lift: [2.2, 0.8], tilt: [2.8, 0.55], peek: [4, 0.7], ring: [4, 1],\n },\n bend: 1.6,\n peek: { angle: 0.3, twist: 0.3, zone: 42 },\n turnZone: 0.3,\n flutter: { kick: 2.4, sheets: 3 },\n paper: { fibre: 3 / 255, mottle: 4 / 255, tooth: 0.55, cockle: 0.35, pitch: 10, dot: 0.42, margin: 9 },\n cloth: { pitch: 0.9, relief: 0.35, sheen: [14, 0.07] },\n ring: { offset: 5, width: 1.5 },\n};\n","// The notebook pass's GPU records, declared once (`defineStruct`: the WGSL text and the packer\n// from one list). `NbUniforms` is the pass's knobs and the desk eye; `NbBook` is one book: its\n// placement, its lamp and shadow map's frame, its dimensions and pose, its palette. The camera,\n// the light and the gobo arrive through the mat's block (`MatUniforms`), filled by the pass as\n// the paper and photo passes fill theirs — a notebook is lit like the mat beside it.\n\nimport type { RGB, RGBA } from \"@ice/desk\";\nimport type { NotebookLaw } from \"./law\";\n\n// the book's records are the kit's (K4a: the 3D kit's WGSL is written against them, and the desk calendar composes it too)\nexport { NbBook, NbUniforms } from \"@ice/desk/kit\";\n\nexport const MAX_NOTEBOOKS = 32;\n/** Books with a shadow map of their own (the rest cast the contact only). */\nexport const MAX_SHADOWED = 8;\nexport const SHADOW_RES = 1024;\n\nexport type Ruling = \"plain\" | \"dots\" | \"rules\" | \"grid\";\nexport const RULINGS: readonly Ruling[] = [\"plain\", \"dots\", \"rules\", \"grid\"];\nconst RULING_CODE: Record<Ruling, number> = { plain: 0, dots: 1, rules: 2, grid: 3 };\n\nexport type Design = \"plain\" | \"orbit\" | \"tiles\" | \"label\" | \"bordered\";\nexport const DESIGNS: readonly Design[] = [\"plain\", \"orbit\", \"tiles\", \"label\", \"bordered\"];\nconst DESIGN_CODE: Record<Design, number> = { plain: 0, orbit: 1, tiles: 2, label: 3, bordered: 4 };\n\n/**\n * A notebook's LOOK — the host's colours (lab/theme.ts `NOTEBOOK_LOOK`) and its choices: the\n * cloth, the band, three accents the design prints with, the endpaper, the page, the print's\n * ink; the design; whether the cover is paper rather than cloth.\n */\nexport interface NotebookLook {\n readonly cloth: RGB; readonly band: RGB;\n readonly accents: readonly [RGB, RGB, RGB];\n readonly endpaper: RGB; readonly paper: RGB; readonly ink: RGB;\n readonly design: Design;\n readonly paperCover: boolean;\n}\n\nexport const rulingCode = (r: Ruling): number => RULING_CODE[r];\nexport const designCode = (d: Design): number => DESIGN_CODE[d];\n\n/** The pass's knobs by name, from the law and the host's colours. */\nexport function nbUniformValues(law: NotebookLaw, eye: { eye: number[]; view: number[] }, dpr: number, cast: RGB, select: RGB, ruleInk: RGBA) {\n return {\n eye: eye.eye, view: eye.view,\n light: [law.light.ambient, law.light.cap, law.dapple.page, law.dapple.cover],\n shadow: [law.shadow.sigma0, law.shadow.perUnit, law.shadow.alpha, law.shadow.contact.alpha],\n shadow2: [law.shadow.contact.sigma, law.shadow.contact.reach, SHADOW_RES, dpr],\n paper: [law.paper.fibre, law.paper.mottle, law.paper.tooth, law.paper.cockle],\n rule: [law.paper.pitch, law.paper.dot, law.paper.margin, 0],\n cloth: [law.cloth.pitch, law.cloth.relief, law.cloth.sheen[0], law.cloth.sheen[1]],\n castCol: [...cast, 1],\n select: [...select, law.ring.width],\n ruleInk: [...ruleInk],\n ring: [law.ring.offset, 0, 0, 0],\n };\n}\n","// The notebook's SHAPE — pure geometry, no GPU (NOTEBOOK.md §3). A notebook is a case (two\n// boards and a spine, cloth-covered) around a text block of sheets bound at one line. This\n// file says where every part is for a pose: the front cover's hinge and swing, the stacks'\n// resting curves out of the gutter, a sheet in the air. `mesh.ts` turns it into triangles and\n// `pick.ts` reads the same numbers, so what is clicked is what is drawn.\n//\n// Book-local coordinates: the closed book's back cover lies on the mat at x ∈ [−W/2, W/2],\n// y ∈ [−H/2, H/2], z ∈ [0, b]; the spine is on the left (x = −W/2). Opening swings the front\n// cover over to the LEFT, so the open spread spans [−W/2 − s − W, W/2] (s = the spine's width).\n//\n// THE RIGHT MODEL. Every stack is described as if it were the right-hand stack on the back\n// cover: sheets bound at the gutter, each rising out of it to its own height and lying flat\n// beyond. The left stack is the same description carried by the front cover (`ride`): at the\n// cover's full swing that map is exactly the mirror about the gutter, so one set of curves\n// serves both sides and a sheet that turns lands on exactly the curve it will rest on.\n\nimport type { NotebookLaw } from \"./law\";\n\n/** One notebook's dimensions (the law's, unless a scene gives its own). */\nexport interface NotebookSpec {\n readonly width: number;\n readonly height: number;\n readonly board: number;\n readonly coverRadius: number;\n readonly sheets: number;\n readonly sheet: number;\n readonly square: number;\n readonly joint: number;\n readonly pageRadius: number;\n readonly band: number;\n readonly bulge: number;\n}\n\nexport const specOf = (law: NotebookLaw, over: Partial<NotebookSpec> = {}): NotebookSpec => ({\n width: law.cover.width, height: law.cover.height, board: law.cover.board, coverRadius: law.cover.radius,\n sheets: law.block.sheets, sheet: law.block.sheet, square: law.block.square, joint: law.block.joint, pageRadius: law.block.radius,\n band: law.spine.band, bulge: law.spine.bulge, ...over,\n});\n\n/** The numbers derived from a spec that every part reads. */\nexport interface Frame {\n readonly spec: NotebookSpec;\n /** Cover width, height, board. */\n readonly W: number; readonly H: number; readonly b: number;\n /** The whole block's thickness. */\n readonly T: number;\n /** The spine's width (the closed book's thickness) — the gap between the two covers when open. */\n readonly sw: number;\n /** A page: its height; its width as bound in the closed book (`Wp`) and as it lies open, out of the gutter (`Wo`). */\n readonly Hp: number; readonly Wp: number; readonly Wo: number;\n /** The closed block's spine edge, x. */\n readonly xp0: number;\n /** The gutter, open: x, and the valley floor's height. */\n readonly xg: number; readonly zg: number;\n}\n\nexport function frameOf(spec: NotebookSpec): Frame {\n const W = spec.width;\n const H = spec.height;\n const b = spec.board;\n const T = spec.sheets * spec.sheet;\n const sw = T + 2 * b;\n const xp0 = -W / 2 + spec.joint;\n const Wp = W - spec.joint - spec.square;\n const xg = -W / 2 - sw / 2;\n // open, a page reaches from the gutter to where the closed fore-edge was (the binding's margin revealed)\n const Wo = W / 2 - spec.square - xg;\n return { spec, W, H, b, T, sw, Hp: H - 2 * spec.square, Wp, Wo, xp0, xg, zg: b * 0.5 };\n}\n\n/** The ease every curve here uses. */\nexport const smooth = (u: number): number => (u <= 0 ? 0 : u >= 1 ? 1 : u * u * (3 - 2 * u));\nconst clamp = (x: number, a: number, b: number): number => Math.min(Math.max(x, a), b);\nconst lerp = (a: number, b: number, t: number): number => a + (b - a) * t;\n\n// ---------------------------------------------------------------- the cover's swing\n\n/** A swing past either end bounces back up off the desk or the block — never through it. */\nexport const swingOf = (theta: number): number => (theta > Math.PI ? 2 * Math.PI - theta : theta < 0 ? -theta : theta);\n\n/** How far the gutter has relaxed into its open curve: none until the cover is nearly down. */\nexport const relaxOf = (theta: number): number => smooth((swingOf(theta) - 0.78 * Math.PI) / (0.22 * Math.PI));\n\n/**\n * The front cover's frame at a swing θ: its origin (the INNER face's spine edge), its u axis\n * (across, spine → fore-edge) and its w axis (through the board, inner → outer), all in the\n * x–z plane. Closed it rests on the block (inner face at b + T); open it lies on the desk to\n * the left of the spine. The hinge travels on the spine's own arc — up like a door, over, and\n * down onto the desk — the spine rotating a quarter turn while the cover rotates a half.\n */\nexport interface CoverFrame { readonly ox: number; readonly oz: number; readonly ux: number; readonly uz: number; readonly wx: number; readonly wz: number }\nexport function coverFrame(F: Frame, theta: number): CoverFrame {\n const th = clamp(swingOf(theta), 0, Math.PI);\n const beta = Math.PI / 2 + th / 2;\n const ox = -F.W / 2 + F.sw * Math.cos(beta);\n const oz = lerp(F.b + F.T - F.sw, F.b, th / Math.PI) + F.sw * Math.sin(beta);\n return { ox, oz, ux: Math.cos(th), uz: Math.sin(th), wx: -Math.sin(th), wz: Math.cos(th) };\n}\n/** A point in the cover's frame (u across from the spine edge, w through the board from the inner face) → book x, z. */\nexport const coverPoint = (C: CoverFrame, u: number, w: number): readonly [number, number] => [C.ox + u * C.ux + w * C.wx, C.oz + u * C.uz + w * C.wz];\n\n/**\n * The RIDE: a point of the right model (x′, z′) carried by the front cover — the left stack.\n * At the full swing this is the mirror about the gutter (x ↦ 2·xg − x, z unchanged).\n */\nexport const ride = (F: Frame, C: CoverFrame, x: number, z: number): readonly [number, number] => coverPoint(C, x + F.W / 2, F.b - z);\n/** A right-model direction (nx, nz) carried by the cover (the ride's linear part — a reflection with a turn). */\nexport const rideDir = (C: CoverFrame, nx: number, nz: number): readonly [number, number] => [nx * C.ux - nz * C.wx, nx * C.uz - nz * C.wz];\n\n// ---------------------------------------------------------------- the gutter's curves\n\n/**\n * A sheet's rise out of the gutter: tangent angle a·(1 − smooth(s/dc)) for s < dc, flat beyond —\n * `a` from the rise (steeper for a thicker stack), `dc` the length the climb takes.\n */\nexport interface Profile { readonly a: number; readonly dc: number }\n\n/** ∫₀¹ sin(a·(1 − smooth(u))) du, by Simpson on 32 intervals — the mean climb per unit of curve. */\nfunction meanSin(a: number): number {\n const n = 32;\n let acc = 0;\n for (let i = 0; i <= n; i++) {\n const u = i / n;\n const w = i === 0 || i === n ? 1 : i % 2 === 1 ? 4 : 2;\n acc += w * Math.sin(a * (1 - smooth(u)));\n }\n return acc / (3 * n);\n}\n\nexport function profileOf(rise: number, law: NotebookLaw[\"gutter\"]): Profile {\n if (!(rise > 1e-4)) return { a: 0, dc: 0 };\n const a = clamp(law.entry0 + law.entryPer * rise, 0.05, law.entryMax);\n return { a, dc: rise / Math.max(meanSin(a), 1e-4) };\n}\n\nexport const angleAt = (p: Profile, s: number): number => (p.dc > 0 && s < p.dc ? p.a * (1 - smooth(s / p.dc)) : 0);\n\n/**\n * A resting sheet of the right model at height `h` (its mid-plane) with the gutter relaxed by\n * `gamma`: where it starts, how long it is, and its climb. Closed (γ 0) it is flat from the\n * block's spine edge; open (γ 1) it is bound at the gutter and climbs to `h`.\n */\nexport interface RestSheet { readonly x0: number; readonly z0: number; readonly len: number; readonly profile: Profile }\nexport function restSheet(F: Frame, h: number, gamma: number, law: NotebookLaw[\"gutter\"]): RestSheet {\n const zfloor = Math.max(Math.min(F.zg, h - law.dip), 0.6);\n const x0 = lerp(F.xp0, F.xg, gamma);\n const z0 = lerp(h, zfloor, gamma);\n return { x0, z0, len: lerp(F.Wp, F.Wo, gamma), profile: profileOf(h - z0, law) };\n}\n\n/** The integrator's longest step, world units: the curves are exact to a hundredth wherever they are sampled. */\nconst STEP = 0.75;\n\n/**\n * Integrate a curve of tangent angle α(s) from (x0, z0) and sample it at `ss` (ascending, from 0):\n * out[i] = x, z, cos α, sin α. Midpoint rule, at least `sub` steps per interval and none longer\n * than `STEP` — the one integrator every curve here goes through, so a sheet in the air, the\n * stack it lands on and the hit test agree however each is sampled.\n */\nexport function integrate(alpha: (s: number) => number, x0: number, z0: number, ss: ArrayLike<number>, sub = 2, out?: Float64Array): Float64Array {\n const o = out ?? new Float64Array(ss.length * 4);\n let x = x0;\n let z = z0;\n let s = 0;\n for (let i = 0; i < ss.length; i++) {\n const target = ss[i] as number;\n const n = Math.max(sub, Math.ceil((target - s) / STEP));\n const h = (target - s) / n;\n if (h > 0) for (let k = 0; k < n; k++) { const a = alpha(s + (k + 0.5) * h); x += Math.cos(a) * h; z += Math.sin(a) * h; }\n s = target;\n const a = alpha(s);\n o[i * 4] = x; o[i * 4 + 1] = z; o[i * 4 + 2] = Math.cos(a); o[i * 4 + 3] = Math.sin(a);\n }\n return o;\n}\n\n/** A resting sheet sampled at arc lengths `ss`: x, z, cos, sin per sample. */\nexport function sampleRest(r: RestSheet, ss: ArrayLike<number>, out?: Float64Array): Float64Array {\n return integrate((s) => angleAt(r.profile, s), r.x0, r.z0, ss, 2, out);\n}\n\n// ---------------------------------------------------------------- the pose\n\n/** A sheet in the air: its root's angle φ and its free edge's ψ (0 = lying right … π = lying left), and the twist that lets one corner lead. */\nexport interface Air { readonly index: number; readonly phi: number; readonly psi: number; readonly twist: number }\n\n/** What the mesh needs: the swing, the counts at rest on each side, and the sheets in the air. */\nexport interface NotebookPose {\n readonly theta: number;\n /** Sheets at rest on the right (on the back cover) and on the left (on the front cover). */\n readonly right: number;\n readonly left: number;\n /** The right stack's top sheet (its recto shows) and the left stack's (its verso shows); −1 = none. */\n readonly rightTop: number;\n readonly leftTop: number;\n readonly airs: readonly Air[];\n /** Where the desk is under the book, in its own z (0 lying; −lift held) — what the ribbon hangs down to. */\n readonly desk?: number;\n}\n\nexport const CLOSED_POSE: NotebookPose = { theta: 0, right: 0, left: 0, rightTop: -1, leftTop: -1, airs: [] };\n\n/** A stack's top and bottom mid-plane heights for k sheets (right model: on a board at z = b). */\nexport const stackHeights = (F: Frame, k: number): readonly [number, number] => [F.b + 0.5 * F.spec.sheet, F.b + (k - 0.5) * F.spec.sheet];\n\n/**\n * A sheet in the air, sampled on the grid (ss × ys), in BOOK coordinates (valid at the full\n * swing — sheets only turn in an open book): each row's tangent angle blends the right stack's\n * resting curve into the left's, by a turn fraction that runs from the root's φ to the edge's\n * ψ (bent by `bend` — the edge curls most), the edge's ψ twisted along the row so one corner\n * leads. Out: per vertex x, y, z and the tangent along s (cos, sin in x–z).\n */\nexport function sampleAir(F: Frame, air: Air, right: number, left: number, gamma: number, ss: ArrayLike<number>, ys: ArrayLike<number>, law: NotebookLaw, rowSS?: (j: number) => ArrayLike<number>): { pos: Float64Array; tan: Float64Array } {\n const t = F.spec.sheet;\n const R = restSheet(F, F.b + (right + 0.5) * t, gamma, law.gutter);\n const L = restSheet(F, F.b + (left + 0.5) * t, gamma, law.gutter);\n const len = R.len;\n const ns = ss.length;\n const ny = ys.length;\n const pos = new Float64Array(ns * ny * 3);\n const tan = new Float64Array(ns * ny * 2);\n const row = new Float64Array(ns * 4);\n const half = F.Hp / 2;\n for (let j = 0; j < ny; j++) {\n const y = ys[j] as number;\n const psiY = clamp(air.psi + air.twist * (y / half), 0, Math.PI);\n // biome-ignore lint/style/useExponentiationOperator: the prototype's arithmetic, moved verbatim — D1 rewrites no expression that feeds a record (design-015 D1)\n const w = (s: number): number => clamp((air.phi + (psiY - air.phi) * Math.pow(clamp(s / len, 0, 1), law.bend)) / Math.PI, 0, 1);\n const alpha = (s: number): number => { const f = w(s); return (1 - f) * angleAt(R.profile, s) + f * (Math.PI - angleAt(L.profile, s)); };\n // the root moves between the two stacks' gutter points with the root's own fraction (L's is the mirror's: same x)\n const f0 = w(0);\n integrate(alpha, lerp(R.x0, 2 * F.xg - L.x0, f0), lerp(R.z0, L.z0, f0), rowSS ? rowSS(j) : ss, 2, row);\n for (let i = 0; i < ns; i++) {\n const k = (j * ns + i);\n pos[k * 3] = row[i * 4] as number; pos[k * 3 + 1] = y; pos[k * 3 + 2] = row[i * 4 + 1] as number;\n tan[k * 2] = row[i * 4 + 2] as number; tan[k * 2 + 1] = row[i * 4 + 3] as number;\n }\n }\n return { pos, tan };\n}\n\n/**\n * A page's rows, down from the head: a few tracing each fore-edge corner's arc (so the grid's\n * last column IS the rounded corner — no pixel is cut away in the shader, and the GPU can hide\n * what lies under a page before shading it), `mid` between. `extent(len, j)` is how far along\n * the page row j reaches.\n */\nexport function pageRows(Hp: number, r: number, mid = 12, arc = 5): { ys: Float64Array; extent: (len: number, j: number) => number } {\n const ys: number[] = [];\n const sin: number[] = [];\n const rr = Math.min(r, Hp / 2);\n for (let k = 0; k <= arc; k++) { const t = (Math.PI / 2) * (k / arc); ys.push(-Hp / 2 + rr - rr * Math.cos(t)); sin.push(Math.sin(t)); }\n for (let k = 1; k < mid; k++) { ys.push(-Hp / 2 + rr + ((Hp - 2 * rr) * k) / mid); sin.push(1); }\n for (let k = arc; k >= 0; k--) { const t = (Math.PI / 2) * (k / arc); ys.push(Hp / 2 - rr + rr * Math.cos(t)); sin.push(Math.sin(t)); }\n return { ys: Float64Array.from(ys), extent: (len, j) => len - rr + rr * (sin[j] as number) };\n}\n\n/** A resting sheet as a dense table (one sample per world unit), read by `curveAt` — rows of any extent from one integration. */\nexport interface CurveTable { readonly data: Float64Array; readonly step: number; readonly n: number }\nexport function curveTable(r: RestSheet, step = 1): CurveTable {\n const n = Math.ceil(r.len / step) + 1;\n const ss = new Float64Array(n);\n for (let i = 0; i < n; i++) ss[i] = Math.min(i * step, r.len);\n return { data: sampleRest(r, ss), step, n };\n}\n/** x, z, cos, sin at arc length s (linear between the table's samples). */\nexport function curveAt(t: CurveTable, s: number, out: Float64Array): Float64Array {\n const f = Math.min(Math.max(s / t.step, 0), t.n - 1);\n const i = Math.min(Math.floor(f), t.n - 2);\n const u = f - i;\n for (let k = 0; k < 4; k++) out[k] = (t.data[i * 4 + k] as number) * (1 - u) + (t.data[(i + 1) * 4 + k] as number) * u;\n return out;\n}\n\n/** Arc-length samples across a page: denser toward the gutter, where the curves are. */\nexport function sheetSamples(len: number, n: number): Float64Array {\n const ss = new Float64Array(n + 1);\n // biome-ignore lint/style/useExponentiationOperator: the prototype's arithmetic, moved verbatim — D1 rewrites no expression that feeds a record (design-015 D1)\n for (let i = 0; i <= n; i++) ss[i] = len * Math.pow(i / n, 1.45);\n return ss;\n}\n","// The notebook's MESH — the shape (`shape.ts`) as triangles, in book-local coordinates\n// (NOTEBOOK.md §3). Pure: typed arrays out, no GPU. Rebuilt only when the pose changes; a\n// book carried across the desk keeps its mesh and moves by its matrix.\n//\n// A vertex is 16 floats: position · normal · uv · (material, page, flags, ao) · the face's\n// size in world units (what uv is a fraction of) · two extras. The shader reads a material\n// by number (`MAT`) — the case's cloth, its endpapers, a board's edge, a page, a stack's\n// edge, the spine — and the uv in that face's own world units, so the weave, the fibre and\n// the ruling stay the same size on every face.\n\nimport { type BuiltMesh, FLAG_TWO_SIDED, type MeshWriter } from \"@ice/desk/kit\";\nimport type { NotebookLaw } from \"./law\";\nimport { type CoverFrame, coverFrame, curveAt, curveTable, type Frame, type NotebookPose, pageRows, relaxOf, restSheet, ride, rideDir, sampleAir, sampleRest, sheetSamples, swingOf } from \"./shape\";\n\n/** The materials, by the number a vertex carries. */\nexport const MAT = { cover: 0, endpaper: 1, board: 2, page: 3, edge: 4, spine: 5, ribbon: 6 } as const;\n\n// the writer is the kit's (K4a — the calendar's pad builds with it too); the book keeps its door for its own files\nexport { type BuiltMesh, FLAG_TWO_SIDED, MeshWriter, VERTEX_BYTES, VERTEX_FLOATS } from \"@ice/desk/kit\";\n\n// ---------------------------------------------------------------- outlines\n\n/** A point on an outline: position, outward normal, arc length so far. */\ninterface OutlinePoint { readonly u: number; readonly v: number; readonly nu: number; readonly nv: number; readonly l: number }\n\n/**\n * The outline of a face with its two fore-edge corners rounded: from (0, −h/2) along the head,\n * round the corner, down the fore-edge, round, back along the tail to (0, h/2). The spine\n * side (u = 0) is not walked — the spine or the gutter is there.\n */\nfunction foreOutline(w: number, h: number, r: number, headSegs: number, arcSegs: number, foreSegs: number, headAt?: ArrayLike<number>): OutlinePoint[] {\n const pts: OutlinePoint[] = [];\n const hy = h / 2;\n const rr = Math.min(r, w, hy);\n let l = 0;\n let pu = 0;\n let pv = -hy;\n const push = (u: number, v: number, nu: number, nv: number) => { l += Math.hypot(u - pu, v - pv); pu = u; pv = v; pts.push({ u, v, nu, nv, l }); };\n pts.push({ u: 0, v: -hy, nu: 0, nv: -1, l: 0 });\n const head: number[] = [];\n if (headAt) { for (let i = 0; i < headAt.length; i++) { const s = headAt[i] as number; if (s > 1e-6 && s < w - rr - 1e-6) head.push(s); } }\n else for (let i = 1; i < headSegs; i++) head.push(((w - rr) * i) / headSegs);\n for (const s of head) push(s, -hy, 0, -1);\n for (let i = 0; i <= arcSegs; i++) { const a = -Math.PI / 2 + (Math.PI / 2) * (i / arcSegs); push(w - rr + rr * Math.cos(a), -hy + rr + rr * Math.sin(a), Math.cos(a), Math.sin(a)); }\n for (let i = 1; i < foreSegs; i++) push(w, -hy + rr + ((2 * hy - 2 * rr) * i) / foreSegs, 1, 0);\n for (let i = 0; i <= arcSegs; i++) { const a = (Math.PI / 2) * (i / arcSegs); push(w - rr + rr * Math.cos(a), hy - rr + rr * Math.sin(a), Math.cos(a), Math.sin(a)); }\n for (let i = head.length - 1; i >= 0; i--) push(head[i] as number, hy, 0, 1);\n push(0, hy, 0, 1);\n return pts;\n}\n\n// ---------------------------------------------------------------- the case\n\n/**\n * A board: a slab `b` thick with its fore-edge corners rounded. `place(u, w)` maps the board's\n * own (u across from the spine edge, w through it from the inner face) to book x, z; `dirU`,\n * `dirW` are its axes in x–z. Emits the inner face (an endpaper), the outer face (the cloth —\n * the design on the front board), and the walls (the cloth wrapped over the board's edge,\n * its rims rounded by their normals).\n */\nfunction board(m: MeshWriter, F: Frame, place: (u: number, w: number) => readonly [number, number], dirU: readonly [number, number], dirW: readonly [number, number], which: 0 | 1, outer: boolean, stacked: boolean): void {\n const W = F.W;\n const H = F.H;\n const b = F.b;\n const ol = foreOutline(W, H, F.spec.coverRadius, 6, 8, 8);\n // the faces: a fan from the middle over the closed polygon (the outline and the spine edge)\n for (const [w, sign, mat] of [[0, -1, 1], [b, 1, 0]] as const) {\n if (mat === 0 && !outer) continue;\n const [cx, cz] = place(W / 2, w);\n const nx = dirW[0] * sign;\n const nz = dirW[1] * sign;\n const e1 = mat === 1 && stacked ? 1 : 0;\n const c = m.vert(cx, 0, cz, nx, 0, nz, 0.5, 0.5, mat === 0 ? 0 : 1, 0, 0, 1, W, H, which, e1);\n const first = m.nv;\n for (const p of ol) { const [x, z] = place(p.u, w); m.vert(x, p.v, z, nx, 0, nz, p.u / W, (p.v + H / 2) / H, mat === 0 ? 0 : 1, 0, 0, 1, W, H, which, e1); }\n const n = ol.length;\n for (let i = 0; i < n; i++) m.tri(c, first + i, first + ((i + 1) % n));\n }\n // the walls: three rows through the board, the rims' normals rolled toward the faces\n const rows = [[0, -0.75], [b * 0.5, 0], [b, 0.75]] as const;\n const first = m.nv;\n for (const [w, roll] of rows) {\n for (const p of ol) {\n const [x, z] = place(p.u, w);\n // outward in the board's plane, rolled toward the face it meets\n const ox = p.nu * dirU[0];\n const oz = p.nu * dirU[1];\n const oy = p.nv;\n const k = Math.abs(roll);\n const fx = dirW[0] * Math.sign(roll);\n const fz = dirW[1] * Math.sign(roll);\n m.vert(x, p.v, z, ox * (1 - k) + fx * k, oy * (1 - k), oz * (1 - k) + fz * k, p.l / W, w / b, MAT.board, 0, 0, 1, W, b, which, 0);\n }\n }\n const cols = ol.length;\n for (let j = 0; j + 1 < rows.length; j++) for (let i = 0; i + 1 < cols; i++) {\n const a = first + j * cols + i;\n m.quad(a, a + 1, a + cols + 1, a + cols);\n }\n}\n\n/** The spine: the cloth from the back board's outer spine edge round to the front board's, bowed out while closed. */\nfunction spine(m: MeshWriter, F: Frame, C: CoverFrame, theta: number): void {\n const H = F.H;\n const ax = -F.W / 2;\n const az = 0;\n const bx = C.ox + F.b * C.wx;\n const bz = C.oz + F.b * C.wz;\n const dx = bx - ax;\n const dz = bz - az;\n const len = Math.hypot(dx, dz) || 1;\n // perpendicular to the chord, away from the block (−x when closed); flattening as the book opens\n // biome-ignore lint/style/useExponentiationOperator: the prototype's arithmetic, moved verbatim — D1 rewrites no expression that feeds a record (design-015 D1)\n const bulge = F.spec.bulge * Math.pow(Math.max(1 - swingOf(theta) / Math.PI, 0), 1.2);\n const px = -dz / len;\n const pz = dx / len;\n const cx = (ax + bx) / 2 + px * bulge * 2;\n const cz = (az + bz) / 2 + pz * bulge * 2;\n const segs = 12;\n const first = m.nv;\n let arc = 0;\n let lx = ax;\n let lz = az;\n for (let i = 0; i <= segs; i++) {\n const t = i / segs;\n const it = 1 - t;\n const x = it * it * ax + 2 * it * t * cx + t * t * bx;\n const z = it * it * az + 2 * it * t * cz + t * t * bz;\n const tx = 2 * it * (cx - ax) + 2 * t * (bx - cx);\n const tz = 2 * it * (cz - az) + 2 * t * (bz - cz);\n arc += Math.hypot(x - lx, z - lz); lx = x; lz = z;\n for (const v of [-H / 2, H / 2]) m.vert(x, v, z, -tz, 0, tx, arc / len, (v + H / 2) / H, MAT.spine, 0, FLAG_TWO_SIDED, 0.92, len, H, 0, 0);\n }\n for (let i = 0; i < segs; i++) { const a = first + i * 2; m.quad(a, a + 2, a + 3, a + 1); }\n}\n\n// ---------------------------------------------------------------- the text block\n\nconst SHEET_COLS = 40;\nconst WALL_ROWS = 5;\n\n/**\n * A stack of `k` sheets in the right model (on a board at z = b), emitted through `map` (the\n * identity for the right stack, the cover's ride for the left): its top page (`page` names what\n * is printed on it) and its walls — the head, the fore-edge, the tail — built through the\n * sheets' own curves, so the fore-edge steps in toward the gutter as the sheets climb (the fan).\n */\nfunction stack(m: MeshWriter, F: Frame, k: number, gamma: number, law: NotebookLaw, page: number, side: 0 | 1, map: (x: number, z: number) => readonly [number, number], mapDir: (nx: number, nz: number) => readonly [number, number]): void {\n if (k <= 0) return;\n const t = F.spec.sheet;\n const Hp = F.Hp;\n const top = restSheet(F, F.b + (k - 0.5) * t, gamma, law.gutter);\n const len = top.len;\n // the top page: a grid over the top sheet's curve, its upper surface (the mid-plane + half a sheet), its rows tracing the rounded corners\n const ss = sheetSamples(len, SHEET_COLS);\n const table = curveTable(top);\n const rows = pageRows(Hp, F.spec.pageRadius);\n const cur = new Float64Array(4);\n const first = m.nv;\n for (let j = 0; j < rows.ys.length; j++) {\n const y = rows.ys[j] as number;\n const f = rows.extent(len, j) / len;\n for (let i = 0; i < ss.length; i++) {\n const sArc = (ss[i] as number) * f;\n curveAt(table, sArc, cur);\n const x = cur[0] as number;\n const z = cur[1] as number;\n const c = cur[2] as number;\n const s = cur[3] as number;\n const [X, Z] = map(x - s * t * 0.5, z + c * t * 0.5);\n const [NX, NZ] = mapDir(-s, c);\n m.vert(X, y, Z, NX, 0, NZ, sArc / len, (y + Hp / 2) / Hp, MAT.page, page, 0, 1, len, Hp, side, k);\n }\n }\n m.gridQuads(first, ss.length, rows.ys.length);\n\n // the walls: rows through the stack from the board up to the top sheet's upper surface\n const outline = foreOutline(len, Hp, F.spec.pageRadius, 0, 6, 10, ss);\n const sList = [...new Set(outline.map((p) => p.u))].sort((a, b) => a - b);\n const at = new Map<number, number>(); sList.forEach((s, i) => at.set(s, i));\n const rowsCur: Float64Array[] = [];\n for (let r = 0; r <= WALL_ROWS; r++) {\n const h = F.b + (k * t * r) / WALL_ROWS;\n rowsCur.push(sampleRest(restSheet(F, h, gamma, law.gutter), sList));\n }\n const wfirst = m.nv;\n for (let r = 0; r <= WALL_ROWS; r++) {\n const c = rowsCur[r] as Float64Array;\n for (const p of outline) {\n const i = at.get(p.u) as number;\n const x = c[i * 4] as number;\n const z = c[i * 4 + 1] as number;\n const cs = c[i * 4 + 2] as number;\n const sn = c[i * 4 + 3] as number;\n const [X, Z] = map(x, z);\n // outward: along the sheet's own tangent for the fore-edge share, across (y) for the head and tail\n const [NX, NZ] = mapDir(p.nu * cs, p.nu * sn);\n m.vert(X, p.v, Z, NX, p.nv, NZ, p.l / len, r / WALL_ROWS, MAT.edge, page, 0, 0.78 + 0.22 * (r / WALL_ROWS), len, k * t, k, side);\n }\n }\n m.gridQuads(wfirst, outline.length, WALL_ROWS + 1);\n}\n\n/** A sheet in the air, both faces: its recto is page 2i + 1, its verso 2i + 2. */\nfunction airSheet(m: MeshWriter, F: Frame, pose: NotebookPose, gamma: number, law: NotebookLaw, a: NotebookPose[\"airs\"][number]): void {\n const Hp = F.Hp;\n const len = restSheet(F, F.b + (pose.right + 0.5) * F.spec.sheet, gamma, law.gutter).len;\n const ss = sheetSamples(len, SHEET_COLS);\n const rows = pageRows(Hp, F.spec.pageRadius);\n const ys = rows.ys;\n const rowSS = ss.map(() => 0);\n const { pos } = sampleAir(F, a, pose.right, pose.left, gamma, ss, ys, law, (j) => { const f = rows.extent(len, j) / len; for (let i = 0; i < ss.length; i++) rowSS[i] = (ss[i] as number) * f; return rowSS; });\n const ns = ss.length;\n const ny = ys.length;\n const first = m.nv;\n const P = (i: number, j: number, c: number) => pos[(Math.min(Math.max(j, 0), ny - 1) * ns + Math.min(Math.max(i, 0), ns - 1)) * 3 + c] as number;\n for (let j = 0; j < ny; j++) for (let i = 0; i < ns; i++) {\n // the normal from the grid: ∂/∂s × ∂/∂y (+z when it lies on the right)\n const i0 = Math.max(i - 1, 0);\n const i1 = Math.min(i + 1, ns - 1);\n const j0 = Math.max(j - 1, 0);\n const j1 = Math.min(j + 1, ny - 1);\n const sx = P(i1, j, 0) - P(i0, j, 0);\n const sy = P(i1, j, 1) - P(i0, j, 1);\n const sz = P(i1, j, 2) - P(i0, j, 2);\n const yx = P(i, j1, 0) - P(i, j0, 0);\n const yy = P(i, j1, 1) - P(i, j0, 1);\n const yz = P(i, j1, 2) - P(i, j0, 2);\n const nx = sy * yz - sz * yy;\n const ny2 = sz * yx - sx * yz;\n const nz = sx * yy - sy * yx;\n const sArc = (ss[i] as number) * rows.extent(len, j) / len;\n m.vert(P(i, j, 0), P(i, j, 1), P(i, j, 2), nx, ny2, nz, sArc / len, (ys[j] as number + Hp / 2) / Hp, MAT.page, 2 * a.index + 1, FLAG_TWO_SIDED, 1, len, Hp, 2, 0);\n }\n m.gridQuads(first, ns, ny);\n}\n\n/**\n * The RIBBON: a satin marker that lies in the gutter of the spread in view (between the stacks\n * when the book is shut), leaves the book at its tail, drapes over the board's edge and lies out\n * on the mat in a loose S, its end cut in a V. A strip along a Catmull-Rom path through a few\n * points, flat across x (it lies on the page and on the desk), both faces seen.\n */\nconst RIBBON_W = 7;\nfunction ribbon(m: MeshWriter, F: Frame, pose: NotebookPose, gamma: number, law: NotebookLaw): void {\n const t = F.spec.sheet;\n const Hp = F.Hp;\n const H = F.H;\n // where it lies in the book: on the right stack's top, just out of the gutter (the block's spine edge when shut)\n let rx: number;\n let rz: number;\n if (pose.right > 0) {\n const top = restSheet(F, F.b + (pose.right - 0.5) * t, gamma, law.gutter);\n const c = sampleRest(top, [0, 2.5 + 3 * (1 - gamma)]);\n rx = (c[4] as number) - (c[7] as number) * (t * 0.5 + 0.25); rz = (c[5] as number) + (c[6] as number) * (t * 0.5 + 0.25);\n } else { rx = F.xp0 + 3; rz = F.b + 0.25; }\n const floorZ = (x: number) => (x < -F.W / 2 ? (swingOf(pose.theta) > 0.9 * Math.PI ? F.b * 0.6 : 0) : F.b);\n // the desk under it: a lifted book's ribbon hangs down the extra height, and less of it lies out on the mat\n const desk = Math.min(pose.desk ?? 0, 0);\n const hang = -desk;\n const ctrl: [number, number, number][] = [\n [rx, -Hp / 2 + 4, rz], [rx, -Hp / 4, rz], [rx, Hp / 4, rz], [rx, Hp / 2 - 6, rz], [rx, Hp / 2, rz],\n [rx + 0.3, H / 2 - 0.4, Math.max(floorZ(rx), rz * 0.55) + 0.25], [rx + 0.9, H / 2 + 1.8, floorZ(rx) * 0.55],\n [rx + 2.4, H / 2 + 5.5 + hang * 0.15, desk * 0.6 + 0.14], [rx + 6, H / 2 + 18 + hang * 0.1, desk + 0.1], [rx + 9.5, H / 2 + 31, desk + 0.1], [rx + 8.5, H / 2 + 43 - hang * 0.4, desk + 0.1],\n ];\n // Catmull-Rom through the controls, four samples a span\n const pts: [number, number, number][] = [];\n const P = (i: number) => ctrl[Math.min(Math.max(i, 0), ctrl.length - 1)] as [number, number, number];\n for (let i = 0; i < ctrl.length - 1; i++) for (let k = 0; k < 4; k++) {\n const u = k / 4;\n const p0 = P(i - 1);\n const p1 = P(i);\n const p2 = P(i + 1);\n const p3 = P(i + 2);\n const q = [0, 1, 2].map((c) => 0.5 * ((2 * (p1[c] as number)) + (-(p0[c] as number) + (p2[c] as number)) * u + (2 * (p0[c] as number) - 5 * (p1[c] as number) + 4 * (p2[c] as number) - (p3[c] as number)) * u * u + (-(p0[c] as number) + 3 * (p1[c] as number) - 3 * (p2[c] as number) + (p3[c] as number)) * u * u * u)) as [number, number, number];\n pts.push(q);\n }\n pts.push(ctrl[ctrl.length - 1] as [number, number, number]);\n const first = m.nv;\n let arc = 0;\n const n = pts.length;\n for (let i = 0; i < n; i++) {\n const a = pts[Math.max(i - 1, 0)] as number[];\n const b = pts[Math.min(i + 1, n - 1)] as number[];\n const p = pts[i] as number[];\n if (i > 0) arc += Math.hypot((p[0] as number) - ((pts[i - 1] as number[])[0] as number), (p[1] as number) - ((pts[i - 1] as number[])[1] as number), (p[2] as number) - ((pts[i - 1] as number[])[2] as number));\n const tx = (b[0] as number) - (a[0] as number);\n const ty = (b[1] as number) - (a[1] as number);\n const tz = (b[2] as number) - (a[2] as number);\n const tl = Math.hypot(tx, ty, tz) || 1;\n // across: level and square to the path; the face's normal: up, out of the path and the across\n let wx = -ty;\n let wy = tx; const wl = Math.hypot(wx, wy) || 1; wx /= wl; wy /= wl;\n let nx = (ty / tl) * 0 - (tz / tl) * wy;\n let ny = (tz / tl) * wx - (tx / tl) * 0;\n let nz = (tx / tl) * wy - (ty / tl) * wx;\n if (nz < 0) { nx = -nx; ny = -ny; nz = -nz; }\n // the V at the end: the edges run on past the middle\n const prev = pts[n - 2] as number[];\n const notch = i === n - 1 ? Math.min(3.2, 0.7 * Math.hypot((p[0] as number) - (prev[0] as number), (p[1] as number) - (prev[1] as number))) : 0;\n for (const side of [-1, 1] as const) {\n const off = (RIBBON_W / 2) * side;\n m.vert((p[0] as number) + wx * off, (p[1] as number) + wy * off, p[2] as number, nx, ny, nz, arc, (side + 1) / 2, MAT.ribbon, 0, FLAG_TWO_SIDED, 1, 1, RIBBON_W, 0, 0);\n }\n if (notch > 0) {\n // the middle of the end sits back up the ribbon: a vertex between the two edge ones\n const c = m.vert((p[0] as number) - (tx / tl) * notch, (p[1] as number) - (ty / tl) * notch, p[2] as number, nx, ny, nz, arc - notch, 0.5, MAT.ribbon, 0, FLAG_TWO_SIDED, 1, 1, RIBBON_W, 0, 0);\n const l = first + (n - 2) * 2;\n const r = l + 1;\n m.tri(l, r, c); m.tri(l, c, l + 2); m.tri(r, r + 2, c);\n }\n }\n // the strip (the last span is the notch's two triangles)\n for (let i = 0; i < n - 2; i++) { const a = first + i * 2; m.quad(a, a + 2, a + 3, a + 1); }\n}\n\n/**\n * The whole notebook for a pose, into the writer (reset first). The back board never moves;\n * the front board swings on the spine's arc; the stacks sit on their boards; the sheets in the\n * air turn between them. Bounds are tracked as it writes.\n */\nexport function buildMesh(m: MeshWriter, F: Frame, pose: NotebookPose, law: NotebookLaw): BuiltMesh {\n m.reset();\n const C = coverFrame(F, pose.theta);\n const gamma = relaxOf(pose.theta);\n // the back board: its inner face is the back endpaper, its outer face is on the mat (never seen)\n // (its w runs DOWN from the inner face, so the inner face is on top at z = b)\n board(m, F, (u, w) => [-F.W / 2 + u, F.b - w], [1, 0], [0, -1], 1, false, pose.right > 0);\n // the front board: the design outside, the front endpaper inside\n board(m, F, (u, w) => [C.ox + u * C.ux + w * C.wx, C.oz + u * C.uz + w * C.wz], [C.ux, C.uz], [C.wx, C.wz], 0, true, pose.left > 0);\n spine(m, F, C, pose.theta);\n // the stacks: the right on the back board as it lies; the left carried by the front board\n stack(m, F, pose.right, gamma, law, 2 * pose.rightTop + 1, 0, (x, z) => [x, z], (nx, nz) => [nx, nz]);\n stack(m, F, pose.left, gamma, law, 2 * pose.leftTop + 2, 1, (x, z) => ride(F, C, x, z), (nx, nz) => rideDir(C, nx, nz));\n for (const a of pose.airs) airSheet(m, F, pose, gamma, law, a);\n ribbon(m, F, pose, gamma, law);\n return { vertices: m.v, indices: m.ix, vcount: m.nv, icount: m.ni, min: [m.min[0], m.min[1], m.min[2]], max: [m.max[0], m.max[1], m.max[2]] };\n}\n","// INK on the notebook's pages (NOTEBOOK.md §7–8) — the pure half: what a stroke is, how wide a\n// pen writes, where a page's point lands in its raster, which pages are in view. The raster is\n// pure arithmetic since D3t-b (notebook/raster.ts — the prototype drew it with Canvas2D, which\n// neither the Node oracle nor the desk-dom-free wall has) into layers of one texture array; the\n// pass samples a page's layer by its number, so the ink turns with the sheet it is on and\n// crosses the gutter's curve, the dapple and the night like the paper under it.\n//\n// Page units: `s` along the page from the gutter (world units, 0 … the page's width), `y` down\n// the page from the head (0 … its height). Recto and verso share them: a sheet's two faces\n// are the same (s, y) seen from either side. A page's NUMBER: sheet i's recto is 2i + 1, its\n// verso 2i + 2 (0 is the front endpaper, which takes no ink).\n\nimport type { RGB } from \"@ice/desk\";\n\nexport interface InkPoint { readonly s: number; readonly y: number; readonly w: number }\nexport interface InkStroke { readonly colour: RGB; readonly points: InkPoint[] }\n/** A page's ink: its strokes, and a version that moves whenever they change (a raster's key). */\nexport interface PageInk { strokes: InkStroke[]; version: number }\n\n/** One page's raster: 1024 texels across its width (5.5 per world unit on the law's page), its height in proportion. */\nexport const INK_W = 1024;\nexport const INK_H = 1360;\n/** Page rasters on the device at once — the spread, a sheet or two in the air, a turn's neighbours. */\nexport const INK_LAYERS = 8;\n/** Pages a book can name in its record's table (the spread and the sheets in the air). */\nexport const INK_TABLE = 8;\n\n/**\n * The pen's law: a nib `width` wide at a writing pace, thinning as it hurries (a fountain pen\n * laying down less ink) and swelling slow — bounded both ways; a stylus's pressure, when the\n * device has one, leads instead.\n */\nexport interface PenLaw { readonly width: number; readonly thin: number; readonly thick: number; readonly pace: number }\nexport const PEN: PenLaw = { width: 1.25, thin: 0.55, thick: 1.3, pace: 900 };\n\n/** The nib's width at a speed (world units per second) and, from a stylus, a pressure in 0 … 1. */\nexport function nibWidth(law: PenLaw, speed: number, pressure: number | null): number {\n if (pressure !== null) return law.width * (law.thin + (law.thick - law.thin) * Math.min(Math.max(pressure, 0), 1));\n const f = 1.15 - speed / law.pace;\n return law.width * Math.min(Math.max(f, law.thin), law.thick);\n}\n\n/** A page point → its raster's texel (the page is `len` wide and `height` tall in world units). */\nexport function texelOf(p: { readonly s: number; readonly y: number }, len: number, height: number): readonly [number, number] {\n return [(p.s / len) * INK_W, (p.y / height) * INK_H];\n}\n\n/** Texels per world unit across the page — a nib's width in the raster. */\nexport const texelsPerUnit = (len: number): number => INK_W / len;\n\n/**\n * The nib's width at each sample (D3t-b) — the pen's law over the hand's pace, as the prototype's pen laid it (lab/notebook.ts\n * `penTo`): the first at rest; each sample that moved at least `still` from the last that did takes 0.6 of that one's width and\n * 0.4 of the law's at the pace between them; one nearer keeps the width it had (a resting pen neither swells nor thins — the\n * prototype dropped such a sample, the data keeps it). Timed samples (ms from the first) read their own clocks; untimed ones are\n * spaced by `speed` (world units/s) as the board's replay spaces an old stroke. Square roots and the four operations only: the\n * widths are bit-identical wherever they are computed (the oracle's Node, the desk's Chrome).\n */\nexport function nibWidths(points: readonly (readonly [number, number])[], times: readonly number[] | null, speed: number, law: PenLaw = PEN, still = 0.35): number[] {\n const n = points.length;\n const out: number[] = [];\n if (n === 0) return out;\n const timed = times !== null && times.length === n;\n const pace = speed > 0 ? speed : 400;\n let t = 0;\n let ref = points[0] as readonly [number, number];\n let refT = 0;\n let w = nibWidth(law, 0, null);\n out.push(w);\n for (let i = 1; i < n; i++) {\n const p = points[i] as readonly [number, number];\n const q = points[i - 1] as readonly [number, number];\n if (timed) t = times[i] as number;\n else t += (Math.sqrt((p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])) / pace) * 1000;\n const d = Math.sqrt((p[0] - ref[0]) * (p[0] - ref[0]) + (p[1] - ref[1]) * (p[1] - ref[1]));\n if (d >= still) {\n const v = d / Math.max((t - refT) / 1000, 1e-3);\n w = w * 0.6 + nibWidth(law, v, null) * 0.4;\n ref = p;\n refT = t;\n }\n out.push(w);\n }\n return out;\n}\n\n/** A stroke's samples as the raster draws them: page units with the nib's width at each (`nibWidths`). */\nexport function inkPoints(points: readonly (readonly [number, number])[], times: readonly number[] | null, speed: number, law: PenLaw = PEN): InkPoint[] {\n const w = nibWidths(points, times, speed, law);\n return points.map(([s, y], i) => ({ s, y, w: w[i] as number }));\n}\n\n/** The page a side of the open spread shows (D3t-b): the right is its top sheet's recto (2i + 1), the left its top sheet's verso (2i + 2); null — an endpaper. */\nexport function pageOfSide(pose: { readonly rightTop: number; readonly leftTop: number }, side: 0 | 1): number | null {\n if (side === 0) return pose.rightTop >= 0 ? 2 * pose.rightTop + 1 : null;\n return pose.leftTop >= 0 ? 2 * pose.leftTop + 2 : null;\n}\n\n/**\n * The pages in view (the prototype's `drawBooks`): once the cover stands past the vertical, the spread — its left page, then its\n * right — and both faces of every sheet in the air (a turn, the peek); none while the book is shut.\n */\nexport function pagesInView(pose: { readonly rightTop: number; readonly leftTop: number; readonly airs: readonly { readonly index: number }[] }, swing: number): number[] {\n const pages: number[] = [];\n if (swing <= Math.PI / 2) return pages;\n if (pose.leftTop >= 0) pages.push(2 * pose.leftTop + 2);\n if (pose.rightTop >= 0) pages.push(2 * pose.rightTop + 1);\n for (const a of pose.airs) pages.push(2 * a.index + 1, 2 * a.index + 2);\n return pages;\n}\n","// The notebook's MOTION — springs, stepped by the host's clock (NOTEBOOK.md §4). Pure.\n//\n// Three things move: the front cover (one spring, θ 0 closed … π open, a little overshoot that\n// bounces off the desk), the sheets (each one resting on the right or the left, or in the AIR\n// with a root angle φ and a free edge ψ), and the book itself (a lift and a tilt while held).\n//\n// A sheet in the air is two coupled springs. Turned by a click or a key, the ROOT springs toward\n// its side and the EDGE follows it — so the edge flicks up first (a kick), is overtaken, and\n// trails as the sheet falls, the way paper does in air. Turned by hand, the EDGE is where the\n// finger says and the ROOT follows it — the sheet bends toward the finger. Let go, the sheet\n// goes the way it was going (past the vertical, or flung), and the springs land it.\n\nimport type { NotebookLaw } from \"./law\";\nimport type { Air, NotebookPose } from \"./shape\";\n\nexport interface SheetMotion {\n /** Where it rests, or is heading when in the air: 0 right, 1 left. */\n side: 0 | 1;\n air: boolean;\n phi: number; phiV: number;\n psi: number; psiV: number;\n tw: number; twV: number;\n /** Held by the pointer: the pinch's angle (and its pace, from the hand) set the sheet; its twist follows the hand. */\n held: boolean;\n psiT: number; twT: number;\n /** The held sheet's pinch angle, its pace (rad/s, smoothed), and the side it was taken from. */\n grip: number; gripV: number; from: 0 | 1;\n}\n\nexport interface NotebookMotion {\n opened: boolean;\n theta: number; thetaV: number;\n held: boolean;\n lift: number; liftV: number;\n /** The tilt (radians about x and y) and where the hand's motion asks it to be. */\n tiltX: number; tiltXV: number; tiltY: number; tiltYV: number;\n tiltTX: number; tiltTY: number;\n selected: boolean;\n ring: number; ringV: number;\n sheets: SheetMotion[];\n /** The corner's peek: its amount and which corner (+1 the tail's, −1 the head's). */\n peek: number; peekV: number; peekOn: boolean; peekSide: 1 | -1;\n /** The landing flutter has played for this opening. */\n fluttered: boolean;\n /** The pointer is over the (closed) book: it rises a little. */\n hover: number; hoverV: number; hoverOn: boolean;\n}\n\nconst sheet = (side: 0 | 1): SheetMotion => ({ side, air: false, phi: side * Math.PI, phiV: 0, psi: side * Math.PI, psiV: 0, tw: 0, twV: 0, held: false, psiT: 0, twT: 0, grip: side * Math.PI, gripV: 0, from: side });\n\n/** A notebook at rest: closed (or open), `left` sheets turned. */\nexport function newMotion(sheets: number, left = 0, opened = false): NotebookMotion {\n const list: SheetMotion[] = [];\n for (let i = 0; i < sheets; i++) list.push(sheet(i < left ? 1 : 0));\n return {\n opened, theta: opened ? Math.PI : 0, thetaV: 0, held: false, lift: 0, liftV: 0,\n tiltX: 0, tiltXV: 0, tiltY: 0, tiltYV: 0, tiltTX: 0, tiltTY: 0,\n selected: false, ring: 0, ringV: 0, sheets: list, peek: 0, peekV: 0, peekOn: false, peekSide: 1, fluttered: opened,\n hover: 0, hoverV: 0, hoverOn: false,\n };\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.min(Math.max(x, a), b);\n\n/** One damped spring step (semi-implicit Euler): x toward `to` at `hz` with damping ratio `z`. */\nfunction springStep(x: number, v0: number, to: number, hz: number, z: number, h: number): [number, number] {\n let v = v0;\n const w = 2 * Math.PI * hz;\n v += (w * w * (to - x) - 2 * z * w * v) * h;\n return [x + v * h, v];\n}\n\n// ---------------------------------------------------------------- the stacks\n\n/** The lowest index resting on the right — its recto is the right page; −1 when none. */\nexport function rightTop(m: NotebookMotion): number { for (let i = 0; i < m.sheets.length; i++) { const s = m.sheets[i] as SheetMotion; if (!s.air && s.side === 0) return i; } return -1; }\n/** The highest index resting on the left — its verso is the left page; −1 when none. */\nexport function leftTop(m: NotebookMotion): number { for (let i = m.sheets.length - 1; i >= 0; i--) { const s = m.sheets[i] as SheetMotion; if (!s.air && s.side === 1) return i; } return -1; }\n/** Sheets resting on each side. */\nexport function counts(m: NotebookMotion): { right: number; left: number } {\n let right = 0;\n let left = 0;\n for (const s of m.sheets) if (!s.air) { if (s.side === 0) right++; else left++; }\n return { right, left };\n}\n/** The spread as a reader names it: the left page's number (0 = the endpaper) and the right's. */\nexport function spreadOf(m: NotebookMotion): { left: number; right: number } {\n let turned = 0;\n for (const s of m.sheets) if ((s.air ? s.side : s.side) === 1) turned++;\n return { left: 2 * turned, right: 2 * turned + 1 };\n}\nexport const anyAir = (m: NotebookMotion): boolean => m.sheets.some((s) => s.air);\n/** A page may turn only in an open book whose cover has landed. */\nexport const turnable = (m: NotebookMotion): boolean => m.opened && m.theta > 0.93 * Math.PI;\n\n/**\n * Turn a page: forward (+1) lifts the right stack's top sheet, back (−1) the left's. A turn the\n * other way while sheets are still flying the first way sends the last of them back instead —\n * sheets are bound in order and can never cross. The edge is kicked up first. False when\n * there is nothing to turn.\n */\nexport function turnPage(m: NotebookMotion, dir: 1 | -1, law: NotebookLaw): boolean {\n if (!turnable(m)) return false;\n const flying = m.sheets.map((s, i) => ({ s, i })).filter(({ s }) => s.air && !s.held);\n const against = flying.filter(({ s }) => s.side === (dir === 1 ? 0 : 1) && s.phi > 0.02 && s.phi < Math.PI - 0.02);\n if (against.length && flying.every(({ s }) => s.side !== (dir === 1 ? 1 : 0))) {\n const pick = dir === 1 ? against[0] : against[against.length - 1];\n if (pick) { pick.s.side = dir === 1 ? 1 : 0; return true; }\n }\n const i = dir === 1 ? rightTop(m) : leftTop(m);\n if (i < 0) return false;\n const s = m.sheets[i] as SheetMotion;\n s.air = true; s.held = false; s.side = dir === 1 ? 1 : 0;\n s.phi = dir === 1 ? 0 : Math.PI; s.psi = s.phi; s.phiV = 0;\n s.psiV = dir * law.flutter.kick * 2.2;\n s.tw = 0; s.twV = dir * 0.9;\n return true;\n}\n\n/** Take hold of the top sheet on a side (0 the right page, 1 the left) — a drag begins. Null when there is none or sheets are flying. */\nexport function grabSheet(m: NotebookMotion, side: 0 | 1): number | null {\n if (!turnable(m) || m.sheets.some((s) => s.air && s.phi > 0.03 && s.phi < Math.PI - 0.03)) return null;\n // a peeking sheet is the right top — it lands first\n for (const s of m.sheets) if (s.air && !s.held) { s.air = false; s.phi = s.psi = s.side * Math.PI; s.phiV = s.psiV = s.tw = s.twV = 0; }\n const i = side === 0 ? rightTop(m) : leftTop(m);\n if (i < 0) return null;\n const s = m.sheets[i] as SheetMotion;\n s.air = true; s.held = true; s.psiT = s.psi; s.twT = 0;\n s.grip = s.side * Math.PI; s.gripV = 0; s.from = s.side;\n m.peek = 0; m.peekV = 0; m.peekOn = false;\n return i;\n}\n\n/**\n * The hand moves a held sheet: the page is pinched at arc length `sGrab` from the gutter, and the\n * pointer is at `xLocal` across the book (right-model x). The pinch follows the pointer's x — its\n * angle about the gutter is the GRIP — and the sheet bows toward the hand: the edge leads the\n * root by a bend that is most while the sheet stands and nothing while it lies. `yFrac` (−1 the\n * head … +1 the tail) is where along the page the pinch is: that corner leads. `dt` is the time\n * since the last move (the grip's pace, which a release reads).\n */\nexport function dragSheet(m: NotebookMotion, i: number, xLocal: number, xg: number, sGrab: number, _len: number, yFrac: number, law: NotebookLaw, dt = 1 / 60): void {\n const s = m.sheets[i];\n if (!s || !s.held) return;\n const reach = Math.max(sGrab, 12);\n const grip = Math.acos(clamp((xLocal - xg) / reach, -1, 1));\n const v = (grip - s.grip) / Math.max(dt, 1e-3);\n s.gripV = s.gripV * 0.5 + v * 0.5;\n s.grip = grip;\n const lead = (s.from === 0 ? 1 : -1) * 0.5 * Math.sin(grip);\n s.psiT = clamp(grip + lead, 0, Math.PI);\n s.twT = clamp(yFrac, -1, 1) * law.peek.twist * 2.2 * Math.sin(Math.max(grip, 0.25));\n}\n\n/** Let go of a held sheet: it goes where the hand was taking it — flung, or past the vertical — else back. */\nexport function releaseSheet(m: NotebookMotion, i: number): void {\n const s = m.sheets[i];\n if (!s || !s.held) return;\n s.held = false;\n const v = s.gripV;\n s.side = v > 2.5 ? 1 : v < -2.5 ? 0 : s.grip > Math.PI / 2 ? 1 : 0;\n}\n\n/** Open or close. Closing lands every sheet in the air on the side it was heading. */\nexport function setOpen(m: NotebookMotion, open: boolean): void {\n if (m.opened === open) return;\n m.opened = open;\n if (!open) {\n for (const s of m.sheets) if (s.air) { s.air = false; s.held = false; s.phi = s.psi = s.side * Math.PI; s.phiV = s.psiV = s.tw = s.twV = 0; }\n m.peekOn = false;\n } else m.fluttered = false;\n}\n\n// ---------------------------------------------------------------- the step\n\n/** The sheets in the air, `n` substeps of `h` seconds: a held one follows the hand, the rest spring to their side and land. True while any is in the air. */\nfunction stepSheets(m: NotebookMotion, h: number, n: number, law: NotebookLaw): boolean {\n const S = law.springs;\n let live = false;\n for (const s of m.sheets) {\n if (!s.air) continue;\n const T = s.side * Math.PI;\n for (let k = 0; k < n; k++) {\n if (s.held) {\n // the edge is where the hand says (stiffly); the root follows it, lagging — the sheet bows toward the hand\n [s.psi, s.psiV] = springStep(s.psi, s.psiV, s.psiT, 9, 0.9, h);\n [s.phi, s.phiV] = springStep(s.phi, s.phiV, s.grip - (s.psiT - s.grip), S.root[0] * 1.6, 0.9, h);\n [s.tw, s.twV] = springStep(s.tw, s.twV, s.twT, 6, 0.8, h);\n } else {\n [s.phi, s.phiV] = springStep(s.phi, s.phiV, T, S.root[0], S.root[1], h);\n [s.psi, s.psiV] = springStep(s.psi, s.psiV, s.phi, S.edge[0], S.edge[1], h);\n [s.tw, s.twV] = springStep(s.tw, s.twV, 0, S.edge[0], S.edge[1], h);\n }\n // a sheet cannot pass through a stack: it lands, it does not sink\n if (s.phi < 0) { s.phi = 0; if (s.phiV < 0) s.phiV *= -0.15; }\n if (s.phi > Math.PI) { s.phi = Math.PI; if (s.phiV > 0) s.phiV *= -0.15; }\n if (s.psi < 0) { s.psi = 0; if (s.psiV < 0) s.psiV *= -0.2; }\n if (s.psi > Math.PI) { s.psi = Math.PI; if (s.psiV > 0) s.psiV *= -0.2; }\n }\n if (!s.held && Math.abs(s.phi - T) < 2e-3 && Math.abs(s.psi - T) < 2e-3 && Math.abs(s.phiV) + Math.abs(s.psiV) < 0.03 && Math.abs(s.tw) < 2e-3) {\n s.air = false; s.phi = s.psi = T; s.phiV = s.psiV = s.tw = s.twV = 0;\n } else live = true;\n }\n return live;\n}\n\n/** The corner's peek, `n` substeps of `h` seconds: up while the pointer invites a turn of an open book with nothing in the air. True while it moves. */\nfunction stepPeek(m: NotebookMotion, h: number, n: number, law: NotebookLaw): boolean {\n const S = law.springs;\n let live = false;\n const peekT = m.peekOn && turnable(m) && !anyAir(m) ? 1 : 0;\n for (let k = 0; k < n; k++) [m.peek, m.peekV] = springStep(m.peek, m.peekV, peekT, S.peek[0], S.peek[1], h);\n if (Math.abs(m.peek - peekT) < 1e-3 && Math.abs(m.peekV) < 1e-2) { m.peek = peekT; m.peekV = 0; } else live = true;\n return live;\n}\n\n/**\n * The SHEETS and the PEEK alone, by dt seconds (D3t-b): a book in hand, whose cover, lift and tilt are the hand's (kinds/notebook.ts\n * — the cover on the palm's spring), keeps its sheets' springs here — the same substeps `stepMotion` takes. True while any moves.\n */\nexport function stepLeaves(m: NotebookMotion, dt0: number, law: NotebookLaw): boolean {\n const dt = Math.min(dt0, 0.05);\n const n = 8;\n const h = dt / n;\n const a = stepSheets(m, h, n, law);\n const b = stepPeek(m, h, n, law);\n return a || b;\n}\n\n/** Advance every spring by dt seconds; true while anything still moves. */\nexport function stepMotion(m: NotebookMotion, dt0: number, law: NotebookLaw): boolean {\n let dt = dt0;\n const S = law.springs;\n dt = Math.min(dt, 0.05);\n const n = 8;\n const h = dt / n;\n let live = false;\n // the cover\n const thetaT = m.opened ? Math.PI : 0;\n const prev = m.theta;\n for (let k = 0; k < n; k++) [m.theta, m.thetaV] = springStep(m.theta, m.thetaV, thetaT, S.cover[0], S.cover[1], h);\n if (Math.abs(m.theta - thetaT) < 1e-4 && Math.abs(m.thetaV) < 1e-3) { m.theta = thetaT; m.thetaV = 0; } else live = true;\n // the landing flutter: as an opening cover comes down, the first sheets lift off the block and fall back\n if (m.opened && !m.fluttered && prev < 0.9 * Math.PI && m.theta >= 0.9 * Math.PI) {\n m.fluttered = true;\n let top = rightTop(m);\n for (let k = 0; k < law.flutter.sheets && top >= 0; k++) {\n const s = m.sheets[top] as SheetMotion;\n const f = 1 - k / law.flutter.sheets;\n s.air = true; s.side = 0; s.phi = 0; s.psi = 0; s.phiV = law.flutter.kick * 0.25 * f; s.psiV = law.flutter.kick * f; s.tw = 0; s.twV = 0.6 * f;\n top = rightTop(m);\n }\n }\n if (stepSheets(m, h, n, law)) live = true;\n if (stepPeek(m, h, n, law)) live = true;\n // the lift and the tilt\n const liftT = m.held ? 1 : 0;\n for (let k = 0; k < n; k++) [m.lift, m.liftV] = springStep(m.lift, m.liftV, liftT, S.lift[0], S.lift[1], h);\n if (Math.abs(m.lift - liftT) < 1e-3 && Math.abs(m.liftV) < 1e-2) { m.lift = liftT; m.liftV = 0; } else live = true;\n const tx = m.held ? m.tiltTX : 0;\n const ty = m.held ? m.tiltTY : 0;\n for (let k = 0; k < n; k++) { [m.tiltX, m.tiltXV] = springStep(m.tiltX, m.tiltXV, tx, S.tilt[0], S.tilt[1], h); [m.tiltY, m.tiltYV] = springStep(m.tiltY, m.tiltYV, ty, S.tilt[0], S.tilt[1], h); }\n if (Math.abs(m.tiltX - tx) + Math.abs(m.tiltY - ty) < 1e-4 && Math.abs(m.tiltXV) + Math.abs(m.tiltYV) < 1e-3) { m.tiltX = tx; m.tiltY = ty; m.tiltXV = m.tiltYV = 0; } else live = true;\n // the tilt target decays toward level on its own: a hand that stops, stops the swing\n m.tiltTX *= Math.exp(-dt * 7); m.tiltTY *= Math.exp(-dt * 7);\n if (Math.abs(m.tiltTX) + Math.abs(m.tiltTY) > 1e-4) live = true;\n // the hover's rise\n const hoverT = m.hoverOn && !m.held && !m.opened ? 1 : 0;\n for (let k = 0; k < n; k++) [m.hover, m.hoverV] = springStep(m.hover, m.hoverV, hoverT, S.lift[0] * 1.6, 0.85, h);\n if (Math.abs(m.hover - hoverT) < 1e-3 && Math.abs(m.hoverV) < 1e-2) { m.hover = hoverT; m.hoverV = 0; } else live = true;\n // the ring: a selected book lying closed on the mat — never under a lifted or an open one\n const ringT = m.selected && !m.held && !m.opened ? 1 : 0;\n for (let k = 0; k < n; k++) [m.ring, m.ringV] = springStep(m.ring, m.ringV, ringT, S.ring[0], S.ring[1], h);\n if (Math.abs(m.ring - ringT) < 1e-3 && Math.abs(m.ringV) < 1e-2) { m.ring = ringT; m.ringV = 0; } else live = true;\n return live;\n}\n\n/** The hand's velocity (CSS px / s) → the tilt it asks for: the leading edge dips, capped. */\nexport function tiltToward(m: NotebookMotion, vx: number, vy: number, law: NotebookLaw): void {\n const k = law.lift.tiltPer;\n const cap = law.lift.tiltMax;\n m.tiltTY = clamp(vx * k, -cap, cap);\n m.tiltTX = clamp(-vy * k, -cap, cap);\n}\n\n// ---------------------------------------------------------------- the pose\n\n/** The pose the mesh is built for: the swing, the stacks' counts and tops, the sheets in the air (a peek is one). */\nexport function poseOf(m: NotebookMotion, law: NotebookLaw): NotebookPose {\n const airs: Air[] = [];\n m.sheets.forEach((s, i) => { if (s.air) airs.push({ index: i, phi: s.phi, psi: s.psi, twist: s.tw }); });\n const c = counts(m);\n let rt = rightTop(m);\n let right = c.right;\n if (m.peek > 1e-3 && rt >= 0 && airs.length === 0) {\n airs.push({ index: rt, phi: 0, psi: law.peek.angle * m.peek, twist: m.peekSide * law.peek.twist * m.peek });\n right -= 1;\n rt = -1;\n for (let i = 0; i < m.sheets.length; i++) { const s = m.sheets[i] as SheetMotion; if (!s.air && s.side === 0 && !airs.some((a) => a.index === i)) { rt = i; break; } }\n }\n return { theta: m.theta, right, left: c.left, rightTop: rt, leftTop: leftTop(m), airs };\n}\n\n/** The pose with the desk under the book (−its lift, in its own z): what the ribbon hangs to. */\nexport const withDesk = (p: NotebookPose, lift: number): NotebookPose => ({ ...p, desk: -Math.max(lift, 0) });\n\n/** A key that changes whenever the pose would build a different mesh. */\nexport function poseKey(p: NotebookPose): string {\n let k = `${p.theta.toFixed(5)}|${p.right}|${p.left}|${p.rightTop}|${p.leftTop}`;\n for (const a of p.airs) k += `|${a.index}:${a.phi.toFixed(5)}:${a.psi.toFixed(5)}:${a.twist.toFixed(5)}`;\n if (p.desk) k += `|d${p.desk.toFixed(2)}`;\n return k;\n}\n","// A PAGE'S RASTER (NOTEBOOK.md §8; D3t-b) — the pen's ink on one page as bytes, drawn by pure arithmetic. The prototype drew\n// it with Canvas2D (lab/notebook-ink.ts, the sticky note's path); neither the Node oracle nor the desk-dom-free wall has a\n// canvas, and a canvas's antialiasing is its browser's — so the stroke is drawn here the way the prototype's canvas stroked\n// it, the same everywhere to the bit: each segment the MIDPOINT QUADRATIC (from the midpoint before a sample, through it, to\n// the midpoint after — the first segment from the first sample, the last to the last: a stroke with no corners), its width\n// the mean of its two ends', round-capped; a stroke of one sample is a dot. A segment is laid ONCE, as a canvas's `stroke()`\n// lays one path: its coverage is the most any piece of it gives a texel (the quadratic flattened into short capsules, each\n// texel's distance to the nearest), then laid over the page source-over in the pen's colour, straight alpha — the texture the\n// pass samples (`ink.rgb`, `ink.a` into the paper's albedo before the light). Square roots and the four operations only.\n//\n// A stroke drawn a segment at a time as the samples come (the pen in hand) lays exactly what the stroke drawn whole lays:\n// segment k needs sample k + 1 (its end is the midpoint after k), so it is drawn once that sample is known — the last at the lift.\n\nimport type { RGB } from \"@ice/desk\";\nimport { INK_H, INK_W, type InkPoint } from \"./ink\";\n\n/** A texel rectangle of a page's raster (x, y its top-left; w, h ≥ 0), clipped to the raster. */\nexport interface InkRect {\n readonly x: number;\n readonly y: number;\n readonly w: number;\n readonly h: number;\n}\n\n/** One page's ink: RGBA8, straight alpha, `INK_W × INK_H` texels, row by row — the layer the pass holds is a copy of these bytes. */\nexport class PageRaster {\n readonly bytes: Uint8Array<ArrayBuffer> = new Uint8Array(INK_W * INK_H * 4);\n clear(): void { this.bytes.fill(0); }\n}\n\n/** The union of two rects (either may be null — nothing touched). */\nexport function unionRect(a: InkRect | null, b: InkRect | null): InkRect | null {\n if (a === null) return b;\n if (b === null) return a;\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n return { x, y, w: Math.max(a.x + a.w, b.x + b.w) - x, h: Math.max(a.y + a.h, b.y + b.h) - y };\n}\n\n/** How many segments a stroke of `n` samples is drawn as, and how many of them are FINAL — known whole (all of them once lifted). */\nexport function segmentsOf(n: number, lifted: boolean): number {\n if (n <= 0) return 0;\n if (n === 1) return lifted ? 1 : 0; // a dot, laid at the lift\n return lifted ? n - 1 : n - 2;\n}\n\n/** The coverage scratch a segment is gathered in before it is laid (grown as needed, never shrunk). */\nlet scratch = new Float32Array(4096);\n\n/** A capsule's coverage into the scratch over the box (bx, by, bw): the most of what each texel had and this piece gives it. */\nfunction capsule(x0: number, y0: number, x1: number, y1: number, rad: number, bx: number, by: number, bw: number, bh: number): void {\n const lo = rad + 1;\n const tx0 = Math.max(Math.floor(Math.min(x0, x1) - lo), bx);\n const ty0 = Math.max(Math.floor(Math.min(y0, y1) - lo), by);\n const tx1 = Math.min(Math.ceil(Math.max(x0, x1) + lo), bx + bw);\n const ty1 = Math.min(Math.ceil(Math.max(y0, y1) + lo), by + bh);\n const dx = x1 - x0;\n const dy = y1 - y0;\n const len2 = dx * dx + dy * dy;\n for (let ty = ty0; ty < ty1; ty++) {\n const py = ty + 0.5;\n const row = (ty - by) * bw;\n for (let tx = tx0; tx < tx1; tx++) {\n const px = tx + 0.5;\n let u = len2 > 0 ? ((px - x0) * dx + (py - y0) * dy) / len2 : 0;\n if (u < 0) u = 0;\n else if (u > 1) u = 1;\n const ex = px - (x0 + dx * u);\n const ey = py - (y0 + dy * u);\n const c = rad + 0.5 - Math.sqrt(ex * ex + ey * ey);\n if (c <= 0) continue;\n const k = row + (tx - bx);\n const v = c >= 1 ? 1 : c;\n if (v > (scratch[k] as number)) scratch[k] = v;\n }\n }\n}\n\n/** Lay the scratch's coverage over the raster in `colour` (sRGB 0 … 1), source-over, straight alpha. */\nfunction lay(r: PageRaster, colour: RGB, bx: number, by: number, bw: number, bh: number): void {\n const b = r.bytes;\n const cr = Math.round(colour[0] * 255);\n const cg = Math.round(colour[1] * 255);\n const cb = Math.round(colour[2] * 255);\n for (let y = 0; y < bh; y++) {\n for (let x = 0; x < bw; x++) {\n const c = scratch[y * bw + x] as number;\n if (c <= 0) continue;\n const i = ((by + y) * INK_W + (bx + x)) * 4;\n const a0 = (b[i + 3] as number) / 255;\n const ao = c + a0 * (1 - c);\n const k0 = a0 * (1 - c);\n b[i] = Math.round((cr * c + (b[i] as number) * k0) / ao);\n b[i + 1] = Math.round((cg * c + (b[i + 1] as number) * k0) / ao);\n b[i + 2] = Math.round((cb * c + (b[i + 2] as number) * k0) / ao);\n b[i + 3] = Math.round(ao * 255);\n }\n }\n}\n\n/** The box a segment may touch, clipped to the raster; null when it lies off it. */\nfunction boxOf(xs: readonly number[], ys: readonly number[], rad: number): InkRect | null {\n const x0 = Math.max(Math.floor(Math.min(...xs) - rad - 1), 0);\n const y0 = Math.max(Math.floor(Math.min(...ys) - rad - 1), 0);\n const x1 = Math.min(Math.ceil(Math.max(...xs) + rad + 1), INK_W);\n const y1 = Math.min(Math.ceil(Math.max(...ys) + rad + 1), INK_H);\n return x1 > x0 && y1 > y0 ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null;\n}\n\n/** Make room in the scratch for a box and zero it. */\nfunction ready(box: InkRect): void {\n const need = box.w * box.h;\n if (scratch.length < need) scratch = new Float32Array(Math.max(need, scratch.length * 2));\n scratch.fill(0, 0, need);\n}\n\n/**\n * Segment `k` of a stroke into a raster (1 ≤ k < n; for a stroke of one sample, k = 1 is its dot): the midpoint quadratic from\n * the midpoint before sample k (sample 0 itself for k = 1) through sample k to the midpoint after it (sample k itself when it is\n * the last), `sx`/`sy` texels per page unit. Returns the rect it touched, or null.\n */\nexport function drawSegment(r: PageRaster, colour: RGB, p: readonly InkPoint[], k: number, sx: number, sy: number): InkRect | null {\n const n = p.length;\n if (n === 0 || k < 1) return null;\n if (n === 1) {\n const q = p[0] as InkPoint;\n const rad = (q.w * sx) / 2;\n const x = q.s * sx;\n const y = q.y * sy;\n const box = boxOf([x], [y], rad);\n if (box === null) return null;\n ready(box);\n capsule(x, y, x, y, rad, box.x, box.y, box.w, box.h);\n lay(r, colour, box.x, box.y, box.w, box.h);\n return box;\n }\n if (k >= n) return null;\n const a = p[k - 1] as InkPoint;\n const b = p[k] as InkPoint;\n const c = k + 1 < n ? (p[k + 1] as InkPoint) : null;\n const m0x = k === 1 ? a.s * sx : ((a.s + b.s) / 2) * sx;\n const m0y = k === 1 ? a.y * sy : ((a.y + b.y) / 2) * sy;\n const m1x = c !== null ? ((b.s + c.s) / 2) * sx : b.s * sx;\n const m1y = c !== null ? ((b.y + c.y) / 2) * sy : b.y * sy;\n const bx = b.s * sx;\n const by = b.y * sy;\n const rad = (((a.w + b.w) / 2) * sx) / 2;\n const box = boxOf([m0x, bx, m1x], [m0y, by, m1y], rad);\n if (box === null) return null;\n ready(box);\n // flattened: pieces of about 3 texels along the control polygon (at least one, at most 48)\n const reach = Math.sqrt((bx - m0x) * (bx - m0x) + (by - m0y) * (by - m0y)) + Math.sqrt((m1x - bx) * (m1x - bx) + (m1y - by) * (m1y - by));\n const pieces = Math.min(Math.max(Math.ceil(reach / 3), 1), 48);\n let px = m0x;\n let py = m0y;\n for (let i = 1; i <= pieces; i++) {\n const t = i / pieces;\n const u = 1 - t;\n const qx = u * u * m0x + 2 * u * t * bx + t * t * m1x;\n const qy = u * u * m0y + 2 * u * t * by + t * t * m1y;\n capsule(px, py, qx, qy, rad, box.x, box.y, box.w, box.h);\n px = qx;\n py = qy;\n }\n lay(r, colour, box.x, box.y, box.w, box.h);\n return box;\n}\n\n/** A page's texels per page unit across and down (the raster spans the page's open width `len` and its height). */\nexport const scaleOf = (len: number, height: number): readonly [number, number] => [INK_W / len, INK_H / height];\n\n/** A whole stroke into a raster — every segment, as the pen laid them; the rect it touched. */\nexport function drawStroke(r: PageRaster, colour: RGB, p: readonly InkPoint[], sx: number, sy: number): InkRect | null {\n let rect: InkRect | null = null;\n const segs = segmentsOf(p.length, true);\n for (let k = 1; k <= segs; k++) rect = unionRect(rect, drawSegment(r, colour, p, k, sx, sy));\n return rect;\n}\n","// THE PAGES' INK ON THE DEVICE (NOTEBOOK.md §8; D3t-b) — the cache the notebook kind keeps on one desk: the pass's eight ink\n// layers handed out LRU to the pages in view that have ink (the prototype's `inkTable`), each a CPU raster the layer mirrors\n// (notebook/raster.ts). A page's raster is a CACHE of its strokes — the notebook's data children (design-015 §5.1): replayed\n// whole when the strokes it holds are not the page's (a stroke undone or redone, a peer's, the look changed, the layer evicted);\n// the pen in hand draws into it a segment at a time, each the moment it is final, uploading only the rectangle it touched; and\n// the stroke it lifts is ADOPTED — the raster already holds it, so the page's strokes growing by exactly that one is no replay.\n// A stroke's identity is its pen, its pace and its path as its cell keeps them (`pageStrokeKey`): the table compares the page's\n// list with what the raster drew.\n\nimport type { RasterBudget, RGB } from \"@ice/desk\";\nimport { INK_H, INK_LAYERS, INK_TABLE, INK_W, type InkPoint } from \"./ink\";\nimport { drawSegment, drawStroke, type InkRect, PageRaster, scaleOf, segmentsOf, unionRect } from \"./raster\";\n\n/**\n * A stroke's identity on its page — what a raster compares: its pen, its pace (the cell's `times`; an untimed stroke's `speed`) and\n * its path (the cell's `points`). Two dots on one spot in two pens are two strokes.\n */\nexport const pageStrokeKey = (ink: string, points: string, times: string, speed: number): string => `${ink}|${times !== \"\" ? times : `@${speed}`}|${points}`;\n\n/** A stroke as a page's raster draws it: its identity (`pageStrokeKey`), its pen by name, its samples with their widths. */\nexport interface PageStroke {\n readonly key: string;\n readonly ink: string;\n readonly points: readonly InkPoint[];\n}\n\n/** The pen in hand's stroke (the pen driver's): its page, its pen, its samples so far (grown in place), lifted or not; its key once lifted. */\nexport interface LiveStroke {\n readonly page: number;\n readonly ink: string;\n readonly points: InkPoint[];\n lifted: boolean;\n key: string;\n}\n\n/** The pages a record names and the layer each is in (the pass's `NotebookDraw.ink`). */\nexport interface InkTable {\n readonly pages: readonly number[];\n readonly layers: readonly number[];\n}\n\n/** Where a raster's bytes go: the notebook pass's layers (`NotebookPass.uploadInk`). */\nexport interface InkUploader {\n uploadInk(layer: number, bytes: Uint8Array<ArrayBuffer>, x?: number, y?: number, w?: number, h?: number): void;\n}\n\ninterface Slot {\n key: string | null;\n raster: PageRaster | null;\n /** The strokes the raster holds whole, in the order drawn; null — nothing yet (a replay is due). */\n drawn: string[] | null;\n look: unknown;\n /** A live stroke partly drawn over them, and how many of its segments are down. */\n live: LiveStroke | null;\n segs: number;\n used: number;\n}\n\nconst same = (a: readonly string[], b: readonly string[]): boolean => a.length === b.length && a.every((k, i) => k === b[i]);\n\nexport class PageInk {\n private readonly slots: Slot[] = Array.from({ length: INK_LAYERS }, () => ({ key: null, raster: null, drawn: null, look: null, live: null, segs: 0, used: 0 }));\n private clock = 0;\n /** Whole-page replays since the cache was made (a witness: the pen's own stroke lands with none). */\n replays = 0;\n /** THE BUDGET (D6): each layer's CPU raster (5.6 MB) charged as it is made; evicted, the layer replays from its strokes when next used. */\n private readonly budget: RasterBudget | undefined;\n constructor(budget?: RasterBudget) { this.budget = budget; }\n\n /** The budget's ask (D6): a layer's raster is kept while its page was in a table this frame. */\n keeps(key: string): boolean {\n const s = this.slots[Number(key)];\n return s !== undefined && s.used === this.clock;\n }\n\n /**\n * The table for one book's pages in view this frame (`pages` in the pass's order): every page with ink — strokes, or the live\n * stroke on it — gets a layer (kept if it has one, else the least recently used is taken), its raster brought up to its\n * strokes (replayed, or the live stroke's new final segments drawn) and uploaded (whole after a replay, else the touched\n * rectangle). `book` is the book's id on this desk; `len × height` the page's open extent in page units. Without an uploader\n * (no pass yet) nothing is drawn and the table is empty — the next frame tries again.\n */\n table(book: number, pages: readonly number[], strokesOf: (page: number) => readonly PageStroke[], live: LiveStroke | null, colourOf: (ink: string) => RGB, look: unknown, up: InkUploader | undefined, len: number, height: number): InkTable {\n this.clock += 1;\n const out: { pages: number[]; layers: number[] } = { pages: [], layers: [] };\n if (up === undefined) return out;\n const [sx, sy] = scaleOf(len, height);\n for (const page of pages) {\n if (out.pages.length >= INK_TABLE) break;\n const strokes = strokesOf(page);\n const lv = live !== null && live.page === page ? live : null;\n const key = `${book}:${page}`;\n if (strokes.length === 0 && lv === null) {\n // no ink (the last stroke undone): the page gives its layer back — only pages with ink hold one\n const held = this.slots.find((s) => s.key === key);\n if (held !== undefined) { held.key = null; held.drawn = null; held.live = null; held.segs = 0; held.used = 0; }\n continue;\n }\n let i = this.slots.findIndex((s) => s.key === key);\n if (i < 0) {\n i = 0;\n for (let k = 1; k < this.slots.length; k++) if ((this.slots[k] as Slot).used < (this.slots[i] as Slot).used) i = k;\n const s = this.slots[i] as Slot;\n s.key = key; s.drawn = null; s.live = null; s.segs = 0;\n }\n const s = this.slots[i] as Slot;\n if (s.raster === null) {\n s.raster = new PageRaster();\n s.drawn = null; // a fresh raster holds nothing: the page replays into it\n const layer = i;\n this.budget?.charge(\"notebook\", String(layer), INK_W * INK_H * 4, () => { const q = this.slots[layer] as Slot; q.raster = null; q.drawn = null; q.live = null; q.segs = 0; });\n } else this.budget?.touch(\"notebook\", String(i));\n const want = strokes.map((st) => st.key);\n let rect: InkRect | null = null;\n let whole = false;\n if (s.drawn === null || s.look !== look || !same(s.drawn, want) || (s.live !== null && s.live !== lv)) {\n s.raster.clear();\n for (const st of strokes) drawStroke(s.raster, colourOf(st.ink), st.points, sx, sy);\n s.drawn = want; s.look = look; s.live = null; s.segs = 0;\n whole = true;\n this.replays += 1;\n }\n if (lv !== null) {\n if (s.live !== lv) { s.live = lv; s.segs = 0; }\n const final = segmentsOf(lv.points.length, lv.lifted);\n const colour = colourOf(lv.ink);\n for (let k = s.segs + 1; k <= final; k++) rect = unionRect(rect, drawSegment(s.raster, colour, lv.points, k, sx, sy));\n s.segs = final;\n // lifted: the raster holds it whole — it is one of the strokes it drew (adopted when its child lands)\n if (lv.lifted) { s.drawn = [...(s.drawn ?? []), lv.key]; s.live = null; s.segs = 0; }\n }\n if (whole) up.uploadInk(i, s.raster.bytes);\n else if (rect !== null) up.uploadInk(i, s.raster.bytes, rect.x, rect.y, rect.w, rect.h);\n s.used = this.clock;\n out.pages.push(page);\n out.layers.push(i);\n }\n return out;\n }\n\n /** A page's raster as its layer holds it (a witness), or undefined when it has none. */\n rasterOf(book: number, page: number): PageRaster | undefined {\n return this.slots.find((s) => s.key === `${book}:${page}`)?.raster ?? undefined;\n }\n\n /** A book left the desk: its layers are free (their rasters kept for the next page to take). */\n forget(book: number): void {\n for (const s of this.slots) if (s.key?.startsWith(`${book}:`) === true) { s.key = null; s.drawn = null; s.live = null; s.segs = 0; s.used = 0; }\n }\n\n /** Everything dropped (the desk ends). */\n dispose(): void {\n for (const [i, s] of this.slots.entries()) { if (s.raster !== null) this.budget?.release(\"notebook\", String(i)); s.key = null; s.raster = null; s.drawn = null; s.live = null; }\n }\n}\n","// The NOTEBOOK pass — real 3D books drawn after the ground (NOTEBOOK.md §6). A second pass,\n// like the photo's: the ground renders the mat, the cards and the notes; this draws the books\n// above them, in three steps each frame there is a book to draw:\n//\n// 1. each book's SHADOW MAP — its depth from its lamp, into its layer of a depth array;\n// 2. the LAYER — a 4× multisampled colour + depth target: every book (depth-tested, opaque,\n// its page corners rounded by the sample mask), then the mat under each book (its\n// shadow and contact, its ring) wherever the book does not cover it; resolved;\n// 3. the COMPOSITE — the resolved layer, premultiplied, over the canvas.\n//\n// The layer is why the books can be meshes: their silhouettes get real antialiasing and their\n// parts real occlusion, and the mat's shadow is a premultiplied darkening the ground never\n// has to know about. Meshes live in per-book buffers, uploaded only when the book's pose\n// changed; a book carried across the desk moves by its matrix.\n//\n// Two hosts (design-015 D3r-b): the prototype's lab drew the books after the ground in a command\n// buffer of their own (`render`: steps 1–3); the desk's registry records steps 1–2 into the\n// frame's own encoder (`layer`) and lays step 3 inside the frame's pass as the things' last run\n// (`composite`, kinds/notebook.ts) — the same commands, the same bytes.\n\nimport { bindGroup, bindLayout, storageBuffer, uniformBuffer, compile, compose } from \"@ice/desk/engine\";\nimport type { RenderTarget, RGB, RGBA } from \"@ice/desk\";\nimport { type FadeIn, type View, type MatConfig, type MatFrame, MatUniforms, type MatPass, DAY_LIGHT, type MatLight, type DeskEye, eyeValues, project, type BuiltMesh, VERTEX_BYTES, inverseOf, lightFrame, matrixOf, type Rigid, worldBounds, PAPER_TEX, paperTexture, generateMips, mipCount, sentBytes, writeChanged, attachmentOf, BoxTargets, layerCompositeLayout } from \"@ice/desk/kit\";\nimport type { NotebookLaw } from \"./law\";\nimport { designCode, MAX_NOTEBOOKS, MAX_SHADOWED, NbBook, NbUniforms, nbUniformValues, type NotebookLook, type Ruling, rulingCode, SHADOW_RES } from \"./layout\";\nimport type { Frame } from \"./shape\";\nimport type { NotebookShaders } from \"./shaders\";\nimport { INK_H, INK_LAYERS, INK_TABLE, INK_W } from \"./ink\";\n\nconst SAMPLES = 4;\nconst BLEND_PREMUL: GPUBlendState = {\n color: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n alpha: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n};\n\n/** One book as the pass draws it this frame. */\nexport interface NotebookDraw {\n /** A stable id: the book's GPU buffers are kept under it. */\n readonly id: number;\n readonly mesh: BuiltMesh;\n /** Bumped whenever the mesh was rebuilt — the upload's key. */\n readonly version: number;\n readonly frame: Frame;\n readonly rigid: Rigid;\n /** The unit direction toward the lamp. */\n readonly lamp: readonly [number, number, number];\n readonly theta: number;\n readonly gamma: number;\n readonly look: NotebookLook;\n readonly ruling: Ruling;\n readonly seed: number;\n /** The selection ring's presence, 0..1. */\n readonly ring: number;\n /** Something of the book rises over the rest (a sheet in the air, the cover swinging): its surfaces read the shadow map. */\n readonly selfShadow: boolean;\n /** The pages whose ink is on the device, and the layer each is in (at most `INK_TABLE`). */\n readonly ink: { readonly pages: readonly number[]; readonly layers: readonly number[] };\n /** The look's ruling ink — the pass's fallback where no host set its own (a record made without the desk's local: a tray specimen, K5a). */\n readonly rule?: RGBA;\n}\n\ninterface BookBuffers { vb: GPUBuffer; ib: GPUBuffer; vcap: number; icap: number; version: number; icount: number; seen: number }\n\n/**\n * What one RENDER TARGET keeps between its prepares (D7): the layer's targets at its size, the books' meshes it drew (swept when a\n * prepare of ITS OWN no longer sees them), its frame count, this prepare's books, their screen extent and box, its stats. A held\n * frame prepares the pass twice — the desk copy behind the hand at half the dpr, then the hand — and with one state each prepare\n * undid the other's (the targets refit, the other's meshes given back): the copy's is kept apart and given back at the hold's end.\n */\ninterface NbTarget {\n /** The layer's targets at the books' screen box (K7a, kit/layer.ts `BoxTargets`). */\n readonly layer: BoxTargets;\n readonly buffers: Map<number, BookBuffers>;\n /** Turns over whenever one of this target's meshes is uploaded (K7a: a layer drawn from other meshes is drawn again). */\n meshGen: number;\n list: NotebookDraw[];\n frameNo: number;\n screen: { x0: number; y0: number; x1: number; y1: number } | null;\n stats: NotebookStats;\n box: readonly [number, number, number, number] | null;\n}\n\nconst nbTarget = (layer: BoxTargets): NbTarget => ({ layer, buffers: new Map(), meshGen: 0, list: [], frameNo: 0, screen: null, stats: { books: 0, triangles: 0, shadowed: 0 }, box: null });\n\n/** The shadow maps' stand-in before a book is drawn: one texel, one layer. */\nconst noShadows = (device: GPUDevice): GPUTexture => device.createTexture({ label: \"notebook/shadow maps (none yet)\", size: [1, 1, 1], format: \"depth32float\", usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING });\n\nfunction dropTarget(t: NbTarget): void {\n for (const b of t.buffers.values()) { b.vb.destroy(); b.ib.destroy(); }\n t.buffers.clear();\n t.layer.dispose();\n}\n\nexport interface NotebookStats { readonly books: number; readonly triangles: number; readonly shadowed: number }\n\nexport class NotebookPass {\n readonly name = \"notebook/books\";\n private readonly device: GPUDevice;\n private readonly format: GPUTextureFormat;\n private readonly mat: MatPass;\n private readonly knobs = NbUniforms.alloc(1);\n private readonly records = NbBook.alloc(MAX_NOTEBOOKS);\n /** What the GPU holds of the records: a prefix is written only when it changed (K4a). */\n private readonly recordsSent = sentBytes(NbBook.size * MAX_NOTEBOOKS);\n private readonly knobBuf: GPUBuffer;\n /** What the GPU holds of the knobs: they are written only when they change (K4a — a standing value costs a frame nothing). */\n private readonly knobsSent = sentBytes(NbUniforms.size);\n private readonly recordBuf: GPUBuffer;\n private readonly layoutMain: GPUBindGroupLayout;\n private readonly layoutShadow: GPUBindGroupLayout;\n private readonly layoutComp: GPUBindGroupLayout;\n private readonly bookPipe: GPURenderPipeline;\n private readonly recvPipe: GPURenderPipeline;\n private readonly shadowPipe: GPURenderPipeline;\n private readonly compPipe: GPURenderPipeline;\n private readonly goboSampler: GPUSampler;\n private readonly noiseSampler: GPUSampler;\n private readonly cmpSampler: GPUSampler;\n /**\n * The shadow maps (K6a, design-016 §6): a placeholder until a book is drawn, then a layer a book drawn (up to MAX_SHADOWED — they\n * are drawn again every frame, so growing them keeps nothing): a desk with no notebook holds none of their 33.5 MB, one with one\n * book 4 MB. With the frame's layer targets they are let go when no book was drawn for a while (`releaseLayer`, the kind's tick)\n * and with the last book — render targets, never under the raster budget (D-K6a.3; sizing them to the books' box is K7's).\n */\n private shadowTex: GPUTexture;\n private shadowLayers: GPUTextureView[] = [];\n /**\n * What each shadow map holds (K7a — cached while the lamp and the book stand still): the book's id, its mesh's version, its\n * placement and its light's frame as the map was drawn — the map is drawn again only when one of them moved. The lamp stands\n * in world space and the eye is not in the map, so a pan, a zoom or a frame drawn for another object draws none.\n */\n private readonly shadowKeys: Float32Array[] = Array.from({ length: MAX_SHADOWED }, () => new Float32Array(34).fill(Number.NaN));\n private readonly recordFloats = new Float32Array(this.records.bytes);\n /** Shadow maps drawn and kept since the pass was made (a witness). */\n private shadowDraws = 0;\n private shadowKept = 0;\n /**\n * Turns over at every pass-wide resource a layer reads changing (K7a) — a page's ink uploaded, the main group made again (the\n * mat's assets, the ink or the shadow maps' texture): with the target's meshes' generation, the silhouette's key, what the pass\n * lists and the box — and by CONTENT the knobs, the records and the slot's view block — what a target's layer is laid again by,\n * undrawn (`BoxTargets.holds`). A shadow map drawn is not in it: its content is its book, mesh and light — in the records.\n */\n private gen = 0;\n private readonly sig = new Float64Array(8);\n private readonly read: Uint8Array[] = [];\n /** Layers drawn and laid again undrawn since the pass was made (a witness). */\n private layerDraws = 0;\n private layerKept = 0;\n private drawnAt = Number.NEGATIVE_INFINITY;\n private readonly shadowGroup: GPUBindGroup;\n private readonly inkSampler: GPUSampler;\n private readonly paperTex: GPUTexture;\n private readonly paperSampler: GPUSampler;\n /** The pages' ink rasters: a placeholder until the first stroke, then `INK_LAYERS` full pages. */\n private inkTex: GPUTexture;\n private inkReady = false;\n private mainGroup!: GPUBindGroup;\n private boundAssets = -1;\n private boundInk = false;\n /** The frame's target (the canvas; the hand) and the held desk copy's, apart (D7) — `t` the one this prepare is for (`use`). */\n private readonly frameT: NbTarget;\n private copyT: NbTarget | null = null;\n private t: NbTarget;\n /** The records the last prepare turned away at the pass's cap — not drawn; the ground reports them (`GroundStats.dropped`, D7). */\n dropped = 0;\n /** Profiling switches (a harness's): 1 no PCSS · 2 no material detail · 4 no gobo · 8 no shadow maps · 16 no composite · 32 no book draw · 64 no mat draw. */\n debug = 0;\n\n private constructor(device: GPUDevice, format: GPUTextureFormat, mat: MatPass, pipes: { layoutMain: GPUBindGroupLayout; layoutShadow: GPUBindGroupLayout; layoutComp: GPUBindGroupLayout; book: GPURenderPipeline; recv: GPURenderPipeline; shadow: GPURenderPipeline; comp: GPURenderPipeline }) {\n this.device = device; this.format = format; this.mat = mat;\n this.layoutMain = pipes.layoutMain; this.layoutShadow = pipes.layoutShadow; this.layoutComp = pipes.layoutComp;\n this.bookPipe = pipes.book; this.recvPipe = pipes.recv; this.shadowPipe = pipes.shadow; this.compPipe = pipes.comp;\n this.frameT = nbTarget(new BoxTargets(device, \"notebook\", this.layoutComp, SAMPLES, mat.view));\n this.t = this.frameT;\n this.knobBuf = uniformBuffer(device, NbUniforms.size, \"notebook/knobs\");\n this.recordBuf = storageBuffer(device, NbBook.size * MAX_NOTEBOOKS, \"notebook/books\");\n this.goboSampler = device.createSampler({ label: \"notebook/gobo\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" });\n this.noiseSampler = device.createSampler({ label: \"notebook/noise\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\" });\n this.cmpSampler = device.createSampler({ label: \"notebook/shadow\", compare: \"less\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" });\n this.shadowTex = noShadows(device);\n this.shadowGroup = device.createBindGroup({ label: \"notebook/shadow\", layout: this.layoutShadow, entries: [{ binding: 2, resource: { buffer: this.recordBuf } }] });\n this.inkSampler = device.createSampler({ label: \"notebook/ink\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" });\n this.inkTex = device.createTexture({ label: \"notebook/ink (none yet)\", size: [1, 1, 2], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });\n // the paper, baked once: its bytes, then its mips\n this.paperTex = device.createTexture({ label: \"notebook/paper\", size: [PAPER_TEX, PAPER_TEX], format: \"rgba8unorm\", mipLevelCount: mipCount(PAPER_TEX, PAPER_TEX), usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });\n device.queue.writeTexture({ texture: this.paperTex }, paperTexture(), { bytesPerRow: PAPER_TEX * 4 }, [PAPER_TEX, PAPER_TEX, 1]);\n generateMips(device, this.paperTex);\n this.paperSampler = device.createSampler({ label: \"notebook/paper\", magFilter: \"linear\", minFilter: \"linear\", mipmapFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\", maxAnisotropy: 8 });\n this.rebind();\n }\n\n static async create(device: GPUDevice, format: GPUTextureFormat, src: NotebookShaders, mat: MatPass): Promise<NotebookPass> {\n const layoutMain = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 2, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n { binding: 3, stages: [\"fragment\"], texture: \"float\" },\n { binding: 4, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 5, stages: [\"fragment\"], texture: \"float\" },\n { binding: 6, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 7, stages: [\"fragment\"], texture: \"depth\", dimension: \"2d-array\" },\n { binding: 8, stages: [\"fragment\"], sampler: \"comparison\" },\n { binding: 9, stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" },\n { binding: 10, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 11, stages: [\"fragment\"], texture: \"float\" },\n { binding: 12, stages: [\"fragment\"], sampler: \"filtering\" },\n ], \"notebook/main\");\n // the shadow pass draws INTO the depth array, so its group must not bind it\n const layoutShadow = device.createBindGroupLayout({ label: \"notebook/shadow\", entries: [{ binding: 2, visibility: GPUShaderStage.VERTEX, buffer: { type: \"read-only-storage\" } }] });\n // the layer, its box's origin (K7a — kit/layer.ts `BoxTargets`: the composite reads a pixel's texel at the pixel less it) and the\n // slot's view block — the composite lays the layer through the slot's portal chain (design-018 §4: the kit's contract, as one)\n const layoutComp = layerCompositeLayout(device, \"notebook/composite\");\n const module = await compile(device, compose(src.program));\n const compModule = await compile(device, compose(src.composite));\n const vertexLayout: GPUVertexBufferLayout = {\n arrayStride: VERTEX_BYTES,\n attributes: [\n { shaderLocation: 0, offset: 0, format: \"float32x3\" },\n { shaderLocation: 1, offset: 12, format: \"float32x3\" },\n { shaderLocation: 2, offset: 24, format: \"float32x2\" },\n { shaderLocation: 3, offset: 32, format: \"float32x4\" },\n { shaderLocation: 4, offset: 48, format: \"float32x2\" },\n { shaderLocation: 5, offset: 56, format: \"float32x2\" },\n ],\n };\n const mainLayout = device.createPipelineLayout({ bindGroupLayouts: [layoutMain] });\n const [book, recv, shadow, comp] = await Promise.all([\n device.createRenderPipelineAsync({\n label: \"notebook/book\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_book\", buffers: [vertexLayout] },\n fragment: { module, entryPoint: \"fs_book\", targets: [{ format: \"rgba8unorm\" }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil: { format: \"depth24plus\", depthWriteEnabled: true, depthCompare: \"less\" },\n multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"notebook/mat\", layout: mainLayout,\n vertex: { module, entryPoint: \"vs_recv\" },\n fragment: { module, entryPoint: \"fs_recv\", targets: [{ format: \"rgba8unorm\", blend: BLEND_PREMUL }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil: { format: \"depth24plus\", depthWriteEnabled: false, depthCompare: \"less\" },\n multisample: { count: SAMPLES },\n }),\n device.createRenderPipelineAsync({\n label: \"notebook/shadow\", layout: device.createPipelineLayout({ bindGroupLayouts: [layoutShadow] }),\n vertex: { module, entryPoint: \"vs_shadow\", buffers: [{ arrayStride: VERTEX_BYTES, attributes: [{ shaderLocation: 0, offset: 0, format: \"float32x3\" }] }] },\n primitive: { topology: \"triangle-list\", cullMode: \"none\" },\n depthStencil: { format: \"depth32float\", depthWriteEnabled: true, depthCompare: \"less\", depthBias: 2, depthBiasSlopeScale: 1.5 },\n }),\n device.createRenderPipelineAsync({\n label: \"notebook/composite\", layout: device.createPipelineLayout({ bindGroupLayouts: [layoutComp] }),\n vertex: { module: compModule, entryPoint: \"vs\" },\n fragment: { module: compModule, entryPoint: \"fs\", targets: [{ format, blend: BLEND_PREMUL }] },\n primitive: { topology: \"triangle-list\" },\n }),\n ]);\n return new NotebookPass(device, format, mat, { layoutMain, layoutShadow, layoutComp, book, recv, shadow, comp });\n }\n\n private rebind(): void {\n if (this.boundAssets === this.mat.assetVersion && this.boundInk === this.inkReady) return;\n this.mainGroup = bindGroup(this.device, this.layoutMain, [\n this.mat.view, this.knobBuf, this.recordBuf, this.mat.silhouette, this.goboSampler, this.mat.noiseTexture.createView(), this.noiseSampler,\n this.shadowTex.createView({ dimension: \"2d-array\" }), this.cmpSampler, this.inkTex.createView({ dimension: \"2d-array\" }), this.inkSampler,\n this.paperTex.createView(), this.paperSampler,\n ], \"notebook/main\");\n this.boundAssets = this.mat.assetVersion;\n this.boundInk = this.inkReady;\n this.gen += 1;\n }\n\n /**\n * Copy part of a page's raster (its bytes — notebook/raster.ts: RGBA8, straight alpha, `INK_W` texels a row) into its layer:\n * only the rectangle the pen touched goes (D3t-b — the bytes, not a canvas: the Node oracle writes the same layers). The first\n * call makes the layers — a book with no ink costs the device nothing.\n */\n uploadInk(layer: number, bytes: Uint8Array<ArrayBuffer>, x = 0, y = 0, w = INK_W, h = INK_H): void {\n if (!this.inkReady) {\n this.inkTex.destroy();\n this.inkTex = this.device.createTexture({ label: \"notebook/ink\", size: [INK_W, INK_H, INK_LAYERS], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.RENDER_ATTACHMENT });\n this.inkReady = true;\n this.rebind();\n }\n const x0 = Math.max(0, Math.floor(x));\n const y0 = Math.max(0, Math.floor(y));\n const x1 = Math.min(INK_W, Math.ceil(x + w));\n const y1 = Math.min(INK_H, Math.ceil(y + h));\n if (x1 <= x0 || y1 <= y0) return;\n this.device.queue.writeTexture({ texture: this.inkTex, origin: { x: x0, y: y0, z: layer } }, bytes, { offset: (y0 * INK_W + x0) * 4, bytesPerRow: INK_W * 4, rowsPerImage: INK_H }, [x1 - x0, y1 - y0, 1]);\n this.gen += 1;\n }\n\n /** The layer's targets at the books' screen `box` (K7a) — and a shadow map a book drawn — made on the first book drawn (K6a). */\n private fit(box: readonly [number, number, number, number], attach: { readonly w: number; readonly h: number }): void {\n const want = Math.min(Math.max(this.t.list.length, 1), MAX_SHADOWED);\n if (this.shadowLayers.length < want) {\n this.shadowTex.destroy();\n this.shadowTex = this.device.createTexture({ label: \"notebook/shadow maps\", size: [SHADOW_RES, SHADOW_RES, want], format: \"depth32float\", usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING });\n this.shadowLayers = Array.from({ length: want }, (_, i) => this.shadowTex.createView({ dimension: \"2d\", baseArrayLayer: i, arrayLayerCount: 1 }));\n this.forgetShadows();\n this.boundAssets = -1;\n this.rebind();\n }\n this.t.layer.fit(box, attach);\n }\n\n /** Was a book drawn within the last `ms`? (The kind lets the layer go once none was for a while.) */\n drawnWithin(ms: number): boolean { return performance.now() - this.drawnAt < ms; }\n /** When the layer was last drawn (`performance.now()`; -Infinity before the first) — the kind's registered wake lets it go LAYER_IDLE_MS after (K7a). */\n get lastDrawn(): number { return this.drawnAt; }\n\n /** Is the frame's layer made (its targets and shadow maps on the device)? */\n get layerMade(): boolean { return this.frameT.layer.made || this.shadowLayers.length > 0; }\n\n /** The pages' ink layers let go (the desk has no notebook — K6a): the placeholder again, made anew by the next page's ink. */\n releaseInk(): void {\n if (!this.inkReady) return;\n this.inkTex.destroy();\n this.inkTex = this.device.createTexture({ label: \"notebook/ink (none yet)\", size: [1, 1, 2], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });\n this.inkReady = false;\n this.rebind();\n }\n\n /**\n * Every mesh on the device given back — the frame's and the held copy's (K7a: the desk has none of this kind's objects left, and\n * no prepare will come to sweep the ones it no longer lists).\n */\n releaseMeshes(): void {\n for (const t of [this.frameT, this.copyT]) {\n if (t === null) continue;\n for (const b of t.buffers.values()) { b.vb.destroy(); b.ib.destroy(); }\n t.buffers.clear();\n }\n }\n\n /**\n * The frame's layer targets and the shadow maps let go (no book drawn for a while, or none on the desk): made again at the next\n * book drawn. The meshes stay (the books'); the held copy's targets are the hold's (`endHold`).\n */\n releaseLayer(): void {\n this.frameT.layer.release();\n if (this.shadowLayers.length > 0) {\n this.shadowTex.destroy();\n this.shadowTex = noShadows(this.device);\n this.shadowLayers = [];\n this.forgetShadows();\n this.boundAssets = -1;\n this.rebind();\n }\n }\n\n /** Every shadow map's content forgotten (its texture made again or let go): each is drawn afresh at its next book. */\n private forgetShadows(): void { for (const k of this.shadowKeys) k.fill(Number.NaN); }\n\n /** The shadow maps drawn and the ones kept (not drawn: their book, mesh and light stood) since the pass was made (K7a). */\n get shadows(): { readonly drawn: number; readonly kept: number } { return { drawn: this.shadowDraws, kept: this.shadowKept }; }\n /** The layers drawn and the ones laid again undrawn (nothing they are drawn from moved) since the pass was made (K7a). */\n get layerFrames(): { readonly drawn: number; readonly kept: number } { return { drawn: this.layerDraws, kept: this.layerKept }; }\n\n /** A book's mesh on the device — uploaded when its version moved, the buffers grown when too small. */\n private upload(d: NotebookDraw): BookBuffers {\n let b = this.t.buffers.get(d.id);\n const vbytes = d.mesh.vcount * VERTEX_BYTES;\n const ibytes = d.mesh.icount * 4;\n if (!b || b.vcap < vbytes || b.icap < ibytes) {\n b?.vb.destroy(); b?.ib.destroy();\n const vcap = Math.max(vbytes * 1.5, 65536) | 0;\n const icap = Math.max(ibytes * 1.5, 65536) | 0;\n b = {\n vb: this.device.createBuffer({ label: `notebook/${d.id} vertices`, size: (vcap + 3) & ~3, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST }),\n ib: this.device.createBuffer({ label: `notebook/${d.id} indices`, size: (icap + 3) & ~3, usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST }),\n vcap, icap, version: -1, icount: 0, seen: 0,\n };\n this.t.buffers.set(d.id, b);\n }\n if (b.version !== d.version) {\n this.device.queue.writeBuffer(b.vb, 0, d.mesh.vertices.buffer, d.mesh.vertices.byteOffset, vbytes);\n this.device.queue.writeBuffer(b.ib, 0, d.mesh.indices.buffer, d.mesh.indices.byteOffset, ibytes);\n b.version = d.version; b.icount = d.mesh.icount;\n this.t.meshGen += 1;\n }\n b.seen = this.t.frameNo;\n return b;\n }\n\n /**\n * This frame's books, the mat's block for the camera and the light, the pass's knobs, the\n * eye. Records every book's placement, lamp, shadow frame, pose and palette; uploads what\n * moved. Returns the count that will draw.\n */\n // biome-ignore lint/style/useDefaultParameterLast: the prototype's signature, moved verbatim — dropping the default would change what an explicit `undefined` means (design-015 D1)\n prepare(view: View & { readonly dpr: number }, fadeIn: FadeIn, cfg: MatConfig, frame: MatFrame | undefined, light: MatLight = DAY_LIGHT, eye: DeskEye, law: NotebookLaw, colours: { readonly cast: RGB; readonly select: RGB; readonly ruleInk: RGBA }, books: readonly NotebookDraw[]): number {\n this.rebind();\n this.t.frameNo += 1;\n // a book wholly off the screen (its box and its shadow) is not drawn, nor mapped\n const onScreen = (d: NotebookDraw): boolean => {\n const wb = worldBounds(d.rigid, d.mesh.min, d.mesh.max);\n const pad = 3 * (law.shadow.sigma0 + law.shadow.perUnit * Math.max(wb.hi[2], 1)) + 2.2 * Math.max(wb.hi[2], 1);\n let x0 = Number.POSITIVE_INFINITY;\n let y0 = Number.POSITIVE_INFINITY;\n let x1 = Number.NEGATIVE_INFINITY;\n let y1 = Number.NEGATIVE_INFINITY;\n for (let c = 0; c < 8; c++) { const [qx, qy] = project(eye, c & 1 ? wb.hi[0] + pad : wb.lo[0] - pad, c & 2 ? wb.hi[1] + pad : wb.lo[1] - pad, c & 4 ? wb.hi[2] : wb.lo[2]); x0 = Math.min(x0, qx); y0 = Math.min(y0, qy); x1 = Math.max(x1, qx); y1 = Math.max(y1, qy); }\n return x1 >= 0 && y1 >= 0 && x0 <= eye.vw && y0 <= eye.vh;\n };\n const shown = books.filter(onScreen);\n this.dropped = Math.max(0, shown.length - MAX_NOTEBOOKS);\n this.t.list = shown.slice(0, MAX_NOTEBOOKS) as NotebookDraw[];\n const n = this.t.list.length;\n // the near plane above the tallest thing a book reaches: a book risen toward the eye in the hand (D4b) climbs past the 900 the law\n // assumed at rest, and the plane follows it (the at-rest numbers are the same bytes: no book reaches past 900 lying down)\n let top = 0;\n for (const d of this.t.list) top = Math.max(top, worldBounds(d.rigid, d.mesh.min, d.mesh.max).hi[2]);\n let tris = 0;\n let shadowed = 0;\n let sx0 = Number.POSITIVE_INFINITY;\n let sy0 = Number.POSITIVE_INFINITY;\n let sx1 = Number.NEGATIVE_INFINITY;\n let sy1 = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < n; i++) {\n const d = this.t.list[i] as NotebookDraw;\n this.upload(d);\n tris += d.mesh.icount / 3;\n const F = d.frame;\n const L = d.lamp;\n const wb = worldBounds(d.rigid, d.mesh.min, d.mesh.max);\n const mapped = i < MAX_SHADOWED;\n if (mapped) shadowed += 1;\n const tallest = Math.max(wb.hi[2], 1);\n // the mat this book darkens: its box cast along the light onto the desk, grown by the widest penumbra and the ring\n const sigma = law.shadow.sigma0 + law.shadow.perUnit * tallest;\n const grow = 3 * sigma + (law.ring.offset + law.ring.width * 2 + 2) / Math.max(eye.zoom, 1e-6);\n let rx0 = wb.lo[0];\n let ry0 = wb.lo[1];\n let rx1 = wb.hi[0];\n let ry1 = wb.hi[1];\n for (let c = 0; c < 8; c++) {\n const px = c & 1 ? wb.hi[0] : wb.lo[0];\n const py = c & 2 ? wb.hi[1] : wb.lo[1];\n const pz = c & 4 ? wb.hi[2] : wb.lo[2];\n const gx = px - (L[0] * pz) / Math.max(L[2], 1e-3);\n const gy = py - (L[1] * pz) / Math.max(L[2], 1e-3);\n rx0 = Math.min(rx0, gx); ry0 = Math.min(ry0, gy); rx1 = Math.max(rx1, gx); ry1 = Math.max(ry1, gy);\n }\n rx0 -= grow; ry0 -= grow; rx1 += grow; ry1 += grow;\n const lf = lightFrame(L, wb.lo, wb.hi, SHADOW_RES, 6, [[rx0, ry0, 0], [rx1, ry0, 0], [rx0, ry1, 0], [rx1, ry1, 0]]);\n // its footprint on the screen (the layer's scissor)\n for (let c = 0; c < 8; c++) {\n const [qx, qy] = project(eye, c & 1 ? wb.hi[0] : wb.lo[0], c & 2 ? wb.hi[1] : wb.lo[1], c & 4 ? wb.hi[2] : wb.lo[2]);\n sx0 = Math.min(sx0, qx); sy0 = Math.min(sy0, qy); sx1 = Math.max(sx1, qx); sy1 = Math.max(sy1, qy);\n }\n for (const [qx, qy] of [[rx0, ry0], [rx1, ry1]] as const) { const [a, b] = project(eye, qx, qy, 0); sx0 = Math.min(sx0, a); sy0 = Math.min(sy0, b); sx1 = Math.max(sx1, a); sy1 = Math.max(sy1, b); }\n const sw = Math.abs(d.theta) > 0.95 * Math.PI ? 1 : 0;\n const lk = d.look;\n this.records.set({\n model: matrixOf(d.rigid), inv: matrixOf(inverseOf(d.rigid)), light: lf.matrix,\n lamp: [L[0], L[1], L[2], i], sh: [lf.texel, lf.depth, mapped ? 1 : 0, tallest],\n size: [F.W, F.H, F.b, F.spec.coverRadius], page: [F.Wo, F.Hp, F.spec.pageRadius, F.spec.band],\n open: [d.theta, d.gamma, F.sw, F.spec.square],\n look: [designCode(lk.design), rulingCode(d.ruling), d.ring, d.seed],\n foot: [sw, lk.paperCover ? 1 : 0, F.spec.sheet, d.selfShadow && mapped ? 1 : 0],\n recv: [rx0, ry0, rx1, ry1],\n col0: [...lk.cloth, 1], col1: [...lk.band, 1], col2: [...lk.accents[0], 1], col3: [...lk.accents[1], 1], col4: [...lk.accents[2], 1],\n col5: [...lk.endpaper, 1], col6: [...lk.paper, 1], col7: [...lk.ink, 1],\n inkPage: Array.from({ length: INK_TABLE }, (_, k) => (this.inkReady ? d.ink.pages[k] ?? -1 : -1)),\n inkLayer: Array.from({ length: INK_TABLE }, (_, k) => d.ink.layers[k] ?? 0),\n }, i);\n }\n if (n > 0) writeChanged(this.device.queue, this.recordBuf, this.records, this.recordsSent, n);\n // a book gone from the list gives its buffers back\n for (const [id, b] of this.t.buffers) if (b.seen !== this.t.frameNo) { b.vb.destroy(); b.ib.destroy(); this.t.buffers.delete(id); }\n this.t.screen = n > 0 ? { x0: sx0, y0: sy0, x1: sx1, y1: sy1 } : null;\n // the knobs, with the layer's box origin (K7a): a fragment's position is the box's, and what samples by it adds the origin back\n const box = this.boxOf(attachmentOf(view), view.dpr);\n this.knobs.set({ ...nbUniformValues(law, eyeValues(eye, Math.max(900, top + 200)), view.dpr, colours.cast, colours.select, colours.ruleInk), ring: [law.ring.offset, this.debug, box?.[0] ?? 0, box?.[1] ?? 0] });\n writeChanged(this.device.queue, this.knobBuf, this.knobs, this.knobsSent);\n this.t.stats = { books: n, triangles: tris, shadowed };\n return n;\n }\n\n get drawn(): NotebookStats { return this.t.stats; }\n\n /** The render target the next prepare, layer and composite are for (D7): the frame's, or the held desk copy's — made on first use. */\n use(target: RenderTarget): void {\n if (target === \"copy\" && this.copyT === null) this.copyT = nbTarget(new BoxTargets(this.device, \"notebook\", this.layoutComp, SAMPLES, this.mat.view));\n this.t = target === \"copy\" && this.copyT !== null ? this.copyT : this.frameT;\n }\n\n /** The hold is over: the desk copy's target gives its layer and meshes back (D7). */\n endHold(): void {\n if (this.copyT) dropTarget(this.copyT);\n this.copyT = null;\n this.t = this.frameT;\n }\n\n /** The books' screen box on an attachment of `size` device px, clamped to it — the layer's scissor and the composite's; null when none shows. */\n private boxOf(size: { readonly w: number; readonly h: number }, dpr: number): readonly [number, number, number, number] | null {\n if (this.t.list.length === 0 || !this.t.screen) return null;\n const W = Math.max(1, size.w);\n const H = Math.max(1, size.h);\n const x0 = Math.max(0, Math.floor(this.t.screen.x0 * dpr) - 2);\n const y0 = Math.max(0, Math.floor(this.t.screen.y0 * dpr) - 2);\n const x1 = Math.min(W, Math.ceil(this.t.screen.x1 * dpr) + 2);\n const y1 = Math.min(H, Math.ceil(this.t.screen.y1 * dpr) + 2);\n return x1 <= x0 || y1 <= y0 ? null : [x0, y0, x1, y1];\n }\n\n /** The books' screen box of the last `layer`, device px [x, y, w, h] — what the composite paints at most; null: no layer to lay. */\n get screenBox(): readonly [number, number, number, number] | null { return this.t.box; }\n\n /** Draw the prepared books onto `target` (the canvas, holding what the ground drew). Its own command buffer: the layer, then the composite. */\n render(target: GPUTextureView, size: { readonly w: number; readonly h: number }, dpr: number): void {\n if (!this.boxOf(size, dpr)) { this.t.box = null; return; }\n // the first frames are watched: a validation error names itself on the console instead of hiding behind the submit's\n const watch = this.t.frameNo < 4;\n if (watch) this.device.pushErrorScope(\"validation\");\n const enc = this.device.createCommandEncoder({ label: \"notebook\" });\n this.layer(enc, size, dpr);\n // 3. the composite, in a pass of its own over what the canvas holds\n if (!(this.debug & 16)) {\n const comp = enc.beginRenderPass({ label: \"notebook/composite\", colorAttachments: [{ view: target, loadOp: \"load\", storeOp: \"store\" }] });\n this.composite(comp);\n comp.end();\n }\n this.device.queue.submit([enc.finish()]);\n if (watch) void this.device.popErrorScope().then((e) => { if (e) console.error(`notebook pass: ${e.message}`); });\n }\n\n /**\n * Record this frame's books into their LAYER, into `encoder` — ahead of the pass the layer is laid in (the host's own, `render`;\n * or the desk's frame, the notebook a kind of its registry — kinds/notebook.ts): (1) each book's shadow map, (2) the 4× layer —\n * the books, then the mat under them — resolved. `size`: the attachment's device px. Returns whether there is a layer to lay\n * (its box: `screenBox`).\n */\n layer(encoder: GPUCommandEncoder, size: { readonly w: number; readonly h: number }, dpr: number): boolean {\n const at = this.boxOf(size, dpr);\n this.t.box = null;\n if (!at) return false;\n this.drawnAt = performance.now();\n const [x0, y0, x1, y1] = at;\n this.fit(at, size);\n // 0. the layer the targets hold laid again UNDRAWN when nothing it was drawn from moved since (K7a): the pass's resources, the\n // meshes, the silhouette, what it lists, the box — and by content this target's knobs and records and the slot's view block\n // (the camera, the clocks, the lamp); no shadow map is drawn for it either\n const sig = this.sig;\n const view = this.mat.viewBytes;\n sig[0] = this.gen; sig[1] = this.t.meshGen; sig[2] = view === undefined ? Number.NaN : (this.mat.silhouetteKey ?? Number.NaN);\n sig[3] = this.t.list.length; sig[4] = x0; sig[5] = y0; sig[6] = x1; sig[7] = y1;\n const read = this.read;\n read.length = 0;\n read.push(this.knobs.view(), this.records.view(this.t.list.length));\n if (view !== undefined) read.push(view);\n if (this.t.layer.holds(sig, read)) {\n this.layerKept += 1;\n this.t.box = [x0, y0, x1 - x0, y1 - y0];\n return true;\n }\n // 1. the shadow maps — each drawn only when its book, its mesh or its light moved since it was (K7a)\n const F = this.recordFloats;\n const stride = NbBook.size / 4;\n const mo = NbBook.slots.model.byte / 4;\n const lo = NbBook.slots.light.byte / 4;\n this.t.list.forEach((d, i) => {\n if (i >= MAX_SHADOWED || (this.debug & 8)) return;\n const b = this.t.buffers.get(d.id);\n if (!b) return;\n const key = this.shadowKeys[i] as Float32Array;\n const at = i * stride;\n let same = key[0] === d.id && key[1] === b.version;\n for (let k = 0; same && k < 16; k++) same = key[2 + k] === F[at + mo + k] && key[18 + k] === F[at + lo + k];\n if (same) { this.shadowKept += 1; return; }\n key[0] = d.id;\n key[1] = b.version;\n for (let k = 0; k < 16; k++) { key[2 + k] = F[at + mo + k] as number; key[18 + k] = F[at + lo + k] as number; }\n this.shadowDraws += 1;\n const p = encoder.beginRenderPass({ label: `notebook/shadow ${i}`, colorAttachments: [], depthStencilAttachment: { view: this.shadowLayers[i] as GPUTextureView, depthClearValue: 1, depthLoadOp: \"clear\", depthStoreOp: \"store\" } });\n p.setPipeline(this.shadowPipe);\n p.setBindGroup(0, this.shadowGroup);\n p.setVertexBuffer(0, b.vb);\n p.setIndexBuffer(b.ib, \"uint32\");\n p.drawIndexed(b.icount, 1, 0, 0, i);\n p.end();\n });\n // 2. the layer: the books, then the mat under them — into the targets at their screen box (K7a), the attachment's pixel grid\n this.layerDraws += 1;\n const pass = this.t.layer.begin(encoder, \"notebook/layer\", size, at);\n pass.setBindGroup(0, this.mainGroup);\n pass.setPipeline(this.bookPipe);\n this.t.list.forEach((d, i) => {\n const b = this.t.buffers.get(d.id);\n if (!b || (this.debug & 32)) return;\n pass.setVertexBuffer(0, b.vb);\n pass.setIndexBuffer(b.ib, \"uint32\");\n pass.drawIndexed(b.icount, 1, 0, 0, i);\n });\n pass.setPipeline(this.recvPipe);\n if (!(this.debug & 64)) for (let i = 0; i < this.t.list.length; i++) pass.draw(6, 1, 0, i);\n pass.end();\n this.t.layer.drew(sig, read);\n this.t.box = [x0, y0, x1 - x0, y1 - y0];\n return true;\n }\n\n /**\n * (3) Lay the last `layer` over what `pass` holds — premultiplied, one fullscreen triangle — scissored to `scissor` (the books'\n * box, or a part of it a host narrows it to). Nothing without a layer, or with the debug bit 16 (no composite).\n */\n composite(pass: GPURenderPassEncoder, scissor: readonly [number, number, number, number] | null = this.t.box): void {\n const group = this.t.layer.compGroup;\n if (!this.t.box || !scissor || !group || (this.debug & 16)) return;\n pass.setScissorRect(scissor[0], scissor[1], scissor[2], scissor[3]);\n pass.setPipeline(this.compPipe);\n pass.setBindGroup(0, group);\n pass.draw(3);\n }\n\n dispose(): void {\n dropTarget(this.frameT);\n if (this.copyT) dropTarget(this.copyT);\n this.shadowTex.destroy(); this.inkTex.destroy(); this.paperTex.destroy(); this.knobBuf.destroy(); this.recordBuf.destroy();\n void this.format;\n }\n}\n","// The HIT TEST — the pointer's ray into the notebook (NOTEBOOK.md §5). Pure. The ray runs from\n// the desk eye through the desk point under the pointer, is carried into the book's own\n// coordinates by its placement, and meets the same surfaces the mesh draws: the closed case,\n// or, open, each stack's top page (a height field over its resting curve) and the case's\n// margins. A page hit says where on the page — the arc length from the gutter and the height\n// down the page — which is what a turn needs (and a pen will).\n\nimport { type DeskEye, type Rigid, dirToLocal, toLocal } from \"@ice/desk/kit\";\nimport type { NotebookLaw } from \"./law\";\nimport { coverFrame, type Frame, type NotebookPose, relaxOf, restSheet, sampleRest, sheetSamples, swingOf } from \"./shape\";\n\nexport type NotebookHit =\n | { readonly part: \"case\"; readonly t: number }\n | { readonly part: \"page\"; readonly side: 0 | 1; readonly s: number; readonly y: number; readonly len: number; readonly t: number };\n\n/** The ray from the eye through a desk point, in the book's own coordinates. */\nexport function localRay(e: DeskEye, g: Rigid, dx: number, dy: number): { o: [number, number, number]; d: [number, number, number] } {\n return { o: toLocal(g, e.ex, e.ey, e.h), d: dirToLocal(g, dx - e.ex, dy - e.ey, -e.h) };\n}\n\n/** Where a ray meets a box, if it does (t along the ray). */\nfunction slab(o: readonly number[], d: readonly number[], lo: readonly number[], hi: readonly number[]): number | null {\n let t0 = Number.NEGATIVE_INFINITY;\n let t1 = Number.POSITIVE_INFINITY;\n for (let k = 0; k < 3; k++) {\n const ok = o[k] as number;\n const dk = d[k] as number;\n const a = lo[k] as number;\n const b = hi[k] as number;\n if (Math.abs(dk) < 1e-12) { if (ok < a || ok > b) return null; continue; }\n let ta = (a - ok) / dk;\n let tb = (b - ok) / dk;\n if (ta > tb) [ta, tb] = [tb, ta];\n t0 = Math.max(t0, ta); t1 = Math.min(t1, tb);\n if (t0 > t1) return null;\n }\n return t1 >= 0 ? Math.max(t0, 0) : null;\n}\n\n/**\n * A stack's top page as a height field: the curve's x and z tabulated along its arc length.\n * `hit` walks the ray down onto it (a few fixed-point steps: the curve is gentle and the ray\n * nearly vertical) and answers the arc length there.\n */\nfunction pageHit(F: Frame, k: number, gamma: number, law: NotebookLaw, o: readonly number[], d: readonly number[]): { s: number; y: number; len: number; t: number } | null {\n if (k <= 0) return null;\n const top = restSheet(F, F.b + (k - 0.5) * F.spec.sheet, gamma, law.gutter);\n const ss = sheetSamples(top.len, 48);\n const c = sampleRest(top, ss);\n const n = ss.length;\n const zAt = (x: number): { z: number; s: number } | null => {\n if (x < (c[0] as number) || x > (c[(n - 1) * 4] as number)) return null;\n let lo = 0;\n let hi = n - 1;\n while (hi - lo > 1) { const mid = (lo + hi) >> 1; if ((c[mid * 4] as number) <= x) lo = mid; else hi = mid; }\n const x0 = c[lo * 4] as number;\n const x1 = c[hi * 4] as number;\n const f = x1 > x0 ? (x - x0) / (x1 - x0) : 0;\n return { z: (c[lo * 4 + 1] as number) + ((c[hi * 4 + 1] as number) - (c[lo * 4 + 1] as number)) * f + F.spec.sheet * 0.5, s: (ss[lo] as number) + ((ss[hi] as number) - (ss[lo] as number)) * f };\n };\n let z = F.b + k * F.spec.sheet;\n let t = 0;\n let hit: { z: number; s: number } | null = null;\n for (let it = 0; it < 6; it++) {\n if (Math.abs(d[2] as number) < 1e-9) return null;\n t = (z - (o[2] as number)) / (d[2] as number);\n const x = (o[0] as number) + (d[0] as number) * t;\n hit = zAt(x);\n if (!hit) return null;\n if (Math.abs(hit.z - z) < 1e-3) break;\n z = hit.z;\n }\n if (!hit) return null;\n const y = (o[1] as number) + (d[1] as number) * t;\n if (Math.abs(y) > F.Hp / 2) return null;\n return { s: hit.s, y, len: top.len, t };\n}\n\n/**\n * The notebook under a desk point, and where. Closed (or mostly), the whole case is one hit;\n * open, a page on either side (the left one found in the right model, through the mirror the\n * cover's full swing is), else the case's margins. Null when the ray misses the book.\n */\nexport function pickNotebook(F: Frame, pose: NotebookPose, law: NotebookLaw, g: Rigid, e: DeskEye, dx: number, dy: number, bounds: { readonly min: readonly number[]; readonly max: readonly number[] }): NotebookHit | null {\n const { o, d } = localRay(e, g, dx, dy);\n const tBox = slab(o, d, bounds.min, bounds.max);\n if (tBox === null) return null;\n const sw = swingOf(pose.theta);\n if (sw < 0.9 * Math.PI) return { part: \"case\", t: tBox };\n const gamma = relaxOf(pose.theta);\n const R = pageHit(F, pose.right, gamma, law, o, d);\n // the left stack: the ray mirrored about the gutter into the right model (the cover lies flat, so the ride IS the mirror)\n const C = coverFrame(F, pose.theta);\n const mirrorX = 2 * F.xg;\n const oL = [mirrorX - (o[0] as number), o[1] as number, o[2] as number + (F.b - C.oz)];\n const dL = [-(d[0] as number), d[1] as number, d[2] as number];\n const L = pageHit(F, pose.left, gamma, law, oL, dL);\n const best = R && (!L || R.t <= L.t) ? { side: 0 as const, h: R } : L ? { side: 1 as const, h: L } : null;\n if (best) return { part: \"page\", side: best.side, s: best.h.s, y: best.h.y, len: best.h.len, t: best.h.t };\n return { part: \"case\", t: tBox };\n}\n\n/** The x a pointer's ray reaches at height z in the book's own coordinates (the right model's x for a drag). */\nexport function localXAt(e: DeskEye, g: Rigid, dx: number, dy: number, z: number): number {\n const { o, d } = localRay(e, g, dx, dy);\n if (Math.abs(d[2]) < 1e-9) return o[0];\n return o[0] + d[0] * ((z - o[2]) / d[2]);\n}\n","// Assemble the notebook pass's programs from the host's shader text — the browser's generated module, a Node host's files on\n// disk; byte-identical either way. The book is drawn by the kit's view block, the mat's light and the 3D kit (kit/wgsl.ts\n// `book`: the eye, the shadow, the materials), then the notebook's entry; its layer is laid by the kit's composite.\n\nimport type { ComposeOptions } from \"@ice/desk/engine\";\nimport { layerComposite, kitWgsl, type ShaderText } from \"@ice/desk/kit\";\n\n/** The notebook's own shader file (the kit's pieces come by name). */\nexport const NOTEBOOK_SHADER_FILES = { pass: \"notebook/notebook-pass.wgsl\" } as const;\n\nexport interface NotebookShaders {\n readonly program: ComposeOptions; // the kit's view · light · book + notebook-pass\n readonly composite: ComposeOptions; // the kit's layer composite\n}\n\nexport function notebookShaders(text: ShaderText): NotebookShaders {\n const t = text(NOTEBOOK_SHADER_FILES);\n return {\n program: kitWgsl([\"view\", \"light\", \"book\"], { entry: { label: \"notebook/notebook-pass.wgsl\", text: t.pass } }, text),\n composite: layerComposite(text),\n };\n}\n","// The NOTEBOOK (NOTEBOOK.md) as a kind (kind.ts): the real 3D book behind the registry's door — a\n// thin adapter, the pass and its WGSL as they were. Stratum `things`, registered `composite`: the\n// pass renders EVERY book into a layer of its own in `prepare` — each book's shadow map, then the 4×\n// layer (the books, then the mat under them), recorded into the frame's encoder after the mat's wind —\n// and its one run is the layer laid over the frame, after every other run of the stratum (the\n// prototype's \"books above everything\": its lab drew them in a command buffer of their own after the\n// ground's). The composite lays every book at once, so a thing laid ON a notebook still draws under it:\n// interleaving books among other things needs a layer per run of books (design-015 §4.2 — D-D4's\n// exception, named, D-D3r-b.2). The desk eye (eye.ts) is the slot's view's; the law and the ruling's\n// ink are the host's (a lab's panel edits the law; the ink is the product's colour — the theme gate).\n// ROOT ONLY (D-D18): a spawned slot's pass draws nothing (kinds/layer.ts).\n//\n// And its WORLD half (kinds/world.ts; D3w): `notebookKind` — an entity of the notebook's widget type becomes a\n// `NotebookDraw` exactly as the lab's `makeBook` → `resolveBooks` → `drawBooks` makes one: its motion from the\n// durable spread (`spread` sheets turned onto the left) and a still's FLUX pin (open, a sheet mid-turn, the\n// peek, the tilt — the kind's own state, never a Grab), its lift the builder's (held ← Grab: 30 units through\n// the desk eye, the hover's 3.5), its ring the selection's — never under a lifted or an open book —, its tilt\n// into the carry's motion (the rect's velocity, sprung), its mesh rebuilt only when its pose moves. Its hit is\n// `pickNotebook`: the eye's ray through the SAME desk eye the pass draws with (the geometry carries it), into\n// the case or a page — `content` either way (the parts, the turn zones and the pen, are D3t's). Its colours\n// are the product's (`theme()`: the covers, the page, the ruling's ink — set on the root pass by the kind's\n// local, the theme gate). A deleted book is gone at once (NOTEBOOK.md: instant) — its ghost draws nothing.\n//\n// IN HAND (D3t-b — NOTEBOOK.md §6–8 on D3t-a's seam): the book's sheets are a MOTION the kind keeps from frame to frame\n// while it is held (the cover stays the hand's spring, D4b): the spread the document says — or the one the hand asked for,\n// until its transaction lands — is where the sheets go, one sheet a frame (a run of turns fans), their springs stepped here;\n// the peek and a sheet in the hand are the hand's (objects/leaf.ts). Its hit answers PARTS in hand: a page's outer 30 % —\n// `turn`; the rest of a page that takes ink — `content`, the pen's; the case and the endpapers — `frame`. Its INK is a cache\n// of its strokes (data children `desk.stroke` with their `page`, board/data.ts): the pass's eight layers handed out LRU to the\n// pages in view (notebook/pages.ts), each page replayed from its strokes, the pen's live stroke drawn into its page a segment\n// at a time and adopted when it lands. Its held bar: ‹ › (the arrow keys — a count of turns the hand turns by), the four pens\n// (the note's, `1`–`4`: the tool in hand), undo (⌘Z) and redo (⇧⌘Z) — the document's history over its strokes.\n\nimport { defineComponent, type Entity, field, type HeldToolApi, type HeldToolDef } from \"@ice/core\";\nimport { BoardStroke, decodePoints, decodeTimes, inking, type StrokeRow, type MatPass, type MarkFrame, type DeskEye, eyeOf, type BuiltMesh, MeshWriter, lampDir, type Rigid, rigidOf, type ShaderText, settled, spring, HOLD, readingTarget, LayeredKind, LAYER_IDLE_MS } from \"@ice/desk/kit\";\nimport { type KindPass, type KindProgram, type SlotContext, MAT_COLORS, type Palette, type RGB, type RGBA, rgb, type ThemeName, type TokenRef, type KindHost, type KindLocal, numberProp, type ObjectContext, type ObjectHit, type ObjectKind, stringProp } from \"@ice/desk\";\nimport { NOTEBOOK, type NotebookLaw } from \"./law\";\nimport { type NotebookLook, type Ruling, RULINGS } from \"./layout\";\nimport { buildMesh } from \"./mesh\";\nimport { inkPoints, pageOfSide, pagesInView } from \"./ink\";\nimport { newMotion, type NotebookMotion, poseKey, poseOf, setOpen, stepLeaves, tiltToward, turnable, turnPage, withDesk } from \"./motion\";\nimport { type InkTable, type LiveStroke, PageInk, type PageStroke, pageStrokeKey } from \"./pages\";\nimport { type NotebookDraw, NotebookPass } from \"./pass\";\nimport { type NotebookHit, pickNotebook } from \"./pick\";\nimport { NOTEBOOK_SHADER_FILES, notebookShaders } from \"./shaders\";\nimport { coverFrame, type Frame, frameOf, type NotebookPose, relaxOf, specOf, swingOf } from \"./shape\";\nimport { shaderText } from \"../shaders\";\n\n/** The notebook's kind name — its key in the registry and in every slot's `objects`. */\nexport const NOTEBOOK_KIND = \"notebook\";\n\n/** No ink: what the knobs carry while no book draws (a host sets `ruleInk` before one does). */\nconst NO_INK: RGBA = [0, 0, 0, 0];\n\nexport class NotebookKind extends LayeredKind<NotebookDraw, NotebookPass> {\n /** The notebook's law — its eye, its light and shadow, its lift: the host's (a lab's panel edits it); `NOTEBOOK` until one says. */\n law: NotebookLaw = NOTEBOOK;\n /** The ruling's ink and its presence on the page — the PRODUCT's colour (the theme gate): a host sets it before a book draws. */\n ruleInk: RGBA | null = null;\n\n /** Root only (D-D18): a spawned slot's pass — a mini mat's inside, a flight's departed desk — holds nothing and draws nothing. */\n spawn(_mat: MatPass): NotebookKind { return new NotebookKind(null); }\n\n /**\n * A slot's own pass of this kind takes the ROOT's host-set state before it prepares (its law and the ruling's ink): a spawned pass draws nothing, but a\n * slot that made its own from the program — the tray's specimen (design-017 §8, K5a) — draws with the desk's.\n */\n tune(root: KindPass<unknown>): void { if (root instanceof NotebookKind && root !== this) { this.law = root.law; this.ruleInk = root.ruleInk; } }\n\n /** The pass's own `prepare`, as the prototype's lab called it: the slot's camera, grid, clocks and light, the desk eye over the slot's view, the law, the colours. */\n protected prepareOwn(pass: NotebookPass, s: SlotContext, records: readonly NotebookDraw[]): number {\n // the host's ink, else a record's own look's (made without the desk's local — a tray specimen, K5a): never none\n const rule = this.ruleInk ?? records.find((r) => r.rule !== undefined)?.rule ?? null;\n if (records.length > 0 && !rule) throw new Error(\"notebook: the ruling's ink is the host's (the theme gate) — set the kind's `ruleInk` before a book draws\");\n const v = s.view;\n const eye = eyeOf({ x: v.camX, y: v.camY, zoom: v.zoom }, { width: v.width, height: v.height }, this.law.eye);\n // a deleted book is gone at once (D3w: its ghost's record is marked, never drawn)\n const shown = records.some((r) => VANISHED.has(r)) ? records.filter((r) => !VANISHED.has(r)) : records;\n return pass.prepare(v, s.fadeIn, s.cfg, s.frame, s.light, eye, this.law, { cast: MAT_COLORS.cast, select: s.select, ruleInk: rule ?? NO_INK }, shown);\n }\n}\n\n/** The records of books being deleted: NOTEBOOK.md's delete is instant, so a ghost's record is kept out of the pass. */\nconst VANISHED = new WeakSet<NotebookDraw>();\n\n/** The notebook's program for a host's shader text: its pass made on the root's mat; its objects one composite run, last in `things`. */\nexport function notebookProgram(text: ShaderText): KindProgram<NotebookDraw> {\n return {\n name: NOTEBOOK_KIND,\n stratum: \"things\",\n composite: true,\n create: async (device, format, mat) => new NotebookKind(await NotebookPass.create(device, format, notebookShaders(text), mat)),\n };\n}\n\n// ---------------------------------------------------------------- the world half (D3w)\n\n/**\n * What the notebook's kind takes from the host's palette (NOTEBOOK.md's covers): the page, the ruling's ink and its\n * presence, and each cover by name — its cloth, band, three accents, endpaper, its design and whether it is paper. Its\n * pens' inks (D3t-b) are the note's — the palette's `pens` (kinds/paper.ts `PaperPalette`), by name.\n */\nexport interface NotebookPalette extends Palette {\n readonly notebooks?: {\n readonly paper: TokenRef;\n readonly ink: TokenRef;\n /** The ruling's presence on the page (the dots, the rules), 0 … 1. */\n readonly rule: number;\n readonly covers: Readonly<Record<string, { readonly cloth: TokenRef; readonly band: TokenRef; readonly a: TokenRef; readonly b: TokenRef; readonly c: TokenRef; readonly endpaper: TokenRef; readonly design: NotebookLook[\"design\"]; readonly paperCover: boolean }>>;\n };\n readonly pens?: Readonly<Record<string, TokenRef>>;\n}\n\n/** The notebook's look for a theme, parsed: each cover's `NotebookLook`, the ruling's ink with its presence; the pens' inks (sRGB) and each pen tool's swatch (D3t-b). */\nexport interface NotebookObjectLook {\n readonly covers: Readonly<Record<string, NotebookLook>>;\n readonly ruleInk: RGBA;\n readonly pens: Readonly<Record<string, RGB>>;\n readonly swatches: Readonly<Record<string, string>>;\n}\n\n/** A book's still, pinned on the kind's own state (a FLUX pin — D-D2a-world.5): open (or a swing, 0 … 1), a sheet mid-turn, the peek, the tilt. */\nexport interface BookPose {\n readonly open?: boolean | number;\n readonly turn?: { readonly dir: 1 | -1; readonly phi: number; readonly psi: number; readonly twist?: number };\n readonly peek?: number;\n readonly tilt?: readonly [number, number];\n}\n\n/** A book as the builder resolved it: what its record draws, and what its hit reads — the same eye the pass draws with. */\nexport interface NotebookGeometry {\n readonly frame: Frame;\n readonly pose: NotebookPose;\n readonly mesh: BuiltMesh;\n readonly version: number;\n readonly rigid: Rigid;\n readonly lamp: readonly [number, number, number];\n readonly theta: number;\n readonly ring: number;\n readonly eye: DeskEye;\n readonly fade: number;\n /** Where it lies: the case's centre on the mat and its turn (the placement's, before the lift and the tilt). */\n readonly cx: number;\n readonly cy: number;\n readonly angle: number;\n /** In hand (D3t-b): its hit answers parts — a turn, the pen's page, the case. */\n readonly held: boolean;\n /** Its pages can turn (open, the cover landed) — the turn parts exist only then. */\n readonly turnable: boolean;\n /** The law it was resolved under (the hit, the hand's pick). */\n readonly law: NotebookLaw;\n}\n\n/** The notebook's own state on one desk: each book's id, mesh and pinned pose, the carry's tilt; the ruling's ink on the root pass; in hand (D3t-b) its sheets' motion, the pen's stroke and the pages' ink. */\nexport interface Books extends KindLocal {\n /** When the kind is next live (K7a — `KindLocal.due`, declared: the six built-ins all say). */\n due(now: number): number;\n /** A still's pose on `e` (undefined unpins). */\n pin(e: Entity, pose: BookPose | undefined): void;\n /** The world half's: the book's pin and its tilt state. */\n state(e: Entity): BookState;\n /** The world half's: the mesh for a pose, rebuilt only when the pose moved. */\n meshFor(e: Entity, F: Frame, pose: NotebookPose, law: NotebookLaw): { readonly mesh: BuiltMesh; readonly version: number };\n /** The world half's: the ruling's ink on the root pass — the product's colour (the theme gate). */\n ink(rule: RGBA): void;\n /** The pages' ink on this desk — the pass's eight layers, a cache of the strokes (a witness's door: its replays, a page's raster). */\n readonly pages: PageInk;\n /** A book's strokes on a page as its raster draws them — the children's, in order, then the stroke the pen lifted until it lands. */\n strokesOn(e: Entity, page: number): readonly PageStroke[];\n /** The world half's: the ink table for a resolved book — its pages in view with ink, each on a layer, brought up to its strokes. */\n table(e: Entity, G: NotebookGeometry, look: NotebookObjectLook): InkTable;\n /** The pen (D3t-b): its stroke in hand on `e` — begun (its samples grow in place, laid a segment at a time) or dropped (null). */\n write(e: Entity, live: LiveStroke | null): void;\n /** The pen lifted its stroke, whose cell will read `key`: drawn to its end, then ADOPTED when its child lands (no replay). */\n lift(e: Entity, key: string): void;\n /** Its transaction was refused (a read-only document, the book gone): the page is its children's again. */\n refuse(e: Entity): void;\n /** The spread the hand asks for (a turn by hand, a click, a key), until its transaction lands; null — the document's again. */\n ask(e: Entity, spread: number | null): void;\n /** The hand moved the book's sheets (a sheet in the hand, the peek): the next frame builds. */\n stir(e: Entity): void;\n /** On a portrait phone, the page of the spread in view (D3t-b — page by page): 0 the right, 1 the left; sprung (the view glides to it). */\n face(e: Entity, side: 0 | 1): void;\n}\n\ninterface BookState {\n readonly id: number;\n pose: BookPose | undefined;\n /** The carry's tilt (radians about x and y), sprung into the rect's motion; where the rect was. */\n tiltX: number; tiltXV: number; tiltY: number; tiltYV: number;\n lastX: number; lastY: number;\n /** The cover IN HAND (D4b): its swing 0 shut … 1 open on the hand's spring, and its velocity. */\n coverT: number; coverV: number;\n writer: MeshWriter | null;\n mesh: BuiltMesh | null;\n key: string;\n version: number;\n /** IN HAND (D3t-b): the sheets' motion, kept from frame to frame (null on the desk and in a still). */\n motion: NotebookMotion | null;\n /** The spread the hand asked for, until the document says it (null: the document's). */\n pending: number | null;\n /** The pen's stroke in hand, and the one it lifted until its child lands (with the page's stroke count at the lift). */\n live: LiveStroke | null;\n adopt: { readonly page: number; readonly stroke: PageStroke; readonly at: number } | null;\n /** The book's strokes by page, as of the children's stamp — and each decoded once (by `pageStrokeKey`), kept while it is the book's. */\n byPage: Map<number, PageStroke[]>;\n decoded: Map<string, PageStroke>;\n stamp: number;\n /** The last frame in hand moved a sheet or the peek, or has turns to go: the next asks a frame too. */\n stirring: boolean;\n /** The phone's page in view (0 the right … 1 the left), sprung toward `faceT`. */\n face: number; faceV: number; faceT: 0 | 1;\n}\n\n/** A stroke's cell → its samples with their widths, once per stroke (`had` — the book's last regroup — is asked first; a replay reads them again). */\nfunction pageStrokeOf(row: StrokeRow, had: ReadonlyMap<string, PageStroke>, now: Map<string, PageStroke>): PageStroke {\n const ink = row.ink ?? \"fountain\";\n const points = row.points ?? \"\";\n const times = row.times ?? \"\";\n const speed = row.speed !== null && row.speed > 0 ? row.speed : 400;\n const key = pageStrokeKey(ink, points, times, speed);\n let st = now.get(key) ?? had.get(key);\n if (st === undefined) st = { key, ink, points: inkPoints(decodePoints(points), times !== \"\" ? decodeTimes(times) : null, speed) };\n now.set(key, st);\n return st;\n}\n\n/** The notebook's `local()`. */\nexport function createBooks(host: KindHost): Books {\n const books = new Map<Entity, BookState>();\n /** The root slot's pass (the layer's owner). */\n const rootPass = (): NotebookPass | undefined => { const k = host.pass(); return k instanceof NotebookKind ? (k.pass ?? undefined) : undefined; };\n /** What has LANDED on each object, counted (D7 — `KindLocal.landed`): the held desk copy is made again when a desk object's moves. */\n const landedOf = new Map<Entity, number>();\n const land = (e: Entity): void => { landedOf.set(e, (landedOf.get(e) ?? 0) + 1); };\n const pages = new PageInk(host.budget); // its page rasters under the desk's one budget (D6)\n let next = 1;\n let woke = false;\n let moving = false;\n const state = (e: Entity): BookState => {\n let st = books.get(e);\n if (st === undefined) {\n st = {\n id: next++, pose: undefined, tiltX: 0, tiltXV: 0, tiltY: 0, tiltYV: 0, lastX: Number.NaN, lastY: Number.NaN, coverT: 0, coverV: 0, writer: null, mesh: null, key: \"\", version: 0,\n motion: null, pending: null, live: null, adopt: null, byPage: new Map(), decoded: new Map(), stamp: -1, stirring: false, face: 0, faceV: 0, faceT: 0,\n };\n books.set(e, st);\n }\n return st;\n };\n /** A book's pen strokes by page, regrouped whenever its children's stamp turns over. */\n const byPage = (e: Entity, st: BookState): Map<number, PageStroke[]> => {\n const stamp = host.children?.stamp(e) ?? 0;\n if (stamp === st.stamp) return st.byPage;\n const m = new Map<number, PageStroke[]>();\n const decoded = new Map<string, PageStroke>();\n for (const row of host.children?.rows(e, BoardStroke) ?? []) {\n const page = row.page ?? 0;\n if (row.tool !== \"pen\" || page < 1) continue;\n let list = m.get(page);\n if (list === undefined) { list = []; m.set(page, list); }\n list.push(pageStrokeOf(row, st.decoded, decoded));\n }\n st.byPage = m;\n st.decoded = decoded;\n st.stamp = stamp;\n return m;\n };\n const strokesOn = (e: Entity, page: number): readonly PageStroke[] => {\n const st = state(e);\n const rows = byPage(e, st).get(page) ?? [];\n const a = st.adopt;\n if (a === null || a.page !== page) return rows;\n // the stroke the pen lifted: its child has landed once the page lists it past where the page stood at the lift\n if (rows.findIndex((r, i) => i >= a.at && r.key === a.stroke.key) >= 0) { st.adopt = null; return rows; }\n return [...rows, a.stroke];\n };\n return {\n pin(e, pose) { state(e).pose = pose; woke = true; },\n state,\n meshFor(e, F, pose, law) {\n const st = state(e);\n const key = `${poseKey(pose)}#${F.spec.sheets}`;\n if (st.mesh === null || key !== st.key) {\n st.writer ??= new MeshWriter();\n st.mesh = buildMesh(st.writer, F, pose, law);\n st.key = key;\n st.version += 1;\n }\n return { mesh: st.mesh, version: st.version };\n },\n ink(rule) {\n const k = host.pass();\n if (!(k instanceof NotebookKind)) return;\n const had = k.ruleInk;\n if (had === null || had[0] !== rule[0] || had[1] !== rule[1] || had[2] !== rule[2] || had[3] !== rule[3]) k.ruleInk = rule;\n },\n pages,\n strokesOn,\n table(e, G, look) {\n const st = state(e);\n byPage(e, st); // the strokes as of now, in view or not: the clock below compares the children's stamp with this one\n const inView = pagesInView(G.pose, swingOf(G.theta));\n const live = st.live;\n let t = NO_TABLE;\n if (inView.length > 0) {\n const k = host.pass();\n const up = k instanceof NotebookKind ? (k.pass ?? undefined) : undefined;\n const fallback: RGB = Object.values(look.pens)[0] ?? [look.ruleInk[0], look.ruleInk[1], look.ruleInk[2]];\n const replays = pages.replays;\n t = pages.table(st.id, inView, (p) => strokesOn(e, p), live, (ink) => look.pens[ink] ?? fallback, look, up, G.frame.Wo, G.frame.Hp);\n if (pages.replays !== replays) land(e);\n }\n // the lifted stroke drawn to its end (a page out of the table replays with it): from here the page lists it until its child lands\n if (live?.lifted === true) {\n st.adopt = { page: live.page, stroke: { key: live.key, ink: live.ink, points: live.points }, at: (byPage(e, st).get(live.page) ?? []).length };\n st.live = null;\n }\n return t;\n },\n write(e, live) {\n state(e).live = live; // dropped (null): the page replays from its strokes at the next table\n moving = true;\n },\n lift(e, key) {\n const st = state(e);\n if (st.live === null) return;\n st.live.lifted = true;\n st.live.key = key;\n moving = true;\n },\n refuse(e) {\n const st = books.get(e);\n if (st === undefined) return;\n st.live = null;\n st.adopt = null;\n moving = true;\n },\n ask(e, spread) { state(e).pending = spread; moving = true; },\n stir() { moving = true; },\n face(e, side) { state(e).faceT = side; moving = true; },\n landed: (e) => landedOf.get(e) ?? 0,\n // K7a: next live now while a book in hand moves or writes (its tick's own test) or a turn, a stroke, a face was asked; when the\n // layer is made, LAYER_IDLE_MS after it was last drawn (it is let go then — at rest too); never otherwise\n due(now) {\n if (woke || moving) return now;\n for (const [e, st] of books) if (st.motion !== null && (st.live !== null || st.pending !== null || st.stirring || (host.children?.stamp(e) ?? 0) !== st.stamp)) return now;\n const own = rootPass();\n return own?.layerMade === true ? own.lastDrawn + LAYER_IDLE_MS : Number.POSITIVE_INFINITY;\n },\n tick() {\n // the layer's targets and shadow maps (K6a, D-K6a.3): made at the first book drawn, let go once none was for LAYER_IDLE_MS\n const own = rootPass();\n if (own?.layerMade && !own.drawnWithin(LAYER_IDLE_MS)) own.releaseLayer();\n const w = woke || moving;\n woke = false;\n moving = false;\n // a book in hand keeps asking while it moves or writes — or while its strokes changed since its pages were last brought up to\n // them (an undo, a redo, a peer's stroke: its pages replay at the next record)\n for (const [e, st] of books) if (st.motion !== null && (st.live !== null || st.pending !== null || st.stirring || (host.children?.stamp(e) ?? 0) !== st.stamp)) return true;\n return w;\n },\n /** The budget's ask (D6): a page raster is kept while its page was in a table this frame. */\n keeps: (key) => pages.keeps(key),\n forget(e) {\n const st = books.get(e);\n if (st !== undefined) pages.forget(st.id);\n books.delete(e);\n if (books.size === 0) { rootPass()?.releaseLayer(); rootPass()?.releaseInk(); rootPass()?.releaseMeshes(); } // no notebook on the desk: its layer, shadow maps and page ink go (K6a)\n landedOf.delete(e);\n },\n dispose() { books.clear(); pages.dispose(); },\n };\n}\n\n/** No page in view with ink. */\nconst NO_TABLE: InkTable = { pages: [], layers: [] };\n\n/** A page of the law's book, open: its width out of the gutter and its height, page units — what a page's raster spans (`INK_W × INK_H`). */\nexport const NOTEBOOK_PAGE: { readonly len: number; readonly height: number } = (() => { const F = frameOf(specOf(NOTEBOOK)); return { len: F.Wo, height: F.Hp }; })();\n\n/** A book's DEFAULT turn on the mat when a host lays one: the lab's `makeBook` (never set down quite square). */\nexport const bookAngle = (seed: number): number => { const s = Math.sin(seed * 127.1 + 311.7) * 43758.5453; return (s - Math.floor(s) - 0.5) * 0.06; };\n\n/**\n * How far a book's drawing reaches past its closed case, world units: the open spread to its left (a cover and the\n * spine), the lift (held and opening) seen through the desk eye and cast along the lamp's capped slope, blurred.\n */\nexport function notebookReach(law: NotebookLaw = NOTEBOOK): number {\n const F = frameOf(specOf(law));\n const h = law.lift.held + law.lift.open + law.lift.hover;\n return F.W + F.sw + law.shadow.slopeMax * h + 3 * (law.shadow.sigma0 + law.shadow.perUnit * h) + F.W * (law.eye.min / (law.eye.min - h) - 1);\n}\n\n/**\n * A book's silhouette for the desk's marks (D4a — the brackets, a member's ticks, the tape): the footprint of its case on\n * the mat at its turn — the closed case W × H about the book's centre and, as the cover swings over, the cover's own\n * footprint beside it (open, the whole spread) — with the fore-edge's corner. The height's parallax aside, as the print's:\n * the marks go around where the book LIES. The oracle's marks read the same function (oracle/frame.mjs).\n */\nexport function bookFrame(F: Frame, theta: number, cx: number, cy: number, angle: number): MarkFrame {\n const c = coverFrame(F, theta);\n const x0 = Math.min(-F.W / 2, c.ox, c.ox + c.ux * F.W);\n const x1 = F.W / 2;\n const mid = (x0 + x1) / 2;\n return { cx: cx + mid * Math.cos(angle), cy: cy + mid * Math.sin(angle), hx: (x1 - x0) / 2, hy: F.H / 2, angle, r: F.spec.coverRadius };\n}\n\n/** The notebook's silhouette on a resolved book (`bookFrame` on its geometry). */\nexport const notebookFrame = (G: NotebookGeometry): MarkFrame => bookFrame(G.frame, G.theta, G.cx, G.cy, G.angle);\n\n/** The page (and where on it) under a desk point of a resolved book — the pick through the SAME eye the pass drew it with (the hand's). */\nexport const pageHitAt = (G: NotebookGeometry, wx: number, wy: number): NotebookHit | null => pickNotebook(G.frame, G.pose, G.law, G.rigid, G.eye, wx, wy, G.mesh);\n\n/** A page hit's share of the page that TURNS it (the outer `turnZone` of its length — NOTEBOOK.md §7). */\nexport const inTurnZone = (h: NotebookHit, law: NotebookLaw): boolean => h.part === \"page\" && h.s > (1 - law.turnZone) * h.len;\n\n/**\n * A held book's PART under a hit (D3t-b): a page's outer 30 % that has a sheet to turn — `turn`; the rest of a page that takes\n * ink — `content`, the pen's (a mode in hand makes a press there the tool's); the case, the endpapers — `frame`, the book itself\n * (two taps put it down — the notebook's case rule).\n */\nexport function partOf(G: NotebookGeometry, h: NotebookHit): ObjectHit {\n if (h.part !== \"page\" || !G.turnable) return \"frame\";\n const page = pageOfSide(G.pose, h.side);\n if (inTurnZone(h, G.law)) return page !== null ? \"turn\" : \"frame\";\n return page !== null ? \"content\" : \"frame\";\n}\n\nconst clamp = (x: number, a: number, b: number): number => Math.min(Math.max(x, a), b);\n/** The phone's glide from one page of the spread to the other (D3t-b): a hand moving the book under the eye. */\nconst FACE = { hz: 1.8, zeta: 0.9 } as const;\n/** One damped spring step (the motion's own: semi-implicit Euler). */\nconst springStep = (x: number, v0: number, to: number, hz: number, z: number, h: number): [number, number] => {\n const w = 2 * Math.PI * hz;\n const v = v0 + (w * w * (to - x) - 2 * z * w * v0) * h;\n return [x + v * h, v];\n};\n\n// ---------------------------------------------------------------- the tools in hand (design-015 §8; D3t-b)\n\n/** The pens a notebook is written with — the NOTE's (objects/note.ts `PENS`, STICKY.md §3): names; the inks are the host's. */\nexport const NOTEBOOK_PENS = [\"felt\", \"ball\", \"fountain\", \"red\"] as const;\n/** The pen in hand when a book is picked up (the note's own default). */\nexport const DEFAULT_PEN = \"fountain\";\n/** A pen's tool id in the held bar (\"pen:fountain\"). */\nexport const penToolId = (pen: string): string => `pen:${pen}`;\n/** The pen a tool id names, or undefined. */\nexport const penOfTool = (id: string): string | undefined => (id.startsWith(\"pen:\") ? id.slice(4) : undefined);\nconst PEN_LABEL: Readonly<Record<string, string>> = { felt: \"Felt pen\", ball: \"Ballpoint\", fountain: \"Fountain pen\", red: \"Red pen\" };\n\n/**\n * Runtime, on the notebook in hand (D3t-b): the pages the keys and the bar asked to turn — a running count, +1 a page on, −1 a\n * page back. The hand (objects/leaf.ts) turns by what the count moved since it last looked: a tool writes a fact, the hand\n * turns (a spread of turns — a sheet each frame — fans; on a portrait phone a step is ONE page). The user's, never the document's.\n */\nexport const PageTurns = defineComponent(\"desk.pageTurns\", { n: field(\"f64\", { default: 0 }) });\n\n/** Ask for a turn: the count moves by `dir` (a tool's op — a runtime write, as the tool in hand is). */\nexport function askTurn(api: Pick<HeldToolApi, \"world\" | \"entity\">, dir: 1 | -1): void {\n const { world, entity } = api;\n const cur = world.get(entity, PageTurns);\n if (cur === undefined) world.addComponent(entity, PageTurns, { n: dir });\n else world.edit(entity).set(PageTurns, { n: cur.n + dir });\n}\n\n/**\n * The notebook's tools in hand (*Marks on the Mat* v2's held bar, `heldBarHTML`): ‹ and › (← → and PageUp/PageDown) — a page\n * back, a page on; the four pens (`1`–`4`) — MODES, the tool in hand, the cursor a crosshair over a page (NOTEBOOK.md §7); undo\n * (⌘Z) and, on keys alone, redo (⇧⌘Z) — the DOCUMENT's history over the book's strokes (a stroke is one transaction), waiting\n * for a stroke in hand to land. A turn is never on the undo stack (D-D3t-b.2): ⌘Z takes back ink, never a page.\n */\nexport const NOTEBOOK_TOOLS: readonly HeldToolDef[] = [\n { id: \"turn:-1\", label: \"Previous page\", kind: \"action\", keys: [\"ArrowLeft\", \"PageUp\"], hint: \"←\", glyph: \"chevron-left\", run: (api) => { askTurn(api, -1); } },\n { id: \"turn:1\", label: \"Next page\", kind: \"action\", keys: [\"ArrowRight\", \"PageDown\"], hint: \"→\", glyph: \"chevron\", run: (api) => { askTurn(api, 1); } },\n ...NOTEBOOK_PENS.map((pen, i): HeldToolDef => ({ id: penToolId(pen), label: PEN_LABEL[pen] ?? pen, kind: \"mode\", keys: [String(i + 1)], hint: String(i + 1), glyph: \"pen\", cursor: \"crosshair\" })),\n { id: \"undo\", label: \"Undo\", kind: \"action\", keys: [\"mod+z\"], hint: \"⌘Z\", glyph: \"undo\", run: (api) => { if (!inking(api.world)) api.undo(); } },\n { id: \"redo\", label: \"Redo\", kind: \"action\", keys: [\"mod+shift+z\", \"mod+y\"], hint: \"⇧⌘Z\", glyph: \"redo\", bar: false, run: (api) => { if (!inking(api.world)) api.redo(); } },\n];\n\nexport interface NotebookKindOptions {\n readonly text?: ShaderText;\n /** The notebook's numbers (notebook/law.ts `NOTEBOOK`) — the engine's unless a host tweaks them. */\n readonly law?: NotebookLaw;\n}\n\n/** The notebook's kind, whole (kinds/world.ts `ObjectKind`): the program, and the world half on the lab's own book. */\nexport function notebookKind(opts: NotebookKindOptions = {}): ObjectKind<NotebookGeometry, NotebookDraw, NotebookObjectLook> {\n const law = opts.law ?? NOTEBOOK;\n const program = notebookProgram(opts.text ?? shaderText);\n const F = frameOf(specOf(law, { sheets: law.block.sheets }));\n const sheets = F.spec.sheets;\n return {\n ...program,\n reach: notebookReach(law),\n local: (host: KindHost): Books => createBooks(host),\n resolve(ctx: ObjectContext): NotebookGeometry {\n const books = ctx.local as Books | undefined;\n const st = books?.state(ctx.entity);\n const pin = st?.pose;\n const left = clamp(Math.round(numberProp(ctx.props, \"spread\", 0)), 0, sheets);\n // IN HAND (design-015 §8, D4b): the cover swings toward its target on the hand's spring (a palm's — 1.4 Hz, ζ .78), snapped for\n // a still; the swing is the kind's `openness`, which the builder reads to time the flight home. On the desk the cover is shut.\n const held = ctx.held;\n let cover: number | undefined;\n if (st !== undefined) {\n if (held === undefined) { st.coverT = 0; st.coverV = 0; }\n else {\n const target = held.open ? 1 : 0;\n if (held.snap) { st.coverT = target; st.coverV = 0; }\n else {\n [st.coverT, st.coverV] = spring(st.coverT, st.coverV, target, HOLD.cover.hz, HOLD.cover.zeta, ctx.dt);\n if (settled(st.coverT, st.coverV, target, 1e-3)) { st.coverT = target; st.coverV = 0; }\n }\n cover = st.coverT;\n }\n }\n let m: NotebookMotion;\n if (st !== undefined && held !== undefined && pin === undefined) {\n // IN HAND, live (D3t-b): the sheets are a motion kept from frame to frame — the cover the hand's, the sheets their own springs,\n // heading for the spread the hand asked for (until its transaction lands) or the document's, one sheet a frame\n m = st.motion ?? newMotion(sheets, left, false);\n st.motion = m;\n const c = cover ?? 0;\n setOpen(m, c >= 0.5); // closing lands every sheet in the air on the side it was heading\n m.theta = c * Math.PI;\n m.fluttered = true;\n if (st.pending !== null && st.pending === left) st.pending = null;\n const want = clamp(st.pending ?? left, 0, sheets);\n let turned = 0;\n for (const q of m.sheets) if (q.side === 1) turned += 1;\n if (turned !== want && turnable(m) && !m.sheets.some((q) => q.held)) turnPage(m, turned < want ? 1 : -1, law);\n st.stirring = stepLeaves(m, ctx.dt, law) || turned !== want;\n // a portrait phone reads the spread a page at a time: the view glides to the page the hand turned to (the pose's `page`)\n const single = readingTarget({ cx: 0, cy: 0, w: ctx.rect.w * 2, h: ctx.rect.h }, { width: ctx.view.width, height: ctx.view.height }, true).single;\n if (!single) st.faceT = 0;\n if (held.snap || !single) { st.face = st.faceT; st.faceV = 0; }\n else {\n [st.face, st.faceV] = spring(st.face, st.faceV, st.faceT, FACE.hz, FACE.zeta, ctx.dt);\n if (settled(st.face, st.faceV, st.faceT, 1e-3)) { st.face = st.faceT; st.faceV = 0; }\n else st.stirring = true;\n }\n } else {\n if (st !== undefined) { st.motion = null; st.stirring = false; if (held === undefined) { st.face = 0; st.faceV = 0; st.faceT = 0; } }\n const open = cover !== undefined ? cover : pin?.open;\n m = newMotion(sheets, left, open === true || (typeof open === \"number\" && open >= 0.5));\n if (typeof open === \"number\") { m.theta = open * Math.PI; m.fluttered = true; }\n if (pin?.turn) {\n const t = pin.turn;\n const i = t.dir === 1 ? m.sheets.findIndex((q) => q.side === 0) : m.sheets.map((q) => q.side).lastIndexOf(1);\n const q = m.sheets[i];\n if (q) { q.air = true; q.side = t.dir === 1 ? 1 : 0; q.phi = t.phi; q.psi = t.psi; q.tw = t.twist ?? 0; }\n }\n if (pin?.peek !== undefined) { m.peek = pin.peek; m.peekOn = pin.peek > 0; }\n }\n m.lift = ctx.flux.lift;\n m.held = ctx.flux.lift > 0;\n m.hover = m.opened ? 0 : ctx.flux.hover;\n // the tilt: a still's pin, else into the carry's motion (the rect's velocity, CSS px/s) while it is lifted, sprung\n if (pin?.tilt) { m.tiltX = pin.tilt[0]; m.tiltY = pin.tilt[1]; }\n else if (st !== undefined) {\n const dt = Math.min(Math.max(ctx.dt, 0), 0.05);\n const moved = !Number.isNaN(st.lastX) && dt > 0;\n const vx = moved ? ((ctx.rect.cx - st.lastX) / dt) * ctx.view.zoom : 0;\n const vy = moved ? ((ctx.rect.cy - st.lastY) / dt) * ctx.view.zoom : 0;\n st.lastX = ctx.rect.cx;\n st.lastY = ctx.rect.cy;\n tiltToward(m, vx, vy, law);\n const tx = m.held ? m.tiltTX : 0;\n const ty = m.held ? m.tiltTY : 0;\n for (let k = 0; k < 8; k++) {\n [st.tiltX, st.tiltXV] = springStep(st.tiltX, st.tiltXV, tx, law.springs.tilt[0], law.springs.tilt[1], dt / 8);\n [st.tiltY, st.tiltYV] = springStep(st.tiltY, st.tiltYV, ty, law.springs.tilt[0], law.springs.tilt[1], dt / 8);\n }\n if (Math.abs(st.tiltX - tx) + Math.abs(st.tiltY - ty) < 1e-4 && Math.abs(st.tiltXV) + Math.abs(st.tiltYV) < 1e-3) { st.tiltX = tx; st.tiltY = ty; st.tiltXV = st.tiltYV = 0; }\n m.tiltX = st.tiltX;\n m.tiltY = st.tiltY;\n }\n // the ring: a selected book lying closed on the mat — never under a lifted or an open one\n m.ring = m.opened ? 0 : ctx.flux.ring * (1 - ctx.flux.lift);\n const angle = numberProp(ctx.props, \"angle\", 0);\n const swing = Math.min(Math.max(swingOf(m.theta), 0), Math.PI);\n // biome-ignore lint/style/useExponentiationOperator: the lab's arithmetic (lab/notebook.ts `placementOf`), verbatim — it feeds a record\n const opening = law.lift.open * Math.pow(Math.sin(swing), 0.85);\n const v = ctx.view;\n const eye = eyeOf({ x: v.camX, y: v.camY, zoom: v.zoom }, { width: v.width, height: v.height }, law.eye);\n // in hand the book RISES toward the desk eye (the pose is the eye's, D4b): a point z up reads H/(H − z) times its size, so\n // z = H·(1 − 1/grow) is the reading size — the perspective of a book held close, not a zoomed camera's\n const rise = held !== undefined && held.grow > 1 ? eye.h * (1 - 1 / held.grow) : 0;\n const place = { cx: ctx.rect.cx, cy: ctx.rect.cy, angle, lift: m.lift * law.lift.held + m.hover * law.lift.hover + opening + rise, tiltX: m.tiltX, tiltY: m.tiltY, zc: F.b + F.T / 2 };\n const pose = withDesk(poseOf(m, law), place.lift);\n const built = books?.meshFor(ctx.entity, F, pose, law) ?? { mesh: buildMesh(new MeshWriter(), F, pose, law), version: 1 };\n return {\n frame: F, pose, mesh: built.mesh, version: built.version, rigid: rigidOf(place), lamp: lampDir(ctx.lamp, ctx.rect.cx, ctx.rect.cy, law.shadow.slopeMax),\n theta: m.theta, ring: m.ring, eye, fade: ctx.flux.fade,\n cx: ctx.rect.cx, cy: ctx.rect.cy, angle,\n held: held !== undefined, turnable: turnable(m), law,\n };\n },\n record(G: NotebookGeometry, ctx: ObjectContext): NotebookDraw {\n const look = ctx.look as NotebookObjectLook | undefined;\n const covers = look?.covers ?? {};\n const cover = covers[stringProp(ctx.props, \"cover\", \"\")] ?? Object.values(covers)[0];\n if (look === undefined || cover === undefined) throw new Error(\"desk/notebook: the covers are the host's — the palette names no `notebooks` (kinds/notebook.ts `NotebookPalette`)\");\n const books = ctx.local as Books | undefined;\n books?.ink(look.ruleInk);\n const rulingName = stringProp(ctx.props, \"ruling\", \"dots\") as Ruling;\n const sw = swingOf(G.theta);\n const draw: NotebookDraw = {\n id: books?.state(ctx.entity).id ?? 1, mesh: G.mesh, version: G.version, frame: G.frame, rigid: G.rigid, lamp: G.lamp,\n theta: G.theta, gamma: relaxOf(G.theta), look: cover, ruling: RULINGS.includes(rulingName) ? rulingName : \"dots\", seed: numberProp(ctx.props, \"seed\", 0) % 97, ring: G.ring,\n // the pages in view with ink, each on a layer brought up to its strokes (D3t-b) — a ghost draws nothing, so asks for none\n selfShadow: G.pose.airs.length > 0 || (sw > 0.02 && sw < Math.PI - 0.02), ink: books !== undefined && G.fade >= 1 ? books.table(ctx.entity, G, look) : NO_TABLE,\n // without the desk's local nobody sets the pass's ink: the record carries its look's\n ...(books === undefined ? { rule: look.ruleInk } : {}),\n };\n if (G.fade < 1) VANISHED.add(draw);\n return draw;\n },\n hit(G: NotebookGeometry, wx: number, wy: number): ObjectHit | null {\n if (G.fade < 1) return null;\n const h = pageHitAt(G, wx, wy);\n if (h === null) return null;\n // on the desk the book is itself (select, carry); in hand its parts (D3t-b)\n return G.held ? partOf(G, h) : \"content\";\n },\n frame: notebookFrame,\n // THE OPENING (design-015 §8, D4b): the spread — twice the case's width, left of the spine — comes to the hand under the desk\n // eye; the cover's swing is its motion; D3t-b: its tools live — ‹ ›, the four pens (the fountain pen in hand at the pickup),\n // undo and redo — each pen's slot the swatch of its ink\n open: {\n extent: (c) => ({ cx: c.rect.cx - c.rect.w / 2, cy: c.rect.cy, w: c.rect.w * 2, h: c.rect.h }),\n pose: \"eye\",\n spread: true,\n openness: (c) => (c.local as Books | undefined)?.state(c.entity).coverT ?? 0,\n page: (c) => (c.local as Books | undefined)?.state(c.entity).face ?? 0,\n tools: NOTEBOOK_TOOLS,\n tool: () => penToolId(DEFAULT_PEN),\n swatches: (look) => (look as NotebookObjectLook).swatches,\n },\n theme(palette: Palette, _name: ThemeName): NotebookObjectLook {\n const n = (palette as NotebookPalette).notebooks;\n const penRefs = (palette as NotebookPalette).pens ?? {};\n const pens: Record<string, RGB> = Object.fromEntries(Object.entries(penRefs).map(([name, t]) => [name, rgb(t.css)]));\n const swatches: Record<string, string> = Object.fromEntries(Object.entries(penRefs).map(([name, t]) => [penToolId(name), t.css]));\n if (n === undefined) return { covers: {}, ruleInk: [0, 0, 0, 0], pens, swatches };\n const paper: RGB = rgb(n.paper.css);\n const ink: RGB = rgb(n.ink.css);\n const covers = Object.fromEntries(Object.entries(n.covers).map(([name, c]) => [name, {\n cloth: rgb(c.cloth.css), band: rgb(c.band.css), accents: [rgb(c.a.css), rgb(c.b.css), rgb(c.c.css)] as const, endpaper: rgb(c.endpaper.css), paper, ink, design: c.design, paperCover: c.paperCover,\n } satisfies NotebookLook]));\n return { covers, ruleInk: [ink[0], ink[1], ink[2], n.rule], pens, swatches };\n },\n };\n}\n","// THE NOTEBOOK IN HAND — its pen and its leaves (NOTEBOOK.md §6–8; design-015 §8; D3t-b): the hand half of the notebook kind,\n// the whiteboard's pen's sibling (objects/pen.ts). It READS the world — the book in hand (core's `Held`), the pen in hand\n// (`HeldTool`), the local pointer through the pose the renderer drew (`HeldPointer`, mapped to the desk by the builder's\n// `heldToWorld`, then into the book through the SAME desk eye the pass drew it with — `pageHitAt`), the press (`HeldPress`:\n// `tool` on a page's writing, `part` on a turn) — and drives the notebook kind's own state (kinds/notebook.ts `Books`): the\n// stroke laid LIVE into its page's raster. It WRITES exactly one kind of thing, ONE transaction each, deferred out of the frame\n// (a reflector never writes — D-D2c.5): at the lift, the stroke — one `desk.stroke` child of the book on its `page`, its path in\n// page units with its samples' times (board/data.ts), which the page's raster ADOPTS rather than replays.\n//\n// A press on a page's writing with a pen in hand begins a stroke at that frame's point; every later frame the pointer is over\n// the SAME page is a sample (a frame it rested is a sample too: the law keeps its width); the frame the press is gone is the\n// lift, at the pointer's last point on the page. The samples reach the raster as f32s — the cell's own — so what the pen laid\n// live is what a replay lays. Put down while a stroke is laid, the stroke lands first.\n//\n// THE LEAVES (NOTEBOOK.md §6–7): a press on a page's outer 30 % (the kind's `turn` part — core's `HeldPress` \"part\") that\n// travels 5 px across takes hold of the top sheet on that side and it follows the hand over the gutter (motion.ts `grabSheet`\n// · `dragSheet` — the pinch's angle is the grip); let go, it goes past the vertical or flung, else it falls back\n// (`releaseSheet`). A press there that never travels is a CLICK: a page on (the right) or back (the left). The keys and the\n// bar's ‹ › count their turns on the book (`PageTurns`); the hand turns by what the count moved. Every completed turn moves the\n// durable `spread` in ONE transaction out of the frame, OFF the undo stack (D-D3t-b.2: a turn is the reader's place, ⌘Z takes\n// back ink) — until it lands the kind heads for it (`Books.ask`), one sheet a frame, so a run of turns fans. Over the right\n// page's fore-edge corner, with nothing pressed, the corner peeks. On a portrait phone (one page of the spread in view, D4b's\n// `spread`) a step is ONE page: from the right page on, the sheet turns and the view follows it to its verso on the left; from\n// the left page on, the view goes to the right page; back, the other way round (`Books.face`).\n\nimport { type Component, defineQuery, type Entity, guardedTransaction, heldEntity, HeldPointer, HeldPress, HeldTool, LocalPointer, Pointer, PointerButtons, PointerScreen, setWidgetProps, Viewport, type World } from \"@ice/core\";\nimport { addStroke, encodePoints, encodeTimes, readingTarget } from \"@ice/desk/kit\";\nimport { type Books, DEFAULT_PEN, type NotebookGeometry, PageTurns, pageHitAt, partOf, penOfTool } from \"./kind\";\nimport { inkPoints, pageOfSide } from \"./ink\";\nimport { counts, dragSheet, grabSheet, releaseSheet } from \"./motion\";\nimport { type LiveStroke, pageStrokeKey } from \"./pages\";\nimport { type NotebookHit, localXAt } from \"./pick\";\nimport { type TypingDocs, writable } from \"@ice/desk\";\n\n/** The notebook's props cell (`desk.notebook:props` — its `spread` the durable fact a completed turn moves). */\n\nexport interface NotebookHandOptions {\n readonly world: World;\n /** The document a stroke commits into — the facade's `engine.docs`. */\n readonly docs: TypingDocs;\n /** The notebook's props cell (its `spread`) — the object hands its own (D-D7-A.3); absent, the spread reads 0. */\n readonly props?: Component | undefined;\n /** The notebook kind's state on this desk (undefined before it is made). */\n readonly books: () => Books | undefined;\n /** Is this entity a notebook (the desk's builder knows each entity's kind). */\n readonly isBook: (e: Entity) => boolean;\n /** A point of the held object's own frame as a desk point, through the pose the last frame drew (the builder's). */\n readonly heldToWorld: (e: Entity, x: number, y: number) => readonly [number, number] | undefined;\n /** The geometry the book was drawn with in hand (the builder's). */\n readonly geometryOf: (e: Entity) => unknown;\n /** Where a transaction runs: out of the frame (a microtask) unless a test says. */\n readonly defer?: (fn: () => void) => void;\n}\n\nexport interface NotebookHand {\n /** Once a frame, before the kinds' clocks: the hand onto the book in hand — its stroke laid, lifted, committed. */\n follow(now: number): void;\n /** Nothing to follow (D7 #14): no book in hand, no stroke laid, no turn in progress. */\n idle(): boolean;\n /** The stroke in hand: its book, its page and how many samples so far; null when none. */\n live(): { readonly book: Entity; readonly page: number; readonly samples: number } | null;\n /** Strokes committed since creation (a rig's witness). */\n commits(): number;\n /** The turn in the hand: its book, the side it was taken from, the sheet held (null until the hand has travelled); null when none. */\n turning(): { readonly book: Entity; readonly side: 0 | 1; readonly sheet: number | null } | null;\n /** Spreads written since creation — each completed turn one transaction (a rig's witness). */\n turns(): number;\n}\n\ninterface Stroke {\n readonly book: Entity;\n readonly pointer: Entity;\n readonly side: 0 | 1;\n readonly page: number;\n readonly t0: number;\n readonly points: [number, number][];\n readonly times: number[];\n readonly live: LiveStroke;\n}\n\ninterface Turn {\n readonly book: Entity;\n readonly pointer: Entity;\n readonly side: 0 | 1;\n /** Where the page was pinched: its arc length from the gutter, its height from the middle, the page's length. */\n readonly s: number;\n readonly y: number;\n readonly len: number;\n /** The screen x the press began at; the sheet held once it travelled; the last move's clock. */\n readonly x0: number;\n sheet: number | null;\n lt: number;\n moved: boolean;\n}\n\nconst pointersQ = defineQuery([Pointer, LocalPointer, PointerScreen]);\nconst f32 = Math.fround;\nconst clamp = (x: number, a: number, b: number): number => Math.min(Math.max(x, a), b);\n/** How far a pinch travels across before the sheet is taken (the prototype's 5 CSS px). */\nconst TAKE_PX = 5;\n\n/** The corner of the right page a hit is over — the tail's (+1) or the head's (−1) — or 0 (NOTEBOOK.md §6: the peek). */\nfunction cornerOf(G: NotebookGeometry, h: NotebookHit): 1 | -1 | 0 {\n if (h.part !== \"page\" || h.side !== 0) return 0;\n const z = G.law.peek.zone;\n if (h.s < h.len - z) return 0;\n const edge = G.frame.Hp / 2 - z;\n return h.y > edge ? 1 : h.y < -edge ? -1 : 0;\n}\n\nexport function createNotebookHand(opts: NotebookHandOptions): NotebookHand {\n const { world, docs } = opts;\n const defer = opts.defer ?? ((fn: () => void) => queueMicrotask(fn));\n let stroke: Stroke | null = null;\n let commits = 0;\n let turn: Turn | null = null;\n let turns = 0;\n /** The book last in hand and the turn count it had when it came into the hand (the keys' and the bar's, `PageTurns`). */\n let inHand: { readonly book: Entity; seen: number } | null = null;\n\n /** The spread the book is at or heading for: the one the hand asked (until it lands), else the document's. */\n const spreadOf = (books: Books, book: Entity): number => {\n const asked = books.state(book).pending;\n if (asked !== null) return asked;\n const v = opts.props === undefined ? undefined : (world.get(book, opts.props as never) as { spread?: number } | undefined)?.spread;\n return typeof v === \"number\" && Number.isFinite(v) ? Math.round(v) : 0;\n };\n /** Move the durable spread to `to` — ONE transaction out of the frame, off the undo stack; the kind heads for it meanwhile. */\n const write = (books: Books, book: Entity, to: number): void => {\n books.ask(book, to);\n defer(() => {\n const session = writable(docs);\n let ok = false;\n if (session !== undefined && world.isAlive(book)) {\n try { setWidgetProps(session.store, world, book, { spread: to }, { undoable: false }); ok = true; } catch { ok = false; }\n }\n if (ok) turns += 1;\n // landed (the document says it now) or refused (the book goes back to the document's): the kind heads for the document's\n if (books.state(book).pending === to) books.ask(book, null);\n });\n };\n /** One page on the phone, a sheet on a desk: `d` steps of the reader, from where the book is heading. */\n const step = (books: Books, book: Entity, G: NotebookGeometry, d: number, single: boolean): void => {\n const sheets = G.frame.spec.sheets;\n let at = spreadOf(books, book);\n if (!single) {\n const to = clamp(at + d, 0, sheets);\n if (to !== at) write(books, book, to);\n return;\n }\n // a portrait phone: page by page — the right page on turns its sheet and the view follows it left; the left page on, the view goes right\n let face = books.state(book).faceT;\n for (let k = 0; k < Math.abs(d); k++) {\n if (d > 0) {\n if (face === 0 && at < sheets) { at += 1; face = 1; }\n else if (face === 1 && at < sheets) face = 0;\n } else if (face === 1 && at > 0) { at -= 1; face = 0; }\n else if (face === 0 && at > 0) face = 1;\n }\n books.face(book, face);\n if (at !== spreadOf(books, book)) write(books, book, at);\n };\n\n /** The page point under a desk point — on `side`'s page of a resolved book, as the cell stores it (page units, f32); null off it. */\n const onPage = (G: NotebookGeometry, at: readonly [number, number], s: Stroke | null): { side: 0 | 1; page: number; s: number; y: number } | null => {\n const h = pageHitAt(G, at[0], at[1]);\n if (h === null || h.part !== \"page\") return null;\n const page = pageOfSide(G.pose, h.side);\n if (page === null || (s !== null && (s.side !== h.side || s.page !== page))) return null;\n return { side: h.side, page, s: f32(h.s), y: f32(h.y + G.frame.Hp / 2) };\n };\n\n /** A sample: its point and time, and the live stroke's next point with its width (the law is causal: the earlier ones stand). */\n const sample = (s: Stroke, x: number, y: number, t: number): void => {\n s.points.push([x, y]);\n s.times.push(t);\n const all = inkPoints(s.points, s.times, 400);\n s.live.points.push(all[all.length - 1] as (typeof all)[number]);\n };\n\n /** The lift: the last sample, the stroke laid to its end, its ONE transaction out of the frame. */\n const lift = (s: Stroke, at: readonly [number, number] | undefined, now: number): void => {\n const books = opts.books();\n const G = opts.geometryOf(s.book) as NotebookGeometry | undefined;\n const q = at !== undefined && G !== undefined ? onPage(G, at, s) : null;\n if (q !== null) sample(s, q.s, q.y, f32(now - s.t0));\n // its identity as its cell will state it: the pen, the samples' times and the path (a live stroke is always timed)\n const key = pageStrokeKey(s.live.ink, encodePoints(s.points), encodeTimes(s.times), 400);\n books?.lift(s.book, key);\n const spec = { tool: \"pen\" as const, ink: s.live.ink, page: s.page, points: s.points, times: s.times };\n defer(() => {\n const session = writable(docs);\n let ok = false;\n if (session !== undefined && world.isAlive(s.book)) {\n try { guardedTransaction(session.store, world, (tx) => { addStroke(tx, s.book, spec); }); ok = true; } catch { ok = false; }\n }\n if (ok) commits += 1;\n else books?.refuse(s.book); // refused (a read-only document, a book gone): the page is its children's again\n });\n };\n\n return {\n idle: () => stroke === null && turn === null && inHand === null && heldEntity(world) === undefined,\n follow(now) {\n const held = heldEntity(world);\n const book = held !== undefined && world.isAlive(held) && opts.isBook(held) ? held : undefined;\n if (stroke !== null && !world.isAlive(stroke.book)) { opts.books()?.write(stroke.book, null); stroke = null; }\n // the book was put down (or another taken up) mid-stroke: the stroke lands first\n if (stroke !== null && stroke.book !== book) { lift(stroke, undefined, now); stroke = null; }\n if (turn !== null && turn.book !== book) turn = null;\n if (book === undefined) { inHand = null; return; }\n const books = opts.books();\n if (books === undefined) return;\n // the keys' and the bar's turns: the count as it came into the hand is where the hand starts from\n const asked = world.get(book, PageTurns)?.n ?? 0;\n if (inHand === null || inHand.book !== book) inHand = { book, seen: asked };\n const pen = penOfTool(world.get(book, HeldTool)?.id ?? \"\") ?? DEFAULT_PEN;\n // the pointer: the one laying the stroke, else one pressing, else the local mouse\n let pointer: Entity | undefined;\n world.query(pointersQ).each((b) => {\n for (const r of b) {\n const p = b.entity(r);\n if (stroke !== null ? p === stroke.pointer : world.get(p, HeldPress) !== undefined || world.read(p, Pointer).device === \"mouse\") pointer = pointer ?? p;\n }\n });\n const hp = pointer !== undefined ? world.get(pointer, HeldPointer) : undefined;\n const at = hp !== undefined ? opts.heldToWorld(book, hp.x, hp.y) : undefined;\n const G = opts.geometryOf(book) as NotebookGeometry | undefined;\n const press = pointer !== undefined ? world.get(pointer, HeldPress) : undefined;\n const buttons = pointer !== undefined ? (world.get(pointer, PointerButtons)?.buttons ?? 0) : 0;\n const writing = press?.kind === \"tool\" && (buttons & 1) !== 0;\n const vp = world.getResource(Viewport);\n const single = G !== undefined && vp !== undefined && readingTarget({ cx: 0, cy: 0, w: G.frame.W * 2, h: G.frame.H }, { width: vp.w, height: vp.h }, true).single;\n if (G !== undefined && asked !== inHand.seen) { step(books, book, G, asked - inHand.seen, single); inHand.seen = asked; }\n const m = books.state(book).motion;\n const screen = pointer !== undefined ? world.get(pointer, PointerScreen) : undefined;\n // THE LEAVES: a turn in the hand follows it, lets go, or was a click\n if (turn !== null && (press?.kind !== \"part\" || turn.pointer !== pointer)) {\n if (turn.sheet !== null && m !== null) {\n const s = m.sheets[turn.sheet];\n releaseSheet(m, turn.sheet);\n // it goes over (past the vertical, or flung): a completed turn; else it falls back — nothing written\n if (s !== undefined && s.side !== turn.side && G !== undefined) {\n const to = clamp(spreadOf(books, book) + (s.side === 1 ? 1 : -1), 0, G.frame.spec.sheets);\n books.face(book, s.side === 1 ? 1 : 0); // a phone follows the sheet: to its verso on the left, or its recto back on the right\n write(books, book, to);\n }\n } else if (!turn.moved && G !== undefined) step(books, book, G, turn.side === 0 ? 1 : -1, single); // a click: a page on, or back\n turn = null;\n } else if (turn !== null && G !== undefined && m !== null && at !== undefined && screen !== undefined) {\n if (press?.moved === true) turn.moved = true;\n if (turn.sheet === null && Math.abs(screen.x - turn.x0) >= TAKE_PX) turn.sheet = grabSheet(m, turn.side);\n if (turn.sheet !== null) {\n const c = counts(m);\n const z = G.frame.b + Math.max(c.right, c.left) * G.frame.spec.sheet;\n const x = localXAt(G.eye, G.rigid, at[0], at[1], z);\n dragSheet(m, turn.sheet, x, G.frame.xg, turn.s, turn.len, turn.y / (G.frame.Hp / 2), G.law, Math.max((now - turn.lt) / 1000, 1e-3));\n turn.lt = now;\n books.stir(book);\n }\n } else if (turn === null && press?.kind === \"part\" && press.part === \"turn\" && pointer !== undefined && G !== undefined && at !== undefined && screen !== undefined) {\n const h = pageHitAt(G, at[0], at[1]);\n if (h !== null && h.part === \"page\") turn = { book, pointer, side: h.side, s: h.s, y: h.y, len: h.len, x0: screen.x, sheet: null, lt: now, moved: false };\n }\n // the peek: over the right page's fore-edge corner with nothing pressed, that corner lifts — an invitation\n if (m !== null) {\n const h = press === undefined && at !== undefined && G !== undefined ? pageHitAt(G, at[0], at[1]) : null;\n const corner = h !== null ? cornerOf(G as NotebookGeometry, h) : 0;\n if ((corner !== 0) !== m.peekOn || (corner !== 0 && corner !== m.peekSide)) {\n m.peekOn = corner !== 0;\n if (corner !== 0) m.peekSide = corner;\n books.stir(book);\n }\n }\n if (stroke !== null && (!writing || stroke.pointer !== pointer)) { lift(stroke, at, now); stroke = null; }\n else if (stroke !== null && at !== undefined && G !== undefined) {\n // a frame of the stroke: a sample where the pen is on its page (off the page, the pen skips — the prototype's)\n const q = onPage(G, at, stroke);\n if (q !== null) { sample(stroke, q.s, q.y, f32(now - stroke.t0)); books.write(book, stroke.live); }\n } else if (stroke === null && writing && pointer !== undefined && at !== undefined && G !== undefined) {\n // the press: the pen meets a page's writing (never a turn's share, never an endpaper)\n const h = pageHitAt(G, at[0], at[1]);\n const q = h !== null && partOf(G, h) === \"content\" ? onPage(G, at, null) : null;\n if (q !== null) {\n const live: LiveStroke = { page: q.page, ink: pen, points: [], lifted: false, key: \"\" };\n stroke = { book, pointer, side: q.side, page: q.page, t0: now, points: [], times: [], live };\n sample(stroke, q.s, q.y, 0);\n books.write(book, live);\n }\n }\n },\n live: () => (stroke === null ? null : { book: stroke.book, page: stroke.page, samples: stroke.points.length }),\n commits: () => commits,\n turning: () => (turn === null ? null : { book: turn.book, side: turn.side, sheet: turn.sheet }),\n turns: () => turns,\n };\n}\n","// The NOTEBOOK (NOTEBOOK.md — the real 3D book) as an OBJECT (design-015 §6; D3w): a clothbound book lying on\n// the desk among its things. Durable props: its `title`, its `cover` and `ruling` by name (the covers' colours are\n// the host's palette), its `seed` (the hand of its paper), the `spread` it is open at (the sheets turned onto the\n// left) and its `angle` on the mat (the prototype kept it on the book; a new one takes its seed's — `bookAngle`).\n// Its rect is the closed case (180 × 252); whether it lies OPEN is a pose — the opening is D4b's (a still pins it).\n// What is WRITTEN in it is not a prop: its INK is its DATA CHILDREN (D3t-b) — `desk.stroke` entities `ChildOf` the book,\n// each on its `page` in page units, laid by the pen in hand (one transaction a stroke; board/data.ts), the pages' rasters a\n// cache replayed from them (kinds/notebook.ts). `spread` moves with a completed turn, off the undo stack (D-D3t-b.2).\n// Things, movable, selectable, snapping both ways; a ROOT object (D-D18: `interaction.drop: \"never\"` — no container\n// takes it, whatever it accepts).\n\nimport { p } from \"@ice/core\";\nimport { StrokePrefab } from \"@ice/desk/kit\";\nimport { type Books, notebookKind } from \"./kind\";\nimport { NOTEBOOK } from \"./law\";\nimport { DESK_OBJECT, defineObject } from \"@ice/desk\";\nimport { createNotebookHand } from \"./leaf\";\n\n/** The covers a notebook is bound in (NOTEBOOK.md §4) — names; the cloths and designs are the host's. */\nexport const COVERS = [\"ink\", \"orbit\", \"tiles\", \"label\", \"linen\"] as const;\nexport type CoverName = (typeof COVERS)[number];\n\n/** The rulings its pages are printed with (notebook/layout.ts `RULINGS`). */\nexport const RULING_NAMES = [\"plain\", \"dots\", \"rules\", \"grid\"] as const;\n\n/** The notebook's durable type id. */\nexport const NOTEBOOK_TYPE = \"desk.notebook\";\n\nexport const Notebook = defineObject({\n type: NOTEBOOK_TYPE,\n version: 1,\n props: {\n title: p.string({ default: \"\" }),\n cover: p.enum(COVERS, { default: \"orbit\" }),\n ruling: p.enum(RULING_NAMES, { default: \"dots\" }),\n seed: p.number({ default: 0 }),\n spread: p.number({ default: 0 }),\n angle: p.number({ default: 0 }),\n },\n size: { w: NOTEBOOK.cover.width, h: NOTEBOOK.cover.height },\n kind: notebookKind(),\n // on the pegboard tray (design-017 §8): the notebook standing on a shelf (a whole number of pitches high, so its top meets the hooks')\n tray: { label: \"Notebook\", category: \"paper\", order: 2, hang: { w: 143, h: 200, accessory: \"shelf\", pegs: [[-1.5, 0.5], [1.5, 0.5]] } },\n interaction: { selectable: true, movable: true, resizable: false, snap: \"both\", drop: \"never\" },\n // it lies on the desk by what it provides (K8a — `DESK_OBJECT`, the desk canvas's one key), as a plugin kind does\n provides: [DESK_OBJECT],\n // its strokes are its DATA (D3t-b, the Board's prefab): the catalog stamps, gates and migrates them with the book\n data: [StrokePrefab],\n // the notebook in hand (D3t-b): its pen and its LEAVES — the hand onto the notebook kind's state, each stroke ONE transaction out of the frame (D-D7-A.3)\n drivers: (h) => createNotebookHand({\n world: h.world, docs: h.docs, books: () => h.local as Books | undefined, isBook: h.isKind, heldToWorld: h.heldToWorld, geometryOf: h.geometryOf,\n props: Notebook.groups[0]?.component,\n }),\n});\n","// THE PRINT'S SAMPLE PICTURE (K5b, D-K5b.4) — what the print on the pegboard shows: a small landscape the photo kind SHIPS, made from\n// arithmetic alone (no network, no blob store, no decoder), so every host — a browser, the Node oracle — makes the same bytes. A print\n// names it as it names any picture, by its blob (`SAMPLE_PICTURE`); the kind's pictures make it where they would fetch one. A dusk\n// over water: a sky warming to the horizon, a low sun, two ranges of hills, the water taking the sky's light, a little grain.\n\n/** The sample's name — a print whose `blob` is this shows the sample (its `width` × `height` the sample's 3 : 2). */\nexport const SAMPLE_PICTURE = \"sample:dusk\";\n/** The sample's size, texels (a 6 × 4's aspect — the print's extent at rest). */\nexport const SAMPLE_SIZE = { w: 240, h: 160 } as const;\n\nconst mix = (a: number, b: number, t: number): number => a + (b - a) * t;\nconst smooth = (a: number, b: number, x: number): number => { const t = Math.min(Math.max((x - a) / (b - a), 0), 1); return t * t * (3 - 2 * t); };\n/** A small integer hash → [0, 1). */\nfunction hash(x: number, y: number): number {\n let h = (Math.imul(x, 374761393) + Math.imul(y, 668265263)) >>> 0;\n h = Math.imul(h ^ (h >>> 13), 1274126177) >>> 0;\n return ((h ^ (h >>> 16)) >>> 0) / 4294967296;\n}\n/** A ridge line: a few sines, 0 … 1 of the height. */\nconst ridge = (u: number, a: number, b: number, c: number): number => a + 0.035 * Math.sin(u * 7.1 + b) + 0.02 * Math.sin(u * 17.3 + c) + 0.008 * Math.sin(u * 41.0 + b * 2);\n\n/** The sample at `width` × `height` texels: sRGB rgba8, row-major from the top. */\nexport function samplePicture(width: number = SAMPLE_SIZE.w, height: number = SAMPLE_SIZE.h): Uint8Array<ArrayBuffer> {\n const w = Math.max(1, Math.round(width));\n const h = Math.max(1, Math.round(height));\n const out = new Uint8Array(w * h * 4);\n const horizon = 0.58;\n const sun = { u: 0.68, v: 0.47, r: 0.055 };\n for (let y = 0; y < h; y++) {\n const v = (y + 0.5) / h;\n for (let x = 0; x < w; x++) {\n const u = (x + 0.5) / w;\n // the sky: deep blue overhead warming to apricot at the horizon\n const k = smooth(0.0, horizon, v);\n let r = mix(58, 246, k * k);\n let g = mix(86, 190, k * k);\n let b = mix(140, 150, k);\n // the sun and its glow\n const d = Math.hypot((u - sun.u) * (w / h), v - sun.v);\n const glow = Math.exp(-d * 9) * 0.55;\n r = mix(r, 255, glow); g = mix(g, 214, glow); b = mix(b, 160, glow);\n if (d < sun.r) { const e = smooth(sun.r, sun.r * 0.8, d); r = mix(r, 255, e); g = mix(g, 238, e); b = mix(b, 200, e); }\n // the far range, then the near one\n const far = ridge(u, 0.5, 1.3, 0.4);\n if (v > far && v < horizon) { const t = smooth(far, horizon, v) * 0.35; r = mix(118, 92, t); g = mix(112, 98, t); b = mix(146, 130, t); }\n const near = ridge(u, 0.555, 4.2, 2.9) + 0.025 * smooth(0.2, 0.0, u);\n if (v > near && v < horizon) { const t = smooth(near, horizon, v); r = mix(62, 44, t); g = mix(78, 64, t); b = mix(70, 60, t); }\n // the water: the sky's light upside down, darker, broken into ripples; the sun's path on it\n if (v >= horizon) {\n const m = horizon - (v - horizon) * 1.6;\n const km = smooth(0.0, horizon, Math.max(m, 0));\n const ripple = 0.5 + 0.5 * Math.sin(v * h * 1.9 + Math.sin(u * 23.0) * 1.7);\n r = mix(46, 214, km * km) * (0.78 + 0.08 * ripple);\n g = mix(70, 166, km * km) * (0.78 + 0.08 * ripple);\n b = mix(118, 146, km) * (0.82 + 0.06 * ripple);\n const path = Math.exp(-Math.abs(u - sun.u) * 26) * smooth(1.0, horizon, v) * ripple;\n r = mix(r, 255, path * 0.7); g = mix(g, 212, path * 0.6); b = mix(b, 150, path * 0.4);\n }\n // a little grain, as a print has\n const n = (hash(x, y) - 0.5) * 6;\n const o = (y * w + x) * 4;\n out[o] = Math.min(255, Math.max(0, Math.round(r + n)));\n out[o + 1] = Math.min(255, Math.max(0, Math.round(g + n)));\n out[o + 2] = Math.min(255, Math.max(0, Math.round(b + n)));\n out[o + 3] = 255;\n }\n }\n return out;\n}\n","// The PHOTO's law — pure: no GPU (PHOTO.md). A print on the desk is a thin\n// rigid sheet with a pose in 3D: a centre on the mat plane and a HEIGHT off\n// it, a turn in the plane, a SLOPE (the tilt a held or gliding sheet takes),\n// a bend (a pinched sheet droops away from the fingers). `stepPhoto` is its\n// physics — held, it hangs from the grab point, which follows the finger\n// exactly, and swings about it under inertia and air; let go, it glides on\n// its air cushion, lands and grips the mat. `resolvePhoto` turns the pose into\n// the GEOMETRY the pass draws, and `unproject` is the CPU mirror of\n// photo.wgsl's ray cast, so what is picked is what is drawn.\n//\n// The camera is top-down and orthographic (thinking-the-desk §6); a lifted\n// sheet reads near through ONE local perspective: an eye `law.eye` world units\n// above the desk over the sheet's anchor (the grab point while held), so a\n// sheet at height h reads eye/(eye − h) larger about the finger — the lift's\n// scale is a consequence, not a number — and a tilted sheet keystones.\n//\n// World units are the desk's (CSS px at zoom 1; the note's scale — theme.ts\n// PAPER.size 200 = 3″, so a 6×4 print is 400 long). Axes: x right, y down the\n// screen, z up off the mat. Time in seconds.\n\nimport { MAT_COLORS, MAT_GRID, type RGB } from \"@ice/desk\";\nimport { PHYSICS, type Lamp, lampOf } from \"@ice/desk/kit\";\n\n/**\n * The desk's ONE light: the mat's gobo projector as a lamp over the desk (paper.ts `lampOf` —\n * world (1930, −826), 994 up), the same the notes and the notebooks are lit and shadowed by.\n * Per print, the direction toward it from the print, and the shadow's ground slope away from\n * it, capped at `PHYSICS.shadow.slopeMax` (a print far from the lamp keeps a finite shadow).\n */\nexport const LAMP: Lamp = lampOf(MAT_GRID.plane);\n\n/**\n * The shadow's two terms: the PENUMBRA is the note's (kit/physics.ts `PHYSICS.shadow`: σ at contact, alpha\n * resting, the slope's cap — one physics for every sheet on the desk; its growth and held alpha below) — and a\n * tight CONTACT term at the base that fades as the sheet rises off the mat (gone by `reach`), as\n * the notebook's slab has (the tree-shadow design system's `--lift-1`).\n */\nexport const DESK_SHADOW = {\n // σ grows 0.36 per unit, not the note's 0.75: a held print rides twice as high as a held note (24 vs 12), and at the\n // note's rate its shadow blurred into nothing — this keeps a held print's penumbra as soft as a held note's (σ ≈ 11).\n // PHOTO.md §8 Q-2: the one law may want to be this (or the note's lift may want to be the print's).\n penumbra: { sigma0: PHYSICS.shadow.sigma, sigmaPerHeight: 0.36, alpha: PHYSICS.shadow.alpha, alphaHeld: 0.42, slopeMax: PHYSICS.shadow.slopeMax },\n contact: { alpha: 0.22, sigma: 1.1, reach: 2.5 },\n} as const;\n\n/** The colour a shadow casts ON the mat — theme.ts `MAT.cast` (the tree-shadow design system's `--cast-rgb`, \"the world's darkest value\"). */\nexport const CAST: RGB = MAT_COLORS.cast;\n\nconst PHOTO_SPEC = {\n /** The print's long side — a 6×4 at the note's scale. */\n long: 400,\n /** The white border, as a fraction of the short side (a classic bordered print). 0 = borderless. */\n border: 0.05,\n /** The die-cut corner. */\n radius: 2.5,\n /** The paper under the emulsion: a resin-coated white, a touch warm (sRGB), and its fibre ±/255. */\n paper: [0.957, 0.953, 0.937] as RGB,\n grain: 1.5 / 255,\n /** The local eye's height over the desk: at h the sheet reads eye/(eye − h) larger. */\n eye: 720,\n /** How high a held sheet rides, and how far a hovered one rises (the edge lifting under the finger). */\n lift: 24,\n hover: 2.2,\n /** Where a pasted print starts its fall from. */\n arrive: 70,\n /** The height spring: rising under the hand, falling to the mat (Hz, ζ), and the landing's bounce (restitution; below this speed it just settles). */\n rise: { hz: 5.5, zeta: 0.82 },\n fall: { hz: 3.6, zeta: 0.5, restitution: 0.18, settle: 30 },\n /**\n * The tilt (the sheet's slope): toward the fingers while held (the far edge hangs lowest — degrees at\n * the far corner), with the air while it moves (the leading edge rides up — degrees per 1000 u/s),\n * never past `max`; a spring (Hz, ζ) so it wobbles once when the hand stops.\n */\n tilt: { grab: 3, motion: 5, max: 12, hz: 3.2, zeta: 0.42 },\n /** The bend: a held sheet droops away from the fingers (units at the far corner); a resting print keeps a faint curl along its long side. */\n bend: { held: 5, rest: 0.9, rate: 9 },\n /**\n * The swing about the grab point: `drag` = the air's pull on the sheet's centre (the centre trails the\n * motion), `inertia` = the share of the hand's acceleration the sheet feels (it swings when the hand\n * jerks or stops), `damp` = rotational damping per second. OFF (James, 2026-09-24: \"do not make them\n * rotate\") — a carried print keeps its turn; only the wheel turns it. The machinery stays for the panel.\n */\n swing: { drag: 0, inertia: 0, damp: 2.2 },\n /**\n * Sliding: in the air a glide with `air` drag per second; on the mat the cutting mat's grip — a\n * constant deceleration (u/s²) plus a viscous share per second; the same for the turn (rad/s², /s).\n */\n slide: { air: 0.9, grip: 2400, viscous: 5, spinGrip: 7, spinViscous: 4 },\n /** A flick's velocity is the hand's over this window (s), capped at this speed (u/s). */\n throw: { window: 0.07, max: 4200 },\n /** The shadow's two terms (`DESK_SHADOW`). */\n shadow: DESK_SHADOW,\n /** The gloss: the lamp's highlight (strength, shininess), and the room's sheen off the coating (strength). */\n gloss: { spec: 0.2, shininess: 42, sheen: 0.5 },\n /**\n * By night (PHOTO.md §4a): the print is lit by the Moon at the mat's night law — `level` of its day\n * luminance in the Moon's light (MAT.md: the moonlit sage shows at ½ the sunlit) — the palm's shade\n * deepening to the sky's fill; its paper seen as the mat is (the rods' blue), its picture foveally\n * (`keep` 1 = cones alone, white-balanced: the picture's hue exactly).\n */\n night: { level: 0.5, keep: 1 },\n /** Going away (delete): the sheet lifts and fades over this long (s). */\n leave: 0.28,\n} as const;\n\n/** The law with its literals widened — what a host tunes (a copy: `structuredClone(PHOTO)`). */\ntype Widen<T> = T extends number ? number : T extends RGB ? RGB : { -readonly [K in keyof T]: Widen<T[K]> };\nexport type PhotoLaw = Widen<typeof PHOTO_SPEC>;\n/** The engine's numbers. Never written — a host tunes its own copy. */\nexport const PHOTO: PhotoLaw = PHOTO_SPEC;\n\n/** The unit direction toward the lamp from a point of the desk at height z (x right, y down, z up). */\nexport function lightAt(x: number, y: number, z = 0, lamp: Lamp = LAMP): readonly [number, number, number] {\n const dx = lamp.x - x;\n const dy = lamp.y - y;\n const dz = lamp.h - z;\n const l = Math.hypot(dx, dy, dz) || 1;\n return [dx / l, dy / l, dz / l];\n}\n\n/** A cast shadow's offset on the mat per unit of height at a desk point — away from the lamp, capped. */\nexport function shadowSlope(x: number, y: number, lamp: Lamp = LAMP, max: number = DESK_SHADOW.penumbra.slopeMax): readonly [number, number] {\n const h = Math.max(lamp.h, 1e-6);\n let sx = -(lamp.x - x) / h;\n let sy = -(lamp.y - y) / h;\n const m = Math.hypot(sx, sy);\n if (m > max) { sx *= max / m; sy *= max / m; }\n return [sx, sy];\n}\n\n// ---------------------------------------------------------------- the body\n\nexport interface Hold {\n /** The grab point in the sheet's own frame (unrotated, centre origin). */\n gx: number; gy: number;\n /** The finger, world — where the grab point is, exactly. */\n px: number; py: number;\n /** The finger's filtered velocity and acceleration (world/s, world/s²). */\n vx: number; vy: number; ax: number; ay: number;\n /** Recent finger samples for the flick: [t, x, y]. */\n trail: [number, number, number][];\n}\n\nexport interface PhotoBody {\n /** Centre on the mat plane, world. */\n x: number; y: number;\n /** The turn in the plane, radians (positive = clockwise on screen). */\n angle: number;\n vx: number; vy: number; spin: number;\n /** Height of the centre off the mat, and its rate. */\n h: number; vh: number;\n /** The slope (dz/dx, dz/dy, world axes) and its rate. */\n sx: number; sy: number; vsx: number; vsy: number;\n bend: number;\n /** Half extents (world). */\n readonly hx: number; readonly hy: number;\n /** The perspective's anchor in the sheet's frame — the grab point while held (so the finger's point never slides), kept after. */\n ax: number; ay: number;\n hold: Hold | null;\n hovered: boolean;\n /** Presence: 1 here, falling to 0 as it leaves; `leaving` = on its way out. */\n alpha: number;\n leaving: boolean;\n}\n\nexport function newBody(x: number, y: number, w: number, h: number, angle = 0, height = 0): PhotoBody {\n return {\n x, y, angle, vx: 0, vy: 0, spin: 0, h: height, vh: 0, sx: 0, sy: 0, vsx: 0, vsy: 0,\n bend: PHOTO.bend.rest, hx: w / 2, hy: h / 2, ax: 0, ay: 0, hold: null, hovered: false, alpha: 1, leaving: false,\n };\n}\n\n/** The print's size for an image: the long side is `law.long`, the aspect is the picture's. */\nexport function printSize(imgW: number, imgH: number, long: number = PHOTO.long): { w: number; h: number } {\n const k = long / Math.max(imgW, imgH, 1);\n return { w: Math.max(imgW * k, 8), h: Math.max(imgH * k, 8) };\n}\n\nconst rot = (a: number, x: number, y: number): [number, number] => {\n const c = Math.cos(a);\n const s = Math.sin(a);\n return [c * x - s * y, s * x + c * y];\n};\nconst cross = (ax: number, ay: number, bx: number, by: number) => ax * by - ay * bx;\nconst clampLen = (x: number, y: number, max: number): [number, number] => {\n const l = Math.hypot(x, y);\n return l > max && l > 0 ? [(x * max) / l, (y * max) / l] : [x, y];\n};\n/** A damped spring's acceleration toward `target` (Hz, ζ). */\nconst spring = (x: number, v: number, target: number, hz: number, zeta: number) => {\n const w = 2 * Math.PI * hz;\n return w * w * (target - x) - 2 * zeta * w * v;\n};\n\n/** Take hold of the sheet at a world point (the finger), in its own frame. */\nexport function grab(b: PhotoBody, wx: number, wy: number, t: number): void {\n const [gx, gy] = rot(-b.angle, wx - b.x, wy - b.y);\n b.hold = { gx, gy, px: wx, py: wy, vx: 0, vy: 0, ax: 0, ay: 0, trail: [[t, wx, wy]] };\n b.ax = gx; b.ay = gy;\n b.vx = 0; b.vy = 0; b.spin = 0;\n}\n\n/** The finger moved (world, at time t in seconds). */\nexport function moveHold(b: PhotoBody, wx: number, wy: number, t: number): void {\n const H = b.hold;\n if (!H) return;\n H.px = wx; H.py = wy;\n H.trail.push([t, wx, wy]);\n while (H.trail.length > 2 && t - (H.trail[0] as [number, number, number])[0] > 0.25) H.trail.shift();\n}\n\n/** Let go at time t: the sheet leaves with the finger's recent velocity (and its own swing). */\nexport function release(b: PhotoBody, t: number, law: PhotoLaw = PHOTO): void {\n const H = b.hold;\n if (!H) return;\n // the flick: the finger's displacement over the last `window` seconds — a finger that stopped before letting go throws nothing\n const recent = H.trail.filter(([ts]) => t - ts <= law.throw.window);\n let vx = 0;\n let vy = 0;\n if (recent.length >= 2) {\n const a = recent[0] as [number, number, number];\n const z = recent[recent.length - 1] as [number, number, number];\n const dt = Math.max(z[0] - a[0], 1 / 240);\n if (t - z[0] < law.throw.window) { vx = (z[1] - a[1]) / dt; vy = (z[2] - a[2]) / dt; }\n }\n // the centre's velocity = the grab point's + the swing's (ω × r); a print never leaves the hand spinning\n const [rx, ry] = rot(b.angle, -H.gx, -H.gy);\n [b.vx, b.vy] = clampLen(vx - b.spin * ry, vy + b.spin * rx, law.throw.max);\n b.spin = 0;\n b.hold = null;\n}\n\n/** Turn a held sheet about the finger (the wheel), radians. */\nexport function twist(b: PhotoBody, da: number): void {\n if (b.hold) { b.angle += da; place(b); } else { b.spin += da * 8; }\n}\n\n/** A held sheet's centre from its grab point and turn. */\nfunction place(b: PhotoBody): void {\n const H = b.hold;\n if (!H) return;\n const [rx, ry] = rot(b.angle, -H.gx, -H.gy);\n b.x = H.px + rx; b.y = H.py + ry;\n}\n\n/** Is the sheet still moving (or still settling)? A host renders on demand while any is. */\nexport function restless(b: PhotoBody): boolean {\n return b.hold !== null || b.leaving || Math.abs(b.vx) + Math.abs(b.vy) > 0.5 || Math.abs(b.spin) > 1e-3 || Math.abs(b.vh) > 0.05\n || Math.abs(b.h - (b.hovered ? PHOTO.hover : 0)) > 0.02 || Math.abs(b.sx) + Math.abs(b.sy) > 1e-4 || Math.abs(b.vsx) + Math.abs(b.vsy) > 1e-4;\n}\n\n/** The half diagonal — the reach of a corner from the centre. */\nconst diag = (b: PhotoBody) => Math.hypot(b.hx, b.hy);\n\n/** Advance the body by `dt` seconds (substepped at 240 Hz). */\nexport function stepPhoto(b: PhotoBody, dt0: number, law: PhotoLaw = PHOTO): void {\n let dt = dt0;\n if (dt <= 0) return;\n dt = Math.min(dt, 0.05);\n const H = b.hold;\n // the finger's velocity and acceleration, filtered once per frame (pointer events are discrete)\n let g0x = 0;\n let g0y = 0;\n if (H) {\n const [rx, ry] = rot(b.angle, H.gx, H.gy);\n g0x = b.x + rx; g0y = b.y + ry; // where the grab point was last frame\n const kv = 1 - Math.exp(-dt / 0.03);\n const ka = 1 - Math.exp(-dt / 0.045);\n const nvx = H.vx + ((H.px - g0x) / dt - H.vx) * kv;\n const nvy = H.vy + ((H.py - g0y) / dt - H.vy) * kv;\n H.ax += ((nvx - H.vx) / dt - H.ax) * ka; H.ay += ((nvy - H.vy) / dt - H.ay) * ka;\n H.vx = nvx; H.vy = nvy;\n }\n const n = Math.max(1, Math.ceil(dt * 240));\n const h = dt / n;\n const I = (b.hx * b.hx + b.hy * b.hy) / 3; // a plate's moment about its centre per unit mass: (w² + h²)/12 = (hx² + hy²)/3\n for (let i = 0; i < n; i++) {\n if (H) {\n // the grab point walks from where it was to the finger over the frame\n const f = (i + 1) / n;\n const gx = g0x + (H.px - g0x) * f;\n const gy = g0y + (H.py - g0y) * f;\n const [rx, ry] = rot(b.angle, -H.gx, -H.gy); // grab point → centre\n const IG = I + rx * rx + ry * ry;\n const vcx = H.vx - b.spin * ry;\n const vcy = H.vy + b.spin * rx;\n const tau = cross(rx, ry, -H.ax * law.swing.inertia, -H.ay * law.swing.inertia) + cross(rx, ry, -vcx * law.swing.drag, -vcy * law.swing.drag);\n b.spin += (tau / IG - law.swing.damp * b.spin) * h;\n b.angle += b.spin * h;\n const [nx, ny] = rot(b.angle, -H.gx, -H.gy);\n b.x = gx + nx; b.y = gy + ny;\n b.vx = H.vx - b.spin * ny; b.vy = H.vy + b.spin * nx;\n } else {\n const onMat = b.h < law.hover + 0.6; // a hovered print only lifts its edge: it still grips\n const s = Math.hypot(b.vx, b.vy);\n if (!onMat) {\n const k = Math.exp(-law.slide.air * h);\n b.vx *= k; b.vy *= k; b.spin *= Math.exp(-law.slide.air * 1.5 * h);\n } else if (s > 0) {\n const ns = Math.max(0, s - (law.slide.grip + law.slide.viscous * s) * h);\n b.vx *= ns / s; b.vy *= ns / s;\n }\n if (onMat) {\n const w = Math.abs(b.spin);\n const nw = Math.max(0, w - (law.slide.spinGrip + law.slide.spinViscous * w) * h);\n b.spin = w > 0 ? (b.spin * nw) / w : 0;\n }\n b.x += b.vx * h; b.y += b.vy * h; b.angle += b.spin * h;\n }\n\n // the height: up under the hand, down to the mat; the mat is a floor\n const target = b.leaving ? law.lift * 1.6 : H ? law.lift : b.hovered ? law.hover : 0;\n const up = target > b.h;\n b.vh += spring(b.h, b.vh, target, up ? law.rise.hz : law.fall.hz, up ? law.rise.zeta : law.fall.zeta) * h;\n b.h += b.vh * h;\n if (b.h < 0) { b.h = 0; b.vh = b.vh < -law.fall.settle ? -b.vh * law.fall.restitution : 0; }\n\n // the slope: toward the fingers, with the air; flat on the mat\n const aloft = Math.min(b.h / law.lift, 1);\n const tanMax = Math.tan((law.tilt.max * Math.PI) / 180);\n let tx = 0;\n let ty = 0;\n if (H) {\n const [gx, gy] = rot(b.angle, H.gx, H.gy); // centre → grab point\n const k = Math.tan((law.tilt.grab * Math.PI) / 180) / diag(b);\n tx += gx * k; ty += gy * k;\n }\n const km = (Math.tan((law.tilt.motion * Math.PI) / 180) / 1000) * aloft;\n tx += b.vx * km; ty += b.vy * km;\n [tx, ty] = clampLen(tx, ty, tanMax);\n b.vsx += spring(b.sx, b.vsx, tx, law.tilt.hz, law.tilt.zeta) * h;\n b.vsy += spring(b.sy, b.vsy, ty, law.tilt.hz, law.tilt.zeta) * h;\n b.sx += b.vsx * h; b.sy += b.vsy * h;\n\n // the bend: a pinched sheet droops, a resting one keeps its curl\n const bendTarget = H ? law.bend.held * Math.min(Math.hypot(H.gx, H.gy) / diag(b) + 0.35, 1) : law.bend.rest;\n b.bend += (bendTarget - b.bend) * (1 - Math.exp(-law.bend.rate * h));\n\n clearMat(b);\n }\n // presence: out over `leave`; a new print comes in over a few frames (never a pop)\n b.alpha = b.leaving ? Math.max(0, b.alpha - dt / law.leave) : Math.min(1, b.alpha + dt / 0.12);\n}\n\n/**\n * No corner goes through the mat: the lowest point of the tilted, drooping sheet is the\n * centre's height less the slope's fall to the far corner less the droop — when that is\n * under 0 the slope gives (the far corner rests on the mat while the near one lifts, as a\n * sheet lifted by its corner does) and its rate with it.\n */\nexport function clearMat(b: PhotoBody): void {\n const c = Math.cos(b.angle);\n const s = Math.sin(b.angle);\n const fall = Math.abs(b.sx * c + b.sy * s) * b.hx + Math.abs(-b.sx * s + b.sy * c) * b.hy;\n const room = Math.max(b.h - droopOf(b), 0);\n if (fall > room) {\n const k = fall > 0 ? room / fall : 0;\n b.sx *= k; b.sy *= k; b.vsx *= k; b.vsy *= k;\n }\n}\n\n/** How far the droop lowers the far corner: only a held sheet droops (the rest curl rises), and never below the mat — a sheet just lifted drapes on it. */\nconst droopOf = (b: PhotoBody) => (b.hold ? Math.min(b.bend, b.h) : 0);\n\n// ---------------------------------------------------------------- the geometry\n\nexport type Vec3 = readonly [number, number, number];\n\nexport interface PhotoGeometry {\n /** The sheet's centre in 3D (world units, z = height). */\n readonly centre: Vec3;\n /** The sheet's own axes in 3D (unit) and its normal. */\n readonly ex: Vec3; readonly ey: Vec3; readonly n: Vec3;\n readonly half: readonly [number, number];\n readonly radius: number;\n /** The local eye (world units): over the anchor, `law.eye` above the mat. */\n readonly eye: Vec3;\n /** The bend: the droop's amount and where it hangs from (the sheet's frame); the rest curl. Signed (droop, held). */\n readonly droop: number; readonly curl: number;\n readonly grab: readonly [number, number];\n readonly alpha: number;\n /** Toward the lamp from the print (unit), the shadow's slope on the mat, the penumbra's alpha (resting → held). */\n readonly light: Vec3;\n readonly slope: readonly [number, number];\n readonly shadowAlpha: number;\n /** The world rect the pass's quad covers: the sheet as seen and its shadow. */\n readonly bounds: { readonly x0: number; readonly y0: number; readonly x1: number; readonly y1: number };\n}\n\nconst sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\nconst dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\nconst norm = (a: Vec3): Vec3 => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };\nconst crs = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];\n\n/** The pose → what the pass draws and the hit-test reads. */\nexport function resolvePhoto(b: PhotoBody, law: PhotoLaw = PHOTO, lamp: Lamp = LAMP): PhotoGeometry {\n const c = Math.cos(b.angle);\n const s = Math.sin(b.angle);\n const n = norm([-b.sx, -b.sy, 1]);\n // the sheet's x axis: its in-plane direction lifted onto the tilted plane; y completes the frame (n × ex points down-screen, as y does)\n const ex = norm([c, s, b.sx * c + b.sy * s]);\n const ey = crs(n, ex);\n let centre: Vec3 = [b.x, b.y, b.h];\n const [axw, ayw] = rot(b.angle, b.ax, b.ay);\n let eye: Vec3 = [b.x + axw, b.y + ayw, law.eye];\n if (b.hold) {\n // a tilted sheet is shorter over the mat by the tilt's cosine: pin the grab point, as drawn, to the finger — and the eye over it\n const g = pointAt({ centre, ex, ey }, b.hold.gx, b.hold.gy);\n centre = [b.x + b.hold.px - g[0], b.y + b.hold.py - g[1], b.h];\n eye = [b.hold.px, b.hold.py, law.eye];\n }\n const G: Omit<PhotoGeometry, \"bounds\"> = {\n centre, ex, ey, n, half: [b.hx, b.hy], radius: law.radius, eye,\n droop: droopOf(b), curl: b.hold ? 0 : b.bend, grab: [b.hold?.gx ?? b.ax, b.hold?.gy ?? b.ay], alpha: b.alpha,\n light: lightAt(b.x, b.y, b.h, lamp), slope: shadowSlope(b.x, b.y, lamp, law.shadow.penumbra.slopeMax),\n shadowAlpha: law.shadow.penumbra.alpha + (law.shadow.penumbra.alphaHeld - law.shadow.penumbra.alpha) * Math.min(Math.max(b.h / law.lift, 0), 1),\n };\n // bounds: every corner as seen and as cast, grown by the widest blur and the bend\n const slope = G.slope;\n let x0 = Number.POSITIVE_INFINITY;\n let y0 = Number.POSITIVE_INFINITY;\n let x1 = Number.NEGATIVE_INFINITY;\n let y1 = Number.NEGATIVE_INFINITY;\n let hmax = 0;\n for (const [u, v] of [[-1, -1], [1, -1], [1, 1], [-1, 1]] as const) {\n const P = pointAt(G, u * b.hx, v * b.hy);\n const [px, py] = project(eye, P);\n hmax = Math.max(hmax, P[2] + b.bend);\n for (const [qx, qy] of [[px, py], [P[0] + slope[0] * (P[2] + b.bend), P[1] + slope[1] * (P[2] + b.bend)]] as const) {\n x0 = Math.min(x0, qx); y0 = Math.min(y0, qy); x1 = Math.max(x1, qx); y1 = Math.max(y1, qy);\n }\n }\n const pad = 3 * (law.shadow.penumbra.sigma0 + law.shadow.penumbra.sigmaPerHeight * hmax) + 2 * b.bend + 4;\n return { ...G, bounds: { x0: x0 - pad, y0: y0 - pad, x1: x1 + pad, y1: y1 + pad } };\n}\n\n/** The sheet's own frame → a 3D point on its (flat) plane. */\nexport function pointAt(G: Pick<PhotoGeometry, \"centre\" | \"ex\" | \"ey\">, u: number, v: number): Vec3 {\n return [G.centre[0] + G.ex[0] * u + G.ey[0] * v, G.centre[1] + G.ex[1] * u + G.ey[1] * v, G.centre[2] + G.ex[2] * u + G.ey[2] * v];\n}\n\n/** A 3D point as the local eye sees it on the desk plane (world units). */\nexport function project(eye: Vec3, P: Vec3): [number, number] {\n const k = eye[2] / Math.max(eye[2] - P[2], 1e-3);\n return [eye[0] + (P[0] - eye[0]) * k, eye[1] + (P[1] - eye[1]) * k];\n}\n\n/** The bend's offset along the normal at a point of the sheet (photo.wgsl `photo_bend`). */\nexport function bendAt(G: Pick<PhotoGeometry, \"half\" | \"droop\" | \"curl\" | \"grab\">, u: number, v: number): number {\n const d = Math.hypot(u - G.grab[0], v - G.grab[1]) / (2 * Math.hypot(G.half[0], G.half[1]));\n const cu = u / Math.max(G.half[0], G.half[1]);\n return G.curl * cu * cu - G.droop * d * d;\n}\n\n/** A desk point (world) → the point of the sheet the eye sees there, in the sheet's frame (photo.wgsl `photo_unproject`). */\nexport function unproject(G: PhotoGeometry, wx: number, wy: number): [number, number] {\n const D: Vec3 = [wx - G.eye[0], wy - G.eye[1], -G.eye[2]];\n const hit = (lift: number): [number, number] => {\n const C: Vec3 = [G.centre[0] + G.n[0] * lift, G.centre[1] + G.n[1] * lift, G.centre[2] + G.n[2] * lift];\n const t = dot(G.n, sub(C, G.eye)) / dot(G.n, D);\n const P: Vec3 = [G.eye[0] + D[0] * t, G.eye[1] + D[1] * t, G.eye[2] + D[2] * t];\n const r = sub(P, C);\n return [dot(r, G.ex), dot(r, G.ey)];\n };\n const [u0, v0] = hit(0);\n return hit(bendAt(G, u0, v0));\n}\n\nexport function sdRoundBox(qx: number, qy: number, hx: number, hy: number, r: number): number {\n const rr = Math.min(Math.max(r, 0), hx, hy);\n const ax = Math.abs(qx) - hx + rr;\n const ay = Math.abs(qy) - hy + rr;\n return Math.hypot(Math.max(ax, 0), Math.max(ay, 0)) + Math.min(Math.max(ax, ay), 0) - rr;\n}\n\n/** Is the desk point on the sheet as drawn? */\nexport function hitPhoto(G: PhotoGeometry, wx: number, wy: number): boolean {\n const [u, v] = unproject(G, wx, wy);\n return sdRoundBox(u, v, G.half[0], G.half[1], G.radius) < 0;\n}\n","// The photo pass's GPU records, declared once. `Photo` is one print as drawn\n// — `resolvePhoto`'s pose in 3D (its centre, its axes, its normal, the local\n// eye), its bend, the quad's world rect and its picture's texel facts.\n// `PhotoUniforms` is the pass's knobs: the cast colour, the paper, the two\n// shadow terms and the gloss; the lamp's direction and slope are per print. The camera, the gobo and the\n// Moon arrive through the mat's block (`MatUniforms`), which the pass fills for\n// itself, as the paper pass does.\n\nimport { defineStruct } from \"@ice/desk/engine\";\nimport { CAST, PHOTO, type PhotoGeometry, type PhotoLaw } from \"./photo\";\n\nexport const Photo = defineStruct(\"Photo\", [\n [\"centre\", \"vec4f\"], // xyz (world, z = height), presence\n [\"ex\", \"vec4f\"], // the sheet's x axis (unit, 3D), half width\n [\"ey\", \"vec4f\"], // the sheet's y axis (unit, 3D), half height\n [\"n\", \"vec4f\"], // the normal, the corner radius\n [\"eye\", \"vec4f\"], // the local eye (world), the border's width (world)\n [\"bend\", \"vec4f\"], // the droop, the rest curl, the grab point u, v (the sheet's frame)\n [\"bounds\", \"vec4f\"], // the quad: x0 y0 x1 y1 (world)\n [\"image\", \"vec4f\"], // the picture: texels wide, high, mip levels, on (0/1)\n [\"light\", \"vec4f\"], // toward the lamp from the print (unit; x right, y down, z up), the penumbra's alpha\n [\"slope\", \"vec4f\"], // the shadow's offset on the mat per unit of height xy, unused ×2\n [\"tier\", \"vec4f\"], // where the picture's pixels are (K6a, pictures.ts): its thumbnail's layer, the chain level it starts at, its detail's pool slot (−1: none), the level the detail starts at\n] as const);\n\nexport const PhotoUniforms = defineStruct(\"PhotoUniforms\", [\n [\"shade\", \"vec4f\"], // the shadow's colour (sRGB), unused\n [\"paper\", \"vec4f\"], // the print's paper (sRGB), its fibre ±\n [\"penumbra\", \"vec4f\"], // unused (the alpha is the print's), σ at contact, σ per unit of height, unused\n [\"contact\", \"vec4f\"], // alpha, σ, the height it is gone by, unused\n [\"gloss\", \"vec4f\"], // the lamp's highlight, its shininess, the room's sheen, unused\n [\"night\", \"vec4f\"], // by night: the level (moonlit / day luminance), the picture's foveal keep (1 = its hue exactly), unused ×2\n] as const);\n\nexport const MAX_PHOTOS = 256;\n\n/** A picture as a record names it: its texels and chain, where its thumbnail lies, and its detail's slot while a frame binds one (pictures.ts `Picture`). */\nexport interface PhotoPicture {\n readonly width: number;\n readonly height: number;\n readonly mips: number;\n readonly layer: number;\n readonly base: number;\n readonly slot: number;\n readonly detail: { readonly base: number } | null;\n}\n\nexport function photoValues(G: PhotoGeometry, border: number, pic: PhotoPicture | null) {\n return {\n centre: [G.centre[0], G.centre[1], G.centre[2], G.alpha],\n ex: [G.ex[0], G.ex[1], G.ex[2], G.half[0]],\n ey: [G.ey[0], G.ey[1], G.ey[2], G.half[1]],\n n: [G.n[0], G.n[1], G.n[2], G.radius],\n eye: [G.eye[0], G.eye[1], G.eye[2], border],\n bend: [G.droop, G.curl, G.grab[0], G.grab[1]],\n bounds: [G.bounds.x0, G.bounds.y0, G.bounds.x1, G.bounds.y1],\n image: pic ? [pic.width, pic.height, pic.mips, 1] : [1, 1, 1, 0],\n light: [G.light[0], G.light[1], G.light[2], G.shadowAlpha],\n slope: [G.slope[0], G.slope[1], 0, 0],\n tier: pic ? [pic.layer, pic.base, pic.slot, pic.slot >= 0 ? (pic.detail?.base ?? 0) : 0] : [0, 0, -1, 0],\n };\n}\n\nexport function photoUniformValues(law: PhotoLaw = PHOTO) {\n const sh = law.shadow;\n return {\n shade: [CAST[0], CAST[1], CAST[2], 0],\n paper: [law.paper[0], law.paper[1], law.paper[2], law.grain],\n penumbra: [0, sh.penumbra.sigma0, sh.penumbra.sigmaPerHeight, 0],\n contact: [sh.contact.alpha, sh.contact.sigma, sh.contact.reach, 0],\n gloss: [law.gloss.spec, law.gloss.shininess, law.gloss.sheen, 0],\n night: [law.night.level, law.night.keep, 0, 0],\n };\n}\n\n/** The border's width in world units for a print of half extents `hx × hy`. */\nexport const borderOf = (hx: number, hy: number, law: PhotoLaw = PHOTO): number => law.border * 2 * Math.min(hx, hy);\n","// THE PICTURES' RESIDENCY (design-016 §6, K-L4; K6a) — every print's picture in SHARED textures under the desk's ONE budget,\n// so a run of prints is ONE instanced draw: its record carries where its pixels are, never a bind group of its own.\n//\n// Two tiers, one mip chain. A picture's chain is made on the device from its level 0 (mips.ts, as it always was) and its\n// TAIL — the levels from the first that fits THUMB² — is copied, texel for texel, into a layer of the THUMBNAIL array\n// (`photo/thumbnails`, THUMB² × layers, grown by doubling): always resident while a print names the picture, so no print is\n// ever blank. A print LARGE on screen — one that samples its picture finer than the thumbnail holds, or within HEADROOM\n// of a level of it — asks for a DETAIL: the chain from the finest level it samples (`floor(lod)`: what the screen needs, never\n// the whole picture for a print a third of the screen wide), made again from the picture's source (a raw picture's bytes;\n// the kind's blob, decoded again) and bound in one of DETAIL_SLOTS pool bindings for the frames it is wanted. Both tiers\n// are cuts of the same chain, so where they overlap they are the same texels: the swap shows nothing while the print\n// samples at or above the thumbnail's base, and the detail is asked a level before that.\n//\n// THE BUDGET (engine/budget.ts — the one the boards, the notebook's pages and the calendar's tiles are under): the thumbnail\n// array is charged and always kept (\"photo\" / \"thumbnails\"); each detail is charged (\"photo\" / \"detail <id>\") and kept while a\n// slot binds it (on screen and wanted) — off screen it is a cache the budget's LRU takes when the desk is over its cap, made\n// again when the print is next large. A detail finer than the print now samples (it zoomed out) is cut down to what it\n// samples by a device copy (no fetch).\n//\n// A frame: each slot's `prepare` ASKS for its prints' pictures at their lod (`ask`); the kind's tick runs `step` once before\n// the next frame's build — slots given and taken, details fetched or cut — so what a frame binds never moves inside it.\n\nimport { bindGroup, bindLayout } from \"@ice/desk/engine\";\nimport type { RasterBudget } from \"@ice/desk\";\nimport { chainBytes, type DecodedPicture, generateMips, LayerArray, mipCount, tailBase } from \"@ice/desk/kit\";\n\n/** The thumbnail array's layer side, texels: a picture's chain from its first level that fits (a print up to THUMB device px wide samples nothing finer). */\nexport const THUMB = 512;\nexport const THUMB_MIPS = mipCount(THUMB, THUMB);\n/** The pool: how many details one frame binds (the prints larger on screen than the thumbnail serves, largest first). */\nexport const DETAIL_SLOTS = 8;\n/**\n * A detail is asked this far (levels) BEFORE the print needs it — once it shows its picture larger than THUMB / √2 device px —\n * so it lands while both tiers are still the same texels and the swap shows nothing (a zoom from there to THUMB px is 1.41×).\n */\nexport const HEADROOM = 0.5;\n/** Details fetched at once (each decodes its picture again). */\nexport const BUILDS = 2;\n\n/** How a picture's level 0 comes back: raw sRGB rgba8 bytes, or a decoded source the device copies; undefined when it cannot. */\nexport type PictureSource = () => Promise<DecodedPicture | undefined>;\n\n/** The finer cut of a picture's chain a print large on screen samples: its own texture from level `base` down. */\nexport interface Detail {\n readonly texture: GPUTexture;\n readonly view: GPUTextureView;\n readonly base: number;\n readonly bytes: number;\n}\n\n/** A picture on the device: its thumbnail's layer, the chain level that layer starts at, the detail and the slot a frame binds it in. */\nexport interface Picture {\n readonly id: number;\n readonly width: number;\n readonly height: number;\n readonly mips: number;\n /** Its thumbnail's layer in the shared array (−1 once dropped). */\n layer: number;\n /** The chain's level the thumbnail's level 0 is (0: the whole picture fits the layer). */\n readonly base: number;\n detail: Detail | null;\n /** The pool slot binding the detail this frame; −1: the thumbnail serves. */\n slot: number;\n /** Turns over whenever the slot or the detail moves — a print's record folds it in (`aux`) and is packed again. */\n tier: number;\n}\n\ninterface Held extends Picture {\n readonly source: PictureSource;\n /** The smallest lod a print asked it at since the last step (Infinity: not asked). */\n want: number;\n /** The lod its slot was last granted or kept at (K9 R4: what the hand's prepare re-asks); Infinity before any. */\n kept: number;\n /** A detail on its way, from this level; Infinity when none. */\n building: number;\n dropped: boolean;\n}\n\n/** The level of a `w × h` picture's chain the thumbnail starts at: the first whose both sides fit `side` (the kit's `tailBase`). */\nexport const thumbBase = (w: number, h: number, side: number = THUMB): number => tailBase(w, h, side);\n\n/**\n * The lod a print samples its picture at (photo.wgsl `photo_picture`): texels per device pixel along the picture's wider axis,\n * log2 — `inner` the picture's half extents on the sheet (world), `zoom · dpr` device pixels a world unit.\n */\nexport function pictureLod(width: number, height: number, inner: readonly [number, number], zoom: number, dpr: number): number {\n return Math.log2(Math.max(width / (2 * Math.max(inner[0], 1e-6)), height / (2 * Math.max(inner[1], 1e-6))) / Math.max(zoom * dpr, 1e-9));\n}\n\n/** The detail a print sampling at `lod` needs: the finest level it samples, below the thumbnail's `base` — null when the thumbnail serves (or will within HEADROOM). */\nexport function detailNeed(lod: number, base: number): number | null {\n if (base === 0 || !(lod < base + HEADROOM)) return null;\n return Math.min(Math.max(Math.floor(lod), 0), base - 1);\n}\n\nexport { chainBytes, Layers } from \"@ice/desk/kit\";\n\nconst USAGE_CHAIN = (): number => GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT;\n\n/** The group-1 layout every print pipeline binds: the thumbnail array, then the pool's DETAIL_SLOTS details. */\nexport function picturesLayout(device: GPUDevice): GPUBindGroupLayout {\n return bindLayout(device, [\n { binding: 0, stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" },\n ...Array.from({ length: DETAIL_SLOTS }, (_, i) => ({ binding: 1 + i, stages: [\"fragment\"] as const, texture: \"float\" as const })),\n ], \"photo/pictures\");\n}\n\nexport interface PictureStats {\n readonly pictures: number;\n /** Thumbnail layers in use, and the array's capacity. */\n readonly layers: number;\n readonly capacity: number;\n readonly details: number;\n readonly slotted: number;\n readonly building: number;\n /** Detail builds landed, detail cuts made, details the budget evicted — since the store was made. */\n readonly built: number;\n readonly cut: number;\n readonly evicted: number;\n readonly bytes: { readonly thumbnails: number; readonly details: number };\n}\n\n/** The pictures of one device: the thumbnail array, the details, the pool — one per photo pass family (every slot shares it). */\nexport class PictureStore {\n readonly layout: GPUBindGroupLayout;\n /** The group every slot binds at 1 this frame: the array and the pool (blank where a slot is empty). */\n group: GPUBindGroup;\n /** A detail landed or went (async): the kind wakes the desk so the next step binds it. */\n onReady: () => void = () => {};\n private readonly device: GPUDevice;\n /** The thumbnails: a layer a picture (the kit's shared array). */\n private readonly thumbs: LayerArray;\n private readonly blank: GPUTexture;\n private readonly blankArray: GPUTexture;\n private readonly pictures = new Map<number, Held>();\n private readonly slots: (Held | null)[] = Array.from({ length: DETAIL_SLOTS }, () => null);\n private readonly asked = new Set<Held>();\n private budget: RasterBudget | undefined;\n private nextId = 1;\n private inflight = 0;\n private built = 0;\n private cut = 0;\n private evicted = 0;\n\n constructor(device: GPUDevice) {\n this.device = device;\n this.layout = picturesLayout(device);\n this.thumbs = new LayerArray(device, { label: \"photo/thumbnails\", format: \"rgba8unorm-srgb\", side: THUMB });\n const usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST;\n this.blank = device.createTexture({ label: \"photo/pictures blank\", size: [1, 1], format: \"rgba8unorm-srgb\", usage });\n this.blankArray = device.createTexture({ label: \"photo/thumbnails (none yet)\", size: [1, 1, 1], format: \"rgba8unorm-srgb\", usage });\n this.group = this.bind();\n }\n\n /** Charge the desk's budget from now on (the kind's host lends it; the oracle's bare pass has none). */\n attach(budget: RasterBudget | undefined): void {\n if (budget === this.budget) return;\n this.budget = budget;\n if (budget === undefined) return;\n this.chargeThumbs();\n for (const p of this.pictures.values()) if (p.detail !== null) this.chargeDetail(p);\n }\n\n /** The budget's ask: the thumbnails always (they RESIDE since K9 R2 — never in the LRU — so this is their word if ever asked); a detail while a slot binds it. */\n keeps(key: string): boolean {\n if (key === \"thumbnails\") return true;\n const id = /^detail (\\d+)$/.exec(key);\n return id !== null && (this.pictures.get(Number(id[1]))?.slot ?? -1) >= 0;\n }\n\n /**\n * A picture from its level 0 — raw bytes written, or a decoded source copied — and how to get that level 0 again (a detail's\n * fetch): its chain made, its tail copied into a thumbnail layer, the chain let go. Null when the array holds no more layers.\n */\n make(first: DecodedPicture, source: PictureSource): Picture | null {\n const was = this.thumbs.version;\n const layer = this.thumbs.take();\n if (layer === null) return null;\n this.chargeThumbs(); // a layer more in use (K9 R2: the resident charge is what the layers in use weigh)\n if (this.thumbs.version !== was) this.group = this.bind(); // the array grew\n const { width, height } = first;\n const mips = mipCount(width, height);\n const base = thumbBase(width, height);\n const chain = this.chain(first);\n this.thumbs.fill(chain, mips, layer, base);\n chain.destroy();\n const p: Held = { id: this.nextId++, width, height, mips, layer, base, detail: null, slot: -1, tier: 0, source, want: Number.POSITIVE_INFINITY, kept: Number.POSITIVE_INFINITY, building: Number.POSITIVE_INFINITY, dropped: false };\n this.pictures.set(p.id, p);\n return p;\n }\n\n /** A picture no print names any more: its layer back to the array, its detail destroyed, its slot freed. */\n drop(pic: Picture): void {\n const p = this.pictures.get(pic.id);\n if (p === undefined) return;\n p.dropped = true;\n this.pictures.delete(p.id);\n this.asked.delete(p);\n const was = this.thumbs.version;\n this.thumbs.give(p.layer); // (K9 R2: the array may shrink here — its version moves, the group is made again)\n this.chargeThumbs();\n p.layer = -1;\n const slotted = p.slot >= 0;\n if (slotted) this.slots[p.slot] = null;\n p.slot = -1;\n this.setDetail(p, null);\n if (slotted || this.thumbs.version !== was) this.group = this.bind();\n }\n\n /** Asks the next `step` has to answer — what a frame drew since the last step (K7a: the kind is due until it answers them). */\n pending(): boolean { return this.asked.size > 0; }\n\n /** A print asked for its picture at `lod` this frame (a slot's prepare). */\n ask(pic: Picture, lod: number): void {\n const p = this.pictures.get(pic.id);\n if (p === undefined) return;\n if (lod < p.want) p.want = lod;\n this.asked.add(p);\n }\n\n /**\n * K9 R4 — the HAND's prepare: every picture a slot binds is asked again at the lod it was granted, so the step keeps it. The\n * desk copy behind a carried print is prepared once per stamp and its prints ask nothing on the frames between; the hand's\n * frame is the only prepare then, and a step that saw its ask alone freed every other slot — a one-frame softness pop at the\n * put-down (the rest frame drew them from their thumbnails, the tick re-slotted them), and while un-slotted `keeps` was false,\n * so over the cap `trim` could evict a detail on screen behind the hand.\n */\n keepSlotted(): void {\n for (const p of this.slots) {\n if (p === null || p === undefined) continue;\n if (p.kept < p.want) p.want = p.kept;\n this.asked.add(p);\n }\n }\n\n /**\n * THE FRAME BOUNDARY (the kind's tick, before the next frame's build): the pictures asked since the last step, largest on\n * screen first — the first DETAIL_SLOTS that need more than the thumbnail (or will within HEADROOM) keep or take a slot\n * once their detail is resident; a missing or too-coarse detail is fetched (a coarser one binds meanwhile), a detail finer\n * than its print samples now is cut down; every other slot is freed. Returns whether a print's tier moved (its record must be\n * packed again, the desk redrawn). O(1) when nothing was drawn since the last step.\n */\n step(): boolean {\n if (this.asked.size === 0) return false;\n const chosen = [...this.asked].filter((p) => detailNeed(p.want, p.base) !== null).sort((a, b) => a.want - b.want).slice(0, DETAIL_SLOTS);\n const keep = new Set(chosen);\n let moved = false;\n for (let s = 0; s < DETAIL_SLOTS; s++) {\n const p = this.slots[s];\n if (p !== null && p !== undefined && (!keep.has(p) || p.detail === null)) { this.slots[s] = null; p.slot = -1; p.tier += 1; moved = true; }\n }\n for (const p of chosen) {\n p.kept = p.want; // what the hand's prepare re-asks for it (K9 R4)\n const need = detailNeed(p.want, p.base) as number;\n const d = p.detail;\n if (d === null || d.base > need) this.fetch(p, need); // (a coarser detail binds meanwhile)\n else if (d.base < need - 1) { this.cutTo(p, need); moved = true; } // zoomed out: only what it samples, by a device copy\n if (p.detail !== null && p.slot < 0) {\n const s = this.slots.indexOf(null);\n if (s >= 0) { this.slots[s] = p; p.slot = s; p.tier += 1; moved = true; }\n }\n if (p.detail !== null) this.budget?.touch(\"photo\", `detail ${p.id}`);\n }\n for (const p of this.asked) p.want = Number.POSITIVE_INFINITY;\n this.asked.clear();\n if (moved) this.group = this.bind();\n return moved;\n }\n\n stats(): PictureStats {\n let details = 0;\n let bytes = 0;\n let building = 0;\n for (const p of this.pictures.values()) {\n if (p.detail !== null) { details += 1; bytes += p.detail.bytes; }\n if (p.building !== Number.POSITIVE_INFINITY) building += 1;\n }\n return {\n pictures: this.pictures.size, layers: this.thumbs.used, capacity: this.thumbs.capacity, details, building,\n slotted: this.slots.filter((s) => s !== null).length, built: this.built, cut: this.cut, evicted: this.evicted,\n bytes: { thumbnails: this.thumbsBytes(), details: bytes },\n };\n }\n\n dispose(): void {\n for (const p of [...this.pictures.values()]) this.drop(p);\n this.thumbs.destroy();\n this.blank.destroy();\n this.blankArray.destroy();\n this.budget?.release(\"photo\", \"thumbnails\");\n }\n\n /** K7b: the thumbnail array as the flat-card pipeline binds it — its view, made again when the array grew (its version moved). */\n thumbView(): { readonly version: number; readonly view: GPUTextureView } {\n if (this.thumbCard === null || this.thumbCard.version !== this.thumbs.version) this.thumbCard = { version: this.thumbs.version, view: this.thumbs.view(this.blankArray) };\n return this.thumbCard;\n }\n private thumbCard: { readonly version: number; readonly view: GPUTextureView } | null = null;\n\n // ---------------------------------------------------------------- the device's side\n\n private bind(): GPUBindGroup {\n const thumbs = this.thumbs.view(this.blankArray);\n const details = this.slots.map((p) => p?.detail?.view ?? this.blank.createView());\n return bindGroup(this.device, this.layout, [thumbs, ...details], \"photo/pictures\");\n }\n\n private thumbsBytes(): number { return this.thumbs.bytes; }\n\n /** The thumbnails RESIDE in the budget (K9 R2): never evicted, outside the caches' room, charged at what the layers in use weigh. */\n private chargeThumbs(): void { this.budget?.reside(\"photo\", \"thumbnails\", this.thumbs.usedBytes); }\n\n private chargeDetail(p: Held): void {\n const d = p.detail;\n if (d === null) return;\n this.budget?.charge(\"photo\", `detail ${p.id}`, d.bytes, () => { this.evicted += 1; this.setDetail(p, null, false); this.onReady(); });\n }\n\n /** A picture's whole chain from its level 0 (as it always was made: written or copied, then mips.ts). */\n private chain(first: DecodedPicture): GPUTexture {\n const { width, height } = first;\n const texture = this.device.createTexture({\n label: `photo/picture ${width}×${height}`, size: [width, height], format: \"rgba8unorm-srgb\", mipLevelCount: mipCount(width, height),\n usage: USAGE_CHAIN(), viewFormats: [\"rgba8unorm\"],\n });\n if (first.kind === \"rgba\") this.device.queue.writeTexture({ texture }, first.bytes, { bytesPerRow: width * 4 }, [width, height, 1]);\n else this.device.queue.copyExternalImageToTexture({ source: first.source as ImageBitmap }, { texture, premultipliedAlpha: false }, [width, height]);\n if (mipCount(width, height) > 1) generateMips(this.device, texture);\n return texture;\n }\n\n /** The levels of `from` (a chain from level `fromBase`) from level `base` down, in a texture of their own — a device copy. */\n private cutChain(from: GPUTexture, fromBase: number, base: number, p: Held): Detail {\n const w = Math.max(p.width >> base, 1);\n const h = Math.max(p.height >> base, 1);\n const levels = p.mips - base;\n const texture = this.device.createTexture({ label: `photo/detail ${p.width}×${p.height} from ${base}`, size: [w, h], format: \"rgba8unorm-srgb\", mipLevelCount: levels, usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC });\n const enc = this.device.createCommandEncoder({ label: \"photo/detail cut\" });\n for (let m = 0; m < levels; m++) enc.copyTextureToTexture({ texture: from, mipLevel: base - fromBase + m }, { texture, mipLevel: m }, [Math.max(w >> m, 1), Math.max(h >> m, 1), 1]);\n this.device.queue.submit([enc.finish()]);\n return { texture, view: texture.createView(), base, bytes: chainBytes(w, h, levels) };\n }\n\n /** Replace `p`'s detail (null: none): the old destroyed and released, the new charged; a slot binding it is rebound. */\n private setDetail(p: Held, d: Detail | null, release = true): void {\n const old = p.detail;\n if (old === d) return;\n p.detail = d;\n p.tier += 1;\n if (old !== null) { old.texture.destroy(); if (release) this.budget?.release(\"photo\", `detail ${p.id}`); }\n if (d !== null) this.chargeDetail(p);\n if (p.slot >= 0) {\n if (d === null) { this.slots[p.slot] = null; p.slot = -1; }\n this.group = this.bind();\n }\n }\n\n /**\n * The finest level from `base` whose chain the budget's ROOM holds beside the other bound details — so the details alone never\n * hold more than the caches' room (K9 R2: the thumbnails reside outside it and pin nothing here; before, they were counted and\n * past ~128 pictures no detail could ever be afforded); null when not even the coarsest detail fits (the thumbnail serves, a\n * little soft). The other owners' rasters are the budget's LRU to trim, as before.\n */\n private afford(p: Held, base: number): number | null {\n const b = this.budget;\n if (b === undefined) return base;\n let pinned = 0;\n for (const q of this.slots) if (q !== null && q !== p && q.detail !== null) pinned += q.detail.bytes;\n const room = b.room() - pinned;\n for (let j = base; j < p.base; j++) if (chainBytes(Math.max(p.width >> j, 1), Math.max(p.height >> j, 1), p.mips - j) <= room) return j;\n return null;\n }\n\n /** Fetch `p`'s level 0 again and make its detail from level `base` — or the finest the budget affords — unless one that fine is on its way, or BUILDS are. */\n private fetch(p: Held, want: number): void {\n const base = this.afford(p, want);\n if (base === null || (p.detail !== null && p.detail.base <= base)) return;\n if (p.building <= base || this.inflight >= BUILDS) return;\n p.building = base;\n this.inflight += 1;\n const done = (): void => { this.inflight -= 1; if (p.building === base) p.building = Number.POSITIVE_INFINITY; };\n p.source().then((first) => {\n done();\n if (first === undefined) return;\n try {\n if (p.dropped || (p.detail !== null && p.detail.base <= base)) return;\n const chain = this.chain(first);\n if (base === 0) this.setDetail(p, { texture: chain, view: chain.createView(), base: 0, bytes: chainBytes(p.width, p.height, p.mips) });\n else { this.setDetail(p, this.cutChain(chain, 0, base, p)); chain.destroy(); }\n this.built += 1;\n this.onReady();\n } finally { if (first.kind === \"source\") first.close?.(); }\n }, done);\n }\n\n /** `p`'s detail cut down to level `base` (it zoomed out): a copy of what it samples, the finer levels let go. */\n private cutTo(p: Held, base: number): void {\n const d = p.detail as Detail;\n this.setDetail(p, this.cutChain(d.texture, d.base, base, p));\n this.cut += 1;\n }\n}\n","// The photo pass — the prints, a run of them ONE instanced draw (K6a, K-L4). Owns\n// its knobs and the record buffer (the camera and the light are the slot's view\n// block, K4a); shares — with every slot spawned from the first — the pipeline,\n// the samplers and the PICTURES (pictures.ts): each picture's mip chain made from\n// whatever the host decoded (a pasted image, a dropped file), its tail a layer of\n// one THUMBNAIL array, and a print large on screen its DETAIL bound in a pool\n// slot — all of it group 1, the same for every print, so a print's record says\n// where its pixels are and a picture made once draws in any slot.\n// A slot reads its OWN mat's animated silhouette and blue noise, so a print is\n// dappled by the same palm as the mat under it — and a slot lit from elsewhere\n// (a mini mat's inside: MINIMAT.md §4) takes the lamp of the desk it lies on,\n// through a second pipeline (`LIT_ELSEWHERE`, the note's precedent). The pass\n// draws in RANGES of the prints it was handed (design-015 §4.2): the desk's runs.\n\nimport { bindGroup, bindLayout, renderPipeline, uniformBuffer, compile, compose } from \"@ice/desk/engine\";\nimport { createRecordStore, type RasterBudget, type RecordStore } from \"@ice/desk\";\nimport { type FadeIn, type View, litByOwn, type MatConfig, type MatFrame, type SlotLight, type MatPass, type Presentation, DAY_LIGHT, type MatLight, sentBytes, writeChanged } from \"@ice/desk/kit\";\nimport { MAX_PHOTOS, Photo, PhotoUniforms, photoUniformValues, photoValues } from \"./layout\";\nimport { type Picture, PictureStore, type PictureSource, type PictureStats, pictureLod } from \"./pictures\";\nimport { PHOTO, type PhotoGeometry, type PhotoLaw } from \"./photo\";\nimport type { PhotoShaders } from \"./shaders\";\n\n/** Premultiplied \"source over\". */\nconst BLEND_PREMUL: GPUBlendState = {\n color: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n alpha: { srcFactor: \"one\", dstFactor: \"one-minus-src-alpha\", operation: \"add\" },\n};\n\n/** The largest side a picture keeps on the device — a 6×4 print at zoom 5 on a 2× screen. */\nexport const PICTURE_MAX = 4096;\n\nexport type { Picture } from \"./pictures\";\n\n/** One print for the pass: its resolved pose, its border's width, its picture. */\nexport interface PhotoInstance {\n readonly geometry: PhotoGeometry;\n readonly border: number;\n readonly picture: Picture | null;\n}\n\n/** What every slot's pass shares with the root's: the layout, the pipeline, the samplers — and the pictures (group 1). */\ninterface PhotoShared {\n readonly layout0: GPUBindGroupLayout;\n readonly pipeline: GPURenderPipeline;\n /** The same, for a slot lit from elsewhere — a mini mat's inside, a handover (MINIMAT.md §4): `LIT_ELSEWHERE` is a pipeline constant. */\n readonly litPipeline: GPURenderPipeline;\n readonly goboSampler: GPUSampler;\n readonly noiseSampler: GPUSampler;\n readonly picSampler: GPUSampler;\n /** The pictures: the thumbnail array, the details, the pool (pictures.ts) — group 1 of every slot. */\n readonly pictures: PictureStore;\n slots: number;\n}\n\nexport class PhotoPass {\n readonly name = \"photo/prints\";\n private readonly knobs = PhotoUniforms.alloc(1);\n /** The prints' PERSISTENT records (engine/records.ts, design-015 §4.3; D6): a slot per print while drawn, written when it changed. */\n private readonly store: RecordStore<PhotoInstance>;\n /** The records the last prepare turned away at the pass's cap — not drawn; the ground reports them (`GroundStats.dropped`, D7). */\n dropped = 0;\n private readonly knobBuf: GPUBuffer;\n /** What the GPU holds of the knobs: they are written only when they change (K4a — a standing value costs a frame nothing). */\n private readonly knobsSent = sentBytes(PhotoUniforms.size);\n private group!: GPUBindGroup;\n private bound = -1;\n private boundStore = -1;\n /** This frame's prints, in the order `prepare` was handed them — what `drawRange` counts in. */\n private count = 0;\n /** This frame's slot is lit from elsewhere: it draws with the second pipeline. */\n private litElsewhere = false;\n /** The print's numbers (photo.ts `PHOTO`) — a host tunes the root's copy; every slot takes it (`tune`). */\n law: PhotoLaw = PHOTO;\n private readonly device: GPUDevice;\n private readonly shared: PhotoShared;\n private readonly mat: MatPass;\n\n private constructor(device: GPUDevice, shared: PhotoShared, mat: MatPass) {\n this.device = device; this.shared = shared; this.mat = mat;\n shared.slots += 1;\n this.knobBuf = uniformBuffer(device, PhotoUniforms.size, \"photo/knobs\");\n this.store = createRecordStore<PhotoInstance, keyof typeof Photo.slots>({\n device, def: Photo, capacity: MAX_PHOTOS, max: MAX_PHOTOS * 64, label: \"photo/prints\",\n // (a print's picture's tier — its detail's slot and cut — is the `aux` the change test folds in: a detail bound or let go repacks it)\n pack: (p, _aux, into, slot) => { into.set(photoValues(p.geometry, p.border, p.picture), slot); return 0; },\n });\n this.rebind();\n }\n\n /** The root's pass, on the root's mat (its silhouette and noise). */\n static async create(device: GPUDevice, format: GPUTextureFormat, src: PhotoShaders, mat: MatPass): Promise<PhotoPass> {\n const layout0 = bindLayout(device, [\n { binding: 0, stages: [\"vertex\", \"fragment\"], buffer: \"uniform\" },\n { binding: 1, stages: [\"fragment\"], buffer: \"uniform\" },\n { binding: 2, stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" },\n { binding: 3, stages: [\"fragment\"], texture: \"float\" },\n { binding: 4, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 5, stages: [\"fragment\"], texture: \"float\" },\n { binding: 6, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 7, stages: [\"fragment\"], sampler: \"filtering\" },\n { binding: 8, stages: [\"vertex\"], buffer: \"read-only-storage\" }, // the draw list: paint index → record slot (D6)\n ], \"photo/prints\");\n const pictures = new PictureStore(device);\n const module = await compile(device, compose(src));\n const pl = device.createPipelineLayout({ bindGroupLayouts: [layout0, pictures.layout] });\n const [pipeline, litPipeline] = await Promise.all([\n renderPipeline(device, { label: \"photo/prints\", layout: pl, module, format, blend: BLEND_PREMUL }),\n renderPipeline(device, { label: \"photo/prints, lit from elsewhere\", layout: pl, module, format, blend: BLEND_PREMUL, constants: { LIT_ELSEWHERE: 1 } }),\n ]);\n const shared: PhotoShared = {\n layout0, pipeline, litPipeline,\n goboSampler: device.createSampler({ label: \"photo/gobo\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" }),\n noiseSampler: device.createSampler({ label: \"photo/noise\", magFilter: \"linear\", minFilter: \"linear\", addressModeU: \"repeat\", addressModeV: \"repeat\" }),\n picSampler: device.createSampler({ label: \"photo/picture\", magFilter: \"linear\", minFilter: \"linear\", mipmapFilter: \"linear\", addressModeU: \"clamp-to-edge\", addressModeV: \"clamp-to-edge\" }),\n pictures, slots: 0,\n };\n return new PhotoPass(device, shared, mat);\n }\n\n /** A second slot on the same pipeline, samplers and pictures, reading ITS mat's silhouette and noise — a mini mat's inside, a flight's departed desk. */\n spawn(mat: MatPass): PhotoPass {\n const p = new PhotoPass(this.device, this.shared, mat);\n p.law = this.law;\n return p;\n }\n\n /** Take the root's law — what every spawned slot does each frame. */\n tune(from: PhotoPass): void { this.law = from.law; }\n\n private rebind(): void {\n if (this.bound === this.mat.assetVersion && this.boundStore === this.store.version) return;\n const s = this.shared;\n this.group = bindGroup(this.device, s.layout0, [this.mat.view, this.knobBuf, this.store.records, this.mat.silhouette, s.goboSampler, this.mat.noiseTexture.createView(), s.noiseSampler, s.picSampler, this.store.order], \"photo/prints\");\n this.bound = this.mat.assetVersion;\n this.boundStore = this.store.version;\n }\n\n /**\n * A picture from raw sRGB rgba8 bytes (row 0 = top, straight alpha) — what a Node host or a test hands in. A picture is\n * the PASS's resource, shared by every slot: a print's record names it by this handle (`PhotoInstance.picture`), and it\n * lives until the host drops it (`dropPicture`). The bytes are kept (by reference) to make a detail from; null when the\n * thumbnail array holds no more pictures (the device's layers — the print draws its paper alone).\n */\n picture(bytes: Uint8Array<ArrayBuffer>, width: number, height: number): Picture | null {\n const raw = { kind: \"rgba\", bytes, width, height } as const;\n return this.shared.pictures.make(raw, async () => raw);\n }\n\n /**\n * A picture from a decoded image (a pasted or dropped file, an `<img>`, a canvas) — the browser's path; `again` decodes it\n * afresh for a print large on screen (its detail) — without it the picture keeps its thumbnail alone.\n */\n pictureFrom(source: ImageBitmap | HTMLCanvasElement | OffscreenCanvas | HTMLImageElement, width: number, height: number, again?: PictureSource): Picture | null {\n return this.shared.pictures.make({ kind: \"source\", source, width, height }, again ?? (async () => undefined));\n }\n\n /** A picture no print names any more: its layer given back, its detail destroyed. */\n dropPicture(p: Picture): void { this.shared.pictures.drop(p); }\n\n /**\n * THE RESIDENCY's frame boundary (pictures.ts `step` — the kind's tick, before the build): details bound, fetched, cut or let\n * go for what the last frame's prints asked. True when a print's tier moved (the desk must draw again).\n */\n residency(): boolean { return this.shared.pictures.step(); }\n /** The last frame's asks still unanswered (K7a): the next tick owes them a `residency` step — a detail fetched, a slot freed. */\n get residencyOwed(): boolean { return this.shared.pictures.pending(); }\n\n /** The pictures under the desk's budget (the kind's host lends it) — and its ask of what stays. */\n budget(budget: RasterBudget | undefined): void { this.shared.pictures.attach(budget); }\n keeps(key: string): boolean { return this.shared.pictures.keeps(key); }\n /** A detail landed or was evicted (async): `wake` asks the desk for a frame. */\n set onPictures(wake: () => void) { this.shared.pictures.onReady = wake; }\n /** The pictures' counters (a rig's witness): thumbnails, details, slots, bytes. */\n get pictureStats(): PictureStats { return this.shared.pictures.stats(); }\n\n /**\n * Upload this frame's prints in paint order (first = lowest) and the mat's block for this slot's camera,\n * its light (`light` the Sun or the Moon, `lit` the lamp it is seen by — MINIMAT.md §4): the dapple falls\n * on the prints. Returns the count that will draw.\n */\n prepare(view: View & { readonly dpr: number }, fadeIn: FadeIn, cfg: MatConfig, frame: MatFrame | undefined, prints: readonly PhotoInstance[], present?: Presentation, light: MatLight = DAY_LIGHT, lit?: SlotLight, keys?: readonly number[], hand = false): number {\n const cap = MAX_PHOTOS * 64;\n const list = prints.length > cap ? prints.slice(0, cap) : prints;\n this.dropped = prints.length - list.length;\n // the store (D6): a print keyed by `keys[i]` keeps its slot and is written only when its record changed; no keys = every one packed\n const n = this.store.prepare(list, keys !== undefined && keys.length > cap ? keys.slice(0, cap) : keys, (i) => list[i]?.picture?.tier ?? 0);\n this.rebind(); // after: the store's buffers may have grown\n this.count = list.length;\n // K7b: the prints the flat-card pipeline draws — every one whose picture has no detail bound (the card reads the thumbnails alone)\n if (this.cards.length < list.length) this.cards = new Int32Array(Math.max(list.length, this.cards.length * 2));\n for (let i = 0; i < list.length; i++) this.cards[i] = (list[i]?.picture?.slot ?? -1) < 0 ? this.store.slotAt(i) : -1;\n // each print ON SCREEN asks for its picture at the lod it samples it (pictures.ts): the residency's next step answers — a\n // print in the cull's margin asks nothing (its thumbnail stands; a detail is the screen's, never a prefetch)\n const pics = this.shared.pictures;\n // K9 R4 — THE HAND's prepare (the carried print alone, every frame of the carry): the desk copy behind it stands as it was\n // prepared, so its prints ask nothing this frame — the details they hold are re-asked here at the lod they were granted, or\n // the step would free every one of them (a softness pop on every put-down; over the cap, a detail behind the hand evictable)\n if (hand) pics.keepSlotted();\n const zd = view.zoom * view.dpr;\n const x0 = view.camX;\n const y0 = view.camY;\n const x1 = x0 + view.width / view.zoom;\n const y1 = y0 + view.height / view.zoom;\n for (const p of list) {\n const pic = p.picture;\n const G = p.geometry;\n if (pic === null || G.alpha <= 0 || G.bounds.x1 < x0 || G.bounds.x0 > x1 || G.bounds.y1 < y0 || G.bounds.y0 > y1) continue;\n pics.ask(pic, pictureLod(pic.width, pic.height, [G.half[0] - p.border, G.half[1] - p.border], zd, 1));\n }\n this.litElsewhere = !litByOwn(view, lit);\n this.knobs.set(photoUniformValues(this.law));\n writeChanged(this.device.queue, this.knobBuf, this.knobs, this.knobsSent);\n return n;\n }\n\n /** The store's counters (a rig's witness): records written, bytes, draw-list writes, slots in use. */\n get records() { return this.store.stats(); }\n\n /** K7b: record `index` of the last prepare drawn by the flat-card pipeline — its slot in the store — or −1: a detail is bound, the pass draws it. */\n cardSlot(index: number): number { return index < this.count ? (this.cards[index] as number) : -1; }\n private cards = new Int32Array(64);\n\n /** K7b: this slot's resources for the print's card material (shaders.ts `photoCard`), in its bindings' order — made again when the store or the thumbnails grew. */\n cardResources(): { readonly version: number; readonly resources: readonly (GPUBuffer | GPUTextureView | GPUSampler)[] } {\n const t = this.shared.pictures.thumbView();\n if (this.card === null || this.cardOver[0] !== this.store.version || this.cardOver[1] !== t.version) {\n const s = this.shared;\n this.cardOver = [this.store.version, t.version];\n this.card = { version: (this.card?.version ?? 0) + 1, resources: [this.knobBuf, this.store.records, s.goboSampler, s.noiseSampler, s.picSampler, t.view] };\n }\n return this.card;\n }\n private card: { readonly version: number; readonly resources: readonly (GPUBuffer | GPUTextureView | GPUSampler)[] } | null = null;\n private cardOver: readonly number[] = [];\n\n get drawn(): number { return this.count; }\n\n /** Every print prepared this frame, into a pass the caller opened: `drawRange` over the whole list. */\n draw(pass: GPURenderPassEncoder): void { this.drawRange(pass, 0, this.count); }\n\n /**\n * The prints `prepare` was handed at [first, end) — indices into ITS list, as the ground's runs count a kind's records —\n * as ONE instanced draw (K6a, K-L4): the slot's group and the pictures' bound once, on the pipeline for the slot's light,\n * each print an instance whose record says where its pixels are. An empty range records nothing, not even the pipeline.\n */\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void {\n const hi = Math.min(end, this.count);\n if (first >= hi) return;\n pass.setPipeline(this.litElsewhere ? this.shared.litPipeline : this.shared.pipeline);\n pass.setBindGroup(0, this.group);\n pass.setBindGroup(1, this.shared.pictures.group);\n pass.draw(6, hi - first, 0, first);\n }\n\n /** This slot's buffers; the pictures go with the last slot standing (a host's pictures are the host's to drop until then). */\n dispose(): void {\n this.knobBuf.destroy(); this.store.dispose();\n const s = this.shared;\n s.slots -= 1;\n if (s.slots === 0) s.pictures.dispose();\n }\n}\n","// Assemble the photo pass's program from the host's shader text — the browser's generated module, a Node host's files\n// on disk. The kit brings the slot's view block, the portal chain, the card's primitives and the mat's light\n// (kit/wgsl.ts, by name); the print's own records, module and entry follow.\n\nimport type { CardMaterial } from \"@ice/desk\";\nimport type { ComposeOptions } from \"@ice/desk/engine\";\nimport { kitWgsl, type ShaderText } from \"@ice/desk/kit\";\nimport { Photo, PhotoUniforms } from \"./layout\";\n\n/** The print's own shader files (the kit's pieces come by name). */\nexport const PHOTO_SHADER_FILES = { photo: \"photo/photo.wgsl\", photoCard: \"photo/photo-card.wgsl\", photoPass: \"photo/photo-pass.wgsl\" } as const;\n\n/** The photo pass's program: the kit's view · portal · sdf · light, then the print's records, module and entry. */\nexport type PhotoShaders = ComposeOptions;\n\nexport function photoShaders(text: ShaderText): PhotoShaders {\n const t = text(PHOTO_SHADER_FILES);\n return kitWgsl([\"view\", \"portal\", \"sdf\", \"light\"], {\n structs: [PhotoUniforms, Photo],\n modules: [{ label: \"photo/photo.wgsl\", text: t.photo }, { label: \"photo/photo-card.wgsl\", text: t.photoCard }],\n entry: { label: \"photo/photo-pass.wgsl\", text: t.photoPass },\n }, text);\n}\n\n/**\n * The print's CARD MATERIAL (K7b, design-016 §6 K7): the flat-card pipeline draws a print with photo-card.wgsl's quad and\n * fragment over the photo pass's own records, knobs, samplers and the thumbnail array (`PhotoPass.cardResources`, in this\n * order) — every print whose picture has no detail bound (the card binds no pool: its `photo_texel` is the thumbnail's).\n */\nexport function photoCard(text: ShaderText): CardMaterial {\n return {\n shaders: () => {\n const t = text(PHOTO_SHADER_FILES);\n return kitWgsl([\"view\", \"portal\", \"sdf\", \"light\"], {\n structs: [PhotoUniforms, Photo],\n modules: [{ label: \"photo/photo.wgsl\", text: t.photo }],\n entry: { label: \"photo/photo-card.wgsl\", text: t.photoCard },\n }, text);\n },\n only: \"fn photo_texel(P: Photo, uv: vec2f, lod: f32) -> vec4f { return photo_thumb(P, uv, lod); } // the card binds no detail pool\",\n bindings: [\n { wgsl: \"var<uniform> photo_k: PhotoUniforms\", entry: { stages: [\"fragment\"], buffer: \"uniform\" } },\n { wgsl: \"var<storage, read> photos: array<Photo>\", entry: { stages: [\"vertex\", \"fragment\"], buffer: \"read-only-storage\" } },\n { wgsl: \"var photo_gobo_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var photo_noise_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var photo_pic_samp: sampler\", entry: { stages: [\"fragment\"], sampler: \"filtering\" } },\n { wgsl: \"var photo_thumbs: texture_2d_array<f32>\", entry: { stages: [\"fragment\"], texture: \"float\", dimension: \"2d-array\" } },\n ],\n quad: \"photo_quad\",\n frag: \"photo_frag\",\n };\n}\n","// The PHOTO print (PHOTO.md) as a kind (kind.ts): the photo pass behind the registry's door — a\n// thin adapter, the pass and its WGSL as they were. Stratum `things`: a print lies among the\n// desk's other things in the desk's own order (a print on a note, a note on a print) — in the\n// prototype the prints lay above everything, drawn by the photo lab in a render pass of their\n// own after the ground's; here they are one more kind's runs in the ground's one pass, with the\n// same blend onto the same bytes. A spawned slot's pass takes the root's law every frame (`tune`), and a\n// print inside a mini mat's face is lit by the lamp of the desk the mini mat lies on (the slot's `lit` —\n// MINIMAT.md §4), through the pass's second pipeline, as the note's is.\n// The PICTURES stay the pass's: a host makes one (`pass.picture`, `pass.pictureFrom`) and a\n// print's record names it by that handle (`PhotoInstance.picture`, null = its paper alone).\n//\n// And its WORLD half (kinds/world.ts; D3w): `photoKind` — a print is a BODY (photo/photo.ts `PhotoBody`, the\n// prototype's), resolved by `resolvePhoto` under the desk's lamp. At rest the body IS the facts: its centre the\n// rect's, its turn the `angle` prop, its edge lifted `hover` × the builder's hover flux (PHOTO.md: 2.2 units),\n// its extent the picture's aspect at the law's long side (`printExtent`). Carried, flicked or gliding, the body\n// LEADS — the carry (objects/carry.ts) holds it on the finger (the kinematic pin), lets it go with the flick\n// of the last 70 ms, and the kind's own state on the desk (`local()` → `Prints`) steps it at 240 Hz through\n// the air and the mat's Coulomb grip; when it comes to rest the carry commits ONE transaction and the body\n// hands back to the facts once they show it. A fading ghost lifts as it goes (its `leave`). The PICTURE is\n// the world half's too (D-D3r-a.2): the `blob` prop names bytes in the app's BlobStore (D-D12), fetched and\n// decoded the first time a print is met — raw RGBA by the kind, anything else through the host's decoder —\n// into one pass `Picture` per blob, shared by every print of it and dropped with the last. `hitPhoto` is the\n// mirror, through the same local eye the pass draws with.\n\nimport { SAMPLE_PICTURE, samplePicture } from \"./sample\";\nimport type { Entity } from \"@ice/core\";\nimport { type KindExtra, type KindPass, type KindProgram, type SlotContext, type KindHost, type KindLocal, numberProp, type ObjectContext, type ObjectHit, type ObjectKind, type ObjectRect, stringProp } from \"@ice/desk\";\nimport { type MarkFrame, type MatPass, type DecodedPicture, RGBA_TYPE, carryOf, type ShaderText, BLOB_STORE, PICTURE_DECODER } from \"@ice/desk/kit\";\nimport { borderOf } from \"./layout\";\nimport { grab, hitPhoto, moveHold, newBody, PHOTO, type PhotoBody, type PhotoGeometry, type PhotoLaw, printSize, release, resolvePhoto, restless, stepPhoto, twist } from \"./photo\";\nimport { type Picture, PICTURE_MAX, type PhotoInstance, PhotoPass } from \"./photo-pass\";\nimport type { PictureStats } from \"./pictures\";\nimport { PHOTO_SHADER_FILES, photoCard, photoShaders } from \"./shaders\";\nimport { shaderText } from \"../shaders\";\n\n/** The print's kind name — its key in the registry and in every slot's `objects`. */\nexport const PHOTO_KIND = \"photo\";\n\nexport class PhotoKind implements KindPass<PhotoInstance> {\n /** The photo pass itself: a host's door to the pictures (`picture`, `pictureFrom`, `dropPicture`) and the print's law (`law`). */\n readonly pass: PhotoPass;\n constructor(pass: PhotoPass) { this.pass = pass; }\n\n spawn(mat: MatPass): PhotoKind { return new PhotoKind(this.pass.spawn(mat)); }\n\n tune(root: KindPass<PhotoInstance>): void { if (root instanceof PhotoKind) this.pass.tune(root.pass); }\n\n /** The pass's own `prepare`, argument for argument: the slot's camera, grid, clocks, the objects' presence, the light, the lamp — and the records' keys (D6). */\n prepare(_encoder: GPUCommandEncoder, s: SlotContext, records: readonly PhotoInstance[], extra?: KindExtra): number {\n return this.pass.prepare(s.view, s.fadeIn, s.cfg, s.frame, records, s.present, s.light, s.lit, extra?.keys, s.target === \"hand\");\n }\n\n dropped(): number { return this.pass.dropped; }\n\n /** Records [first, end) — indices into the prints `prepare` was handed, each drawn with its picture. */\n drawRange(pass: GPURenderPassEncoder, first: number, end: number): void { this.pass.drawRange(pass, first, end); }\n records() { return this.pass.records; }\n cardResources() { return this.pass.cardResources(); }\n cardSlot(index: number): number { return this.pass.cardSlot(index); }\n\n dispose(): void { this.pass.dispose(); }\n}\n\n/** The print's program for a host's shader text: its pass made on the root's mat. */\nexport function photoProgram(text: ShaderText): KindProgram<PhotoInstance> {\n return {\n name: PHOTO_KIND,\n stratum: \"things\",\n card: photoCard(text),\n create: async (device, format, mat) => new PhotoKind(await PhotoPass.create(device, format, photoShaders(text), mat)),\n };\n}\n\n/** The print's silhouette for the desk's marks (D4a): the sheet's own axes on the desk plane (its height's parallax aside), its corner. */\nexport function photoFrame(G: PhotoGeometry): MarkFrame {\n return { cx: G.centre[0], cy: G.centre[1], hx: G.half[0], hy: G.half[1], angle: Math.atan2(G.ex[1], G.ex[0]), r: G.radius };\n}\n\n// ---------------------------------------------------------------- the world half (D3w)\n\n/** A print's extent on the desk, world units: its picture's aspect at the law's long side (the lab's `addPicture`); 3:2 without one. */\nexport const printExtent = (width: number, height: number, long: number = PHOTO.long): { readonly w: number; readonly h: number } =>\n width > 0 && height > 0 ? printSize(width, height, long) : printSize(3, 2, long);\n\n/**\n * How far a print's drawing reaches past its rect, world units: the leave's height (1.6 × the lift) and the held droop cast\n * along the lamp's capped slope and blurred, and the local eye's scale of a sheet at that height about its far corner.\n */\nexport function photoReach(law: PhotoLaw = PHOTO): number {\n const h = law.lift * 1.6 + law.bend.held;\n const p = law.shadow.penumbra;\n const shadow = p.slopeMax * h + 3 * (p.sigma0 + p.sigmaPerHeight * h) + 2 * law.bend.held + 4;\n const scale = (law.long / 2) * Math.SQRT2 * (law.eye / (law.eye - law.lift * 1.6) - 1);\n return shadow + scale;\n}\n\n/** A print's pose as a still pins it (a FLUX pin, never a Grab — D-D2a-world.5): its height, slope, bend, anchor and the hand holding it. */\nexport interface PhotoPose {\n readonly h?: number;\n readonly sx?: number;\n readonly sy?: number;\n readonly bend?: number;\n readonly ax?: number;\n readonly ay?: number;\n readonly hold?: { readonly gx: number; readonly gy: number; readonly px: number; readonly py: number };\n}\n\n/** A print that came to rest where its facts are not — ONE transaction's worth for the carry: its centre, world units, and its turn (the wheel twists a carried print, D3t-a). */\nexport interface PrintRest { readonly entity: Entity; readonly x: number; readonly y: number; readonly angle: number }\n\n/** A flick's witness: the body as the hand let it go, and every step the desk took with it since (the law replays them). */\nexport interface FlickWitness { readonly body: PhotoBody; readonly dts: number[]; landed: { readonly x: number; readonly y: number } | null }\n\n/** The photo kind's own state on one desk: the prints' bodies, their pictures, the carry's door. */\nexport interface Prints extends KindLocal {\n /** When the kind is next live (K7a — `KindLocal.due`, declared: the six built-ins all say). */\n due(now: number): number;\n /** The hand takes print `e` at a world point (the carry); a body at rest is lifted off its facts. */\n hold(e: Entity, wx: number, wy: number, t: number): void;\n /** The hand moved (world, t seconds) — the grab point follows it exactly. */\n move(e: Entity, wx: number, wy: number, t: number): void;\n /** The hand let go: the flick from the last 70 ms, capped; the body glides from here. */\n drop(e: Entity, t: number): void;\n /**\n * The carry was CANCELLED (Esc — D3t-a): the hand lets go and the print flies back to where it began — its facts, its turn —\n * in `PRINT_RETURN_MS` on the island ease, landing there; nothing is committed.\n */\n cancel(e: Entity, t: number): void;\n /** The wheel turns a carried print about the finger (PHOTO.md), radians; a print in the air takes it as spin. */\n twist(e: Entity, da: number): void;\n /** The print is drawn LIFTED — in a hand, in the air, flying home, its rest not yet in the facts (the builder paints it on top). */\n lifted(e: Entity): boolean;\n /** Prints that came to rest away from their facts since the last ask — the carry commits each in ONE transaction. */\n rests(): PrintRest[];\n /** How many rests wait to be asked for (D7 #14: the carry never idles over one). */\n owed(): number;\n /** The carry committed `e`'s rest (or could not): the body leads until the facts show it (or a second runs out). */\n settle(e: Entity, committed: boolean): void;\n /** A still's pose on `e` (undefined unpins). */\n pin(e: Entity, pose: PhotoPose | undefined): void;\n /** A print just laid by a paste or a drop arrives: it falls from `arrive` onto its place and fades in (PHOTO.md §3). */\n arrive(e: Entity): void;\n /** Fetch, decode and upload a blob's picture before a print names it (a scene's still); resolves once it is on the device. */\n preload(hash: string, width: number, height: number): Promise<void>;\n /** Print `e`'s body as it is now — a copy (a rig's witness); undefined for a print never met. */\n body(e: Entity): PhotoBody | undefined;\n /** The last flick of print `e` — a copy. */\n flick(e: Entity): FlickWitness | undefined;\n /** The pictures: on the device, on their way, missing from the store or undecodable — and where they are resident (K6a: thumbnails, details, slots). */\n pictures(): { readonly ready: number; readonly loading: number; readonly failed: number; readonly resident?: PictureStats };\n /** The world half's: the body to resolve for this frame (the facts at rest, the live body while it leads). */\n bodyFor(ctx: ObjectContext, hx: number, hy: number): PhotoBody;\n /** The world half's: the picture a print's `blob` names (null while it loads, or without one). */\n pictureFor(e: Entity, hash: string, width: number, height: number): Picture | null;\n}\n\ninterface Print {\n body: PhotoBody;\n /** The body leads the facts: held, gliding, arriving, or its rest committed and not yet in the facts. */\n leads: boolean;\n /** The rest was handed to the carry (queued or committed); the clock at the commit, −1 before it. */\n resting: boolean;\n committedAt: number;\n /** The perspective's anchor, kept after a hold (PHOTO.md: \"kept after\"). */\n ax: number;\n ay: number;\n pose: PhotoPose | undefined;\n flick: FlickWitness | undefined;\n /** The blob the print draws, for the picture's user count. */\n hash: string;\n /** Where its facts put its centre and its turn, as last resolved. */\n fx: number;\n fy: number;\n fa: number;\n /** A cancelled carry's flight home (D3t-a): where it began, when; null otherwise. */\n back: { readonly x: number; readonly y: number; readonly angle: number; readonly h: number; readonly t0: number } | null;\n}\n\ninterface Pic {\n picture: Picture | null;\n state: \"loading\" | \"ready\" | \"failed\";\n readonly users: Set<Entity>;\n /** A preload holds it until a print takes it. */\n held: boolean;\n load: Promise<void>;\n}\n\n/** A cancelled carry's flight home, ms (D3t-a) — the put-down's own length (design-015 §8: 440 ms home), on the hand's island ease. */\nexport const PRINT_RETURN_MS = 440;\n\nconst copyBody = (b: PhotoBody): PhotoBody => ({ ...b, hold: b.hold ? { ...b.hold, trail: b.hold.trail.map((s) => [...s] as [number, number, number]) } : null });\nconst near = (a: number, b: number): boolean => Math.abs(a - b) < 1e-6;\n\n/** The photo kind's `local()` on one desk. */\nexport function createPrints(host: KindHost, law: PhotoLaw = PHOTO): Prints {\n const prints = new Map<Entity, Print>();\n /** The prints whose body LEADS (in a hand, in the air, flying home, arriving) — the ones the tick steps (D6: never every print). */\n const leading = new Set<Entity>();\n const pics = new Map<string, Pic>();\n /** What has LANDED on each object, counted (D7 — `KindLocal.landed`): the held desk copy is made again when a desk object's moves. */\n const landedOf = new Map<Entity, number>();\n const land = (e: Entity): void => { landedOf.set(e, (landedOf.get(e) ?? 0) + 1); };\n const queue: PrintRest[] = [];\n let last = -1;\n let woke = false;\n let attached = false;\n const passOf = (): PhotoPass | undefined => { const k = host.pass(); return k instanceof PhotoKind ? k.pass : undefined; };\n\n /** A body at rest where the facts say: the rect's centre, the prop's turn, the builder's hover lifting its edge. */\n const restBody = (ctx: ObjectContext, hx: number, hy: number, pr: Print | undefined): PhotoBody => {\n const b = newBody(ctx.rect.cx, ctx.rect.cy, 2 * hx, 2 * hy, numberProp(ctx.props, \"angle\", 0), law.hover * ctx.flux.hover);\n b.ax = pr?.ax ?? 0;\n b.ay = pr?.ay ?? 0;\n return b;\n };\n const withPose = (b: PhotoBody, pose: PhotoPose | undefined): PhotoBody => {\n if (pose === undefined) return b;\n if (pose.h !== undefined) b.h = pose.h;\n if (pose.sx !== undefined) b.sx = pose.sx;\n if (pose.sy !== undefined) b.sy = pose.sy;\n if (pose.bend !== undefined) b.bend = pose.bend;\n if (pose.ax !== undefined) b.ax = pose.ax;\n if (pose.ay !== undefined) b.ay = pose.ay;\n if (pose.hold !== undefined) { const H = pose.hold; b.hold = { gx: H.gx, gy: H.gy, px: H.px, py: H.py, vx: 0, vy: 0, ax: 0, ay: 0, trail: [[0, H.px, H.py]] }; }\n return b;\n };\n const print = (e: Entity): Print => {\n let pr = prints.get(e);\n if (pr === undefined) {\n pr = { body: newBody(0, 0, 1, 1), leads: false, resting: false, committedAt: -1, ax: 0, ay: 0, pose: undefined, flick: undefined, hash: \"\", fx: Number.NaN, fy: Number.NaN, fa: 0, back: null };\n prints.set(e, pr);\n }\n return pr;\n };\n /** Print `e` stops naming `hash`: the picture goes with its last print (a preload holds it until one takes it). */\n const unuse = (e: Entity, hash: string): void => {\n const pic = pics.get(hash);\n if (pic === undefined) return;\n pic.users.delete(e);\n if (pic.users.size > 0 || pic.held) return;\n if (pic.picture !== null) passOf()?.dropPicture(pic.picture);\n pics.delete(hash);\n };\n /** A blob's picture fetched and decoded: raw RGBA by the kind, anything else through the host's decoder (≤ PICTURE_MAX). */\n const decodeOf = async (hash: string, width: number, height: number): Promise<DecodedPicture | undefined> => {\n // the kind's own sample (K5b — the print on the pegboard): made, never fetched\n if (hash === SAMPLE_PICTURE) return { kind: \"rgba\", bytes: samplePicture(width, height), width, height };\n const blob = await host.use?.(BLOB_STORE)?.get(hash);\n if (blob === undefined) return undefined;\n if (blob.type === RGBA_TYPE) return { kind: \"rgba\", bytes: blob.bytes, width, height };\n return host.use?.(PICTURE_DECODER)?.(blob, PICTURE_MAX);\n };\n /** The upload: raw RGBA by the kind, a decoded source by the device's copy — and how to decode it again (a print large on screen: its detail, K6a). */\n const upload = (d: DecodedPicture, hash: string, width: number, height: number): Picture | null => {\n const pass = passOf();\n if (pass === undefined) return null;\n if (d.kind === \"rgba\") return d.bytes.length === d.width * d.height * 4 ? pass.picture(d.bytes, d.width, d.height) : null;\n return pass.pictureFrom(d.source as ImageBitmap, d.width, d.height, () => decodeOf(hash, width, height));\n };\n const load = (hash: string, width: number, height: number): Pic => {\n const had = pics.get(hash);\n if (had !== undefined) return had;\n const pic: Pic = { picture: null, state: \"loading\", users: new Set(), held: false, load: Promise.resolve() };\n pics.set(hash, pic);\n pic.load = (async () => {\n const decoded = await decodeOf(hash, width, height);\n const picture = decoded === undefined ? null : upload(decoded, hash, width, height);\n if (decoded?.kind === \"source\") decoded.close?.();\n if (pics.get(hash) !== pic) { if (picture !== null) passOf()?.dropPicture(picture); return; } // nobody wants it any more\n pic.picture = picture;\n pic.state = picture === null ? \"failed\" : \"ready\";\n for (const u of pic.users) land(u);\n woke = true;\n })().catch(() => { pic.state = \"failed\"; woke = true; });\n return pic;\n };\n\n return {\n hold(e, wx, wy, t) {\n const pr = prints.get(e);\n if (pr === undefined) return; // never drawn: nothing to lift\n if (!pr.leads) pr.body = copyBody(pr.body);\n pr.leads = true;\n leading.add(e);\n pr.resting = false;\n pr.committedAt = -1;\n pr.back = null; // caught on its way home: the hand has it again\n pr.body.hovered = false;\n grab(pr.body, wx, wy, t);\n pr.ax = pr.body.ax;\n pr.ay = pr.body.ay;\n },\n move(e, wx, wy, t) { const pr = prints.get(e); if (pr?.body.hold) moveHold(pr.body, wx, wy, t); },\n drop(e, t) {\n const pr = prints.get(e);\n if (!pr?.body.hold) return;\n release(pr.body, t, law);\n pr.flick = { body: copyBody(pr.body), dts: [], landed: null };\n },\n cancel(e, t) {\n const pr = prints.get(e);\n if (pr === undefined || !pr.leads) return;\n const b = pr.body;\n b.hold = null;\n b.vx = 0; b.vy = 0; b.spin = 0;\n pr.back = { x: b.x, y: b.y, angle: b.angle, h: b.h, t0: t };\n pr.flick = undefined;\n },\n twist(e, da) {\n const pr = prints.get(e);\n if (pr === undefined || !pr.leads || pr.back !== null) return;\n twist(pr.body, da);\n },\n lifted: (e) => prints.get(e)?.leads === true,\n rests: () => queue.splice(0, queue.length),\n owed: () => queue.length,\n settle(e, committed) {\n const pr = prints.get(e);\n if (pr === undefined) return;\n if (committed) pr.committedAt = last < 0 ? 0 : last;\n else { pr.leads = false; pr.resting = false; }\n },\n pin(e, pose) { print(e).pose = pose; woke = true; },\n arrive(e) {\n const pr = print(e);\n pr.leads = true;\n leading.add(e);\n pr.resting = false;\n pr.body.h = law.arrive;\n pr.body.alpha = 0;\n pr.body.x = Number.NaN; // placed on its facts at the first resolve\n },\n preload(hash, width, height) { const pic = load(hash, width, height); pic.held = true; return pic.load; },\n body: (e) => { const pr = prints.get(e); return pr === undefined ? undefined : copyBody(pr.body); },\n flick: (e) => { const f = prints.get(e)?.flick; return f === undefined ? undefined : { body: copyBody(f.body), dts: [...f.dts], landed: f.landed }; },\n pictures() {\n let ready = 0;\n let loading = 0;\n let failed = 0;\n for (const p of pics.values()) { if (p.state === \"ready\") ready += 1; else if (p.state === \"loading\") loading += 1; else failed += 1; }\n const resident = passOf()?.pictureStats;\n return resident === undefined ? { ready, loading, failed } : { ready, loading, failed, resident };\n },\n bodyFor(ctx, hx, hy) {\n const pr = print(ctx.entity);\n pr.fx = ctx.rect.cx;\n pr.fy = ctx.rect.cy;\n pr.fa = numberProp(ctx.props, \"angle\", 0);\n if (pr.leads && pr.committedAt >= 0 && ((near(ctx.rect.cx, pr.body.x) && near(ctx.rect.cy, pr.body.y) && near(pr.fa, pr.body.angle)) || last - pr.committedAt > 1000)) { pr.leads = false; pr.resting = false; pr.committedAt = -1; }\n if (pr.leads && Number.isNaN(pr.body.x)) { const b = restBody(ctx, hx, hy, pr); b.h = pr.body.h; b.alpha = pr.body.alpha; pr.body = b; }\n if (!pr.leads) pr.body = withPose(restBody(ctx, hx, hy, pr), pr.pose);\n const b = pr.body;\n if (ctx.flux.fade >= 1) return b;\n // a ghost leaves: it lifts toward 1.6 × the lift as it fades (PHOTO.md's `leave`)\n return { ...b, h: b.h + law.lift * 1.6 * (1 - ctx.flux.fade), alpha: Math.min(b.alpha, ctx.flux.fade) };\n },\n pictureFor(e, hash, width, height) {\n const pr = print(e);\n if (pr.hash !== hash) { unuse(e, pr.hash); pr.hash = hash; }\n if (hash === \"\") return null;\n const pic = load(hash, width, height);\n pic.users.add(e);\n pic.held = false;\n return pic.picture;\n },\n landed: (e) => landedOf.get(e) ?? 0,\n // K7a: next live now while a print leads (in a hand, in the air, flying home, resting to commit), a picture landed, or the last\n // frame's asks wait for their residency step (a detail to fetch); never otherwise — a landing wakes it (`onPictures`)\n due: (now) => (woke || leading.size > 0 || passOf()?.residencyOwed === true ? now : Number.POSITIVE_INFINITY),\n tick(now) {\n const dt = last < 0 ? 0 : Math.min(Math.max((now - last) / 1000, 0), 0.05);\n last = now;\n // the pictures' residency (K6a): under the desk's budget, a landed detail waking the desk; the frame boundary — what the\n // last frame's prints asked is bound, fetched or let go before this frame's build\n const pass = passOf();\n if (pass !== undefined) {\n if (!attached) { pass.budget(host.budget); pass.onPictures = () => { woke = true; host.wake?.(); }; attached = true; }\n if (pass.residency()) woke = true;\n }\n let want = woke;\n woke = false;\n // the prints that lead, and those alone (D6): a desk of a thousand prints at rest costs the tick nothing per print\n for (const e of leading) {\n const pr = prints.get(e);\n if (pr === undefined || !pr.leads) { leading.delete(e); continue; }\n if (pr.resting) { want = true; continue; }\n want = true;\n if (pr.back !== null) {\n // a cancelled carry flies home (D3t-a): from where the hand let go to the facts, on the island ease — then the facts lead\n const B = pr.back;\n const u = Math.min(Math.max((now / 1000 - B.t0) / (PRINT_RETURN_MS / 1000), 0), 1);\n const k = carryOf(u); // the island ease — the hand's own (hold/pose.ts)\n let da = pr.fa - B.angle;\n da = Math.atan2(Math.sin(da), Math.cos(da));\n const b = pr.body;\n b.x = B.x + (pr.fx - B.x) * k; b.y = B.y + (pr.fy - B.y) * k; b.angle = B.angle + da * k; b.h = B.h * (1 - k);\n b.sx *= 1 - k; b.sy *= 1 - k; b.vsx = 0; b.vsy = 0; b.vh = 0;\n if (u >= 1) { pr.back = null; pr.leads = false; }\n continue;\n }\n if (Number.isNaN(pr.body.x) || dt <= 0) continue;\n stepPhoto(pr.body, dt, law);\n const flick = pr.flick;\n if (flick !== undefined && flick.landed === null && pr.body.hold === null) flick.dts.push(dt);\n if (pr.body.hold !== null || restless(pr.body)) continue;\n // at rest: ONE transaction's worth for the carry — a print that came back where its facts are commits nothing\n if (flick !== undefined && flick.landed === null) flick.landed = { x: pr.body.x, y: pr.body.y };\n if (near(pr.body.x, pr.fx) && near(pr.body.y, pr.fy) && near(pr.body.angle, pr.fa)) { pr.leads = false; continue; }\n pr.resting = true;\n queue.push({ entity: e, x: pr.body.x, y: pr.body.y, angle: pr.body.angle });\n }\n return want;\n },\n /** The budget's ask (K6a): the thumbnails always, a picture's detail while a frame binds it. */\n keeps: (key) => passOf()?.keeps(key) ?? false,\n forget(e) {\n landedOf.delete(e);\n const pr = prints.get(e);\n if (pr === undefined) return;\n unuse(e, pr.hash);\n prints.delete(e);\n },\n dispose() {\n const pass = passOf();\n for (const p of pics.values()) if (p.picture !== null) pass?.dropPicture(p.picture);\n pics.clear();\n prints.clear();\n },\n };\n}\n\nexport interface PhotoKindOptions {\n /** The host's shader text; the generated module unless a host says. */\n readonly text?: ShaderText;\n /** The print's numbers (photo.ts `PHOTO`) — the engine's unless a host tweaks them. */\n readonly law?: PhotoLaw;\n}\n\n/** The print's kind, whole (kinds/world.ts `ObjectKind`): the program, and the world half on the photo lab's body. */\nexport function photoKind(opts: PhotoKindOptions = {}): ObjectKind<PhotoGeometry, PhotoInstance> {\n const law = opts.law ?? PHOTO;\n const program = photoProgram(opts.text ?? shaderText);\n const extentOf = (ctx: ObjectContext): { w: number; h: number } => printExtent(numberProp(ctx.props, \"width\", 0), numberProp(ctx.props, \"height\", 0), law.long);\n return {\n ...program,\n reach: photoReach(law),\n local: (host: KindHost): Prints => createPrints(host, law),\n resolve(ctx: ObjectContext): PhotoGeometry {\n const { w, h } = extentOf(ctx);\n const prints = ctx.local as Prints | undefined;\n if (prints !== undefined) return resolvePhoto(prints.bodyFor(ctx, w / 2, h / 2), law, ctx.lamp);\n const b = newBody(ctx.rect.cx, ctx.rect.cy, w, h, numberProp(ctx.props, \"angle\", 0), law.hover * ctx.flux.hover);\n if (ctx.flux.fade < 1) { b.h += law.lift * 1.6 * (1 - ctx.flux.fade); b.alpha = ctx.flux.fade; }\n return resolvePhoto(b, law, ctx.lamp);\n },\n record(G: PhotoGeometry, ctx: ObjectContext): PhotoInstance {\n const { w, h } = extentOf(ctx);\n const border = borderOf(w / 2, h / 2, { ...law, border: numberProp(ctx.props, \"border\", law.border) });\n const prints = ctx.local as Prints | undefined;\n const picture = prints?.pictureFor(ctx.entity, stringProp(ctx.props, \"blob\", \"\"), numberProp(ctx.props, \"width\", 0), numberProp(ctx.props, \"height\", 0)) ?? null;\n return { geometry: G, border, picture };\n },\n hit(G: PhotoGeometry, wx: number, wy: number): ObjectHit | null {\n return hitPhoto(G, wx, wy) ? \"content\" : null;\n },\n frame: photoFrame,\n };\n}\n\n/** The rect a print lies in at rest, for a host that places one by its centre: top-left and the f32 size the world stores. */\nexport function printRect(cx: number, cy: number, width: number, height: number, long: number = PHOTO.long): ObjectRect & { readonly x: number; readonly y: number } {\n const e = printExtent(width, height, long);\n const w = Math.fround(e.w);\n const h = Math.fround(e.h);\n return { x: cx - w / 2, y: cy - h / 2, cx, cy, w, h };\n}\n","// THE PRINT'S CARRY (PHOTO.md §3; design-015 §6's photo behaviours; D3w) — the hand half of the photo kind's\n// physics, the note's typing's sibling: it READS the world (the local pointers, what each press captured, where\n// each finger is) and drives the photo kind's bodies (kinds/photo.ts `Prints`), and it WRITES exactly one thing,\n// once per carry: the print's rest.\n//\n// A print is not core-movable (a press on it claims the pointer and drives no core behaviour — core's own\n// grammar for a widget that is not `Movable`). While a pointer is down and its press captured a print, the\n// print is HELD: its grab point is a kinematic pin on the finger (`hold` at the press, `move` every frame — a\n// pan or a zoom under a held print moves it too), it rises to the hand's height, tips toward the fingers and\n// droops away from them; the swing about the grab point stays OFF (ruled: \"do not make them rotate\"). Let go\n// (`drop`), it leaves with the finger's velocity over the last 70 ms, capped at 4200 u/s — a finger that\n// stopped throws nothing — and glides: 0.9/s of air in the air, the cutting mat's Coulomb grip on it (2400 u/s²\n// + 5/s), stepped at 240 Hz. All of it is FLUX: the document does not move while the print is in the hand or\n// in the air. When the body comes to rest where its facts are not, the carry commits ONE transaction — the\n// print's Position at the rest, and the raise (the top of its siblings, the prototype's `toTop`) — so one carry\n// is one undo step, whatever the glide did. The commit is DEFERRED out of the frame (`defer`, a microtask by\n// default): the carry runs in the desk's reflector, and a reflector never writes (D-D2c.5's rule).\n// A press that never moved the print commits nothing. A taped print (`Locked`) is not carried: a press on it that\n// becomes a drag meets the tape, and the carry says so (`refused`, once a gesture) — the desk's marks answer it with the\n// tape's GIVE, as a core drag that meets a taped note makes it give (D4a).\n//\n// D3t-a, the carry's owed rows: ESC CANCELS a carry — the gestures' cancel (core's one-tick `CancelRequest`, read by its\n// resource stamp: it is written only by a cancel and its clearing) lets go of the print with no flick, and it flies back to\n// where it began, committing nothing; THE WHEEL over a carried print TWISTS it about the finger (PHOTO.md — the print is\n// `wheelTurns`, so core cedes that pointer's wheel to it and sums it in `PressWheel`: 0.0035 rad a wheel unit, the lab's),\n// and the rest commits the turn with the place; a press on a print in the AIR catches it where it is drawn (the pick asks\n// what the kind draws lifted first), and a print carried, gliding or flying home paints above its siblings like a `Grab`.\n\nimport { CancelRequest, ChildOf, type Component, defineQuery, Drag, type Entity, GestureActive, GestureCancelled, GestureEnded, GestureFailed, guardedTransaction, LocalPointer, Locked, Pointer, PointerButtons, PointerWorld, Position, PressWheel, Size, Captures, Watches, type World } from \"@ice/core\";\nimport type { Prints } from \"./kind\";\nimport { type TypingDocs, writable } from \"@ice/desk\";\n\nexport interface PhotoCarryOptions {\n readonly world: World;\n /** The document a rest commits into — the facade's `engine.docs`. */\n readonly docs: TypingDocs;\n /** The print's props cell (its `angle`) — the object hands its own (D-D7-A.3); absent, a rest commits no turn. */\n readonly props?: Component | undefined;\n /** The photo kind's state on this desk (undefined before it is made). */\n readonly prints: () => Prints | undefined;\n /** Is this entity a print (the desk's builder knows each entity's kind). */\n readonly isPrint: (e: Entity) => boolean;\n /** Where a rest's transaction runs: out of the frame (a microtask) unless a test says. */\n readonly defer?: (fn: () => void) => void;\n /** A press on a TAPED print became a drag (the recognizer Active): not carried — told once a gesture, so the desk's marks give it (D4a). */\n readonly refused?: (e: Entity) => void;\n}\n\nexport interface PhotoCarry {\n /** Nothing to follow (D7 #14): no print in a hand, no press on the desk, no rest owed by the kind. */\n idle(): boolean;\n /** Once a frame, before the kinds' clocks: the hands onto the bodies, and last frame's rests into their transactions. */\n follow(now: number): void;\n /** The prints in a hand now. */\n held(): readonly Entity[];\n /** Carries cancelled since creation (a rig's witness). */\n cancels(): number;\n /** Transactions committed since creation (a rig's witness). */\n commits(): number;\n}\n\nconst pointersQ = defineQuery([Pointer, LocalPointer, PointerWorld, PointerButtons]);\n/** The lab's wheel: a wheel unit turns a held print by this many radians (lab/photo.ts). */\nexport const TWIST_PER_WHEEL = 0.0035;\n\nexport function createPhotoCarry(opts: PhotoCarryOptions): PhotoCarry {\n const { world, docs } = opts;\n const defer = opts.defer ?? ((fn: () => void) => queueMicrotask(fn));\n const held = new Set<Entity>();\n /** The drags on taped prints already told of (their recognizers), so each gesture gives once. */\n const refusing = new Set<Entity>();\n /** Each held print's wheel as its pointer's `PressWheel` last read (the twist is the difference). */\n const wheel = new Map<Entity, number>();\n /** The gestures' cancel as last seen: `CancelRequest` is written only by a cancel and its clearing, so its stamp moving IS a cancel. */\n let cancelStamp = world.resourceStamp(CancelRequest);\n let commits = 0;\n let cancels = 0;\n\n /** ONE transaction: the print where it came to rest, at the turn it came to rest at, raised to the top of its siblings. False when it could not. */\n const commit = (e: Entity, x: number, y: number, angle: number): boolean => {\n const session = writable(docs);\n const size = world.get(e, Size);\n if (session === undefined || size === undefined || !world.isAlive(e)) return false;\n const group = opts.props;\n const props = group !== undefined ? (world.get(e, group as never) as Record<string, unknown> | undefined) : undefined;\n try {\n guardedTransaction(session.store, world, (tx) => {\n tx.edit(e).set(Position, { x: x - size.w / 2, y: y - size.h / 2 });\n if (group !== undefined && props !== undefined && props.angle !== angle) tx.edit(e).set(group as never, { ...props, angle } as never);\n if (world.getRelation(e, ChildOf) !== undefined) tx.moveRelation(e, ChildOf, \"last\");\n });\n } catch {\n return false;\n }\n commits += 1;\n return true;\n };\n\n return {\n follow(now) {\n const prints = opts.prints();\n if (prints === undefined) return;\n // last frame's rests: each its one transaction, out of the frame\n for (const r of prints.rests()) defer(() => prints.settle(r.entity, commit(r.entity, r.x, r.y, r.angle)));\n const stamp = world.resourceStamp(CancelRequest);\n const cancelled = stamp !== cancelStamp;\n cancelStamp = stamp;\n // the hands: a pointer down whose press captured a print holds it at the finger's world point\n const t = now / 1000;\n const hands = new Map<Entity, { readonly x: number; readonly y: number; readonly wheel: number }>();\n const taped = new Set<Entity>();\n world.query(pointersQ).each((b) => {\n for (const row of b) {\n const p = b.entity(row);\n if ((world.read(p, PointerButtons).buttons & 1) === 0) continue;\n for (const rec of world.getReverse(p, Watches)) {\n // a recognizer past its gesture (cancelled, failed, ended) holds nothing: it lingers a frame before the reap, and a\n // cancelled one must let go on the very frame the cancel lands (D3t-a — Esc puts the print back)\n if (world.hasTag(rec, GestureCancelled) || world.hasTag(rec, GestureFailed) || world.hasTag(rec, GestureEnded)) continue;\n const e = world.getRelation(rec, Captures);\n if (e === undefined || hands.has(e) || !world.isAlive(e) || !opts.isPrint(e)) continue;\n if (world.hasTag(e, Locked)) {\n // taped: never carried — a press that has become a drag meets the tape (once a gesture)\n if (world.has(rec, Drag) && world.hasTag(rec, GestureActive)) { taped.add(rec); if (!refusing.has(rec)) opts.refused?.(e); }\n continue;\n }\n const at = world.read(p, PointerWorld);\n hands.set(e, { x: at.x, y: at.y, wheel: world.get(p, PressWheel)?.dy ?? 0 });\n }\n }\n });\n refusing.clear();\n for (const rec of taped) refusing.add(rec);\n for (const [e, at] of hands) {\n if (held.has(e)) {\n prints.move(e, at.x, at.y, t);\n const turned = at.wheel - (wheel.get(e) ?? at.wheel);\n if (turned !== 0) prints.twist(e, turned * TWIST_PER_WHEEL);\n } else { prints.hold(e, at.x, at.y, t); held.add(e); }\n wheel.set(e, at.wheel);\n }\n for (const e of [...held]) {\n if (hands.has(e)) continue;\n // let go — or, the gestures cancelled (Esc), put back where it began: no flick, nothing committed\n if (cancelled) { prints.cancel(e, t); cancels += 1; } else prints.drop(e, t);\n held.delete(e);\n wheel.delete(e);\n }\n },\n idle() {\n if (held.size > 0 || (opts.prints()?.owed() ?? 0) > 0) return false;\n let pressed = false;\n world.query(pointersQ).each((b) => { for (const r of b) if ((world.read(b.entity(r), PointerButtons).buttons & 1) !== 0) pressed = true; });\n if (pressed) return false;\n cancelStamp = world.resourceStamp(CancelRequest); // a cancel while idle cancels nothing: the stamp stays current\n return true;\n },\n held: () => [...held],\n commits: () => commits,\n cancels: () => cancels,\n };\n}\n","// The PHOTO print (PHOTO.md) as an OBJECT (design-015 §6; D3w): a 6×4 on the desk among its things. Durable\n// props: its picture BY NAME — `blob`, the hash of its bytes in the app's BlobStore (D-D12; photo/blobs.ts),\n// never the bytes — and the picture's size in pixels (`width` × `height`: its aspect, and a raw RGBA's rows),\n// its white `border` (a fraction of the short side), and its `angle` — the turn it lies at (the prototype kept\n// it on the body; the wheel turns it, a paste lays it ±6°). Its extent on the desk is the picture's aspect at\n// the law's long side (`printExtent` — exact; `Size` is its f32 shadow for the index, the cull and the marks).\n// Things, selectable; NOT core-movable: a print's CARRY is its own physics (objects/carry.ts over the photo\n// kind's bodies — the kinematic pin, the flick, the glide, the grip), and its drop is ONE transaction when it\n// comes to rest. Offered to a mini mat (`provides`) for D2b's nesting.\n\nimport { p } from \"@ice/core\";\nimport { photoKind, printExtent, type Prints } from \"./kind\";\nimport { DESK_OBJECT, defineObject } from \"@ice/desk\";\nimport { PHOTO } from \"./photo\";\nimport { createPhotoCarry } from \"./carry\";\nimport { SAMPLE_PICTURE, SAMPLE_SIZE } from \"./sample\";\n\n/** The print's durable type id. */\nexport const PHOTO_TYPE = \"desk.photo\";\nexport { printExtent };\n\nexport const Photo = defineObject({\n type: PHOTO_TYPE,\n version: 1,\n props: {\n blob: p.string({ default: \"\" }),\n width: p.number({ default: 0 }),\n height: p.number({ default: 0 }),\n border: p.number({ default: PHOTO.border }),\n angle: p.number({ default: 0 }),\n },\n size: { w: printExtent(0, 0).w, h: printExtent(0, 0).h },\n kind: photoKind(),\n // on the pegboard tray (design-017 §8): a print, clipped\n // …showing the kind's sample picture (K5b, D-K5b.4) through its own pictures (`local`); one taken is blank — it asks for a picture\n tray: { label: \"Print\", category: \"paper\", order: 1, props: { blob: SAMPLE_PICTURE, width: SAMPLE_SIZE.w, height: SAMPLE_SIZE.h }, local: true, hang: { w: 150, h: 100, accessory: \"clip\", pegs: [[0, -0.5]] } },\n // the wheel TURNS a print held in a hand (PHOTO.md; D3t-a — core cedes that pointer's wheel to it, `PressWheel`)\n interaction: { selectable: true, movable: false, resizable: false, snap: \"both\", wheelTurns: true },\n // it lies on the desk by what it provides (K8a — `DESK_OBJECT`, the desk canvas's one key), as a plugin kind does\n provides: [PHOTO_TYPE, DESK_OBJECT],\n // the prints' CARRY (D3w): the hands onto the photo kind's bodies, each rest ONE transaction out of the frame (D-D7-A.3)\n drivers: (h) => createPhotoCarry({ world: h.world, docs: h.docs, prints: () => h.local as Prints | undefined, isPrint: h.isKind, refused: h.refused, props: Photo.groups[0]?.component }),\n});\n","// The desk's ENGINE PRESET (design-015 §9, D2a-core's settings; SHIPPED at D7, D-D7-C.1): what\n// `createCanvasEngine` needs for the desk the README describes — the reference objects, infinite\n// zoom, the prototype's wheel (a plain wheel zooms about the pointer by exp(−Δ · 0.0016)), the\n// zoom-through, and the desk's SELECT tool — a drag on the bare mat PANS, shift draws the marquee\n// (D-D11) — as the root canvas type's default. Core registers no desk tool or settings (its\n// defaults are the plain canvas's: a wheel that pans, a bare drag that marquees, zoom 0.1–5); until\n// D7 this lived in apps/desk only, so the published quickstart could not do what it said.\n// Importing this module DEFINES the tool and the canvas type (core's registries are process-global).\n\nimport { type CanvasEngineOpts, defineCanvasType, defineTool, type Tool, tools } from \"@ice/core\";\nimport { DESK_OBJECT, ZOOM_MAX, ZOOM_MIN } from \"@ice/desk\";\nimport { Board } from \"./board/object\";\nimport { Calendar } from \"./calendar/object\";\nimport { MiniMat } from \"./minimat/object\";\nimport { Note } from \"./paper/object\";\nimport { Notebook } from \"./notebook/object\";\nimport { Photo } from \"./photo/object\";\n\n/** The desk's reference objects, in the order an app registers them. */\nexport const DESK_OBJECTS = [Note, MiniMat, Board, Photo, Notebook, Calendar] as const;\n\nfunction builtin(id: string): Tool {\n const tool = tools.get(id);\n if (tool === undefined) throw new Error(`desk: missing built-in tool ${id}`);\n return tool;\n}\n\n/**\n * The desk's select tool: the bare mat pans, shift-drag draws the vellum marquee; a drag on an object moves it. It answers `v` — core's\n * select's letter — since core's select is compiled but never legal on the desk, and the keymap binds a letter only to a tool legal in\n * the current canvas (K9 S8: `v` threw on the desk, and `h` left it in pan with no letter back).\n */\nexport const deskSelect: Tool = defineTool({ id: \"desk.select\", shortcut: \"v\", route: { canvasDrag: \"pan\", canvasDragShift: \"marquee\" } });\n\n/** The tools the engine compiles — a typed engine must name `select` even when no canvas allows it. */\nexport const DESK_TOOLS: readonly Tool[] = [builtin(\"select\"), deskSelect, builtin(\"pan\")];\n\n/**\n * The desk as a canvas type: what it places, its two tools, the natural arrival band (FIT: pad 80, zoom ½–1). It places every object\n * that PROVIDES `DESK_OBJECT` (K5b's D-K5b.2, the SDK's key since K8a — the six declare it as a plugin kind does) and names no type: no\n * list here names a kind.\n */\nexport const DeskCanvas = defineCanvasType({\n id: \"desk.desk\",\n semanticVersion: 1,\n semantic: { placement: { accepts: [DESK_OBJECT] } },\n presentation: {\n tools: { allowed: [deskSelect, builtin(\"pan\")], default: deskSelect },\n camera: { arrival: \"fit\", padding: 80, minZoom: 0.5, maxZoom: 1 },\n },\n});\n\n/**\n * THE PRESET — `createCanvasEngine(DESK_ENGINE)` is the desk the README describes: the six reference objects, the desk's\n * tools with `desk.select` in hand, the desk canvas as the root, the scale-free zoom (design-015 §9: `ZOOM_MIN`–`ZOOM_MAX`),\n * the plain wheel zooming about the pointer, and the zoom-through ON (a wheel that leaves a face covering the view cuts into it).\n * Spread it to add to it: `createCanvasEngine({ ...DESK_ENGINE, widgets: [...DESK_OBJECTS, Mine] })`.\n */\nexport const DESK_ENGINE = {\n widgets: [...DESK_OBJECTS],\n tools: DESK_TOOLS,\n canvasTypes: [DeskCanvas],\n rootCanvas: DeskCanvas,\n presentationFallback: DeskCanvas,\n settings: { zoom: { min: ZOOM_MIN, max: ZOOM_MAX }, gestures: { wheel: \"zoom\" }, nav: { zoomThrough: { enabled: true } } },\n} as const satisfies CanvasEngineOpts;\n","// The reference objects' PALETTE — VibeField's projection into the desk, SHIPPED (design-015 D7,\n// D-D7-C.1: `@vibecook/ice/desk/objects` exports `deskPalette`/`deskTheme`, so `deskLayer` mounts\n// with the documented options; until D7 this table was the oracle's fixture and the quickstart\n// pointed at an app file the package did not ship). It is still the PRODUCT's half of the theme —\n// the kinds hold no colour and read only what their `theme()` is handed — shipped as the six\n// reference kinds' default look, which an app replaces by handing `deskLayer` its own palette.\n// `oracle/fixtures/vf-theme.ts` re-exports this module: the oracle, apps/desk and the units read\n// ONE table.\n//\n// Every colour here is a token from `vibe-field/DESIGN.md` (§2 Color), or a\n// desk material transcribed WITH ITS NAME from the tree-shadow design system\n// (research/tree-shadow/prototype/design/mat.css), the same discipline as\n// `packages/design-kit/src/tokens.css`: the doc moves first, then this file.\n// `test/vf-theme.test.ts` cross-checks the tokens against the real tokens.css\n// and DESIGN.md when the repo is beside us. At the fold this is the shape\n// field-app's `canvas-appearance.ts` takes, reading `--vf-*` off the stamped\n// root instead of transcribing. The engine's half — the types, the parser,\n// `themeFrom`, the mat and the desk's materials — is `src/theme.ts`.\n// Transcribed 2026-09-01 (the prototype's lab/theme.ts); split out 2026-09-07.\n// The card chrome's roles, the cards' committed surfaces and the product's\n// magnet grid retired with the cards and the dot and needle grids on 2026-09-25.\n\nimport { cssColor, type GroundTheme, type Palette, type RGB, type RGBA, rgb, themeFrom, type ThemeName } from \"@ice/desk\";\nimport type { BoardPalette } from \"./board/kind\";\nimport type { CalendarPalette } from \"./calendar/kind\";\nimport type { MiniMatPalette } from \"./minimat/kind\";\nimport type { NotebookPalette } from \"./notebook/kind\";\nimport type { PaperPalette } from \"./paper/kind\";\n\nexport const PALETTE: Record<ThemeName, Palette> = {\n light: {\n canvasBg: { token: \"--vf-canvas-bg\", css: \"#fafafa\" },\n select: { token: \"--vf-select\", css: \"#4a90d9\" },\n },\n dark: {\n canvasBg: { token: \"--vf-canvas-bg\", css: \"#171717\" },\n select: { token: \"--vf-select\", css: \"#4a90d9\" },\n },\n};\n\n/**\n * §2.2 committed content surfaces the desk's paper takes — a note's colour, carried across BOTH\n * themes like an iOS widget on any wallpaper (the LIGHT is the desk's).\n */\nexport const SURFACES = {\n note: { token: \"--vf-note-surface\", css: \"#f6e7a9\" },\n} as const;\nexport type SurfaceName = keyof typeof SURFACES;\nexport const surface = (name: SurfaceName): RGB => rgb(SURFACES[name].css);\n\n/**\n * The NOTEBOOK's materials (BOOK.md) — the tree-shadow design system's paper layer\n * (research/tree-shadow/prototype/design/mat.css, the cutting mat's own UI system),\n * transcribed by token: `--cream` is a page (\"text on the mat, primary paper\"), `--paper` an\n * endpaper (\"index card, secondary paper\"), the covers wear `--kraft` · `--ink` · `--cork` ·\n * `--paper` and, the product's own black, `--vf-card` (DESIGN.md §2.2). Rules on paper are\n * ink at 28 % (mat.css `--hair-paper`). Like a card's committed surface, a notebook keeps\n * its colours in both themes; the LIGHT is the desk's.\n */\nexport const BOOK_PAPER = {\n page: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" },\n end: { token: \"tree-shadow mat.css --paper\", css: \"#f6e0c6\" },\n rule: { token: \"tree-shadow mat.css --hair-paper (--ink at 28 %)\", css: \"rgb(16 9 4 / 28%)\" },\n} as const;\nexport const COVERS = {\n ink: { cover: { token: \"tree-shadow mat.css --ink\", css: \"#100904\" }, spine: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" } },\n kraft: { cover: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" }, spine: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" } },\n cork: { cover: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" }, spine: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" } },\n paper: { cover: { token: \"tree-shadow mat.css --paper\", css: \"#f6e0c6\" }, spine: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" } },\n card: { cover: { token: \"--vf-card\", css: \"#1c1c1e\" }, spine: { token: \"tree-shadow mat.css --brass-mute\", css: \"#9a7f55\" } },\n} as const;\nexport type CoverName = keyof typeof COVERS;\nexport const COVER_NAMES = Object.keys(COVERS) as CoverName[];\n/** A notebook's look, parsed: its cover and spine, the endpaper and the page every notebook shares, the rule ink. */\nexport const bookLook = (name: CoverName): { cover: RGB; spine: RGB; end: RGB; paper: RGB; rule: RGBA } =>\n ({ cover: rgb(COVERS[name].cover.css), spine: rgb(COVERS[name].spine.css), end: rgb(BOOK_PAPER.end.css), paper: rgb(BOOK_PAPER.page.css), rule: cssColor(BOOK_PAPER.rule.css) });\n\n/**\n * The PENS a sticky note is written with (STICKY.md §3) — the host's colours, like a\n * card's committed surface: a felt tip's near-black, a ballpoint's blue-black, a\n * fountain pen's blue, a red marker. None is a DESIGN.md token yet; adding the pens\n * to the doc's material book is the step before any of this leaves draft/ (STICKY.md §8).\n */\nexport const PENS = {\n felt: { token: \"STICKY.md §3 felt tip\", css: \"#2b2a33\" },\n ball: { token: \"STICKY.md §3 ballpoint\", css: \"#1f2f5c\" },\n fountain: { token: \"STICKY.md §3 fountain pen\", css: \"#264a9a\" },\n red: { token: \"STICKY.md §3 red marker\", css: \"#c0392b\" },\n} as const;\nexport type PenName = keyof typeof PENS;\nexport const PEN_NAMES: readonly PenName[] = [\"felt\", \"ball\", \"fountain\", \"red\"];\nexport const pen = (name: PenName): RGB => rgb(PENS[name].css);\n\n/**\n * The WHITEBOARD's materials (BOARD.md) — the board's own colours, kept in both themes like a\n * card's committed surface; the LIGHT is the desk's. The melamine is the research board's\n * albedo as it displays (research/whiteboard board.wgsl); the frame is anodised aluminium in\n * the tree-shadow design's warm greys (\"no neutral grey — greys are grey-brown\"); the eraser\n * wears the design's `--kraft` back and `--ink-2` felt. None is a DESIGN.md token yet; the doc's\n * material book moves first before any of this leaves draft/ (BOARD.md §8).\n */\nexport const BOARD_LOOK = {\n surface: { token: \"research/whiteboard melamine (board.wgsl albedo, displayed)\", css: \"#f3f2ed\" },\n frame: { token: \"anodised aluminium, warm (tree-shadow: greys are grey-brown)\", css: \"#cdc7ba\" },\n barrel: { token: \"a marker's barrel, warm white plastic\", css: \"#ece8e0\" },\n felt: { token: \"tree-shadow mat.css --ink-2 (the eraser's felt)\", css: \"#382416\" },\n wood: { token: \"tree-shadow mat.css --kraft (the eraser's back)\", css: \"#d9b57c\" },\n} as const;\n/** The board's colours, parsed. */\nexport const boardLook = (): { surface: RGB; frame: RGB; barrel: RGB; felt: RGB; wood: RGB } =>\n ({ surface: rgb(BOARD_LOOK.surface.css), frame: rgb(BOARD_LOOK.frame.css), barrel: rgb(BOARD_LOOK.barrel.css), felt: rgb(BOARD_LOOK.felt.css), wood: rgb(BOARD_LOOK.wood.css) });\n\n/**\n * The dry-erase MARKERS — the research whiteboard's inks (research/whiteboard tools.ts `MARKERS`)\n * and the coverage one pass of each lays. Its orange is dropped: orange is the desk's `--hot`,\n * reserved for state (the tree-shadow design). Content colours, like the note's pens.\n */\nexport const MARKERS = {\n black: { token: \"research/whiteboard black marker\", css: \"#1b1c20\", opacity: 0.985 },\n blue: { token: \"research/whiteboard blue marker\", css: \"#2350b5\", opacity: 0.97 },\n red: { token: \"research/whiteboard red marker\", css: \"#c92a2e\", opacity: 0.96 },\n green: { token: \"research/whiteboard green marker\", css: \"#1e8f4e\", opacity: 0.95 },\n} as const;\nexport type MarkerName = keyof typeof MARKERS;\nexport const MARKER_NAMES: readonly MarkerName[] = [\"black\", \"blue\", \"red\", \"green\"];\nexport const marker = (name: MarkerName): RGB => rgb(MARKERS[name].css);\n\n/**\n * The marker TRAY — the board's tools while it is open: the tree-shadow design's INK layer\n * (mat.css: 94 % ink, cream on it, brass for mono labels, `--hot` for the active tool only, the\n * shadows cast lower-left in the world's darkest value). The tray's stylesheet names these as\n * custom properties; the values are set from here, so no colour lives in its CSS.\n */\nexport const TRAY = {\n ink: { token: \"tree-shadow mat.css --ink\", css: \"#100904\" },\n cream: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" },\n brass: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" },\n brassMute: { token: \"tree-shadow mat.css --brass-mute\", css: \"#9a7f55\" },\n hot: { token: \"tree-shadow mat.css --hot\", css: \"#dc5000\" },\n cast: { token: \"tree-shadow mat.css --cast-rgb\", css: \"rgb(14 26 10)\" },\n} as const;\n\n/**\n * The MINI MATS' vinyls (MINIMAT.md §2) — the colours a self-healing mat is sold in, and the desk a\n * mini mat opens onto: enter a slate mini mat and the whole desk is slate. `sage` is the desk's own\n * (MAT.ground, whatever the panel has made it). Each is the colour the mat's chain STARTS from (the\n * reference's double gamma darkens it, as it darkens the sage to #3d5a30): slate shows as #34505a,\n * charcoal as #1e221e. None is a DESIGN.md token yet; the doc's material book moves first (§8).\n */\nexport const VINYLS = {\n slate: { token: \"a blue self-healing mat (shows #34505a through the mat's chain)\", css: \"#7d98a0\" },\n charcoal: { token: \"a black self-healing mat, green-black (shows #1e221e — no pure black on the desk)\", css: \"#616661\" },\n} as const;\nexport type VinylName = \"sage\" | keyof typeof VINYLS;\nexport const VINYL_NAMES: readonly VinylName[] = [\"sage\", \"slate\", \"charcoal\"];\n/** A vinyl's colour: the desk's own sage (`sage`, the host's), or one of the others. */\nexport const vinyl = (name: VinylName, sage: RGB): RGB => (name === \"sage\" ? sage : rgb(VINYLS[name].css));\n\n/** VibeField's two themes, as the passes read them. */\nexport const THEMES: Record<ThemeName, GroundTheme> = {\n light: themeFrom(\"light\", PALETTE.light),\n dark: themeFrom(\"dark\", PALETTE.dark),\n};\n\n/**\n * The 3D NOTEBOOK's materials (NOTEBOOK.md §4) — five covers after the Paper app's shelf (a\n * cloth or paper case, a band of cloth down the spine, a printed design) in the tree-shadow\n * design system's paper layer (research/tree-shadow/prototype/design/mat.css), plus the page's\n * own ivory. Every colour by token; the two that are not a mat.css token say what they are.\n * Like a card's committed surface, a notebook keeps its colours in both themes; the LIGHT is\n * the desk's. `--hot` is left out on purpose: the mat's orange is for state, never a cover.\n */\nexport const NOTEBOOK_LOOK = {\n /** The page: an ivory a shade cooler than `--cream`, so the ink's dots and the dapple read on it. */\n paper: { token: \"notebook ivory (a writing paper's white: warmer than --vf-canvas-bg, cooler than --cream)\", css: \"#f3ebdc\" },\n /** The ruling's dots and the label's rules. */\n ink: { token: \"tree-shadow mat.css --ink-3\", css: \"#6c5f51\" },\n covers: {\n ink: {\n cloth: { token: \"bookcloth black (tree-shadow --ink, lifted to a cloth's black so the weave reads)\", css: \"#221b16\" },\n band: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" },\n a: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" }, b: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" }, c: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" },\n endpaper: { token: \"tree-shadow mat.css --paper\", css: \"#f6e0c6\" },\n design: \"plain\", paperCover: false,\n },\n orbit: {\n cloth: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" },\n band: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" },\n a: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" }, b: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" }, c: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" },\n endpaper: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" },\n design: \"orbit\", paperCover: false,\n },\n tiles: {\n cloth: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" },\n band: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" },\n a: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" }, b: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" }, c: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" },\n endpaper: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" },\n design: \"tiles\", paperCover: false,\n },\n label: {\n cloth: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" },\n band: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" },\n a: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" }, b: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" }, c: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" },\n endpaper: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" },\n design: \"label\", paperCover: true,\n },\n linen: {\n cloth: { token: \"tree-shadow mat.css --paper\", css: \"#f6e0c6\" },\n band: { token: \"tree-shadow mat.css --brass-mute\", css: \"#9a7f55\" },\n a: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" }, b: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" }, c: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" },\n endpaper: { token: \"tree-shadow mat.css --cream\", css: \"#ffedd7\" },\n design: \"bordered\", paperCover: false,\n },\n },\n} as const;\nexport type NotebookCover = keyof typeof NOTEBOOK_LOOK.covers;\nexport const NOTEBOOK_COVERS = Object.keys(NOTEBOOK_LOOK.covers) as NotebookCover[];\n/** A cover's look, parsed: what the notebook pass's record takes. */\nexport const notebookLook = (name: NotebookCover): { cloth: RGB; band: RGB; accents: [RGB, RGB, RGB]; endpaper: RGB; paper: RGB; ink: RGB; design: \"plain\" | \"orbit\" | \"tiles\" | \"label\" | \"bordered\"; paperCover: boolean } => {\n const c = NOTEBOOK_LOOK.covers[name];\n return { cloth: rgb(c.cloth.css), band: rgb(c.band.css), accents: [rgb(c.a.css), rgb(c.b.css), rgb(c.c.css)], endpaper: rgb(c.endpaper.css), paper: rgb(NOTEBOOK_LOOK.paper.css), ink: rgb(NOTEBOOK_LOOK.ink.css), design: c.design, paperCover: c.paperCover };\n};\n/** The ruling's ink with its presence on the page. */\nexport const notebookRuleInk = (): RGBA => [...rgb(NOTEBOOK_LOOK.ink.css), 0.55] as unknown as RGBA;\n\n/**\n * The DESK CALENDAR's materials (CALENDAR.md §4) — a pad of the notebook's own ivory under a cloth\n * tape, printed in the tree-shadow design's inks: the dates and the month in `--ink-2`, the year,\n * the eyebrows and the weekend in `--ink-3`, the weekend's columns washed with `--kraft`; today is\n * `--hot` (a state — \"what is happening\"), ringed by a marker. The pens are the sticky note's; the\n * highlighters are new: the fluorescents a desk has, muted to sit on the ivory under the mat's\n * light (the shader lays them in by MULTIPLY, as a highlighter's dye does). The chipboard back is\n * kraft gone grey. None is a DESIGN.md token yet — the doc's material book moves first (§12).\n */\nexport const CALENDAR_LOOK = {\n paper: { token: \"notebook ivory (NOTEBOOK_LOOK.paper — the desk's one writing paper)\", css: \"#f3ebdc\" },\n ink: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" },\n muted: { token: \"tree-shadow mat.css --ink-3\", css: \"#6c5f51\" },\n weekend: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" },\n hot: { token: \"tree-shadow mat.css --hot (a state: today)\", css: \"#dc5000\" },\n pencil: { token: \"graphite — a warm grey-brown (the design has no neutral grey)\", css: \"#5f574f\" },\n chipboard: { token: \"chipboard — kraft gone grey (the pad's back)\", css: \"#9c8b76\" },\n /** The presences: the rules, the heading rule, the weekend's wash, a neighbour month's wash and its dates, a highlighter. */\n alpha: { rule: 0.3, head: 0.62, weekend: 0.1, outside: 0.06, faint: 0.26, highlight: 0.62 },\n tapes: {\n ink: { cloth: { token: \"bookcloth black (NOTEBOOK_LOOK.covers.ink)\", css: \"#221b16\" }, foil: { token: \"tree-shadow mat.css --brass\", css: \"#c4a574\" } },\n tobacco: { cloth: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" }, foil: { token: \"tree-shadow mat.css --cork\", css: \"#c48a52\" } },\n kraft: { cloth: { token: \"tree-shadow mat.css --kraft\", css: \"#d9b57c\" }, foil: { token: \"tree-shadow mat.css --ink-2\", css: \"#382416\" } },\n },\n highlighters: {\n yellow: { token: \"highlighter yellow\", css: \"#f2d64f\" },\n green: { token: \"highlighter green\", css: \"#b4d98a\" },\n pink: { token: \"highlighter pink\", css: \"#f0a9bf\" },\n blue: { token: \"highlighter blue\", css: \"#a3cde8\" },\n orange: { token: \"highlighter orange\", css: \"#f4b673\" },\n },\n} as const;\nexport type CalendarTape = keyof typeof CALENDAR_LOOK.tapes;\nexport const CALENDAR_TAPES = Object.keys(CALENDAR_LOOK.tapes) as CalendarTape[];\nexport type HighlighterName = keyof typeof CALENDAR_LOOK.highlighters;\nexport const HIGHLIGHTER_NAMES = Object.keys(CALENDAR_LOOK.highlighters) as HighlighterName[];\n/** A colour as the Canvas 2D takes it, with a presence. */\nconst cssOf = (c: RGB, a = 1): string => `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${a})`;\n/** The print's colours, for the raster (lab/calendar-print.ts `PrintLook`). */\nexport const calendarPrint = () => {\n const L = CALENDAR_LOOK;\n const pens: Record<string, string> = {};\n for (const name of PEN_NAMES) pens[name] = cssOf(pen(name));\n const highlighters: Record<string, string> = {};\n for (const name of HIGHLIGHTER_NAMES) highlighters[name] = cssOf(rgb(L.highlighters[name].css));\n return { ink: cssOf(rgb(L.ink.css)), muted: cssOf(rgb(L.muted.css)), faint: L.alpha.faint, hot: cssOf(rgb(L.hot.css)), pencil: cssOf(rgb(L.pencil.css), 0.55), pens, highlighters, highlight: L.alpha.highlight };\n};\n/** The pad's materials, for the pass: the paper, the print's rules and wash, the chipboard, the tape's cloth and foil. */\nexport const calendarLook = (tape: CalendarTape): { paper: RGB; ink: RGB; muted: RGB; weekend: RGB; hot: RGB; chipboard: RGB; cloth: RGB; foil: RGB; alpha: typeof CALENDAR_LOOK.alpha } => {\n const L = CALENDAR_LOOK;\n const t = L.tapes[tape];\n return { paper: rgb(L.paper.css), ink: rgb(L.ink.css), muted: rgb(L.muted.css), weekend: rgb(L.weekend.css), hot: rgb(L.hot.css), chipboard: rgb(L.chipboard.css), cloth: rgb(t.cloth.css), foil: rgb(t.foil.css), alpha: L.alpha };\n};\n\n/**\n * The inks a PERSON takes in apps/desk's rooms (D5a) — the colour `@ice/dom`'s remote-cursors reflector paints a peer's cursor and\n * name chip in (core's `PresenceInfo.color`): violet and the warm hues, which read over the green mat by day and under the Moon;\n * none a green of the mat's, none the pencil's blue (YOUR hand's). A demo's choice, not yet a DESIGN.md token.\n */\nexport const PRESENCE_INKS = [\"#8e4ec6\", \"#e2a336\", \"#e5484d\", \"#d6409f\", \"#f76b15\"] as const;\n\n/** A palette every reference kind reads its look from: the roles, the note's papers and pens, the vinyls, the board's, the notebooks' and the calendars' materials. */\nexport type DeskPalette = PaperPalette & MiniMatPalette & BoardPalette & NotebookPalette & CalendarPalette;\n\n/**\n * THE DEFAULT PALETTE (D-D7-C.1) — complete for `DESK_OBJECTS`: the roles, the note's one paper (`yellow` — the product's\n * `--vf-note-surface`), its pens, the mini mats' vinyls, the whiteboard's materials and markers (BOARD.md), the notebooks' page,\n * ruling and covers (NOTEBOOK.md §4), the calendar's paper, print, tapes and presences (CALENDAR.md §4). `deskLayer({ palette })`\n * takes it as it is; an app with its own tokens hands its own (the kinds read only what `theme()` is given).\n */\nexport const deskPalette = (name: ThemeName): DeskPalette => ({\n ...PALETTE[name], papers: { yellow: SURFACES.note }, pens: PENS, vinyls: VINYLS,\n board: BOARD_LOOK, markers: MARKERS,\n notebooks: { ...NOTEBOOK_LOOK, rule: notebookRuleInk()[3] },\n calendars: CALENDAR_LOOK,\n});\n\n/** The theme the passes read for a name — `themeFrom` on the default palette's roles (the oracle's `THEMES[name]` exactly). */\nexport const deskTheme = (name: ThemeName): GroundTheme => themeFrom(name, PALETTE[name]);\n","// The NOTEBOOK's spec as BOOK.md set it (moved out of the engine's src/theme.ts at K4a, design-016 §5). The 3D notebook\n// draws by its own law (notebook/law.ts); what the book shares with the note, the whiteboard and the mini mat — the lift,\n// the slab's shadow, the face's light, the ring — is the kit's ONE PHYSICS (kit/physics.ts), by name.\n\nimport { PHYSICS } from \"@ice/desk/kit\";\n\n/**\n * The NOTEBOOK (BOOK.md) — a desk object under the mat's lamp, ONE PHYSICS with the sticky\n * note: it lifts as the note lifts and casts as the note casts (`PAPER`'s numbers, by name),\n * plus what a slab has and a sheet has not — a CONTACT shadow at its base (the tree-shadow\n * design system's paper elevation, mat.css `--lift-1`: a tight `-1px 2px 0 cast/.22` under the\n * soft `-3px 5px 10px`), the lamp's fill on a face turned from it (the cover mid-swing), and\n * the materials: the page's fibre is the note's grain; the board wears a cloth, a rolled edge\n * and the spine's roll; a bound page dips into the gutter; a stack shows its sheets' edges.\n * Lengths are world units (CSS px at zoom 1); the colours are the product's (lab/theme.ts).\n */\nexport const BOOK = {\n lift: PHYSICS.lift,\n /** The slab's shadow: the note's penumbra with a contact term at its base — the one physics's (kit/physics.ts). */\n shadow: PHYSICS.slab,\n /** The lamp's fill on a face: the one physics's. */\n light: PHYSICS.light,\n /**\n * The leaves' dapple on the object, as a share of the mat's own (1 = the reference's shade, floor 0.5):\n * a PAGE takes it gently so writing under the palm stays legible (thinking-the-desk §6 guardrail 3),\n * a board takes it whole. BOOK.md Q-b — James's to rule.\n */\n dapple: { page: 0.55, board: 1 },\n /** The fibre (the note's grain, a touch more — a notebook's sheet is heavier than a Post-it's), the gutter's depth and width, the sheets' edge pitch (device px). */\n paper: { fibre: 3.5 / 255, gutterDepth: 0.35, gutterWidth: 14, edgeStep: 1.3 },\n /** The board: its cloth (±/255), the rolled edge's width and tilt (rad), the spine's roll. */\n cover: { cloth: 6 / 255, bevel: 2.2, bevelTilt: 0.96, roll: 5 },\n /** The ruling: the pitch (the fine lattice at zoom 1), a dot's radius, a rule's width. */\n rule: { pitch: 20, dot: 0.7, width: 0.6 },\n ring: PHYSICS.ring,\n /** A notebook as a host spawns one: A6 at the card grid's scale — 176 × 248, a 16 px tape, 9 px fore-edge corners, 1.8 px boards, 80 sheets of 0.12, 2.5 px squares. */\n spec: { width: 176, height: 248, spine: 16, radius: 9, board: 1.8, sheet: 0.12, sheets: 80, inset: 2.5 },\n} as const;\n","// The reference kinds as the ground registers them (kind.ts's `KindProgram`; design-015 §5.2's render half): the note, the mini\n// mat, the whiteboard, the photo print, the desk calendar and the notebook, each a thin adapter over its pass (the last two\n// LAYERED — the kit's `LayeredKind`: a target of their own, laid as one composite run; root only, D-D18). The desk never imports\n// this module — a host hands `Ground.create` a registry, and the reference one is `DESK_KINDS`.\n//\n// And the kinds WHOLE (`ObjectKind`, D2a-world): `paperKind()`, `minimatKind()`, … — each a `KindProgram` with its world half\n// (resolve · record · hit · reach · theme) — what `defineObject` binds a widget type to and the builder drives. Their own package\n// since design-016 K4b (`@ice/objects`): each kind's folder imports the desk's public entries alone.\nimport type { KindProgram, ShaderText } from \"@ice/desk\";\nimport { shaderText } from \"./shaders\";\nimport { boardProgram } from \"./board/kind\";\nimport { calendarProgram } from \"./calendar/kind\";\nimport { miniMatProgram } from \"./minimat/kind\";\nimport { notebookProgram } from \"./notebook/kind\";\nimport { paperProgram } from \"./paper/kind\";\nimport { photoProgram } from \"./photo/kind\";\n\nexport { BOARD_KIND, BOARD_TOOLS, type BoardInk, boardInked, BoardKind, type BoardKindOptions, type BoardObjectLook, type BoardPalette, boardFrame, boardKind, boardPose, boardProgram, boardReach, boardRest, createBoardInk, ERASER_TOOL_ID, inking, inkOfTool, markerToolId, type PenHand, type PenPin } from \"./board/kind\";\nexport { CALENDAR_KIND, type CalendarAlpha, calendarFrame, type CalendarGeometry, CalendarKind, type CalendarKindOptions, calendarKind, type CalendarObjectLook, type CalendarPalette, calendarProgram, calendarReach, type CalendarPart, type CalendarPartName, createPads, DRAFT_ID, type PadDraft, type PadMarks, type PadPose, type Pads, partAt, sheetDayBox, sheetDraw, sheetOnScreen, sheetPoint } from \"./calendar/kind\";\nexport type { EventLine, PrintLook, SheetPrint } from \"./calendar/print\";\nexport type { PinnedSheet } from \"./calendar/printing\";\nexport { INSIDE_GRID, MINIMAT_KIND, MiniMatKind, type MiniMatKindOptions, type MiniMatLook, type MiniMatPalette, miniMatFrame, miniMatProgram, miniMatReach, minimatKind, SAGE } from \"./minimat/kind\";\nexport { INK_H, INK_W } from \"./notebook/ink\";\n// the kinds' own specs — each kind's law as numbers, in its own folder since K4a (design-016 §5; the one physics they share is the kit's)\nexport { BOARD } from \"./board/theme\";\nexport { MINIMAT } from \"./minimat/theme\";\nexport { BOOK } from \"./notebook/theme\";\nexport { PAPER } from \"./paper/theme\";\nexport { askTurn, bookAngle, bookFrame, type BookPose, type Books, createBooks, DEFAULT_PEN, inTurnZone, NOTEBOOK_KIND, NOTEBOOK_PAGE, NOTEBOOK_PENS, NOTEBOOK_TOOLS, notebookFrame, type NotebookGeometry, NotebookKind, type NotebookKindOptions, notebookKind, type NotebookObjectLook, type NotebookPalette, notebookProgram, notebookReach, PageTurns, pageHitAt, partOf, penOfTool, penToolId } from \"./notebook/kind\";\nexport { PAPER_KIND, type PaperAsset, PaperKind, type PaperKindOptions, type PaperLook, type PaperPalette, paperFrame, paperProgram, paperReach, paperKind } from \"./paper/kind\";\nexport { createPrints, type FlickWitness, PHOTO_KIND, photoFrame, photoKind, PhotoKind, type PhotoKindOptions, type PhotoPose, photoProgram, photoReach, PRINT_RETURN_MS, printExtent, printRect, type PrintRest, type Prints } from \"./photo/kind\";\n// the text stack's seam and the note's writing (D2c, design-015 §6.1)\nexport { createWriting, DEFAULT_BLEED, DEFAULT_FACE, DEFAULT_HAND_LAW, type InkPages, type NoteInk, type NoteRasterInfo, type Writing, type WritingStats } from \"./paper/writing\";\n\n/**\n * The desk's kinds in the order they prepare — the prototype's (the notes, the mini mats, the whiteboards; its prints\n * after the ground, as its photo lab drew them; then its two layers in the order its lab rendered them: the calendar's\n * before the frame, the notebooks' after it) — each made from `text`: the kinds' shader text (theirs and the kit's — ./shaders.ts)\n * unless a host says (the Node oracle hands the .wgsl files on disk).\n */\nexport function deskKinds(text: ShaderText = shaderText): readonly KindProgram[] {\n return [paperProgram(text), miniMatProgram(text), boardProgram(text), photoProgram(text), calendarProgram(text), notebookProgram(text)];\n}\n\n/** The desk's kinds on the kinds' generated shader text (and the kit's) — what a browser host registers: `Ground.create({ device, canvas, mat, kinds: DESK_KINDS })`. */\nexport const DESK_KINDS: readonly KindProgram[] = deskKinds();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBO,IAAM,UAAU;AAAA;AAAA,EAErB,MAAM,EAAE,GAAG,KAAK,GAAG,IAAI;AAAA;AAAA,EAEvB,QAAQ;AAAA,EAAI,QAAQ;AAAA,EAAI,OAAO;AAAA;AAAA,EAE/B,MAAM,EAAE,QAAQ,IAAI,OAAO,KAAK;AAAA,EAAG,OAAO;AAAA;AAAA,EAE1C,QAAQ,QAAQ;AAAA;AAAA,EAEhB,MAAM,EAAE,OAAO,KAAK,OAAO,KAAK,MAAM,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAY3C,OAAO;AAAA,IACL,OAAO;AAAA,IAAM,MAAM;AAAA,IAAM,OAAO;AAAA,IAAG,OAAO,CAAC,GAAG,GAAG,EAAE;AAAA,IACnD,QAAQ,EAAE,KAAK,GAAG,KAAK,KAAK,KAAK,EAAE;AAAA,IAAG,YAAY,CAAC,IAAI,EAAE;AAAA,IACzD,MAAM,EAAE,KAAK,GAAG,UAAU,KAAK;AAA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,gBAAgB,EAAE,CAAC,EAAE;AAAA,EAC1D,WAAW;AACb;AAGO,IAAM,YAAY,CAAC,SAAiC,UAAU,MAAM,QAAQ,IAAI,CAAC;;;AC/RjF,IAAM,OAAO;AAAA,EAClB,MAAM,QAAQ;AAAA;AAAA,EAEd,QAAQ,QAAQ;AAAA;AAAA,EAEhB,OAAO,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMf,QAAQ,EAAE,MAAM,MAAM,OAAO,EAAE;AAAA;AAAA,EAE/B,OAAO,EAAE,OAAO,MAAM,KAAK,aAAa,MAAM,aAAa,IAAI,UAAU,IAAI;AAAA;AAAA,EAE7E,OAAO,EAAE,OAAO,IAAI,KAAK,OAAO,KAAK,WAAW,MAAM,MAAM,EAAE;AAAA;AAAA,EAE9D,MAAM,EAAE,OAAO,IAAI,KAAK,KAAK,OAAO,IAAI;AAAA,EACxC,MAAM,QAAQ;AAAA;AAAA,EAEd,MAAM,EAAE,OAAO,KAAK,QAAQ,KAAK,OAAO,IAAI,QAAQ,GAAG,OAAO,KAAK,OAAO,MAAM,QAAQ,IAAI,OAAO,IAAI;AACzG;;;ACGO,SAAS,UAAUC,QAAmBC,aAAoC;AAC/E,SAAO,CAAC,aAAaD,KAAI,GAAG,eAAeA,KAAI,GAAG,aAAaA,KAAI,GAAG,aAAaA,KAAI,GAAG,gBAAgBA,KAAI,GAAG,gBAAgBA,KAAI,CAAC;AACxI;AAGO,IAAM,aAAqC,UAAU;","names":["p","p","text","shaderText","text","p","shaderText","MiniMat","p","BLEND_PREMUL","p","text","text","release","near","lay","band","entryOf","order","text","shaderText","p","NOTE_INK","NOTE_PROPS","inkOf","font","b","p","px","py","BLEND_PREMUL","linear","t","p","text","text","OWNER","p","lay","shaderText","board","p","TIPS","Board","p","p","p","text","r","BLEND_PREMUL","sheet","p","c","text","text","track","name","band","band","clamp01","p","text","text","p","today","sheet","t","release","shaderText","pointersQ","p","part","dropTarget","today","carried","pointersQ","today","p","font","band","p","text","smooth","p","sub","a","place","first","p","INK_LAYERS","p","clamp","s","i","clamp","clamp","p","p","rad","box","INK_LAYERS","s","SAMPLES","BLEND_PREMUL","dropTarget","INK_LAYERS","at","same","p","text","text","p","clamp","springStep","shaderText","q","place","pointersQ","f32","clamp","p","mix","smooth","near","spring","project","unproject","sdRoundBox","lod","p","release","BLEND_PREMUL","p","text","text","p","hash","ready","b","shaderText","pointersQ","p","Photo","MiniMat","Board","Photo","COVERS","PENS","MARKERS","VINYLS","PENS","VINYLS","MARKERS","text","shaderText"]}