diff --git a/.agents/skills/formblocks-driving/SKILL.md b/.agents/skills/formblocks-driving/SKILL.md index 10c3e7a..906173e 100644 --- a/.agents/skills/formblocks-driving/SKILL.md +++ b/.agents/skills/formblocks-driving/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-driving -description: "Use when asked to build, stack, change, check, picture or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats bricks on placements or the ground, builds walls in overlapping courses with plates, tiles and slopes, moves, drags, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into building steps and walks them, counts parts and saves the parts list as CSV, saves PNG pictures and reads them back to check a build, checks overlaps and floating parts, and opens, saves and exports .fblk, .ldr and .mpd files. Covers Claude Code, Codex, Cursor and Antigravity in the agent dock or outside it, and the person's approval, which an agent never gives itself. Includes worked examples, coordinates, error codes and scripts. Not for changing FormBlocks' source code, installing or building it (formblocks-harness)." +description: "Use when asked to build, stack, change, check, picture or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats bricks, clips and hinge halves on placements or the ground, builds walls in overlapping courses with plates, tiles and slopes, moves, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into steps and walks them, counts parts and saves the parts list as CSV, saves PNG pictures and reads them back to check a build, checks overlaps, and opens, saves and exports .fblk, .ldr and .mpd files. Covers Claude Code, Codex, Cursor and Antigravity in the agent dock or outside it, and the person's approval, which an agent never gives itself. Includes worked examples, coordinates, error codes and scripts. Not for changing FormBlocks' source code or installing it (formblocks-harness)." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.4.0" + pack-version: "0.5.0" audience: operating agent --- @@ -20,14 +20,17 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L | Search words, categories, part numbers, moved parts, parts of other systems | `sub-skills/finding-parts/SUB-SKILL.md` | | Colour codes, colour names, finishes, colour 16 inside submodels, recolouring | `sub-skills/colours/SUB-SKILL.md` | | Studs and anti-studs, seating on a part or the ground, part.place, part.fit, on, seated, refused placements | `sub-skills/placing-and-snapping/SUB-SKILL.md` | +| Clips on bars, hinge halves, hinge plates and bricks, swivel plates, sliding a clip, folding a hinge, part.connectors kinds | `sub-skills/clips-and-hinges/SUB-SKILL.md` | | Planning a build, walls in overlapping courses, corners, openings, plates and tiles, roofs of slopes | `sub-skills/building-in-order/SUB-SKILL.md` | | Moving, turning, duplicating, recolouring, hiding, showing and deleting placements, undo and redo | `sub-skills/changing-parts/SUB-SKILL.md` | +| Turning parts by any angle, about a point, an axis or a hinge's axis, part.pivot, the angle step, a turn lifted or refused | `sub-skills/turning-parts/SUB-SKILL.md` | | Moving or copying parts along a pointer ray as the window drags them, part.pick, the scene's axes, resting across a gap, what the person's drags and Ctrl+D do | `sub-skills/moving-parts/SUB-SKILL.md` | | Reading and setting the selection, selecting by colour or part, showing the person which parts | `sub-skills/selection/SUB-SKILL.md` | | Packing repeated units into submodels, placing uses, editing inside one, unpacking, renaming, deleting | `sub-skills/submodels/SUB-SKILL.md` | | Building steps: what a sensible step is, adding, naming, moving and deleting steps, the step shown | `sub-skills/steps/SUB-SKILL.md` | | Walking the steps: step.goto by number or first, previous, next, last, what each step adds, dimmed earlier steps, leaving the step shown right | `sub-skills/step-walking/SUB-SKILL.md` | | New, open, save, save as, LDraw export, inserting a model, what `.fblk`, `.ldr`, `.mpd` and `.dat` keep | `sub-skills/files/SUB-SKILL.md` | +| What a model is: its name, description, author, licence, counts, size, file facts, missing parts, and setting them (the Info tab) | `sub-skills/model-information/SUB-SKILL.md` | | Checking a build: the overlap check, floating parts, reading the model back, counting parts | `sub-skills/checking-a-model/SUB-SKILL.md` | | The parts list: counts per part and colour, scopes, missing and moved parts, selecting a row's parts, saving it as CSV | `sub-skills/parts-list/SUB-SKILL.md` | | A picture of the model or of every step, and looking at your own build by saving a PNG and reading it back | `sub-skills/pictures/SUB-SKILL.md` | diff --git a/.agents/skills/formblocks-driving/evals/evals.json b/.agents/skills/formblocks-driving/evals/evals.json index 8a56786..5df2ecb 100644 --- a/.agents/skills/formblocks-driving/evals/evals.json +++ b/.agents/skills/formblocks-driving/evals/evals.json @@ -92,6 +92,36 @@ "Refuses to answer the window's question or change the standing choice, and says the person can choose Always allow or set it in the Outside agents dialog", "Refuses to fetch the library or type the consent words, and names the library card or the command the person runs" ] + }, + { + "id": 9, + "name": "turn-by-45", + "prompt": "Turn the red brick p1 45 degrees about its up axis in FormBlocks and tell me if anything is wrong afterwards.", + "files": [], + "expected_behavior": [ + "Sends part.rotate with ids [p1], axis y and angle 45, not quarter_turns, and passes ids rather than relying on the selection", + "Reads the answer's lifted value, runs overlap.check afterwards, and says a turn that is not a quarter turn seats nothing" + ] + }, + { + "id": 10, + "name": "open-a-hinge", + "prompt": "Put a 44301a hinge half beside the 44302a at the top of my model and open the hinge 90 degrees.", + "files": [], + "expected_behavior": [ + "Turns the half a half turn about y before placing it near its partner, because snapping never turns a part, and reads seated and joined", + "Reads part.pivot for the hinge's point and axis and sends part.rotate with axis_vector, about and angle 90 for that half only" + ] + }, + { + "id": 11, + "name": "who-made-this-model", + "prompt": "How big is the open model, how many different parts and colours does it use, and which parts is the library missing? Put my name as the author.", + "files": [], + "expected_behavior": [ + "Reads model.info with table false and answers from counts, size and missingParts", + "Sets the author with model.set_info and says it is one undo step; does not touch the licence line" + ] } ], "trigger_evals": [ @@ -105,6 +135,9 @@ { "query": "register the formblocks MCP server with my agent", "should_trigger": true }, { "query": "how many bricks does this model need, save the parts list as csv", "should_trigger": true }, { "query": "save a picture of each building step of my brick model", "should_trigger": true }, + { "query": "tilt this brick 22.5 degrees and tell me if it lifted off the ground in FormBlocks", "should_trigger": true }, + { "query": "clip the plate onto the bar and slide it along in my brick model", "should_trigger": true }, + { "query": "what licence and author does my open brick model carry and how many studs across is it", "should_trigger": true }, { "query": "add a new MCP tool to the FormBlocks engine source", "should_trigger": false }, { "query": "fix the typecheck error in the FormBlocks window code", "should_trigger": false }, { "query": "write a parser for LDraw files in Rust", "should_trigger": false }, diff --git a/.agents/skills/formblocks-driving/references/command-catalogue.md b/.agents/skills/formblocks-driving/references/command-catalogue.md index 3e76eb4..9c9f875 100644 --- a/.agents/skills/formblocks-driving/references/command-catalogue.md +++ b/.agents/skills/formblocks-driving/references/command-catalogue.md @@ -4,8 +4,8 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never ## Contents -- MCP tools: the 69 tools an agent sees, each with whether it only reads. -- Commands: the 63 catalogue commands with their titles, parameters and summaries, in name order. +- MCP tools: the 72 tools an agent sees, each with whether it only reads. +- Commands: the 66 catalogue commands with their titles, parameters and summaries, in name order. ## MCP tools @@ -17,12 +17,13 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `formblocks_redo` | no | Redo changes that formblocks_undo took back, one step each. A new change after an undo empties what can be redone. Returns {revision, labels, label}. | | `formblocks_status` | yes | Read what this FormBlocks is: its version, the model's revision, placement count, file and unsaved mark, how many commands there are, its data folder, whether the window's engine is running, and the person's standing choice for outside agents (ask, allowed or blocked). Call it first. | | `formblocks_undo` | no | Undo the last changes, one step per command. Returns {revision, labels, label}: the new revision and the titles of the commands taken back, newest first. Nothing to undo answers an empty labels list. | +| `cmd_angle_step` | yes | Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_current` | yes | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_list` | yes | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. Only reads. | | `cmd_colours_used` | yes | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. Only reads. | | `cmd_grid_step` | yes | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_library_status` | yes | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. Only reads. | -| `cmd_model_info` | yes | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. Only reads. | +| `cmd_model_info` | yes | Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use; its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them); the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false. Only reads. | | `cmd_model_insert` | no | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_new` | no | Start a new model named Untitled with one empty step, and a new history. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_open` | no | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | @@ -32,9 +33,10 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_model_save_as` | no | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_set_info` | no | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_tree` | yes | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. Only reads. | -| `cmd_overlap_check` | yes | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. Only reads. | -| `cmd_overlap_set` | yes | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | -| `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. Only reads. | +| `cmd_overlap_check` | yes | List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU. Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked. Only reads. | +| `cmd_overlap_nested` | yes | Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole. Nested pairs never block placing or moving either way. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_overlap_set` | yes | Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind. Only reads. | | `cmd_part_delete` | no | Remove placements from the model; deleting the last use of a submodel keeps the submodel. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate` | no | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate_at_ray` | no | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | @@ -44,10 +46,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_part_move` | no | Move placements by an offset in LDU, exactly, with no snapping. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_move_at_ray` | no | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers, resting on what lies under its footprint when the place under the pointer would cut into another part; the others keep their places relative to it. Give held as the drag preview answered it so the part lands as previewed. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_pick` | yes | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. Only reads. | +| `cmd_part_pivot` | yes | Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone; with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point. Only reads. | | `cmd_part_place` | no | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_place_at_ray` | no | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers, resting on what lies under its whole footprint when the place under the pointer would cut into another part; it goes into the step shown of the submodel being edited and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_recolour` | no | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | -| `cmd_part_rotate` | no | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_rotate` | no | Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given. What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_set_transform` | no | Put one placement at an exact position, rotation or both, as the details panel does. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_show` | no | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_parts_list` | yes | Read the parts a model needs, one row per part and colour with its description, colour name, count and the placements of the submodel being edited that hold it; a submodel's parts counted once for each use unless submodels is row, a moved part counted under the number it moved to, parts missing from the library first and marked. With text true the answer also holds the list as tab separated text. Only reads. | @@ -85,12 +88,13 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | Command | Title | Reads only | Parameters | What it does | | --- | --- | --- | --- | --- | +| `angle.step` | Angle Step | yes | `step` (number) | Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting. | | `colours.current` | Current Colour | yes | `colour` (integer) | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. | | `colours.list` | Colours | yes | `text` (string, optional), `group` (string, optional), `hue` (string, optional) | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. | | `colours.used` | Colours Used | yes | none | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. | | `grid.step` | Grid Step | yes | `step` (string) | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. | | `library.status` | Library Status | yes | none | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. | -| `model.info` | Model Information | yes | none | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. | +| `model.info` | Model Information | yes | `table` (boolean, optional) | Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use; its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them); the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false. | | `model.insert` | Insert LDraw Model | no | `path` (string), `position` (array, optional), `submodel` (string, optional) | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. | | `model.new` | New Model | no | `discard` (boolean, optional) | Start a new model named Untitled with one empty step, and a new history. | | `model.open` | Open | no | `path` (string), `discard` (boolean, optional) | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. | @@ -100,9 +104,10 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `model.save_as` | Save As | no | `path` (string) | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. | | `model.set_info` | Set Model Information | no | `title` (string, optional), `author` (string, optional), `licence` (string, optional) | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. | | `model.tree` | Model Tree | yes | `submodel` (string, optional) | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. | -| `overlap.check` | Check Overlaps | yes | `ids` (array, optional) | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. | -| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. | -| `part.connectors` | Part Connectors | yes | `part` (string) | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. | +| `overlap.check` | Check Overlaps | yes | `ids` (array, optional), `nested` (boolean, optional) | List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU. Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked. | +| `overlap.nested` | Nested Pairs | yes | `on` (boolean) | Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole. Nested pairs never block placing or moving either way. Kept as the person's setting. | +| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting. | +| `part.connectors` | Part Connectors | yes | `part` (string), `kind` (string, optional) | List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind. | | `part.delete` | Delete | no | `ids` (array, optional) | Remove placements from the model; deleting the last use of a submodel keeps the submodel. | | `part.duplicate` | Duplicate | no | `ids` (array, optional), `delta` (array, optional) | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. | | `part.duplicate_at_ray` | Duplicate at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. | @@ -112,10 +117,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `part.move` | Move | no | `ids` (array, optional), `delta` (array) | Move placements by an offset in LDU, exactly, with no snapping. | | `part.move_at_ray` | Move Selection at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers, resting on what lies under its footprint when the place under the pointer would cut into another part; the others keep their places relative to it. Give held as the drag preview answered it so the part lands as previewed. One undo step. | | `part.pick` | Pick at Pointer | yes | `origin` (array), `direction` (array), `ground` (boolean, optional) | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. | +| `part.pivot` | Pivot | yes | `ids` (array, optional), `origin` (array, optional), `direction` (array, optional) | Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone; with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point. | | `part.place` | Place Part | no | `part` (string), `colour` (integer), `position` (array, optional), `rotation` (array, optional), `submodel` (string, optional), `step` (integer, optional), `on` (string, optional), `snap` (boolean, optional) | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. | | `part.place_at_ray` | Place Part at Pointer | no | `part` (string), `colour` (integer), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `step` (integer, optional), `snap` (boolean, optional) | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers, resting on what lies under its whole footprint when the place under the pointer would cut into another part; it goes into the step shown of the submodel being edited and becomes the selection. | | `part.recolour` | Recolour | no | `ids` (array, optional), `colour` (integer) | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. | -| `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string), `quarter_turns` (integer), `about` (array, optional) | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. | +| `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string, optional), `quarter_turns` (integer, optional), `angle` (number, optional), `axis_vector` (array, optional), `about` (array, optional) | Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given. What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step. | | `part.set_transform` | Set Position and Rotation | no | `id` (string), `position` (array, optional), `rotation` (array, optional) | Put one placement at an exact position, rotation or both, as the details panel does. | | `part.show` | Show | no | `ids` (array, optional) | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). | | `parts.list` | Parts List | yes | `scope` (string, optional), `group` (string, optional), `submodels` (string, optional), `text` (boolean, optional) | Read the parts a model needs, one row per part and colour with its description, colour name, count and the placements of the submodel being edited that hold it; a submodel's parts counted once for each use unless submodels is row, a moved part counted under the number it moved to, parts missing from the library first and marked. With text true the answer also holds the list as tab separated text. | diff --git a/.agents/skills/formblocks-driving/references/error-codes.md b/.agents/skills/formblocks-driving/references/error-codes.md index 59f5912..be3d89c 100644 --- a/.agents/skills/formblocks-driving/references/error-codes.md +++ b/.agents/skills/formblocks-driving/references/error-codes.md @@ -53,7 +53,7 @@ A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids | "part: ... is not in the LDraw parts library in use" | Search with `parts.search` and place the number it answers. A number with letters (`3068b`) is a different part from the bare number. | | "No LDraw parts library is installed" | Nothing can be placed. Tell the person; only they can find or fetch the library (`sub-skills/parts-library/SUB-SKILL.md`). | | "position: give a position, a placement to seat on (on), or a pointer ray" | `part.place` needs `position` or `on`. | -| "position: the part would overlap ... with the overlap check on" | The person's overlap check is on and the place is taken. Pick another place; the check is coarse inside arches and hollows, so tell the person if a part is refused where it should fit. | +| "position: the part would overlap ... by ... LDU with the overlap check on, so it was not placed." | The person's overlap check is on and the place is taken by more than 1 LDU of real shape. Pick another place; a part whose surface is not closed can be refused where it should fit, so tell the person if that happens. | | "... must stay within 1000000 LDU of the origin" | A position or offset is out of range: check signs and units. | | "on: ... has no free connector that ... can seat on" | Every stud of that placement is taken. Seat on another placement, or give a position. | | "on: ... is hidden" | Hidden parts offer no connectors. Show it with `part.show` first, or use a position. | @@ -87,6 +87,6 @@ A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids - `part.place` answering `"seated": false`: the part did not join anything. With the overlap check off (its first setting) it was put on the grid step instead and may float in the air or sit inside another part. Undo it and fix the position, unless a loose part is what you meant. - `part.place` with `on` seating on a different part of the target than you wanted: `on` takes the first free studs nearest the target's middle. Give a position for an exact place. -- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. +- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. A `nested_count` above 0 is not a fault: those parts sit in each other's hollows by design, and are listed only with `nested: true`. - `model.open` answering an `issueCount` above 0: some lines could not be read; `model.report` lists them. The rest of the file opened. - A JSON-RPC timeout on a `change` sent from outside: the person may still have the question open. Read the model before sending again. diff --git a/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md index e359a5c..22c5308 100644 --- a/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md +++ b/.agents/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md @@ -47,7 +47,7 @@ Where two walls meet, let one wall run through the corner cell in one course and - A half turn about Y, `rotation` `[-1,0,0, 0,1,0, 0,0,-1]`, makes it face the back. - Lay a flat layer of plates on the walls first, so every slope has studs under its whole footprint. - A gable roof: a row of slopes facing front along the front edge and a row facing back along the back edge. Each further row steps in by one stud and up by one brick, standing on the studs of the row below and on filler bricks behind it. Close the ridge with plates or tiles over the last studs. -- The overlap check follows a slope's face in slabs 4 LDU thick, so a part held clear above the face is not refused, but one cutting into the face is. The slabs step by half a plate, so a part within a few LDU of the face can still be reported; tell the person why when it is. +- The overlap check compares real shapes, so a part held clear above a slope's face is not refused and one cutting more than 1 LDU into the face is. Where it still reports a part that fits, such as one tucked under a roof whose surface is not closed, tell the person why. ## After each course diff --git a/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md index 6b42af5..4704707 100644 --- a/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md +++ b/.agents/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md @@ -17,7 +17,7 @@ Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left o | --- | --- | --- | | `part.move` | `ids`, `delta` | Moves by an exact offset in LDU, `[dx, dy, dz]`. No snapping: the parts go exactly where sent. Up is a negative `dy`. | | `part.set_transform` | `id`, `position`, `rotation` | Puts one placement at an exact position, an exact rotation, or both. | -| `part.rotate` | `ids`, `axis`, `quarter_turns`, `about` | Turns by quarter turns about `x`, `y` or `z`, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the placements' origins, and works out the new positions and matrices. | +| `part.rotate` | `ids`, `axis` or `axis_vector`, `quarter_turns` or `angle`, `about` | Turns by whole quarter turns or by an angle in degrees, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the box round the placements' shapes. Lifts a turn off the ground and, with the overlap check on, refuses one into a part that stays; `sub-skills/turning-parts/SUB-SKILL.md` has the rest. | | `part.duplicate` | `ids`, `delta` | Copies the placements with their colours and relative places, offset by `delta`. The copies go into the step shown and become the selection; the answer lists their new ids. | | `part.recolour` | `ids`, `colour` | Gives a colour code. Parts already in it are left as they are. | | `part.delete` | `ids` | Removes placements. Deleting the last use of a submodel keeps the submodel itself. | @@ -32,8 +32,9 @@ Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left o ## Turning in place - A quarter turn about Y of one 2 x 4 brick about its own origin turns it crosswise on the same spot; it may then overlap its neighbours. -- To turn a whole group as one, give all their ids: they turn about the centre of their origins and keep their places relative to one another. +- To turn a whole group as one, give all their ids: they turn about the centre of their box and keep their places relative to one another. - To turn about a stud, give `about` as that stud's position. +- Any other angle than a quarter turn is the same command with `angle` (`sub-skills/turning-parts/SUB-SKILL.md`). ## Repeating a row diff --git a/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md index a022c85..a811ab9 100644 --- a/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md +++ b/.agents/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md @@ -9,16 +9,18 @@ Never report a build as done from memory of the commands you sent. Read the mode ## The overlap check -`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose bodies overlap, with the depth of the overlap in LDU. Give `ids` to check only those placements against the rest; leave it out for the whole model. It works whatever the person's overlap switch says. +`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose real shapes cut into each other, with the depth in LDU and the shared volume in cubic LDU. Give `ids` to check only those placements against their neighbours; leave it out for the whole model. It works whatever the person's overlap switch says. ```json -{"checked": 28, "overlaps": [], "count": 0} -{"checked": 5, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p5", "depth": 23.0}], "count": 1} +{"checked": 28, "overlaps": [], "count": 0, "nested_count": 0, "nested_listed": false} +{"checked": 2, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p2", "depth": 24.0, "kind": "overlap", "volume": 16952.0, "parts": ["3001.dat", "3001.dat"]}], "count": 1, "nested_count": 0, "nested_listed": false} ``` - `count` 0 is the goal. -- Parts seated on each other never count, and parts that only touch face to face never count. -- The check is coarse: each part is stood in for by a box round its body, without its studs, shrunk by half an LDU, and a part whose outline changes with height (a slope, a windscreen, a round part) by a stack of slabs 4 LDU thick, so the open wedge over a slope's face is free. The space inside an arch, under a hinge or inside a hollow still counts as solid, so a part tucked there is reported although it fits. Say so to the person rather than moving a part that is right. +- Parts seated on each other never count, and parts that only touch, or cut into each other by 1 LDU or less, never count. +- Since 0.5.0 each part is its real solid, studs included, filled into cells of 1 LDU, so a part tucked into a hollow, an arch or under a hinge without cutting into the walls is not an overlap. A part with a surface that is not closed, or a part the library lacks, can still be reported wrongly; say so to the person rather than moving a part that is right. +- A pair whose outlines meet but whose solids do not, and which no seated connector joins, such as a rim in its tyre or a pin in a hole, is a nested pair. Two hinge halves or a clip on a bar, seated, are fitted and not listed at all. It is counted in `nested_count` and listed only when you pass `nested: true` or the person's setting "Report nested pairs" is on (`nested_listed` says which). Nested pairs are never refused when placing, moving or turning. On the library's sample car the answer is 0 overlaps and 19 nested pairs. +- `overlap.nested` (`on`) is that setting, the person's, like the overlap switch: ask before you change it, and prefer `nested: true` on one call. - A depth near a whole brick (24) or plate (8) usually means a part was placed on top of another at the same height: undo it or move it. ## Seated, or floating @@ -41,7 +43,7 @@ Check the counts against the plan: the number of placements, the number in each ## Counting parts - `parts.list` counts what the model needs, one row per part and colour, a submodel's parts once per use, missing parts first; `parts.list_save` writes it as CSV. `sub-skills/parts-list/SUB-SKILL.md` gives the scopes and the answer. -- `model.info` (read) answers the model's name, author, file and library update, `counts` (`parts`, `differentParts`, `pairs`, `missing`, `submodels`, `steps`, `placements`), its `size` in LDU, studs, bricks and millimetres, and the parts list with it. +- `model.info` (read) answers the model's name, author, file and library update, `counts` (`parts`, `differentParts`, `pairs`, `colours`, `overlaps`, `missing`, `submodels`, `steps`, `placements`), `missingParts` by number, its `size` in LDU, studs, bricks and millimetres, and the parts list with it unless `table` is false (`sub-skills/model-information/SUB-SKILL.md`). - `colours.used` (read) lists each colour of the model with its number, name and how many parts are in it, most used first; `known` false marks a colour the library does not define. Check the counts against the plan: parts in each colour, kinds of part, the number of steps. diff --git a/.agents/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md new file mode 100644 index 0000000..a54221b --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md @@ -0,0 +1,66 @@ +--- +name: clips-and-hinges +description: Seats and turns clips on bars and hinge halves on each other in FormBlocks with part.place, part.fit, part.connectors and part.rotate about a hinge axis. Use when asked to build with clips, bars, handles, hinges, hinge plates, hinge bricks or swivel plates, to fold or open a hinge, to slide a clip along a bar, when a clip or hinge half will not seat, or to read which clip, bar or hinge kinds a part has. +--- + +# Clips, bars and hinges + +Besides studs and anti-studs, the engine finds three more kinds of join from a part's own shape and snaps them with the same rule: `part.place`, `part.fit` and the window's drags all use it. Read the kinds of any part with `part.connectors` (`cmd_part_connectors`, read; pass `kind` to list only one kind, such as `clip`, `bar` or `hinge_click_1`). A part with none of them seats as before. + +## The kinds + +| Kind | Pairs with | What it is | +| --- | --- | --- | +| `clip` | `bar` | Jaws that close round a rod 8 LDU across, from the library's clip pieces, such as the one on `4085c`, a Plate 1 x 1 with Clip. | +| `bar` | `clip` | Any free rod of radius 4 with room round it for jaws: the handle of a plate with a handle, `87994` Bar 3L (free length 60 LDU), the rods of many accessories. Found from the shape, so a rod never meant to be gripped can count too. | +| `hinge_click_1`, `hinge_click_2` | each other | Single-finger and dual-finger click hinge halves, such as `44301a` and `44302a`. | +| `hinge_plate_2`, `hinge_plate_3` | each other | Two-finger and three-finger plate hinge halves, `4276b` and `4275b`. | +| `hinge_arm_2`, `hinge_arm_3` | each other | The hinge arm with discs. | +| `hinge_brick_base`, `hinge_brick_top` | each other | The 1 x 2 hinge brick, `3937` and `3938`. | +| `hinge_swivel_base`, `hinge_swivel_top` | each other | The 1 x 4 swivel hinge plates, `2429` and `2430`. | + +A half pairs only with the other half of its own family. A clip does not take a stud, and a bar does not go into an anti-stud. + +## Seating a clip on a bar + +The clip's centre is put on the bar's line, and it slides along the bar in grid steps measured from the bar's middle: at the Stud step the middle and 20 LDU either side of it, at Plate every 10, at Fine anywhere along the free length. One bar holds several clips side by side; a second clip over a taken stretch is not seated. + +```bash +./formblocks cli run part.place part=87994 colour=7 'position=[0,-80,0]' +./formblocks cli run part.set_transform id=p1 'position=[0,-80,0]' +./formblocks cli run part.place part=4085c colour=4 on=p1 +./formblocks cli run part.place part=4085c colour=4 'position=[2,-45,21]' +``` + +A floating bar is put exactly with `part.set_transform`, because `part.place` rounds an unseated part to the grid (the first line answered position `[4, -76, 4]` and `seated` false). With `on`, the clip took the first free stretch of the bar, its centre at y = -70. With a position, a clip whose centre was at y = -41 seated at -50, the nearest place at the Stud step. The clip of `4085c` is at `[0, 4, -20]` in the part's own axes (`part.connectors part=4085c`), so its origin ends up 4 above the clip's centre and 20 behind the bar's line. Always read `seated`, `joined` and `marks` in the answer. + +## Seating hinge halves + +Snapping never turns a part. Turn the half first so its pivot line runs the way its partner's does, then place it near: it moves so the two lines meet. + +```bash +./formblocks cli run part.place part=44302a colour=4 'position=[0,-100,0]' +./formblocks cli run part.set_transform id=p1 'position=[0,-100,0]' +./formblocks cli run part.place part=44301a colour=1 'position=[63,-102,2]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' +``` + +The last answered `seated` true at `[60, -100, 0]`, one joined pair and a mark at `[30, -98, 0]`. With `part.fit`, the same half unturned at `[2, -101, 1]` answered `seated` false, a three-finger plate hinge half held against another `4275b` answered false, and a `4276b` held against a `4275b` turned a half turn answered true at `[60, -100, 0]`; unturned it answered false. `3938` seated on `3937` at `[0, -100, 0]`. + +## Opening and closing a hinge + +`part.pivot` (read) on a seated half answers `kind` `hinge`, the hinge's point as `about` and its axis in `axes` (LDraw and scene axes); a clip seated on a bar answers the same, since it turns on the bar. Give that point and axis to `part.rotate`: + +```bash +./formblocks cli run part.pivot 'ids=["p2"]' +./formblocks cli run part.rotate 'ids=["p2"]' 'axis_vector=[0,0,-1]' 'about=[30,-98,0]' angle=90 +``` + +The half turned 90 degrees, from `[60, -100, 0]` to `[28, -128, 0]`. `part.rotate` turns only the placements in `ids`: when other parts are attached to the half, give their ids too. A hinge turns all the way round; with the person's overlap check on, a turn into a part that does not turn is refused (`sub-skills/turning-parts/SUB-SKILL.md`). In the window the person turns the same half with the one ring of the pivot dial, in angle steps. + +## What overlap.check says + +Two halves joined by a seated hinge answered `count` 0. A clip seated on a bar, anywhere along it, answered `count` 0 and `nested_count` 0: a pair joined by a seated connector is fitted, never an overlap and never nested. + +## Not found, not built + +A hinge or clip drawn without the library's own pieces is found only where the engine's list of corrections names it (the 1 x 2 hinge brick, the swivel plates, the 1 x 1 tile with a clip); other parts do not snap, so place them by position and say so. Pins, axles, ball joints, a bar into a hole, hinge turning limits, click positions and flexible parts are not built: do not promise them. diff --git a/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md index 0d46b5d..2b050bd 100644 --- a/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md +++ b/.agents/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md @@ -27,7 +27,7 @@ A saved file holds references to parts (`3001.dat`), never a part's own lines. F | `model.insert` | change | `path`, `position`, `submodel` | Brings another `.ldr`, `.mpd` or `.fblk` in as new submodels and places one use of its main model (at `position`, or the origin). | | `model.recent` | read | none | The last ten files opened or saved, newest first, each with whether it still exists. | | `model.report` | read | none | What opening reported: lines that could not be read, with their numbers, and the text encoding. | -| `model.info` | read | none | The model's title, author, licence, file, library update, counts and size. | +| `model.info` | read | `table` | The model's name, title, author, licence, file, library update, counts, size and missing parts, with its parts list unless `table` is false (`sub-skills/model-information/SUB-SKILL.md`). | | `model.set_info` | change | `title`, `author`, `licence` | Changes the main model's header: the title (its file's first line), the author, and the licence, empty or one of the Creative Commons licences the parameter lists. | Two other commands write files of their own and wait for the person like a save: `parts.list_save` (a CSV, `sub-skills/parts-list/SUB-SKILL.md`) and `picture.save` with `picture.steps` (PNG pictures, `sub-skills/pictures/SUB-SKILL.md`). diff --git a/.agents/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md new file mode 100644 index 0000000..b9e46d0 --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md @@ -0,0 +1,40 @@ +--- +name: model-information +description: Reads and changes a FormBlocks model's own information, its name, description, author, licence, counts, size, file facts and missing parts, with model.info, model.set_info and submodel.rename, the facts the window shows in its Info tab. Use when asked what a model is, how big it is, how many parts, colours or steps it has, which parts the library lacks, who made it, what licence line it carries, or to set its title, author, licence or name. +--- + +# Model information + +The window's Info tab (the fourth tab of the right column) shows these facts and lets the person edit four of them. The engine counts every value; an agent reads and writes the same ones. + +## Reading: model.info + +`model.info` (`cmd_model_info`, read) answers: + +| Key | What it holds | +| --- | --- | +| `name`, `title`, `author`, `licence` | The main model's `Name:` line, its description (the title line an LDraw file starts with), its author, and the licence line, empty when none. | +| `path`, `kind`, `builtWith`, `library` | The file it came from or was saved to, its kind (`fblk`, `ldr`, `mpd`), the library update it was last saved with (`null` for an LDraw file that did not come from FormBlocks), and the update in use. | +| `counts` | `placements`, `parts` (through every use of a submodel), `differentParts`, `colours`, `pairs` (part and colour rows), `submodels`, `steps` of the main model, `missing` (parts the library lacks) and `overlaps` (as `overlap.check` counts them, nested pairs left out). | +| `size` | `ldu`, `studs`, `bricks`, `plates`, `mm` and the `box`; an LDU is 0.4 mm. | +| `missingParts` | Each part the library lacks: `part`, `file` and `count`. | +| `licences` | The licence lines `model.set_info` accepts. | +| `partsList`, `csv` | The parts list rows and its CSV text. Pass `table` false to leave them out; the answer is large on a big model. | + +On the library's sample car, `model.info` with `table` false answered 61 placements, 26 different parts, 7 colours, 32 rows, 8 steps, 0 overlaps and a size of 4.5 by 10.8 studs and 5.17 bricks high, which a hand count of the file matched. + +## Changing it + +| Command | Parameters | What it changes | +| --- | --- | --- | +| `model.set_info` | `title`, `author`, `licence` | The description, the author and the licence line. Any of them may be left out. `licence` is empty or one of the lines in `licences`; another is refused with the list. | +| `submodel.rename` | `name`, `new_name` | The main model's name when `name` is it, and every use of it. `.ldr` is added when `new_name` has no extension. | + +Each is a change command: one undo step labelled "Change model information" or "Rename ...", approved by the person when it comes from outside the window. A model that was never saved keeps its changes only in memory until `model.save_as`. + +## Habits + +- Read `counts` and `missingParts` before telling the person a build is complete; a part in `missingParts` is drawn as a marked box and counted in the parts list as "Not in this library". +- `overlaps` here is the same as `count` in `overlap.check`; for the pairs themselves call `overlap.check`. +- Set the licence line only when the person says which; it describes the model, never the parts, which keep their own licences. +- The window shows a changed value in place at once, because the tab is rewritten from the engine's answer. diff --git a/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md index d673fcd..43eb734 100644 --- a/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md +++ b/.agents/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md @@ -78,7 +78,7 @@ The full list is `references/error-codes.md`. ## The overlap check -The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's body box would overlap another part's; with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. +The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's real shape would cut more than 1 LDU into another part's (a part resting in a hollow it fits is not refused, and a nested pair never is); with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. ## Habits that save undo steps diff --git a/.agents/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md b/.agents/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md new file mode 100644 index 0000000..a52a37b --- /dev/null +++ b/.agents/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md @@ -0,0 +1,52 @@ +--- +name: turning-parts +description: Turns placed parts in FormBlocks by any angle with part.rotate (angle in degrees or quarter turns, about x, y or z or any axis_vector, about a point), reads what a turn would turn about with part.pivot, and explains the angle step, the pivot dial and J that the person uses in the window. Use when asked to turn, tilt, tip, roll, angle or swivel parts, to turn by 45 or 22.5 degrees, to turn about a stud, a corner or a hinge, when a turn lifts a part or is refused, or when the person talks about the pivot dial or the angle step. +--- + +# Turning parts + +A turn is one `part.rotate` and one undo step, whoever asks for it: the person's key, a drag on the pivot dial, or an agent. + +## What part.rotate takes + +| Parameter | Meaning | +| --- | --- | +| `ids` | Placement ids such as `["p1","p2"]`; the selection when left out, which may be the person's, so pass `ids`. | +| `axis` | `x`, `y` or `z`, LDraw's axes, `y` being up and down. Give this or `axis_vector`. | +| `axis_vector` | Any direction as `[x, y, z]` in LDraw axes, such as a hinge's axis, in place of `axis`. | +| `quarter_turns` | Whole quarter turns, right-handed about the positive axis; negative goes the other way. Give this or `angle`. | +| `angle` | Degrees, right-handed about the axis; negative goes the other way. | +| `about` | The point to turn about, in LDU. Left out, the centre of the box round the placements' real shapes. | + +Giving both `quarter_turns` and `angle`, or neither, or neither axis, is refused with a sentence that names the parameter. A quarter turn leaves a part where its studs can seat again; any other angle does not seat anything, and a turn never seats a part. Four quarter turns give back the same numbers exactly; other angles are settled to six places. + +```bash +./formblocks cli run part.rotate 'ids=["p1"]' axis=y angle=45 +./formblocks cli run part.rotate 'ids=["p1","p2"]' axis=y quarter_turns=1 'about=[0,0,0]' +``` + +The answer lists each turned placement with its new `position`, `rotation` and `matrix`, the `about` point, the `angle` and `axis` used, and `lifted`, how far the turned parts were raised. + +## Two rules the engine keeps + +- A turn never leaves a part below the ground. When the turned parts would end lower than the ground, the whole turned group is lifted straight up until it rests on it, and `lifted` says how far. A 2 x 4 brick standing on the ground, turned 45 degrees about y and then 90 about x, answered `lifted` 28.426 on the second turn. +- With the person's overlap check on, a turn that would push a turned part into a part that does not turn is refused and nothing turns: "ids: the turn would overlap p1 with p2 by 3.0 LDU with the overlap check on, so nothing was turned." With the check off the turn happens and `overlap.check` reports it afterwards. + +A turn of a whole number of full circles changes nothing and adds no undo step. + +## part.pivot + +`part.pivot` (read) says what the person's pivot dial turns about: for `ids` or the selection, `kind` `centre` with the centre of the box and the three axes in LDraw's axes (`about`, `axes`) and in the window's scene axes (`scene`), and `reach`, how far the box extends from the point. For one part joined by a hinge it answers the hinge's own point and axis alone. With a pointer ray (`origin`, `direction`, scene axes) it answers the point the ray meets on a part, or the connector within 8 LDU of it. Use it to find the axis for an `axis_vector` turn; it changes nothing. + +## The angle step, the person's setting + +`angle.step` (`step`: 90, 45, 22.5, 15, 5 or 1) sets the step the dial and Alt with R, T or Y turn by; it is the person's setting like the grid step, so ask before changing it. `part.rotate` does not use it: give the angle you want. + +## What the person sees + +Selected parts show a green pivot ring lying flat about the up axis; pressing on it and dragging turns them in angle steps, Shift for whole degrees, Esc to put them back. J shows three rings and a click on a part sets the pivot on its nearest connector. A key turn is Alt with R, T or Y; A goes to the next angle step. An agent's turn shows in the window at once. Typing an angle on the dial is not built; send `part.rotate` instead. + +## Traps + +- `part.rotate`'s `axis` is LDraw's, with -Y up. A pointer ray's axes are the scene's (`sub-skills/moving-parts/SUB-SKILL.md`). +- After a turn other than a quarter turn nothing is seated: check with `overlap.check`, and turn the part back or move it if the person wants it joined. diff --git a/.agents/skills/formblocks-harness/SKILL.md b/.agents/skills/formblocks-harness/SKILL.md index 00b4f7a..a0cc957 100644 --- a/.agents/skills/formblocks-harness/SKILL.md +++ b/.agents/skills/formblocks-harness/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-harness -description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, meshes, connections, command catalogue), its window, its setup scripts, its agent dock wiring or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, boot and ports, doctor, selfcheck, contract and agents checks, looking at the window headless under throttling with layout shift recorded, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash or flicker, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, where code lives, what packages may import, and adding a command, a connector kind, a router, a pane, or an agent program to the dock. Also the picture round trip, the parts list's rows, the parts library's scratch copy, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." +description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, meshes, connections, command catalogue), its window, its setup scripts, its agent dock wiring or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, boot and ports, doctor, selfcheck, contract and agents checks, the window looked at headless under throttling with layout shift recorded, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, where code lives, and adding a command, a connector kind, a router, a pane, or an agent program to the dock. Also the picture round trip, the parts list's rows, the library's scratch copy, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.4.0" + pack-version: "0.5.0" audience: developer agent --- diff --git a/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md index a2075b1..1559257 100644 --- a/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: add-connector-kind -description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding pins, axles, clips, bars, hinges or any joint beyond studs and anti-studs, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. +description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding a joint beyond studs, anti-studs, clips, bars and the hinge families, such as pins or axles, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. --- # Add a connector kind @@ -36,6 +36,11 @@ A subclass of `Kind` from `backend/app/connect/kinds/__init__.py`: | `from_mesh(mesh, connectors)` | Optional: connectors found from the whole flattened part. | | `mate(a, b)` | `None`, or a `Mate`: the correction that brings `a` onto `b`, the residual, and the `Freedom` left (`Freedom.spin`, `slide`, `hinge` or `fixed`). `axial_mate` covers round connectors on a shared axis. | | `blocks(connector, other)` | Optional: a blocked test of the kind's own, as the stud's blocked-stud test is. | +| `line` | True when the connector is a line, not a facing: its axis has no sign, the mate compares lines (clips, bars and hinge halves). | +| `takes_step` | True when the seat moves in grid steps: `mate(a, b, step)` is then also given the grid step's across value, and gets 0 when pairs are only being counted. | +| `spans` | True when a connector is a segment from `position` along `axis` for `length` (a bar): reach and mating distance are measured to the segment, the spatial hash keeps it by every cell it passes, and it is taken stretch by stretch. A `Mate` then says where along the partner it sits (`at`) and half the stretch it takes (`span`). | + +`kinds/clip.py` (clip and bar) and `kinds/hinge.py` (the five hinge families, three read from primitives and two from overrides only) are the worked examples; each has its numbers in `clip.json` or `hinge.json`. `mates_with` is declared once per kind and the registry makes it symmetric, so a half pairs only with the other half of its own family. Connectors already carry `ref` (for kinds whose turn about the axis matters) and `length` (for kinds that slide), so the connector shape does not change. @@ -48,5 +53,6 @@ Connectors already carry `ref` (for kinds whose turn about the axis matters) and 1. Selfcheck: `backend/venv/bin/python backend/formblocks_engine.py --selfcheck` imports the kinds. 2. With a library in reach, `./formblocks cli run part.connectors part=[number]` for each part you worked by hand: the counts, positions, axes and `source` must match your numbers. Run it with a throwaway data folder (`--settings-dir ''`) so no old cache answers. 3. Place two parts that should mate with `part.fit` and `part.place` and read `seated` and `joined`; run `overlap.check`. -4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. -5. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. +4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. `part.connectors` takes `kind` to list one kind, and its counts always cover every kind. +5. A mate that is a line needs the half turned first: snapping never turns a part. Check a pair with `part.fit` once turned and once not, as `spec/CONNECTIONS.md`, "Worked snaps: a clip along a bar, and hinge halves", does, and read `seated`. +6. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. diff --git a/.agents/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md index fd877a7..406f3d8 100644 --- a/.agents/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md @@ -41,4 +41,5 @@ The Outside agents tab is the model: kind `agent`, read only, made by the engine ## Checking -Only Claude Code may be real on a check machine, and nothing may sign in or start a paid turn. Codex may be installed from the npm registry into a scratch prefix under `/tmp` to check its version call and that it takes the arguments. Every other program is checked with a stand-in: a script under `/tmp` named as the program, put on the path through `FORMBLOCKS_[PROGRAM]_BIN`, which records its arguments, folder, environment names and the MCP entry it finds, then calls the MCP address with the token it was given. Open its tab in the window headless (`sub-skills/verify/SUB-SKILL.md`), then check: `formblocks_status` with the tab's token answers 200, `/api/terminal` with it 403, the token absent from the arguments, 401 after the tab closes, the shell tab's environment without either variable, `./formblocks [program] --print-config`, `./formblocks agents status`, and layout shift 0 opening and closing the tab. Say which programs were real and which were stand-ins. +Nothing may sign in or start a paid turn. On 27 November 2026 all four programs were real on a check machine: Claude Code from the machine, Codex from the npm registry into a scratch prefix, and Cursor's agent and Antigravity from their own installers into a scratch home folder given to the engine as `HOME`, so the finder found them in their known folders. +When an installer cannot be reached, or for a program being added, use a stand-in: a script under `/tmp` named as the program, put on the path through `FORMBLOCKS_[PROGRAM]_BIN`, which records its arguments, folder, environment names and the MCP entry it finds, then calls the MCP address with the token it was given. Open its tab in the window headless (`sub-skills/verify/SUB-SKILL.md`), then check: `formblocks_status` with the tab's token answers 200, `/api/terminal` with it 403, the token absent from the arguments, 401 after the tab closes, the shell tab's environment without either variable, `./formblocks [program] --print-config`, `./formblocks agents status`, and layout shift 0 opening and closing the tab. Say which programs were real and which were stand-ins. diff --git a/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md index d53f42e..65942d2 100644 --- a/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md @@ -24,5 +24,6 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. The window renders what the 4. Style it in `frontend/src/styles/[name].css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. Interface text goes in `ui/strings.ts`. 5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('[name]')`. No icon library, no copied icon art, never a three-star sparkle. 6. A window command (a button, a menu item, a key) is added through `commands` in `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. -7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. The right column's tabs (Model, Steps, Parts) come from the one list in `ui/tabs.ts`; a pane there takes its host with `tabHost(name, fn)` and hears `onTabShown`. A list that can grow long uses `RowScroller` from `ui/parts-list-scroller.ts` and its rules (`sub-skills/parts-list-rows/SUB-SKILL.md`). A panel over the view, like Save Picture, is built once hidden and shown at its final size. +7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. The right column's tabs (Model, Steps, Parts, Info) come from the one list in `ui/tabs.ts`; a pane there takes its host with `tabHost(name, fn)` and hears `onTabShown`. The column is three sections, the colour palette, the tabs and the details panel, laid out and folded by `ui/splits.ts` with their least, default and greatest heights and the header height from `styles/tokens.css`; the tab section takes the room the other two leave, the heights and folds are kept in the engine's `right_column` setting and read before the first paint, and Reset Right Column is a window command. + A new tab never changes those heights: give it a place in the one list and fill its host in place, as the Info tab does (`ui/model-info.ts`, every value's place present before it arrives). A list that can grow long uses `RowScroller` from `ui/parts-list-scroller.ts` and its rules (`sub-skills/parts-list-rows/SUB-SKILL.md`). A panel over the view, like Save Picture, is built once hidden and shown at its final size. 8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then look at the window headless (`sub-skills/verify/SUB-SKILL.md`, "Looking at the window"): a screenshot of the pane, and a hard reload under 4x CPU and network throttling with a layout shift score of 0. Say what you looked at, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. diff --git a/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md index 6a13d0c..288fc67 100644 --- a/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md @@ -19,7 +19,7 @@ Nothing in this repository pushes, signs (beyond the frozen engine on macOS) or | `./build_app` | a desktop build for a person, start to finish | Logs to `build_app.log`; `--no-install`, `--install`, `--open`, `--clean`, `--config FILE`. | | `./formblocks clean`, `clean --all` | removes build output; `--all` also the venv and `node_modules` | Ask before `--all`: other agents may be using them. | -Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing, as on the check machines here, no Tauri build runs: say so, never claim one passed. +Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing no Tauri build runs: say so, never claim one passed. One Linux build (deb and AppImage, unsigned) has run; its report is in `src-tauri/HASHOUT_LOG.md`. Its self-check imports numpy and every module, and the freeze must carry the connector data files (clip and hinge kinds included). macOS, Windows, signing and rpm are not run. ## Data files the freeze must carry diff --git a/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md b/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md index bb6ae9b..0bb322c 100644 --- a/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md +++ b/.agents/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md @@ -44,7 +44,7 @@ This is the method the 0.4.0 lanes used, several at once in one tree. Then do each interaction you built and add up `window.__shifts` entries without `input`. A score above 0 on load or on any of them is a defect to fix. Vite's development server sends hundreds of modules, so under this network a load takes over a minute: give it the time rather than lifting the throttle. 6. The outside agent path: run `./formblocks mcp` as a child process speaking JSON-RPC on its standard input and output, call the tool in one thread, and answer the window's question from Playwright in the other. The question is a dialog; the dock's Chat holds a hidden button of the same name, so pick the visible one (`page.get_by_role("button", name="Allow once", exact=True).locator("visible=true")`). The answer from a test is yours as the person in a scratch data folder, never an agent's on a real one. -7. Agent programs: only Claude Code may be real here, never signed in; the others are stand-ins (`sub-skills/add-dock-program/SUB-SKILL.md`). Say which were which. +7. Agent programs: never sign in. Use the real programs where they install (all four did on 27 November 2026) and a stand-in where one cannot (`sub-skills/add-dock-program/SUB-SKILL.md`). Say which were which. 8. Scripts, screenshots and data stay under `/tmp`, never in the repository. Stop the engine, Vite and the browser when the check is done, each by the process id you started; never by name, since other lanes' engines carry the same name. ## What CI runs diff --git a/.claude/skills/formblocks-driving/SKILL.md b/.claude/skills/formblocks-driving/SKILL.md index 10c3e7a..906173e 100644 --- a/.claude/skills/formblocks-driving/SKILL.md +++ b/.claude/skills/formblocks-driving/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-driving -description: "Use when asked to build, stack, change, check, picture or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats bricks on placements or the ground, builds walls in overlapping courses with plates, tiles and slopes, moves, drags, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into building steps and walks them, counts parts and saves the parts list as CSV, saves PNG pictures and reads them back to check a build, checks overlaps and floating parts, and opens, saves and exports .fblk, .ldr and .mpd files. Covers Claude Code, Codex, Cursor and Antigravity in the agent dock or outside it, and the person's approval, which an agent never gives itself. Includes worked examples, coordinates, error codes and scripts. Not for changing FormBlocks' source code, installing or building it (formblocks-harness)." +description: "Use when asked to build, stack, change, check, picture or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats bricks, clips and hinge halves on placements or the ground, builds walls in overlapping courses with plates, tiles and slopes, moves, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into steps and walks them, counts parts and saves the parts list as CSV, saves PNG pictures and reads them back to check a build, checks overlaps, and opens, saves and exports .fblk, .ldr and .mpd files. Covers Claude Code, Codex, Cursor and Antigravity in the agent dock or outside it, and the person's approval, which an agent never gives itself. Includes worked examples, coordinates, error codes and scripts. Not for changing FormBlocks' source code or installing it (formblocks-harness)." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.4.0" + pack-version: "0.5.0" audience: operating agent --- @@ -20,14 +20,17 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L | Search words, categories, part numbers, moved parts, parts of other systems | `sub-skills/finding-parts/SUB-SKILL.md` | | Colour codes, colour names, finishes, colour 16 inside submodels, recolouring | `sub-skills/colours/SUB-SKILL.md` | | Studs and anti-studs, seating on a part or the ground, part.place, part.fit, on, seated, refused placements | `sub-skills/placing-and-snapping/SUB-SKILL.md` | +| Clips on bars, hinge halves, hinge plates and bricks, swivel plates, sliding a clip, folding a hinge, part.connectors kinds | `sub-skills/clips-and-hinges/SUB-SKILL.md` | | Planning a build, walls in overlapping courses, corners, openings, plates and tiles, roofs of slopes | `sub-skills/building-in-order/SUB-SKILL.md` | | Moving, turning, duplicating, recolouring, hiding, showing and deleting placements, undo and redo | `sub-skills/changing-parts/SUB-SKILL.md` | +| Turning parts by any angle, about a point, an axis or a hinge's axis, part.pivot, the angle step, a turn lifted or refused | `sub-skills/turning-parts/SUB-SKILL.md` | | Moving or copying parts along a pointer ray as the window drags them, part.pick, the scene's axes, resting across a gap, what the person's drags and Ctrl+D do | `sub-skills/moving-parts/SUB-SKILL.md` | | Reading and setting the selection, selecting by colour or part, showing the person which parts | `sub-skills/selection/SUB-SKILL.md` | | Packing repeated units into submodels, placing uses, editing inside one, unpacking, renaming, deleting | `sub-skills/submodels/SUB-SKILL.md` | | Building steps: what a sensible step is, adding, naming, moving and deleting steps, the step shown | `sub-skills/steps/SUB-SKILL.md` | | Walking the steps: step.goto by number or first, previous, next, last, what each step adds, dimmed earlier steps, leaving the step shown right | `sub-skills/step-walking/SUB-SKILL.md` | | New, open, save, save as, LDraw export, inserting a model, what `.fblk`, `.ldr`, `.mpd` and `.dat` keep | `sub-skills/files/SUB-SKILL.md` | +| What a model is: its name, description, author, licence, counts, size, file facts, missing parts, and setting them (the Info tab) | `sub-skills/model-information/SUB-SKILL.md` | | Checking a build: the overlap check, floating parts, reading the model back, counting parts | `sub-skills/checking-a-model/SUB-SKILL.md` | | The parts list: counts per part and colour, scopes, missing and moved parts, selecting a row's parts, saving it as CSV | `sub-skills/parts-list/SUB-SKILL.md` | | A picture of the model or of every step, and looking at your own build by saving a PNG and reading it back | `sub-skills/pictures/SUB-SKILL.md` | diff --git a/.claude/skills/formblocks-driving/evals/evals.json b/.claude/skills/formblocks-driving/evals/evals.json index 8a56786..5df2ecb 100644 --- a/.claude/skills/formblocks-driving/evals/evals.json +++ b/.claude/skills/formblocks-driving/evals/evals.json @@ -92,6 +92,36 @@ "Refuses to answer the window's question or change the standing choice, and says the person can choose Always allow or set it in the Outside agents dialog", "Refuses to fetch the library or type the consent words, and names the library card or the command the person runs" ] + }, + { + "id": 9, + "name": "turn-by-45", + "prompt": "Turn the red brick p1 45 degrees about its up axis in FormBlocks and tell me if anything is wrong afterwards.", + "files": [], + "expected_behavior": [ + "Sends part.rotate with ids [p1], axis y and angle 45, not quarter_turns, and passes ids rather than relying on the selection", + "Reads the answer's lifted value, runs overlap.check afterwards, and says a turn that is not a quarter turn seats nothing" + ] + }, + { + "id": 10, + "name": "open-a-hinge", + "prompt": "Put a 44301a hinge half beside the 44302a at the top of my model and open the hinge 90 degrees.", + "files": [], + "expected_behavior": [ + "Turns the half a half turn about y before placing it near its partner, because snapping never turns a part, and reads seated and joined", + "Reads part.pivot for the hinge's point and axis and sends part.rotate with axis_vector, about and angle 90 for that half only" + ] + }, + { + "id": 11, + "name": "who-made-this-model", + "prompt": "How big is the open model, how many different parts and colours does it use, and which parts is the library missing? Put my name as the author.", + "files": [], + "expected_behavior": [ + "Reads model.info with table false and answers from counts, size and missingParts", + "Sets the author with model.set_info and says it is one undo step; does not touch the licence line" + ] } ], "trigger_evals": [ @@ -105,6 +135,9 @@ { "query": "register the formblocks MCP server with my agent", "should_trigger": true }, { "query": "how many bricks does this model need, save the parts list as csv", "should_trigger": true }, { "query": "save a picture of each building step of my brick model", "should_trigger": true }, + { "query": "tilt this brick 22.5 degrees and tell me if it lifted off the ground in FormBlocks", "should_trigger": true }, + { "query": "clip the plate onto the bar and slide it along in my brick model", "should_trigger": true }, + { "query": "what licence and author does my open brick model carry and how many studs across is it", "should_trigger": true }, { "query": "add a new MCP tool to the FormBlocks engine source", "should_trigger": false }, { "query": "fix the typecheck error in the FormBlocks window code", "should_trigger": false }, { "query": "write a parser for LDraw files in Rust", "should_trigger": false }, diff --git a/.claude/skills/formblocks-driving/references/command-catalogue.md b/.claude/skills/formblocks-driving/references/command-catalogue.md index 3e76eb4..9c9f875 100644 --- a/.claude/skills/formblocks-driving/references/command-catalogue.md +++ b/.claude/skills/formblocks-driving/references/command-catalogue.md @@ -4,8 +4,8 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never ## Contents -- MCP tools: the 69 tools an agent sees, each with whether it only reads. -- Commands: the 63 catalogue commands with their titles, parameters and summaries, in name order. +- MCP tools: the 72 tools an agent sees, each with whether it only reads. +- Commands: the 66 catalogue commands with their titles, parameters and summaries, in name order. ## MCP tools @@ -17,12 +17,13 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `formblocks_redo` | no | Redo changes that formblocks_undo took back, one step each. A new change after an undo empties what can be redone. Returns {revision, labels, label}. | | `formblocks_status` | yes | Read what this FormBlocks is: its version, the model's revision, placement count, file and unsaved mark, how many commands there are, its data folder, whether the window's engine is running, and the person's standing choice for outside agents (ask, allowed or blocked). Call it first. | | `formblocks_undo` | no | Undo the last changes, one step per command. Returns {revision, labels, label}: the new revision and the titles of the commands taken back, newest first. Nothing to undo answers an empty labels list. | +| `cmd_angle_step` | yes | Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_current` | yes | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_list` | yes | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. Only reads. | | `cmd_colours_used` | yes | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. Only reads. | | `cmd_grid_step` | yes | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_library_status` | yes | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. Only reads. | -| `cmd_model_info` | yes | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. Only reads. | +| `cmd_model_info` | yes | Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use; its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them); the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false. Only reads. | | `cmd_model_insert` | no | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_new` | no | Start a new model named Untitled with one empty step, and a new history. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_open` | no | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | @@ -32,9 +33,10 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_model_save_as` | no | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_set_info` | no | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_tree` | yes | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. Only reads. | -| `cmd_overlap_check` | yes | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. Only reads. | -| `cmd_overlap_set` | yes | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | -| `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. Only reads. | +| `cmd_overlap_check` | yes | List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU. Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked. Only reads. | +| `cmd_overlap_nested` | yes | Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole. Nested pairs never block placing or moving either way. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_overlap_set` | yes | Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind. Only reads. | | `cmd_part_delete` | no | Remove placements from the model; deleting the last use of a submodel keeps the submodel. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate` | no | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate_at_ray` | no | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | @@ -44,10 +46,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_part_move` | no | Move placements by an offset in LDU, exactly, with no snapping. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_move_at_ray` | no | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers, resting on what lies under its footprint when the place under the pointer would cut into another part; the others keep their places relative to it. Give held as the drag preview answered it so the part lands as previewed. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_pick` | yes | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. Only reads. | +| `cmd_part_pivot` | yes | Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone; with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point. Only reads. | | `cmd_part_place` | no | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_place_at_ray` | no | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers, resting on what lies under its whole footprint when the place under the pointer would cut into another part; it goes into the step shown of the submodel being edited and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_recolour` | no | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | -| `cmd_part_rotate` | no | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_rotate` | no | Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given. What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_set_transform` | no | Put one placement at an exact position, rotation or both, as the details panel does. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_show` | no | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_parts_list` | yes | Read the parts a model needs, one row per part and colour with its description, colour name, count and the placements of the submodel being edited that hold it; a submodel's parts counted once for each use unless submodels is row, a moved part counted under the number it moved to, parts missing from the library first and marked. With text true the answer also holds the list as tab separated text. Only reads. | @@ -85,12 +88,13 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | Command | Title | Reads only | Parameters | What it does | | --- | --- | --- | --- | --- | +| `angle.step` | Angle Step | yes | `step` (number) | Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting. | | `colours.current` | Current Colour | yes | `colour` (integer) | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. | | `colours.list` | Colours | yes | `text` (string, optional), `group` (string, optional), `hue` (string, optional) | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. | | `colours.used` | Colours Used | yes | none | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. | | `grid.step` | Grid Step | yes | `step` (string) | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. | | `library.status` | Library Status | yes | none | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. | -| `model.info` | Model Information | yes | none | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. | +| `model.info` | Model Information | yes | `table` (boolean, optional) | Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use; its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them); the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false. | | `model.insert` | Insert LDraw Model | no | `path` (string), `position` (array, optional), `submodel` (string, optional) | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. | | `model.new` | New Model | no | `discard` (boolean, optional) | Start a new model named Untitled with one empty step, and a new history. | | `model.open` | Open | no | `path` (string), `discard` (boolean, optional) | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. | @@ -100,9 +104,10 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `model.save_as` | Save As | no | `path` (string) | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. | | `model.set_info` | Set Model Information | no | `title` (string, optional), `author` (string, optional), `licence` (string, optional) | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. | | `model.tree` | Model Tree | yes | `submodel` (string, optional) | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. | -| `overlap.check` | Check Overlaps | yes | `ids` (array, optional) | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. | -| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. | -| `part.connectors` | Part Connectors | yes | `part` (string) | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. | +| `overlap.check` | Check Overlaps | yes | `ids` (array, optional), `nested` (boolean, optional) | List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU. Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked. | +| `overlap.nested` | Nested Pairs | yes | `on` (boolean) | Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole. Nested pairs never block placing or moving either way. Kept as the person's setting. | +| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting. | +| `part.connectors` | Part Connectors | yes | `part` (string), `kind` (string, optional) | List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind. | | `part.delete` | Delete | no | `ids` (array, optional) | Remove placements from the model; deleting the last use of a submodel keeps the submodel. | | `part.duplicate` | Duplicate | no | `ids` (array, optional), `delta` (array, optional) | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. | | `part.duplicate_at_ray` | Duplicate at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. | @@ -112,10 +117,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `part.move` | Move | no | `ids` (array, optional), `delta` (array) | Move placements by an offset in LDU, exactly, with no snapping. | | `part.move_at_ray` | Move Selection at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers, resting on what lies under its footprint when the place under the pointer would cut into another part; the others keep their places relative to it. Give held as the drag preview answered it so the part lands as previewed. One undo step. | | `part.pick` | Pick at Pointer | yes | `origin` (array), `direction` (array), `ground` (boolean, optional) | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. | +| `part.pivot` | Pivot | yes | `ids` (array, optional), `origin` (array, optional), `direction` (array, optional) | Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone; with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point. | | `part.place` | Place Part | no | `part` (string), `colour` (integer), `position` (array, optional), `rotation` (array, optional), `submodel` (string, optional), `step` (integer, optional), `on` (string, optional), `snap` (boolean, optional) | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. | | `part.place_at_ray` | Place Part at Pointer | no | `part` (string), `colour` (integer), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `step` (integer, optional), `snap` (boolean, optional) | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers, resting on what lies under its whole footprint when the place under the pointer would cut into another part; it goes into the step shown of the submodel being edited and becomes the selection. | | `part.recolour` | Recolour | no | `ids` (array, optional), `colour` (integer) | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. | -| `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string), `quarter_turns` (integer), `about` (array, optional) | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. | +| `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string, optional), `quarter_turns` (integer, optional), `angle` (number, optional), `axis_vector` (array, optional), `about` (array, optional) | Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given. What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step. | | `part.set_transform` | Set Position and Rotation | no | `id` (string), `position` (array, optional), `rotation` (array, optional) | Put one placement at an exact position, rotation or both, as the details panel does. | | `part.show` | Show | no | `ids` (array, optional) | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). | | `parts.list` | Parts List | yes | `scope` (string, optional), `group` (string, optional), `submodels` (string, optional), `text` (boolean, optional) | Read the parts a model needs, one row per part and colour with its description, colour name, count and the placements of the submodel being edited that hold it; a submodel's parts counted once for each use unless submodels is row, a moved part counted under the number it moved to, parts missing from the library first and marked. With text true the answer also holds the list as tab separated text. | diff --git a/.claude/skills/formblocks-driving/references/error-codes.md b/.claude/skills/formblocks-driving/references/error-codes.md index 59f5912..be3d89c 100644 --- a/.claude/skills/formblocks-driving/references/error-codes.md +++ b/.claude/skills/formblocks-driving/references/error-codes.md @@ -53,7 +53,7 @@ A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids | "part: ... is not in the LDraw parts library in use" | Search with `parts.search` and place the number it answers. A number with letters (`3068b`) is a different part from the bare number. | | "No LDraw parts library is installed" | Nothing can be placed. Tell the person; only they can find or fetch the library (`sub-skills/parts-library/SUB-SKILL.md`). | | "position: give a position, a placement to seat on (on), or a pointer ray" | `part.place` needs `position` or `on`. | -| "position: the part would overlap ... with the overlap check on" | The person's overlap check is on and the place is taken. Pick another place; the check is coarse inside arches and hollows, so tell the person if a part is refused where it should fit. | +| "position: the part would overlap ... by ... LDU with the overlap check on, so it was not placed." | The person's overlap check is on and the place is taken by more than 1 LDU of real shape. Pick another place; a part whose surface is not closed can be refused where it should fit, so tell the person if that happens. | | "... must stay within 1000000 LDU of the origin" | A position or offset is out of range: check signs and units. | | "on: ... has no free connector that ... can seat on" | Every stud of that placement is taken. Seat on another placement, or give a position. | | "on: ... is hidden" | Hidden parts offer no connectors. Show it with `part.show` first, or use a position. | @@ -87,6 +87,6 @@ A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids - `part.place` answering `"seated": false`: the part did not join anything. With the overlap check off (its first setting) it was put on the grid step instead and may float in the air or sit inside another part. Undo it and fix the position, unless a loose part is what you meant. - `part.place` with `on` seating on a different part of the target than you wanted: `on` takes the first free studs nearest the target's middle. Give a position for an exact place. -- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. +- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. A `nested_count` above 0 is not a fault: those parts sit in each other's hollows by design, and are listed only with `nested: true`. - `model.open` answering an `issueCount` above 0: some lines could not be read; `model.report` lists them. The rest of the file opened. - A JSON-RPC timeout on a `change` sent from outside: the person may still have the question open. Read the model before sending again. diff --git a/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md index e359a5c..22c5308 100644 --- a/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md +++ b/.claude/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md @@ -47,7 +47,7 @@ Where two walls meet, let one wall run through the corner cell in one course and - A half turn about Y, `rotation` `[-1,0,0, 0,1,0, 0,0,-1]`, makes it face the back. - Lay a flat layer of plates on the walls first, so every slope has studs under its whole footprint. - A gable roof: a row of slopes facing front along the front edge and a row facing back along the back edge. Each further row steps in by one stud and up by one brick, standing on the studs of the row below and on filler bricks behind it. Close the ridge with plates or tiles over the last studs. -- The overlap check follows a slope's face in slabs 4 LDU thick, so a part held clear above the face is not refused, but one cutting into the face is. The slabs step by half a plate, so a part within a few LDU of the face can still be reported; tell the person why when it is. +- The overlap check compares real shapes, so a part held clear above a slope's face is not refused and one cutting more than 1 LDU into the face is. Where it still reports a part that fits, such as one tucked under a roof whose surface is not closed, tell the person why. ## After each course diff --git a/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md index 6b42af5..4704707 100644 --- a/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md +++ b/.claude/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md @@ -17,7 +17,7 @@ Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left o | --- | --- | --- | | `part.move` | `ids`, `delta` | Moves by an exact offset in LDU, `[dx, dy, dz]`. No snapping: the parts go exactly where sent. Up is a negative `dy`. | | `part.set_transform` | `id`, `position`, `rotation` | Puts one placement at an exact position, an exact rotation, or both. | -| `part.rotate` | `ids`, `axis`, `quarter_turns`, `about` | Turns by quarter turns about `x`, `y` or `z`, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the placements' origins, and works out the new positions and matrices. | +| `part.rotate` | `ids`, `axis` or `axis_vector`, `quarter_turns` or `angle`, `about` | Turns by whole quarter turns or by an angle in degrees, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the box round the placements' shapes. Lifts a turn off the ground and, with the overlap check on, refuses one into a part that stays; `sub-skills/turning-parts/SUB-SKILL.md` has the rest. | | `part.duplicate` | `ids`, `delta` | Copies the placements with their colours and relative places, offset by `delta`. The copies go into the step shown and become the selection; the answer lists their new ids. | | `part.recolour` | `ids`, `colour` | Gives a colour code. Parts already in it are left as they are. | | `part.delete` | `ids` | Removes placements. Deleting the last use of a submodel keeps the submodel itself. | @@ -32,8 +32,9 @@ Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left o ## Turning in place - A quarter turn about Y of one 2 x 4 brick about its own origin turns it crosswise on the same spot; it may then overlap its neighbours. -- To turn a whole group as one, give all their ids: they turn about the centre of their origins and keep their places relative to one another. +- To turn a whole group as one, give all their ids: they turn about the centre of their box and keep their places relative to one another. - To turn about a stud, give `about` as that stud's position. +- Any other angle than a quarter turn is the same command with `angle` (`sub-skills/turning-parts/SUB-SKILL.md`). ## Repeating a row diff --git a/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md index a022c85..a811ab9 100644 --- a/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md +++ b/.claude/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md @@ -9,16 +9,18 @@ Never report a build as done from memory of the commands you sent. Read the mode ## The overlap check -`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose bodies overlap, with the depth of the overlap in LDU. Give `ids` to check only those placements against the rest; leave it out for the whole model. It works whatever the person's overlap switch says. +`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose real shapes cut into each other, with the depth in LDU and the shared volume in cubic LDU. Give `ids` to check only those placements against their neighbours; leave it out for the whole model. It works whatever the person's overlap switch says. ```json -{"checked": 28, "overlaps": [], "count": 0} -{"checked": 5, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p5", "depth": 23.0}], "count": 1} +{"checked": 28, "overlaps": [], "count": 0, "nested_count": 0, "nested_listed": false} +{"checked": 2, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p2", "depth": 24.0, "kind": "overlap", "volume": 16952.0, "parts": ["3001.dat", "3001.dat"]}], "count": 1, "nested_count": 0, "nested_listed": false} ``` - `count` 0 is the goal. -- Parts seated on each other never count, and parts that only touch face to face never count. -- The check is coarse: each part is stood in for by a box round its body, without its studs, shrunk by half an LDU, and a part whose outline changes with height (a slope, a windscreen, a round part) by a stack of slabs 4 LDU thick, so the open wedge over a slope's face is free. The space inside an arch, under a hinge or inside a hollow still counts as solid, so a part tucked there is reported although it fits. Say so to the person rather than moving a part that is right. +- Parts seated on each other never count, and parts that only touch, or cut into each other by 1 LDU or less, never count. +- Since 0.5.0 each part is its real solid, studs included, filled into cells of 1 LDU, so a part tucked into a hollow, an arch or under a hinge without cutting into the walls is not an overlap. A part with a surface that is not closed, or a part the library lacks, can still be reported wrongly; say so to the person rather than moving a part that is right. +- A pair whose outlines meet but whose solids do not, and which no seated connector joins, such as a rim in its tyre or a pin in a hole, is a nested pair. Two hinge halves or a clip on a bar, seated, are fitted and not listed at all. It is counted in `nested_count` and listed only when you pass `nested: true` or the person's setting "Report nested pairs" is on (`nested_listed` says which). Nested pairs are never refused when placing, moving or turning. On the library's sample car the answer is 0 overlaps and 19 nested pairs. +- `overlap.nested` (`on`) is that setting, the person's, like the overlap switch: ask before you change it, and prefer `nested: true` on one call. - A depth near a whole brick (24) or plate (8) usually means a part was placed on top of another at the same height: undo it or move it. ## Seated, or floating @@ -41,7 +43,7 @@ Check the counts against the plan: the number of placements, the number in each ## Counting parts - `parts.list` counts what the model needs, one row per part and colour, a submodel's parts once per use, missing parts first; `parts.list_save` writes it as CSV. `sub-skills/parts-list/SUB-SKILL.md` gives the scopes and the answer. -- `model.info` (read) answers the model's name, author, file and library update, `counts` (`parts`, `differentParts`, `pairs`, `missing`, `submodels`, `steps`, `placements`), its `size` in LDU, studs, bricks and millimetres, and the parts list with it. +- `model.info` (read) answers the model's name, author, file and library update, `counts` (`parts`, `differentParts`, `pairs`, `colours`, `overlaps`, `missing`, `submodels`, `steps`, `placements`), `missingParts` by number, its `size` in LDU, studs, bricks and millimetres, and the parts list with it unless `table` is false (`sub-skills/model-information/SUB-SKILL.md`). - `colours.used` (read) lists each colour of the model with its number, name and how many parts are in it, most used first; `known` false marks a colour the library does not define. Check the counts against the plan: parts in each colour, kinds of part, the number of steps. diff --git a/.claude/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md new file mode 100644 index 0000000..a54221b --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md @@ -0,0 +1,66 @@ +--- +name: clips-and-hinges +description: Seats and turns clips on bars and hinge halves on each other in FormBlocks with part.place, part.fit, part.connectors and part.rotate about a hinge axis. Use when asked to build with clips, bars, handles, hinges, hinge plates, hinge bricks or swivel plates, to fold or open a hinge, to slide a clip along a bar, when a clip or hinge half will not seat, or to read which clip, bar or hinge kinds a part has. +--- + +# Clips, bars and hinges + +Besides studs and anti-studs, the engine finds three more kinds of join from a part's own shape and snaps them with the same rule: `part.place`, `part.fit` and the window's drags all use it. Read the kinds of any part with `part.connectors` (`cmd_part_connectors`, read; pass `kind` to list only one kind, such as `clip`, `bar` or `hinge_click_1`). A part with none of them seats as before. + +## The kinds + +| Kind | Pairs with | What it is | +| --- | --- | --- | +| `clip` | `bar` | Jaws that close round a rod 8 LDU across, from the library's clip pieces, such as the one on `4085c`, a Plate 1 x 1 with Clip. | +| `bar` | `clip` | Any free rod of radius 4 with room round it for jaws: the handle of a plate with a handle, `87994` Bar 3L (free length 60 LDU), the rods of many accessories. Found from the shape, so a rod never meant to be gripped can count too. | +| `hinge_click_1`, `hinge_click_2` | each other | Single-finger and dual-finger click hinge halves, such as `44301a` and `44302a`. | +| `hinge_plate_2`, `hinge_plate_3` | each other | Two-finger and three-finger plate hinge halves, `4276b` and `4275b`. | +| `hinge_arm_2`, `hinge_arm_3` | each other | The hinge arm with discs. | +| `hinge_brick_base`, `hinge_brick_top` | each other | The 1 x 2 hinge brick, `3937` and `3938`. | +| `hinge_swivel_base`, `hinge_swivel_top` | each other | The 1 x 4 swivel hinge plates, `2429` and `2430`. | + +A half pairs only with the other half of its own family. A clip does not take a stud, and a bar does not go into an anti-stud. + +## Seating a clip on a bar + +The clip's centre is put on the bar's line, and it slides along the bar in grid steps measured from the bar's middle: at the Stud step the middle and 20 LDU either side of it, at Plate every 10, at Fine anywhere along the free length. One bar holds several clips side by side; a second clip over a taken stretch is not seated. + +```bash +./formblocks cli run part.place part=87994 colour=7 'position=[0,-80,0]' +./formblocks cli run part.set_transform id=p1 'position=[0,-80,0]' +./formblocks cli run part.place part=4085c colour=4 on=p1 +./formblocks cli run part.place part=4085c colour=4 'position=[2,-45,21]' +``` + +A floating bar is put exactly with `part.set_transform`, because `part.place` rounds an unseated part to the grid (the first line answered position `[4, -76, 4]` and `seated` false). With `on`, the clip took the first free stretch of the bar, its centre at y = -70. With a position, a clip whose centre was at y = -41 seated at -50, the nearest place at the Stud step. The clip of `4085c` is at `[0, 4, -20]` in the part's own axes (`part.connectors part=4085c`), so its origin ends up 4 above the clip's centre and 20 behind the bar's line. Always read `seated`, `joined` and `marks` in the answer. + +## Seating hinge halves + +Snapping never turns a part. Turn the half first so its pivot line runs the way its partner's does, then place it near: it moves so the two lines meet. + +```bash +./formblocks cli run part.place part=44302a colour=4 'position=[0,-100,0]' +./formblocks cli run part.set_transform id=p1 'position=[0,-100,0]' +./formblocks cli run part.place part=44301a colour=1 'position=[63,-102,2]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' +``` + +The last answered `seated` true at `[60, -100, 0]`, one joined pair and a mark at `[30, -98, 0]`. With `part.fit`, the same half unturned at `[2, -101, 1]` answered `seated` false, a three-finger plate hinge half held against another `4275b` answered false, and a `4276b` held against a `4275b` turned a half turn answered true at `[60, -100, 0]`; unturned it answered false. `3938` seated on `3937` at `[0, -100, 0]`. + +## Opening and closing a hinge + +`part.pivot` (read) on a seated half answers `kind` `hinge`, the hinge's point as `about` and its axis in `axes` (LDraw and scene axes); a clip seated on a bar answers the same, since it turns on the bar. Give that point and axis to `part.rotate`: + +```bash +./formblocks cli run part.pivot 'ids=["p2"]' +./formblocks cli run part.rotate 'ids=["p2"]' 'axis_vector=[0,0,-1]' 'about=[30,-98,0]' angle=90 +``` + +The half turned 90 degrees, from `[60, -100, 0]` to `[28, -128, 0]`. `part.rotate` turns only the placements in `ids`: when other parts are attached to the half, give their ids too. A hinge turns all the way round; with the person's overlap check on, a turn into a part that does not turn is refused (`sub-skills/turning-parts/SUB-SKILL.md`). In the window the person turns the same half with the one ring of the pivot dial, in angle steps. + +## What overlap.check says + +Two halves joined by a seated hinge answered `count` 0. A clip seated on a bar, anywhere along it, answered `count` 0 and `nested_count` 0: a pair joined by a seated connector is fitted, never an overlap and never nested. + +## Not found, not built + +A hinge or clip drawn without the library's own pieces is found only where the engine's list of corrections names it (the 1 x 2 hinge brick, the swivel plates, the 1 x 1 tile with a clip); other parts do not snap, so place them by position and say so. Pins, axles, ball joints, a bar into a hole, hinge turning limits, click positions and flexible parts are not built: do not promise them. diff --git a/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md index 0d46b5d..2b050bd 100644 --- a/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md +++ b/.claude/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md @@ -27,7 +27,7 @@ A saved file holds references to parts (`3001.dat`), never a part's own lines. F | `model.insert` | change | `path`, `position`, `submodel` | Brings another `.ldr`, `.mpd` or `.fblk` in as new submodels and places one use of its main model (at `position`, or the origin). | | `model.recent` | read | none | The last ten files opened or saved, newest first, each with whether it still exists. | | `model.report` | read | none | What opening reported: lines that could not be read, with their numbers, and the text encoding. | -| `model.info` | read | none | The model's title, author, licence, file, library update, counts and size. | +| `model.info` | read | `table` | The model's name, title, author, licence, file, library update, counts, size and missing parts, with its parts list unless `table` is false (`sub-skills/model-information/SUB-SKILL.md`). | | `model.set_info` | change | `title`, `author`, `licence` | Changes the main model's header: the title (its file's first line), the author, and the licence, empty or one of the Creative Commons licences the parameter lists. | Two other commands write files of their own and wait for the person like a save: `parts.list_save` (a CSV, `sub-skills/parts-list/SUB-SKILL.md`) and `picture.save` with `picture.steps` (PNG pictures, `sub-skills/pictures/SUB-SKILL.md`). diff --git a/.claude/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md new file mode 100644 index 0000000..b9e46d0 --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md @@ -0,0 +1,40 @@ +--- +name: model-information +description: Reads and changes a FormBlocks model's own information, its name, description, author, licence, counts, size, file facts and missing parts, with model.info, model.set_info and submodel.rename, the facts the window shows in its Info tab. Use when asked what a model is, how big it is, how many parts, colours or steps it has, which parts the library lacks, who made it, what licence line it carries, or to set its title, author, licence or name. +--- + +# Model information + +The window's Info tab (the fourth tab of the right column) shows these facts and lets the person edit four of them. The engine counts every value; an agent reads and writes the same ones. + +## Reading: model.info + +`model.info` (`cmd_model_info`, read) answers: + +| Key | What it holds | +| --- | --- | +| `name`, `title`, `author`, `licence` | The main model's `Name:` line, its description (the title line an LDraw file starts with), its author, and the licence line, empty when none. | +| `path`, `kind`, `builtWith`, `library` | The file it came from or was saved to, its kind (`fblk`, `ldr`, `mpd`), the library update it was last saved with (`null` for an LDraw file that did not come from FormBlocks), and the update in use. | +| `counts` | `placements`, `parts` (through every use of a submodel), `differentParts`, `colours`, `pairs` (part and colour rows), `submodels`, `steps` of the main model, `missing` (parts the library lacks) and `overlaps` (as `overlap.check` counts them, nested pairs left out). | +| `size` | `ldu`, `studs`, `bricks`, `plates`, `mm` and the `box`; an LDU is 0.4 mm. | +| `missingParts` | Each part the library lacks: `part`, `file` and `count`. | +| `licences` | The licence lines `model.set_info` accepts. | +| `partsList`, `csv` | The parts list rows and its CSV text. Pass `table` false to leave them out; the answer is large on a big model. | + +On the library's sample car, `model.info` with `table` false answered 61 placements, 26 different parts, 7 colours, 32 rows, 8 steps, 0 overlaps and a size of 4.5 by 10.8 studs and 5.17 bricks high, which a hand count of the file matched. + +## Changing it + +| Command | Parameters | What it changes | +| --- | --- | --- | +| `model.set_info` | `title`, `author`, `licence` | The description, the author and the licence line. Any of them may be left out. `licence` is empty or one of the lines in `licences`; another is refused with the list. | +| `submodel.rename` | `name`, `new_name` | The main model's name when `name` is it, and every use of it. `.ldr` is added when `new_name` has no extension. | + +Each is a change command: one undo step labelled "Change model information" or "Rename ...", approved by the person when it comes from outside the window. A model that was never saved keeps its changes only in memory until `model.save_as`. + +## Habits + +- Read `counts` and `missingParts` before telling the person a build is complete; a part in `missingParts` is drawn as a marked box and counted in the parts list as "Not in this library". +- `overlaps` here is the same as `count` in `overlap.check`; for the pairs themselves call `overlap.check`. +- Set the licence line only when the person says which; it describes the model, never the parts, which keep their own licences. +- The window shows a changed value in place at once, because the tab is rewritten from the engine's answer. diff --git a/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md index d673fcd..43eb734 100644 --- a/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md +++ b/.claude/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md @@ -78,7 +78,7 @@ The full list is `references/error-codes.md`. ## The overlap check -The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's body box would overlap another part's; with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. +The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's real shape would cut more than 1 LDU into another part's (a part resting in a hollow it fits is not refused, and a nested pair never is); with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. ## Habits that save undo steps diff --git a/.claude/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md b/.claude/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md new file mode 100644 index 0000000..a52a37b --- /dev/null +++ b/.claude/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md @@ -0,0 +1,52 @@ +--- +name: turning-parts +description: Turns placed parts in FormBlocks by any angle with part.rotate (angle in degrees or quarter turns, about x, y or z or any axis_vector, about a point), reads what a turn would turn about with part.pivot, and explains the angle step, the pivot dial and J that the person uses in the window. Use when asked to turn, tilt, tip, roll, angle or swivel parts, to turn by 45 or 22.5 degrees, to turn about a stud, a corner or a hinge, when a turn lifts a part or is refused, or when the person talks about the pivot dial or the angle step. +--- + +# Turning parts + +A turn is one `part.rotate` and one undo step, whoever asks for it: the person's key, a drag on the pivot dial, or an agent. + +## What part.rotate takes + +| Parameter | Meaning | +| --- | --- | +| `ids` | Placement ids such as `["p1","p2"]`; the selection when left out, which may be the person's, so pass `ids`. | +| `axis` | `x`, `y` or `z`, LDraw's axes, `y` being up and down. Give this or `axis_vector`. | +| `axis_vector` | Any direction as `[x, y, z]` in LDraw axes, such as a hinge's axis, in place of `axis`. | +| `quarter_turns` | Whole quarter turns, right-handed about the positive axis; negative goes the other way. Give this or `angle`. | +| `angle` | Degrees, right-handed about the axis; negative goes the other way. | +| `about` | The point to turn about, in LDU. Left out, the centre of the box round the placements' real shapes. | + +Giving both `quarter_turns` and `angle`, or neither, or neither axis, is refused with a sentence that names the parameter. A quarter turn leaves a part where its studs can seat again; any other angle does not seat anything, and a turn never seats a part. Four quarter turns give back the same numbers exactly; other angles are settled to six places. + +```bash +./formblocks cli run part.rotate 'ids=["p1"]' axis=y angle=45 +./formblocks cli run part.rotate 'ids=["p1","p2"]' axis=y quarter_turns=1 'about=[0,0,0]' +``` + +The answer lists each turned placement with its new `position`, `rotation` and `matrix`, the `about` point, the `angle` and `axis` used, and `lifted`, how far the turned parts were raised. + +## Two rules the engine keeps + +- A turn never leaves a part below the ground. When the turned parts would end lower than the ground, the whole turned group is lifted straight up until it rests on it, and `lifted` says how far. A 2 x 4 brick standing on the ground, turned 45 degrees about y and then 90 about x, answered `lifted` 28.426 on the second turn. +- With the person's overlap check on, a turn that would push a turned part into a part that does not turn is refused and nothing turns: "ids: the turn would overlap p1 with p2 by 3.0 LDU with the overlap check on, so nothing was turned." With the check off the turn happens and `overlap.check` reports it afterwards. + +A turn of a whole number of full circles changes nothing and adds no undo step. + +## part.pivot + +`part.pivot` (read) says what the person's pivot dial turns about: for `ids` or the selection, `kind` `centre` with the centre of the box and the three axes in LDraw's axes (`about`, `axes`) and in the window's scene axes (`scene`), and `reach`, how far the box extends from the point. For one part joined by a hinge it answers the hinge's own point and axis alone. With a pointer ray (`origin`, `direction`, scene axes) it answers the point the ray meets on a part, or the connector within 8 LDU of it. Use it to find the axis for an `axis_vector` turn; it changes nothing. + +## The angle step, the person's setting + +`angle.step` (`step`: 90, 45, 22.5, 15, 5 or 1) sets the step the dial and Alt with R, T or Y turn by; it is the person's setting like the grid step, so ask before changing it. `part.rotate` does not use it: give the angle you want. + +## What the person sees + +Selected parts show a green pivot ring lying flat about the up axis; pressing on it and dragging turns them in angle steps, Shift for whole degrees, Esc to put them back. J shows three rings and a click on a part sets the pivot on its nearest connector. A key turn is Alt with R, T or Y; A goes to the next angle step. An agent's turn shows in the window at once. Typing an angle on the dial is not built; send `part.rotate` instead. + +## Traps + +- `part.rotate`'s `axis` is LDraw's, with -Y up. A pointer ray's axes are the scene's (`sub-skills/moving-parts/SUB-SKILL.md`). +- After a turn other than a quarter turn nothing is seated: check with `overlap.check`, and turn the part back or move it if the person wants it joined. diff --git a/.claude/skills/formblocks-harness/SKILL.md b/.claude/skills/formblocks-harness/SKILL.md index 00b4f7a..a0cc957 100644 --- a/.claude/skills/formblocks-harness/SKILL.md +++ b/.claude/skills/formblocks-harness/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-harness -description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, meshes, connections, command catalogue), its window, its setup scripts, its agent dock wiring or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, boot and ports, doctor, selfcheck, contract and agents checks, looking at the window headless under throttling with layout shift recorded, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash or flicker, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, where code lives, what packages may import, and adding a command, a connector kind, a router, a pane, or an agent program to the dock. Also the picture round trip, the parts list's rows, the parts library's scratch copy, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." +description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, meshes, connections, command catalogue), its window, its setup scripts, its agent dock wiring or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, boot and ports, doctor, selfcheck, contract and agents checks, the window looked at headless under throttling with layout shift recorded, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, where code lives, and adding a command, a connector kind, a router, a pane, or an agent program to the dock. Also the picture round trip, the parts list's rows, the library's scratch copy, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.4.0" + pack-version: "0.5.0" audience: developer agent --- diff --git a/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md index a2075b1..1559257 100644 --- a/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: add-connector-kind -description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding pins, axles, clips, bars, hinges or any joint beyond studs and anti-studs, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. +description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding a joint beyond studs, anti-studs, clips, bars and the hinge families, such as pins or axles, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. --- # Add a connector kind @@ -36,6 +36,11 @@ A subclass of `Kind` from `backend/app/connect/kinds/__init__.py`: | `from_mesh(mesh, connectors)` | Optional: connectors found from the whole flattened part. | | `mate(a, b)` | `None`, or a `Mate`: the correction that brings `a` onto `b`, the residual, and the `Freedom` left (`Freedom.spin`, `slide`, `hinge` or `fixed`). `axial_mate` covers round connectors on a shared axis. | | `blocks(connector, other)` | Optional: a blocked test of the kind's own, as the stud's blocked-stud test is. | +| `line` | True when the connector is a line, not a facing: its axis has no sign, the mate compares lines (clips, bars and hinge halves). | +| `takes_step` | True when the seat moves in grid steps: `mate(a, b, step)` is then also given the grid step's across value, and gets 0 when pairs are only being counted. | +| `spans` | True when a connector is a segment from `position` along `axis` for `length` (a bar): reach and mating distance are measured to the segment, the spatial hash keeps it by every cell it passes, and it is taken stretch by stretch. A `Mate` then says where along the partner it sits (`at`) and half the stretch it takes (`span`). | + +`kinds/clip.py` (clip and bar) and `kinds/hinge.py` (the five hinge families, three read from primitives and two from overrides only) are the worked examples; each has its numbers in `clip.json` or `hinge.json`. `mates_with` is declared once per kind and the registry makes it symmetric, so a half pairs only with the other half of its own family. Connectors already carry `ref` (for kinds whose turn about the axis matters) and `length` (for kinds that slide), so the connector shape does not change. @@ -48,5 +53,6 @@ Connectors already carry `ref` (for kinds whose turn about the axis matters) and 1. Selfcheck: `backend/venv/bin/python backend/formblocks_engine.py --selfcheck` imports the kinds. 2. With a library in reach, `./formblocks cli run part.connectors part=[number]` for each part you worked by hand: the counts, positions, axes and `source` must match your numbers. Run it with a throwaway data folder (`--settings-dir ''`) so no old cache answers. 3. Place two parts that should mate with `part.fit` and `part.place` and read `seated` and `joined`; run `overlap.check`. -4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. -5. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. +4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. `part.connectors` takes `kind` to list one kind, and its counts always cover every kind. +5. A mate that is a line needs the half turned first: snapping never turns a part. Check a pair with `part.fit` once turned and once not, as `spec/CONNECTIONS.md`, "Worked snaps: a clip along a bar, and hinge halves", does, and read `seated`. +6. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. diff --git a/.claude/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md index fd877a7..406f3d8 100644 --- a/.claude/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md @@ -41,4 +41,5 @@ The Outside agents tab is the model: kind `agent`, read only, made by the engine ## Checking -Only Claude Code may be real on a check machine, and nothing may sign in or start a paid turn. Codex may be installed from the npm registry into a scratch prefix under `/tmp` to check its version call and that it takes the arguments. Every other program is checked with a stand-in: a script under `/tmp` named as the program, put on the path through `FORMBLOCKS_[PROGRAM]_BIN`, which records its arguments, folder, environment names and the MCP entry it finds, then calls the MCP address with the token it was given. Open its tab in the window headless (`sub-skills/verify/SUB-SKILL.md`), then check: `formblocks_status` with the tab's token answers 200, `/api/terminal` with it 403, the token absent from the arguments, 401 after the tab closes, the shell tab's environment without either variable, `./formblocks [program] --print-config`, `./formblocks agents status`, and layout shift 0 opening and closing the tab. Say which programs were real and which were stand-ins. +Nothing may sign in or start a paid turn. On 27 November 2026 all four programs were real on a check machine: Claude Code from the machine, Codex from the npm registry into a scratch prefix, and Cursor's agent and Antigravity from their own installers into a scratch home folder given to the engine as `HOME`, so the finder found them in their known folders. +When an installer cannot be reached, or for a program being added, use a stand-in: a script under `/tmp` named as the program, put on the path through `FORMBLOCKS_[PROGRAM]_BIN`, which records its arguments, folder, environment names and the MCP entry it finds, then calls the MCP address with the token it was given. Open its tab in the window headless (`sub-skills/verify/SUB-SKILL.md`), then check: `formblocks_status` with the tab's token answers 200, `/api/terminal` with it 403, the token absent from the arguments, 401 after the tab closes, the shell tab's environment without either variable, `./formblocks [program] --print-config`, `./formblocks agents status`, and layout shift 0 opening and closing the tab. Say which programs were real and which were stand-ins. diff --git a/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md index d53f42e..65942d2 100644 --- a/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md @@ -24,5 +24,6 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. The window renders what the 4. Style it in `frontend/src/styles/[name].css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. Interface text goes in `ui/strings.ts`. 5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('[name]')`. No icon library, no copied icon art, never a three-star sparkle. 6. A window command (a button, a menu item, a key) is added through `commands` in `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. -7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. The right column's tabs (Model, Steps, Parts) come from the one list in `ui/tabs.ts`; a pane there takes its host with `tabHost(name, fn)` and hears `onTabShown`. A list that can grow long uses `RowScroller` from `ui/parts-list-scroller.ts` and its rules (`sub-skills/parts-list-rows/SUB-SKILL.md`). A panel over the view, like Save Picture, is built once hidden and shown at its final size. +7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. The right column's tabs (Model, Steps, Parts, Info) come from the one list in `ui/tabs.ts`; a pane there takes its host with `tabHost(name, fn)` and hears `onTabShown`. The column is three sections, the colour palette, the tabs and the details panel, laid out and folded by `ui/splits.ts` with their least, default and greatest heights and the header height from `styles/tokens.css`; the tab section takes the room the other two leave, the heights and folds are kept in the engine's `right_column` setting and read before the first paint, and Reset Right Column is a window command. + A new tab never changes those heights: give it a place in the one list and fill its host in place, as the Info tab does (`ui/model-info.ts`, every value's place present before it arrives). A list that can grow long uses `RowScroller` from `ui/parts-list-scroller.ts` and its rules (`sub-skills/parts-list-rows/SUB-SKILL.md`). A panel over the view, like Save Picture, is built once hidden and shown at its final size. 8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then look at the window headless (`sub-skills/verify/SUB-SKILL.md`, "Looking at the window"): a screenshot of the pane, and a hard reload under 4x CPU and network throttling with a layout shift score of 0. Say what you looked at, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. diff --git a/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md index 6a13d0c..288fc67 100644 --- a/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md @@ -19,7 +19,7 @@ Nothing in this repository pushes, signs (beyond the frozen engine on macOS) or | `./build_app` | a desktop build for a person, start to finish | Logs to `build_app.log`; `--no-install`, `--install`, `--open`, `--clean`, `--config FILE`. | | `./formblocks clean`, `clean --all` | removes build output; `--all` also the venv and `node_modules` | Ask before `--all`: other agents may be using them. | -Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing, as on the check machines here, no Tauri build runs: say so, never claim one passed. +Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing no Tauri build runs: say so, never claim one passed. One Linux build (deb and AppImage, unsigned) has run; its report is in `src-tauri/HASHOUT_LOG.md`. Its self-check imports numpy and every module, and the freeze must carry the connector data files (clip and hinge kinds included). macOS, Windows, signing and rpm are not run. ## Data files the freeze must carry diff --git a/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md b/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md index bb6ae9b..0bb322c 100644 --- a/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md +++ b/.claude/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md @@ -44,7 +44,7 @@ This is the method the 0.4.0 lanes used, several at once in one tree. Then do each interaction you built and add up `window.__shifts` entries without `input`. A score above 0 on load or on any of them is a defect to fix. Vite's development server sends hundreds of modules, so under this network a load takes over a minute: give it the time rather than lifting the throttle. 6. The outside agent path: run `./formblocks mcp` as a child process speaking JSON-RPC on its standard input and output, call the tool in one thread, and answer the window's question from Playwright in the other. The question is a dialog; the dock's Chat holds a hidden button of the same name, so pick the visible one (`page.get_by_role("button", name="Allow once", exact=True).locator("visible=true")`). The answer from a test is yours as the person in a scratch data folder, never an agent's on a real one. -7. Agent programs: only Claude Code may be real here, never signed in; the others are stand-ins (`sub-skills/add-dock-program/SUB-SKILL.md`). Say which were which. +7. Agent programs: never sign in. Use the real programs where they install (all four did on 27 November 2026) and a stand-in where one cannot (`sub-skills/add-dock-program/SUB-SKILL.md`). Say which were which. 8. Scripts, screenshots and data stay under `/tmp`, never in the repository. Stop the engine, Vite and the browser when the check is done, each by the process id you started; never by name, since other lanes' engines carry the same name. ## What CI runs diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index d135e44..a77d505 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -31,7 +31,7 @@ It cannot agree to the parts library download: the engine refuses a fetch asked ## What was run -Claude Code was the real program, not signed in; Codex was the real package from the npm registry in a scratch folder, not signed in; Cursor and Antigravity were stand-in scripts named as the programs that record what they are given. No signed-in conversation has been run with any of the four. +All four were real programs, none signed in: Claude Code 2.1.332, Codex 0.172.0 from the npm registry, Cursor's agent 2026.11.22 and Antigravity 1.5.18, the last two from their own installers into a scratch home folder. Each was found, started from a dock tab and from the launcher, and given a token that opened `/mcp`, was refused on `/api` and died with its tab. No signed-in conversation has been run with any of the four, and no `.bat` file or Windows machine was used. ## Skills diff --git a/.docs/wiki/Building.md b/.docs/wiki/Building.md index de707c9..21f1e89 100644 --- a/.docs/wiki/Building.md +++ b/.docs/wiki/Building.md @@ -55,6 +55,6 @@ CI also boots the engine and probes `/api/health`, runs `bash -n` over the shell ## The desktop app and releases -`./formblocks install-desktop` checks the toolchain, `./formblocks desktop dev` runs the shell and `./build_app` builds and installs it. The bundle takes its icons from `src-tauri/icons`, made from the owner's art in `assets/`. No desktop build has been run on the machines this was written on. +`./formblocks install-desktop` checks the toolchain, `./formblocks desktop dev` runs the shell and `./build_app` builds and installs it. The bundle takes its icons from `src-tauri/icons`, made from the owner's art in `assets/`. One desktop build has been run, on Linux x64 (a deb and an AppImage, unsigned, made as formcompiler makes them). Its frozen engine started, the window drew under a virtual display with software WebGL and opened the sample car, and closing it ended every process. The macOS and Windows builds, signing, the updater and the rpm have not been run. Nothing in this repository pushes, signs or publishes a release. The family's compiler, formcompiler, builds each release from `apps/formblocks.json` after `ci.yml` has passed on a `compile_vX.Y.Z` branch, and an owner publishes it. `docs/RELEASE.md` lists the version sites a release bumps by hand and says what formcompiler runs. diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index a51550b..d127ed2 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,11 +2,12 @@ FormBlocks is an Apache-2.0 brick building app for macOS, Linux and Windows. You find parts in the open LDraw parts library, place and snap them in a 3D view, colour them, build in steps, count what the model needs, save LDraw files and pictures, and an agent program can do the same through the engine's command line and MCP server. -Version: 0.4.0 (in active development, functional). +Version: 0.5.0 (in active development, functional). ## Start here - [[Building]] · install, boot, the commands, the desktop app, the release +- [[Window]] · the window's regions, turning parts, clips and hinges, overlaps and the Info tab in short - [[Parts-Library]] · what is fetched, from where, under which licence, and who agrees to it - [[Agents]] · the agent dock, the four programs, outside agents and what asks you first diff --git a/.docs/wiki/Window.md b/.docs/wiki/Window.md new file mode 100644 index 0000000..6f1191a --- /dev/null +++ b/.docs/wiki/Window.md @@ -0,0 +1,25 @@ +# The window in short + +The full walk through is `docs/MANUAL.md` in the repository. This page is the map: what the window has, where to find it, and the keys that matter most. Everything here was seen working in the running window. + +## Where things are + +- **Left:** the parts palette. Type to search; `brick 2 x 4` puts 3001 first. +- **Middle:** the 3D view, the step strip under it, and the status bar at the bottom with the switches **Snap**, the grid step, the **angle step**, **Overlap** and **Nested**. +- **Right:** three sections that fold to their headers. **Colours** at the top; the tabs **Model**, **Steps**, **Parts** and **Info** in the middle, which take whatever height the others leave; **Details** at the bottom. Drag a divider to change a height, double-click it to put it back, click a header to fold a section, and use Reset Right Column in Search Commands (Ctrl+K) to go back to the first layout. Heights and folds are kept from one start to the next. + +## Turning parts + +Select parts and a pivot dial shows: one ring about the up axis. Drag along it to turn in angle steps, Shift for whole degrees, Esc to put the parts back. Press **A** for the next angle step (90, 45, 22.5, 15, 5 or 1 degrees), **J** for the pivot tool with three rings and a click to set the pivot, and hold Alt with **R**, **T** or **Y** to turn by the angle step. A turn never leaves a part under the ground. A hinge half turns about its hinge. + +## Clips and hinges + +A clip seats on a bar and slides along it in grid steps; two hinge halves of one family seat on one pivot line once the half is turned the right way round. The manual's "Clips, bars and hinges" lists the five hinge families and what is not built yet (pins, axles, ball joints, hinge limits). + +## Overlaps and nested pairs + +The overlap check compares the parts' real shapes: parts overlap when they cut more than 1 LDU into each other. A part resting in a hollow it fits, such as a rim in its tyre, is a nested pair: never a block, counted apart, and listed only when **Nested** is on. **Show Overlaps** in the Model menu selects the parts of every overlap and says the count in the status bar. + +## The Info tab + +The model's name, description, author and licence (editable, each change one undo step), its counts and size, its file, and the parts the library lacks. diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index 99cab84..6ae62c9 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -2,5 +2,6 @@ - [[Home]] - [[Building]] +- [[Window]] - [[Parts-Library]] - [[Agents]] diff --git a/CHANGELOG.md b/CHANGELOG.md index 45b3162..1c45d44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## v0.5.0 · 2026-11-27 + +The fifth version turns parts with the pointer, adds clips, bars and hinges as joins, makes the overlap check quiet on real models, gives the right column room and a model information tab, and was built and started as a desktop app for the first time, on Linux. The repository is private until 13 December 2026. + +- Turning with the pointer: press J for the pivot tool and three rings appear about the selection; drag a ring to turn it, in steps of the angle setting, or hold Shift for whole degrees. The turn is previewed in place, sent on release, and is one undo step; Esc puts everything back. The angle step is 90, 45, 22.5, 15, 5 or 1 degree, shown in the status bar beside the grid step, and A moves to the next. Alt+R, Alt+T and Alt+Y turn by the step, with Shift the other way. A turn that would end below the ground is lifted onto it, and with the overlap check on a turn into another part is refused. With the pivot tool on, a click on a part sets the pivot there. Four quarter turns leave a saved file byte for byte as it was. +- Clips, bars and hinges: a clip grips a bar and can sit anywhere along its free length in grid steps, and two hinge halves seat when their axes meet. Both are found from each part's own shape; 1,795 parts of the official library gain such a join. A part joined by a hinge turns about the hinge when you turn it. Snapping still never turns a part, so a hinge half must be the right way up before it seats. +- The overlap check judges real shapes: two parts overlap when their solids share a region thicker than 1 LDU, studs included, so the library's sample car now reports 0 overlaps where 0.4.0 reported 20. A part that sits in another's hollow without cutting into it is counted apart as nested and listed only when asked, with a Nested switch in the status bar and a row in Preferences; a pair joined by a clip or a hinge counts as fitted unless the shapes really cut into each other. Overlapping parts are drawn in the warning colour while the check is on. This rule is a proposed default: what counts as an overlap is the owner's decision. +- The right column: the colour palette, the tabs and Details are three sections with dividers you can drag, each folding to its header, and the sizes are remembered. The tab you work in takes the room left over; at 1440 by 900 the Parts tab shows about six rows where it showed three. Reset Right Column in the command palette puts the sizes back. +- An Info tab, the fourth tab of the right column: the model's name, description, author and licence, each editable and one undo step, and counts of placements, different parts, colours, submodels and steps, the model's size, the file and the library update it was saved with, parts the library lacks, and overlaps. `model.info` returns the same. +- T, Y and the arrow keys follow the screen's axes, as the specification says. After choosing a part from the search field with Enter, R, T, Y and Esc reach the held part. Save As to `.fblk` shows the library update it was saved with at once. +- Windows: a first message to Claude Code, Codex, Cursor or Antigravity, from the launcher or a dock tab, no longer passes through the command interpreter, and the server an agent program starts is the engine's own Python instead of the `.bat` launcher. None of this could be run here: this version was built on Linux and no `.bat` script was run. +- The desktop build ran for the first time, on Linux: `./formblocks desktop build` made a deb and an AppImage, unsigned; the app started with its engine, drew the viewport and the sample car, and stopped with nothing left running. What the first build turned up is fixed: the engine's self-check imports every module and names its data files, the frozen engine carries the clip and hinge data, the Linux package no longer carries numpy's libraries twice, the package has its own description and category, the Tauri packages match the crates (`@tauri-apps/api` and `@tauri-apps/cli` 2.12.5), and `./formblocks doctor` lists what a Linux desktop build needs. +- Agents: `part.rotate` takes an angle and an axis, `part.pivot` and `angle.step` are new, `part.connectors` filters by kind, `overlap.check` lists nested pairs when asked and `overlap.nested` sets the default. Three new sub-skills in the driving pack: turning parts, clips and hinges, model information. The manual, the wiki, the README and both packs are brought up to this version through the skill creator's gates, and `assets/screenshot.png` is a new picture of this version's window. +- Run for this version: `./formblocks doctor`, the type check, the window build, the engine's self-check from source and frozen, `./formblocks agents check`, the Form App Contract checker (0 MUST, 0 SHOULD, 83 clauses checked) and the registry's eight checks, all passing; the Linux desktop build and a start of the built app under a virtual display; headless Chrome walks with real pointer events (a brick turned by each step about each axis, a clip plate seated on a bar, a hinge half folded with the pivot dial, a brick turned 45 degrees into another and reported, the right column dragged and folded, the Info tab edited, saved and reopened) with layout shift 0 on a hard reload and without recent input under a 4x slower processor and a slow network. Claude Code 2.1.332, Codex 0.172.0, Cursor 2026.11.22 and Antigravity 1.5.18 were all real programs this time, none signed in; stand-in scripts were used only to record exactly what a program was given. +- Not run for this version: a signed-in agent turn in any program, any `.bat` script, Windows, macOS, an rpm, a desktop build after the last change to the Tauri packages, the workflow on GitHub, and a frame time on a real graphics card. +- Known: a plate that carries a clip, a handle or a hinge finger does not seat on studs from above, because its side piece widens its footprint; with the overlap check off a clip plate can seat on a bar with its plate inside another part; a new model saved under a file name keeps `untitled.ldr` as its model name until you change it on the Info tab; at 1280 by 720 the palette's solid colours sit below the fold until scrolled; typing an angle on the pivot dial is not built; a picture still cannot be drawn with no window open. + ## v0.4.0 · 2026-11-26 The fourth version makes the mouse enough to build with, adds the parts list and pictures, and proves the agent dock for Claude Code, Codex, Cursor and Antigravity. The repository is private until 13 December 2026. diff --git a/CLAUDE.md b/CLAUDE.md index 2d46893..4c2d224 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ FormBlocks is a Form family desktop app for building with bricks on the open LDr - `frontend/src/dock/` is the family's shared agent dock, copied unchanged and checked against its `MANIFEST.json`; reach it through `frontend/src/dock-adapter.ts`. - `apps/formblocks.json` and `apps/products-row.json` are the proposed registry entry and portal row: kind `bricks`, project file `.fblk`, state `prelaunch`. - The data folder (`FORMBLOCKS_DATA_DIR`, else the system's application data folder) holds `settings.json`, `session.token`, the fetched library under `library/` with its `manifest.json` and saved index, and the mesh cache. `FORMBLOCKS_LDRAW_DIR` names a library folder when the settings name none; it is how a check runs against a library unpacked by hand, and nothing from such a folder is ever committed. -- The engine's library routes are `/api/library` (`status`, `fetch`, `cancel`, `use`, `check_update`), `/api/parts` (`categories`, `search`, `{name}`, `{name}/mesh`), `/api/colours` and `/api/settings`; `./formblocks cli parts`, `part-mesh`, `library` and `colours` print the same JSON. +- The engine's library routes are `/api/library` (`status`, `fetch`, `cancel`, `use`, `check_update`), `/api/parts` (`categories`, `search`, `{name}`, `{name}/mesh`), `/api/colours` and `/api/settings`; `./formblocks cli parts`, `part-mesh`, `library` and `colours` print the same JSON. The routes under `/api/place` (`preview`, `drag`, `pick` and, since 0.5.0, `turn`) answer what a placement, a drag or a turn would do; they read, need the window key and never change the model. - The engine has no renderer: a picture is drawn by the window and written by the engine (`/api/picture`), so `picture.save` and `picture.steps` need the window open. The parts list is counted by the engine (`backend/app/doc/partslist.py`, `parts.list`) and the window's Parts tab patches its rows in place by each row's key. - `README.md` follows the Form family layout; keep it honest about what the current version does. diff --git a/NOTICE.md b/NOTICE.md index c80fe06..0e99a4a 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -25,11 +25,11 @@ FormBlocks was made from FormAnything's app template, which is FormCAD's skeleto | Work | Licence | Where | | --- | --- | --- | | @fontsource/inter 5.3.0, @fontsource/jetbrains-mono 5.3.0 | OFL-1.1 (fonts), MIT (package) | `frontend/package.json` | -| @tauri-apps/api 2.12.4 | Apache-2.0 OR MIT | `frontend/package.json` | +| @tauri-apps/api 2.12.5 | Apache-2.0 OR MIT | `frontend/package.json` | | @xterm/xterm 6.0.0, @xterm/addon-fit 0.11.0 | MIT, Copyright (c) 2017-2019 The xterm.js authors and others; the agent dock's terminal, loaded only when a tab opens | `frontend/package.json` | | three 0.186.1 | MIT, Copyright 2010-2026 three.js authors; the 3D viewport and the part thumbnails | `frontend/package.json`, `frontend/src/view/` | | @types/three 0.186.0 | MIT, from the DefinitelyTyped project; type declarations for three, development only and erased by the build | `frontend/package.json` (development) | -| @tauri-apps/cli 2.11.4, typescript 7.0.2, vite 8.3.5 | Apache-2.0 OR MIT, Apache-2.0, MIT | build tools, not shipped | +| @tauri-apps/cli 2.12.5, typescript 7.0.2, vite 8.3.5 | Apache-2.0 OR MIT, Apache-2.0, MIT | build tools, not shipped | ### Engine (backend) diff --git a/README.md b/README.md index c191f26..2c5c0e8 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version 0.4.0 + version 0.5.0 TypeScript Python Tauri 2 @@ -42,7 +42,11 @@ FormBlocks is an open brick building app. Its parts are the LDraw Parts Library, > [!IMPORTANT] -> **Status:** in active development, functional. In the window you can choose or fetch the parts library, find parts in the palette, place them with the pointer in the 3D view where they seat on studs (including across a gap, resting on the tops of what is under them), drag placed parts and copies of them, select with the pointer or a box, turn and colour parts, nudge, hide, pack parts into submodels, add and walk building steps with the earlier steps dimmed, read the model tree and the details of a part, count what a model needs in the Parts tab and save it as CSV, save a picture of the view (and one picture per step), and save and open `.fblk`, `.ldr` and `.mpd` files. The agent dock runs Claude Code, Codex, Cursor and Antigravity beside the model. Not yet in the window: the stamp, pivot, brush and sampler tools, move handles, turns finer than a quarter turn and a panel for the model's own information. [docs/MANUAL.md](docs/MANUAL.md) walks through all of it and ends with what does not work yet. +> **Status:** in active development, functional. In the window you can choose or fetch the parts library, find parts in the palette, place them with the pointer in the 3D view where they seat on studs (including across a gap, resting on the tops of what is under them) and, with the clip and hinge parts, on bars and on each other's hinge halves, drag placed parts and copies of them, select with the pointer or a box, turn parts by the pointer on a pivot dial in angle steps from 90 degrees down to 1 (a hinge half turns about its hinge), colour parts, nudge, hide, pack parts into submodels, add and walk building steps with the earlier steps dimmed, read the model tree and the details of a part. +> +> You can also count what a model needs in the Parts tab and save it as CSV, read and edit the model's name, description, author and licence beside its counts and size in the Info tab, fold and resize the right column's three sections, tell real overlaps from parts that nest by design, save a picture of the view (and one picture per step), and save and open `.fblk`, `.ldr` and `.mpd` files. +> +> The agent dock runs Claude Code, Codex, Cursor and Antigravity beside the model. Not yet in the window: the stamp, brush and sampler tools, move handles, a typed angle on the pivot dial, pins, axles and ball joints, and a limit on how far a hinge opens. [docs/MANUAL.md](docs/MANUAL.md) walks through all of it and ends with what does not work yet. ## Quick start @@ -95,7 +99,9 @@ The fetch runs only with your consent, given on the library card in the window o A checkout already names the server for Claude Code ([`.mcp.json`](.mcp.json)), Cursor ([`.cursor/mcp.json`](.cursor/mcp.json)), Codex ([`.codex/config.toml`](.codex/config.toml)) and Antigravity ([`.agents/mcp_config.json`](.agents/mcp_config.json)). Two skill packs live in [`skills/`](skills): `formblocks-harness`, for changing this code, and `formblocks-driving`, for using the running app; its `references/command-catalogue.md` lists every tool and command and is written by `agents sync`. -The agent dock in the window (Ctrl+J) holds Chat for Claude Code, a terminal tab for each of Claude Code, Codex, Cursor and Antigravity, and a plain shell; each tab is connected to this engine with a token of its own that is revoked when the tab closes. A program that is not installed shows the line that installs it and nothing is run for you. An agent program started outside the window with `./formblocks claude` (or `codex`, `cursor`, `antigravity`) reads the model freely, and the window asks you before it changes anything: **Deny**, **Allow once** or **Always allow**, with a read-only Outside agents tab logging each call. [docs/AGENT_DOCK.md](docs/AGENT_DOCK.md) says what each program gets and what was run; Claude Code and Codex were real programs there, Cursor and Antigravity were stand-ins. Every `cli` subcommand prints JSON, so an agent can read the library's status, search parts and read a part's mesh counts; fetching the library is the one thing it is refused, because only you can agree to that download. +The agent dock in the window (Ctrl+J) holds Chat for Claude Code, a terminal tab for each of Claude Code, Codex, Cursor and Antigravity, and a plain shell; each tab is connected to this engine with a token of its own that is revoked when the tab closes. A program that is not installed shows the line that installs it and nothing is run for you. An agent program started outside the window with `./formblocks claude` (or `codex`, `cursor`, `antigravity`) reads the model freely, and the window asks you before it changes anything: **Deny**, **Allow once** or **Always allow**, with a read-only Outside agents tab logging each call. + +[docs/AGENT_DOCK.md](docs/AGENT_DOCK.md) says what each program gets and what was run; all four programs were real there (none signed in, so no turn with a model was run). Every `cli` subcommand prints JSON, so an agent can read the library's status, search parts and read a part's mesh counts; fetching the library is the one thing it is refused, because only you can agree to that download. ## What FormBlocks sends over the network @@ -145,7 +151,8 @@ Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`CO ## Status -In active development, functional. It is made to run from source on macOS, Linux and Windows, and has been run from source on Linux only; desktop builds come from formcompiler; the app has its icons, and no desktop build has been run yet. The engine and the window have been run against the full official library of release 2026-10, the window in a headless browser with software rendering, so how fast it draws on a real graphics card is not measured. Of the four agent programs, Claude Code and Codex were run for real (neither signed in) and Cursor and Antigravity through stand-in programs. Releases are made by the family's compiler from [`apps/formblocks.json`](apps/formblocks.json), never by this repository. +In active development, functional. It is made to run from source on macOS, Linux and Windows, and has been run from source on Linux only; desktop builds come from formcompiler; the app has its icons. +One desktop build has been made, on Linux x64 only (a deb of 50 MB and an AppImage of 121 MB, unsigned): its frozen engine started, the window drew and showed the sample car under a virtual display, and closing it ended every process; no macOS or Windows build has been run. The engine and the window have been run against the full official library of release 2026-10, the window in a headless browser with software rendering, so how fast it draws on a real graphics card is not measured. All four agent programs were run for real, none signed in: Claude Code 2.1.332, Codex 0.172.0, Cursor's agent and Antigravity 1.5.18, each found, started from a dock tab and from the launcher, and given a token that opened the engine's `/mcp` and nothing else, and stopped working when the tab closed. Releases are made by the family's compiler from [`apps/formblocks.json`](apps/formblocks.json), never by this repository. ## Licensing diff --git a/SECURITY.md b/SECURITY.md index eb2c567..1058e27 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,7 +6,7 @@ Security fixes go into the newest release. Please update before reporting, and c | Version | Supported | | --- | --- | -| 0.1.x (latest release) | Yes | +| The latest release | Yes | | Anything older | No | ## Reporting a vulnerability @@ -29,4 +29,4 @@ Bugs that need someone to already control your computer, or to run a modified bu ## What FormBlocks sends over the network -Nothing. FormBlocks has no account, no telemetry and no update check. When an agent program in the dock is missing, the dock shows the line that installs it; FormBlocks never runs that line. A program you start in a tab talks to its own service as it does anywhere. A request from FormBlocks itself to any address but 127.0.0.1 is a vulnerability. +Nothing, unless you ask. FormBlocks has no account, no telemetry and no update check of its own. The one server it reaches is `library.ldraw.org`, only to fetch the parts library after your consent, to show the archive's size on the library card, or when you choose Check for an update. When an agent program in the dock is missing, the dock shows the line that installs it; FormBlocks never runs that line. A program you start in a tab talks to its own service as it does anywhere. A request from FormBlocks itself to any address but 127.0.0.1 and `library.ldraw.org`, or to that server without your asking, is a vulnerability. diff --git a/agents/manifest.json b/agents/manifest.json index 5e8c8d8..b54fb86 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -10,6 +10,7 @@ "formblocks_redo", "formblocks_status", "formblocks_undo", + "cmd_angle_step", "cmd_colours_current", "cmd_colours_list", "cmd_colours_used", @@ -26,6 +27,7 @@ "cmd_model_set_info", "cmd_model_tree", "cmd_overlap_check", + "cmd_overlap_nested", "cmd_overlap_set", "cmd_part_connectors", "cmd_part_delete", @@ -37,6 +39,7 @@ "cmd_part_move", "cmd_part_move_at_ray", "cmd_part_pick", + "cmd_part_pivot", "cmd_part_place", "cmd_part_place_at_ray", "cmd_part_recolour", @@ -78,6 +81,7 @@ "formblocks_get_doc", "formblocks_list_commands", "formblocks_status", + "cmd_angle_step", "cmd_colours_current", "cmd_colours_list", "cmd_colours_used", @@ -88,10 +92,12 @@ "cmd_model_report", "cmd_model_tree", "cmd_overlap_check", + "cmd_overlap_nested", "cmd_overlap_set", "cmd_part_connectors", "cmd_part_fit", "cmd_part_pick", + "cmd_part_pivot", "cmd_parts_list", "cmd_parts_search", "cmd_parts_show", @@ -160,10 +166,12 @@ "building-in-order", "changing-parts", "checking-a-model", + "clips-and-hinges", "colours", "connect-and-status", "files", "finding-parts", + "model-information", "moving-parts", "parts-library", "parts-list", @@ -173,6 +181,7 @@ "step-walking", "steps", "submodels", + "turning-parts", "working-with-the-person" ] }, diff --git a/assets/screenshot.png b/assets/screenshot.png index 1400978..a4e9546 100644 Binary files a/assets/screenshot.png and b/assets/screenshot.png differ diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 4a752e3..c865299 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,6 +2,87 @@ Living record of decisions and removed context for the engine, newest first. Read before editing. +## The self-check names every data file the engine reads · 0.5.0 (formblocks_engine.py) + +`--selfcheck` listed the stud kind's data, the overrides and the categories under `data_files`; the clip and hinge kinds' `clip.json` and `hinge.json`, added in 0.5.0, were caught only indirectly, as a module that fails to import. They are now named with the others, so a freeze that drops one says which file is missing. These five are every file the engine's package reads beside its code (the rest of `app/` that is not Python is hashout logs and `FORMAT.md`). Checked: `./formblocks freeze` then `src-tauri/engine/formblocks-engine --selfcheck` answers `data_files` ok and `modules` ok, and the frozen `_internal/app` holds all five. + +## "Saved with" follows a save to a project file · 0.5.0 (app/cmd/commands/model.py, app/services/model_info.py) + +`model.info`'s `builtWith` was read from the project lines the model was opened with, so after Save As to a `.fblk` the Info tab kept the value of the file it came from (none, for an LDraw file) until the new file was opened again. Writing a project file now keeps the library update it wrote in the document's file report (`savedWith`), which a later open or `model.new` replaces; `builtWith` prefers it. The model itself is not touched, so a save adds no undo step and an undo never brings an old value back. An export to `.ldr` or `.mpd` writes no library line and leaves it alone. Checked on an engine on 9270: the sample car opened as `car.ldr` said none, after Save As `.fblk` 2026-10, after a further Save As `.ldr` still 2026-10, after reopening the `.fblk` 2026-10, after `model.new` none. + +## On Windows a program is started without the command interpreter whenever it can be · 0.5.0 (app/services/windows_start.py, agent_programs.py, chat.py) + +The first fix for Windows (below, "a tab's first message is typed") kept every `.cmd` program behind `cmd.exe` and only kept the message off its line. FormAnything's agent lane, working on the same fault, described a stronger rule, and this is FormBlocks' own version of it: most `.cmd` programs are not batch programs at all but npm's or pnpm's small shim, whose one real line runs `node` on a script in the package (Claude Code and Codex from npm) or runs an `.exe` the package carries. `windows_start.py` reads the shim, finds the last quoted path that starts with the shim's own folder (`%dp0%` or `%~dp0`) on the line that passes `%*`, and, when that file exists and is a script or a program, starts it directly: the `.exe` itself, or `node.exe` beside the shim (else the `node` on the child's PATH) with the script. No interpreter is involved, so a message, a folder or a JSON setting reaches the program exactly, and the message stays an argument after `--` even on Windows. Any other batch file must go through the interpreter, and then only as `cmd.exe /d /v:off /c call ` (no AutoRun commands, no delayed expansion, `call` so a quoted path with spaces is run as one), and only when no word holds `"`, `%`, `^`, `!`, a line break or NUL, and `& | < > ( )` appear only in words with a space or tab, which the C runtime's joining puts inside quotes the interpreter respects; otherwise it is refused with a sentence. A dock tab whose program needs the interpreter still gets its first message typed, as before. `start_words` takes the child's environment so `node` and `COMSPEC` are looked for where the program will run, so a tab now issues its token before building the command and revokes it if the command is refused. Unix is unchanged: the login shell with each word in single quotes. `agent_lookup.py` (the family's file, held to its hash) still starts `--version` checks its own way, which carries no supplied text. Checked here, on Linux, with shims written in npm's and pnpm's forms and the platform made to take this path: an npm `codex.cmd` started `node codex.js -- `, an npm `claude.cmd` naming an `.exe` started that `.exe`, a pnpm `cursor-agent.cmd` started the `node.exe` beside it with its `.mjs`, all with a message holding quotes, `&`, `%`, `|`, `<`, `^`, `!` and a line break intact; a plain `other.bat` was refused for that message and for a JSON word, allowed `plain` and `a & b`, refused `a&b`. The dock and Chat on Linux started as before. Not run: Windows. + +## A pivot ray that meets no part answers the centre, not a refusal · 0.5.0 (app/cmd/commands/part.py) + +This corrects "part.pivot takes a pointer ray to turn about the point clicked". A click on empty space with the pivot tool is how the person goes back to the centre, so a refusal there was an expected answer reported as a failure: the throttled headless walk logged a 422 in the window's console for it. `part.pivot` with a ray that meets nothing now answers exactly what it answers with no ray (the centre, or the hinge). Checked in process on a 3001: a ray beside it answered kind `centre` about (0, -14, 0); rays onto it still answered their points. + +## A clicked pivot within 8 LDU of a connector is the connector · 0.5.0 (app/cmd/commands/part.py) + +`SPEC.md` 5.2 sets the pivot by clicking "a connector or a point on a part". A point read off a triangle under the pointer has arbitrary decimals, so a brick turned about it lands off every grid (checked headless: a 3001 turned a quarter about a clicked point went to x 36.171, z -3.829). `part.pivot` with a ray now takes the nearest connector of the part met, placed by its pose, when it is within 8 LDU of the hit (a little more than a stud's radius, so a click anywhere on a stud's top takes the stud), and the hit itself otherwise. Checked in process on a 3001 at the origin: a ray 3.6 LDU from a stud's centre answered the stud (30, -24, -10); one on the top between studs 10 LDU from the nearest stud kept its point (30, -24, 0); one on the side face kept its point. + +## part.pivot takes a pointer ray to turn about the point clicked · 0.5.0 (app/cmd/commands/part.py) + +`SPEC.md` 5.2 lets the pivot tool turn about a point the person clicks on a part. The window cannot turn a pointer's hit into LDraw coordinates itself (the one conversion lives in the engine), so `part.pivot` takes the ray, in the scene's axes like every other ray (0.2, decided in 0.3.0), picks the first part of the submodel being edited it meets on real triangles, hidden parts passed through and the ground not counted, and answers that point (kind `point`, with `on` naming the part) with the three axes, in both axes, and a reach measured from the point to the far corner of the selection's box so the dial still rings the whole selection. A ray that meets no part is refused, and the window then goes back to the centre. Checked in process: a ray straight down at x 30 onto a 3001 at the origin answered the point (30, -24, 0), reach 76.7; one beside it was refused; an origin without a direction was refused. + +## A turn about a hinge is never lifted: the ground stops it · 0.5.0 (app/cmd/placing.py, app/cmd/commands/part.py) + +Lifting a turned part off the ground is right for a part turned about its own centre, but a part turned about the hinge it hangs on would be lifted off the hinge, and the next `part.pivot` no longer found it joined: checked in process with a Hinge Plate 1 x 2 with 2 Fingers (4276b) joined to one with 3 Fingers (4275b) on the ground, a turn of -45 degrees about the hinge was lifted 28.5 LDU and the hinge came apart. `placing.turn` now asks `on_hinge` whether the turn's point lies on the hinge axis `hinge_of` finds (within 0.5 LDU) and its axis is that axis either way; such a turn that would go below the ground is blocked, with the ground named as what it meets, so the dial stops at the last free angle and `part.rotate` refuses with a sentence saying why. A turn of the same part about its centre (R, or the dial of a group) still lifts. The label names a negative axis as such ("about -Z") rather than as a direction. Checked in process with the same pair: -45 about the hinge was refused, +45 turned it up off the ground with the hinge still joined and `part.pivot` still answering the hinge, and a further +90 was refused at 5.7 LDU into the ground. + +## part.connectors lists one kind when asked, with each connector's index · 0.5.0 (app/cmd/commands/connect.py) + +With clips, bars and six pairs of hinge halves beside studs, a baseplate's hundreds of studs bury the one hinge an agent is looking for. `part.connectors` takes an optional `kind` and keeps only that kind's connectors; the counts still cover every kind, so the answer still says what else the part has. Each listed connector now carries its `index` in the part's full list, the number `held` and `part.place` take, so a filtered list can still be used to hold a part by its clip. A kind the registry does not know is refused with the list of kinds, read from the registry rather than written here. Checked through the engine on port 9220: 2540 with `kind=bar` lists its three bars as indexes 0 to 2 with counts for bars and studs, `kind=pin` is refused with the fourteen kinds, and 3001 without a kind gives its 19 connectors as before. + +## A part joined by a hinge turns about the hinge, through the connect lane's hinge_axes · 0.5.0 (app/cmd/placing.py) + +`SPEC.md` 5.2 (decided in 0.5.0) turns one part joined by a hinge connector about the hinge's axis. `placing.hinge_of` is the one place that finds it: for a selection of one library part it asks `app.connect.hinge_axes` (the interface the connector lane wrote down this turn, stable by its word) for the axes that placement is joined on, in the hash of its submodel, and takes the first one's `point_ldraw` and `direction_ldraw`; `part.pivot` then answers that point with the one hinge axis, and the dial sends it back to `part.rotate` as `about` and `axis_vector`. The import is made when asked and a missing name means no hinge, so the engine runs the same with or without the hinge kinds, and nothing here names a kind. A group, or a part joined by two hinges, turns about the first axis only for one part and about its centre for a group, since a group's members may sit on hinges that do not share an axis. Checked in process: with `hinge_axes` not yet in `app.connect`, `part.pivot` on a 3001 still answered its centre; the hinge path itself was not run, for want of the function. + +## `overlap.check` lists nested pairs apart, and when asked · 0.5.0 (app/cmd/commands/connect.py) + +The command always works out both kinds in one pass and always says how many nested pairs there are (`nested_count`), so a nested pair is never hidden; it lists them under `nested` when its `nested` argument is true, or, when the argument is left out, when the `overlap_nested` setting is on, and says which it did in `nested_listed`. +`overlaps` and `count` hold real overlaps only, so an agent confirming a build reads `count` as before and the sample car now gives 0. Each pair carries `kind` and `volume` (cubic LDU) beside its depth, and the answer carries `ms`, the time the check took inside the engine, so a person timing a large model sees the check's own cost without the command line's start. +Checked through an engine on a scratch port: the sample car 0 overlaps and 20 nested in 30 ms warm, 190 ms with the grids read from the disk cache; the 152 pairs of constructed faults reported but for the two 1 LDU deep. + +## `overlap.nested` sets what the overlap check reports · 0.5.0 (app/cmd/commands/switches.py) + +The owner has not decided whether a part sitting in another's hollow by design (a rim in its tyre, a pin in its hole, two hinge halves) is an overlap. +The decision is one setting, `overlap_nested`, and one command to set it, `overlap.nested`, registered as a view command beside `overlap.set` so it is no undo step and no model change, as `SPEC.md` 7.6 says of the switches. +False, the proposed default awaiting the owner's decision, reports only real overlaps and counts nested pairs apart; true lists nested pairs too. It is a separate command rather than a second argument of `overlap.set`, because `on` is required there and an id or argument once released is not changed under agents' feet. +Every switch command now answers `overlap_nested` with the other three. The summary of `overlap.set` no longer says "box": the check compares real shapes since this version. Checked through an engine on a scratch port: `overlap.nested on=true` and back, with `settings.json` reading the value. + +## On Windows a tab's first message is typed, never put where the command interpreter reads it · 0.5.0 (app/services/agent_programs.py, app/services/chat.py) + +A dock tab opened with a first message started Claude Code as `claude ... -- `. On Windows the program found is often a `.cmd` file (npm's shim), and the family finder starts such a file as `cmd.exe /c claude.cmd ...`. The command interpreter reads that whole line before the program does: `&`, `|`, `<` and `>` outside its idea of a quoted stretch start other commands or redirect, `^` is eaten, `%NAME%` is replaced by a variable even inside quotes, and a line break ends the command. The pseudo-terminal library joins the words with the C runtime's quoting (`\"` for a quote), which the interpreter does not know, so a message with a quote in it flips the interpreter's quoting and leaves the rest of the message bare. No quoting fixes this for any text (a line break cannot be carried at all), so the message is kept off that line: when the program would start through the interpreter, the tab starts it without the message and types the message into the tab once the program has printed something and then been quiet for 0.8 seconds (up to 30 seconds), the same keystrokes as a message sent to a Claude tab already running. Everywhere else the message stays an argument after `--`, because the login shell's start quotes each word in single quotes and nothing is read twice. Second, `start_words` refuses to start a `.cmd` or `.bat` program when any of its arguments holds a character the interpreter acts on (`& | < > ^ % !`, a line break or NUL); FormBlocks' own arguments (the MCP settings, the note, a resume id, Codex's `-c` settings) have none, so this refuses only text that should not be there, and Chat, which sends every message on standard input already, goes through the same check. `agent_lookup.py` is the family's file, held to its hash, so this lives in FormBlocks' own module; the family's copy should start an interpreter with `/d` and make the same check. Checked here on Linux with a stand-in `claude` that records its arguments, folder and typed lines, the message `it's "quoted" & 50% | ^ !x %PATH%`, a line break, `second line`, a line break, `-p --leading-dash`, in a folder named `odd & 50% folder`: as before, the stand-in received the message intact as the last argument, in that folder, with the tab's token in its environment; with the start made to take the interpreter path, the argument list ended at the note and the three lines arrived as typed input. `start_words` refused a `.cmd` with the message as an argument and passed the Claude and Codex arguments FormBlocks gives. Not run: Windows itself. + +## POST /api/place/turn answers a turn without making it · 0.5.0 (app/routers/place.py) + +The pivot dial turns the selected parts in place in the window while the person drags, and `SPEC.md` 5.2 (decided in 0.5.0) has the engine decide each step's lift and whether it is blocked. The route takes the ids, the axis as a direction in LDraw's axes, the angle in degrees and the point, exactly what `part.rotate` takes on release, runs `placing.turn` under the document's lock and answers the lift (in LDU and as a scene vector, `up`), whether it is blocked, the overlap pairs and each placement's pose in both axes, changing nothing, like `/preview` and `/drag`. The window asks it once per step reached, not per pointer move. Checked on 9230 with the 2026-10 library: a grounded 3001 tipped 90 degrees about X answered `lifted` 6 and `up` (0, 6, 0); the request was 58 bytes and the answer 336. + +## part.rotate turns by an angle about any axis, lifts off the ground and refuses an overlap; part.pivot and angle.step · 0.5.0 (app/cmd/commands/part.py, app/cmd/placing.py) + +`SPEC.md` 5.2 (decided in 0.5.0). `part.rotate` keeps `axis` and `quarter_turns` as they were, so the window's R, T and Y and every saved script still work, and takes `angle` in degrees in place of `quarter_turns` and `axis_vector` (a direction in LDraw axes, such as a hinge's) in place of `axis`; exactly one of each pair. Its default point is now the centre of the box around the placements' shapes as placed, not the centre of their origins: a part's origin is the top of its body, so tipping a brick about its origin swung it half its height off where it was, and the dial needs a point a person sees as the middle. The rule lives in `placing.turn` so the window's preview route and the command run the same code: every placement turns about the point, a quarter turn about X, Y or Z unrounded and anything else through `transform.settle`; the lowest point before and after is read from the parts' real triangles (a turned box of a part turned 45 degrees reaches lower than the part does), from the shape's box when there are none, and through the placements of a use's submodel; when the turned lowest point is below the ground (LDraw's y over 0), or below where the selection already was when it started lower, the whole turn is lifted straight up by the difference. With the overlap check on, each turned library part is checked by the overlap check's own `overlap_check` against the parts of its submodel that do not turn, hidden ones skipped and parts it is still joined to (a turn about a hinge keeps its joint) allowed, and a clash refuses the whole command with the pairs named, as a move is. `part.pivot` (read) answers the point, the axes in both LDraw and scene axes, and the box's half diagonal for the dial's size, so the window draws only what it is told; `placing.hinge_of` is the one place a hinge pivot is found. `angle.step` (view) sets the setting as `grid.step` sets its own. Checked in process with the 2026-10 library: four quarter turns of a 3001 gave back its exact matrix and position; a grounded 3001 tipped about X was lifted 6 LDU; a 22.5 degree turn wrote six place entries; a turn into a neighbour with the check on was refused naming both parts and changed nothing; `angle.step 30` was refused with the list. + +## The right column's layout is a setting · 0.5.0 (app/core/settings.py) + +`SPEC.md` 1.2 keeps the layout (collapsed panels, which tab is open, the sizes) from one start to the next, and the window kept the right column's two divider heights in the browser's local storage only, which a desktop build and a browser on the same data folder do not share. `right_column` holds the colour palette's and the details panel's heights in pixels (null for the window's own default from its tokens), the sections folded to their headers (`colours`, `tabs`, `details`) and the tab shown (`model`, `steps`, `parts`, `info`, or null). The engine only checks the shape: a height from 1 to 4,000 pixels, known section and tab names, nothing else in the object; whether a height fits the window is the window's to decide, since only it knows how tall it is. The region sits after `CHECKS` so the setting is one edit in this shared file. Checked on 9240: a write of colours 250, details folded and the Parts tab came back with details null, a height of `true` was refused with the sentence, and the value reached `settings.json`. + +## model.info counts colours and overlaps and names the missing parts · 0.5.0 (app/cmd/commands/info.py, app/routers/doc.py) + +The window's model information panel shows only what the engine counted, so `model.info` now also answers `counts.colours` (the different colour numbers in the whole model's parts list, through every use), `counts.overlaps` (the `count` that `overlap.check` answers for the whole model, reached through the registry so that what counts as an overlap stays that command's alone; null when no library is in use), and `missingParts`, one entry per part number the library lacks with its file and how many the model needs in all colours, and `licences`, the list `model.set_info` accepts, so the window's licence choice offers exactly those without a copy of them. A `table` parameter, true by default, leaves the parts list and its CSV text out when false: the panel asks again after every change, and the list is the Parts tab's work, not the panel's. `GET /api/doc/info` now runs the command instead of the service function, so the route and the command cannot drift apart again; `?table=false` passes through. The description a person edits is the title line LDraw files start with, already answered as `title`, so no second field holds it. Checked on 9240 with the sample car: 61 placements, 7 colours and 8 steps, the same as counting the file's type 1 lines, their colour numbers (0, 1, 4, 7, 36, 39, 46) and its `0 STEP` lines by hand; 20 overlaps, as `overlap.check` answered at that moment; a three-line model with two uses of a part the library lacks answered `zz999`, 2. + +## A turn by any angle about any axis, exact for quarter turns · 0.5.0 (app/doc/transform.py) + +`SPEC.md` 5.2 (decided in 0.5.0) turns the selection by the angle step or by whole degrees about any axis, a hinge's included. `turn_by(axis, degrees)` builds the turn from the axis and angle; when the angle is a whole number of quarter turns its cosine and sine are taken from the table 1, 0, -1, 0 rather than computed, so a quarter turn about X, Y or Z has entries of exactly 0, 1 and -1 and only moves and negates the numbers of the matrix it turns: four of them give back the same matrix bit for bit, which a computed cosine of 90 degrees (6e-17) would not. Any other turn goes through `settle`, which takes the nearest true rotation by a singular value decomposition when the matrix is one to within 0.001 (a scaled or sheared matrix read from a file is left as it is) and rounds each entry to six places, so a matrix read back from the saved file is the one in memory and 360 turns of one degree drift by under 2e-5 rather than compounding. `settle_place` rounds a turned position to three places, the precision of FormBlocks' own lines (`LDRAW.md`). Checked in process: four quarter turns about Y gave the identity exactly, two 45 degree turns settled to the exact quarter turn, 360 one degree turns ended within 1.6e-5 of the identity with determinant 1.0000000003. + +## The self-check imports every module of the engine · 0.5.0 (formblocks_engine.py) + +The connect lane added two connector kinds, `clip` and `hinge`, each reading a JSON file beside its module when it is imported. The freeze carried a fixed list of data files, so the frozen engine had neither, and `formblocks-engine cli run part.connectors part=3001` ended in `RuntimeError: the clip kind's data file clip.json cannot be read`, while `--selfcheck` said `"data_files": "ok"`: it checked the three files it knew by name and imported the routers, the catalogue and the tool list, none of which imports the kinds at start. The self-check now also walks the `app` package and imports every module, reporting `"modules": "ok"` or each module that failed with its error, which fails the check and the freeze. Checked: the venv's self-check imports all 144 modules; a freeze made with the old data list now fails at its last step naming `app.connect.kinds.clip` and `app.connect.kinds.hinge`; with the freeze fixed (`setup/HASHOUT_LOG.md`) it passes and `part.connectors` lists the brick's connectors. + +## The self-check says whether numpy came along · 0.5.0 (formblocks_engine.py) + +The part flattener under `app/mesh/` is the only user of `numpy`, and nothing the self-check imports (the routers, the catalogue, the MCP tool list) reaches it, so a frozen engine that lost `numpy` or its `numpy.libs` passed `--selfcheck` and failed only when the window asked for its first part. `numpy` is now one of the modules the self-check imports and reports, and a missing one fails the check, and so the freeze's last step. Checked: the venv's self-check and the frozen engine's both print `"numpy": "2.5.4"`; the frozen engine's `cli part-mesh 3001` against the scratch library flattened the brick to 700 triangles. The parts library is not inside the frozen folder: no `.dat`, `.ldr`, `.mpd` or colour file is under `src-tauri/engine`. + ## Every pointer ray is in the scene's axes, part.fit's too · 0.4.0 (app/cmd/commands/connect.py) `SPEC.md` decided in 0.3.0 that a pointer ray belongs to the viewport, and `part.pick` and the three `*_at_ray` commands take theirs in the window's scene axes (+Y up), while `part.fit`'s `origin` and `direction` were read in LDraw axes, so one ray meant two places depending on the command and the driving pack had to warn against carrying a ray across. `part.fit` now reads its ray in the scene's axes and turns it into LDraw's with `mesh.from_scene`, the one conversion, before fitting; its `position` and `rotation` stay in LDraw axes, as for `part.place`, and each summary says which axes it takes. This changes what an old caller's ray means: a ray straight down was `direction` `[0, 1, 0]` and is now `[0, -1, 0]`; nothing in the window or the packs sent `part.fit` a ray, and the driving pack's two pages say the new rule. Checked in process with a 3001 at the origin: a scene ray from (0, 200, 0) straight down fitted a second 3001 on top, seated at LDraw (0, -24, 0). diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 6a9beea..3d18726 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.4.0" +__version__ = "0.5.0" diff --git a/backend/app/cmd/commands/connect.py b/backend/app/cmd/commands/connect.py index 3edb716..4467b71 100644 --- a/backend/app/cmd/commands/connect.py +++ b/backend/app/cmd/commands/connect.py @@ -1,9 +1,12 @@ +import time + import numpy as np from app.cmd import args, fitting from app.cmd.registry import CommandError, Param, command from app.mesh import from_scene from app.connect import OverlapSettings, check_model, table +from app.core import settings from app.library import NoLibrary from app.services import connect_host @@ -11,11 +14,14 @@ @command( "part.connectors", "Part Connectors", - "List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint.", - params=(Param("part", "string", "The part's file name, such as 3001.dat (3001 is read as 3001.dat).", True, args.NAME_MAX),), + "List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind.", + params=( + Param("part", "string", "The part's file name, such as 3001.dat (3001 is read as 3001.dat).", True, args.NAME_MAX), + Param("kind", "string", "Only connectors of this kind, such as stud, anti_stud, clip, bar or hinge_click_1; every kind when left out. Counts always cover every kind.", False, args.NAME_MAX), + ), kind="read", ) -def connectors(doc, part: str) -> dict: +def connectors(doc, part: str, kind: str | None = None) -> dict: name = part.strip() if "." not in name.replace("\\", "/").rsplit("/", 1)[-1]: name += ".dat" @@ -26,11 +32,14 @@ def connectors(doc, part: str) -> dict: counts: dict[str, int] = {} for c in info.connectors: counts[c.kind] = counts.get(c.kind, 0) + 1 + wanted = None if kind is None or not kind.strip() else kind.strip() + if wanted is not None and wanted not in connect_host.service().registry.names(): + raise CommandError("kind: %s is not a connector kind; the kinds are %s." % (wanted, ", ".join(connect_host.service().registry.names()))) return { "part": info.name, "found": info.found, "description": info.description, - "connectors": [c.as_dict() for c in info.connectors], + "connectors": [c.as_dict() | {"index": i} for i, c in enumerate(info.connectors) if wanted is None or c.kind == wanted], "counts": counts, "shape": info.shape.as_dict(), "missing": list(info.missing), @@ -73,19 +82,31 @@ def fit(doc, part: str, rotation=None, position=None, on=None, origin=None, dire @command( "overlap.check", "Check Overlaps", - "List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count.", - params=(args.ids_param("Placement ids to check against their neighbours; every placement of every submodel when left out."),), + "List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU." + " Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked.", + params=( + args.ids_param("Placement ids to check against their neighbours; every placement of every submodel when left out."), + Param("nested", "boolean", "true to list nested pairs too, false to list only real overlaps; the overlap_nested setting when left out.", False), + ), kind="read", ) -def overlap_check(doc, ids=None) -> dict: +def overlap_check(doc, ids=None, nested=None) -> dict: m = doc.model chosen = args.ids(doc, ids) if ids else None keys = m.keys() if chosen is None else sorted({m.where(pid)[0] for pid in chosen}, key=m.keys().index) - pairs = [] + listed = settings.store().get()["overlap_nested"] if nested is None else bool(nested) + started = time.perf_counter() + pairs: list[dict] = [] + apart: list[dict] = [] try: for key in keys: - found = check_model(connect_host.hash_of(m, key), OverlapSettings(enabled=True), only=chosen) - pairs.extend({"submodel": m.name_of(key)} | o.as_dict() | {"parts": [m.placement(o.a)["part"], m.placement(o.b)["part"]]} for o in found) + found = check_model(connect_host.hash_of(m, key), OverlapSettings(enabled=True), only=chosen, nested=True) + for o in found: + row = {"submodel": m.name_of(key)} | o.as_dict() | {"parts": [m.placement(o.a)["part"], m.placement(o.b)["part"]]} + (pairs if o.kind == "overlap" else apart).append(row) except NoLibrary: raise CommandError(fitting.NO_LIBRARY) from None - return {"checked": len(chosen) if chosen is not None else len(m.all_ids()), "overlaps": pairs, "count": len(pairs)} + out = {"checked": len(chosen) if chosen is not None else len(m.all_ids()), "overlaps": pairs, "count": len(pairs), "nested_count": len(apart), "nested_listed": listed} + if listed: + out["nested"] = apart + return out | {"ms": round((time.perf_counter() - started) * 1000, 1)} diff --git a/backend/app/cmd/commands/info.py b/backend/app/cmd/commands/info.py index fd0609b..0d71f60 100644 --- a/backend/app/cmd/commands/info.py +++ b/backend/app/cmd/commands/info.py @@ -1,16 +1,44 @@ +from app.cmd import registry from app.cmd.registry import CommandError, Param, command, precheck from app.doc import files, partslist from app.services import model_info +def _missing(rows: list[dict]) -> list[dict]: + found: dict[str, dict] = {} + for r in rows: + if r["missing"]: + entry = found.setdefault(r["number"].lower(), {"part": r["number"], "file": r["part"], "count": 0}) + entry["count"] += r["count"] + return sorted(found.values(), key=lambda e: e["part"].lower()) + + +def _overlaps(doc) -> int | None: + try: + return registry.resolve("overlap.check").run(doc)["count"] + except CommandError: + return None + + @command( "model.info", "Model Information", - "Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list.", + "Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use;" + " its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them);" + " the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false.", + params=(Param("table", "boolean", "Leave the parts list and its CSV text out of the answer when false; true when left out.", False),), kind="read", ) -def info(doc) -> dict: - return model_info.info(doc) +def info(doc, table=True) -> dict: + answer = model_info.info(doc) + rows = answer["partsList"] + answer["counts"]["colours"] = len({r["colour"] for r in rows}) + answer["counts"]["overlaps"] = _overlaps(doc) + answer["missingParts"] = _missing(rows) + answer["licences"] = list(LICENCES) + if not table: + del answer["partsList"], answer["csv"] + return answer LICENCES = ("CC BY 4.0", "CC BY-SA 4.0", "CC BY-NC 4.0", "CC BY-NC-SA 4.0", "CC BY-ND 4.0", "CC BY-NC-ND 4.0", "CC0 1.0") diff --git a/backend/app/cmd/commands/model.py b/backend/app/cmd/commands/model.py index 4e8b5d4..63d7b17 100644 --- a/backend/app/cmd/commands/model.py +++ b/backend/app/cmd/commands/model.py @@ -73,11 +73,14 @@ def _apply_snap(model) -> dict | None: def _write(doc, target, kind: str) -> int: project = kind == "fblk" + library = library_host.update_name() if project else None if project: - data = convert.write(doc.model, kind, doc.show_state(), library_host.update_name(), _snap_line()) + data = convert.write(doc.model, kind, doc.show_state(), library, _snap_line()) else: data = convert.write(doc.model, kind) files.write(target, data) + if project: + doc.report = doc.report | {"savedWith": library or (doc.model.meta.get("project") or {}).get("library")} return len(data) diff --git a/backend/app/cmd/commands/part.py b/backend/app/cmd/commands/part.py index 5e39366..9ba6f16 100644 --- a/backend/app/cmd/commands/part.py +++ b/backend/app/cmd/commands/part.py @@ -1,7 +1,11 @@ -from app.cmd import args, fitting +import numpy as np + +from app.cmd import args, fitting, placing from app.cmd.registry import CommandError, Param, command from app.doc import transform, views from app.doc.model import new_placement +from app.mesh import to_scene +from app.services import connect_host, picking def _selected_if_editing(doc, key: str, new_ids: list[str]) -> None: @@ -122,32 +126,144 @@ def set_transform(doc, id: str, position: list | None = None, rotation: list | N return _moved(doc, [id]) +AXIS_VECTORS = {"x": [1.0, 0.0, 0.0], "y": [0.0, 1.0, 0.0], "z": [0.0, 0.0, 1.0]} + + +def _axis(axis: str | None, axis_vector: list | None) -> tuple[list, str]: + if (axis is None) == (axis_vector is None): + raise CommandError("axis: give axis (x, y or z) or axis_vector (a direction), one of them.") + if axis is not None: + name = axis.lower() + if name not in transform.AXES: + raise CommandError("axis must be x, y or z, not %s." % axis) + return AXIS_VECTORS[name], name.upper() + try: + unit = transform.unit(axis_vector) + except ValueError: + raise CommandError("axis_vector needs a direction that is not zero.") from None + named = next((sign + k.upper() for k, v in AXIS_VECTORS.items() for sign, w in (("", v), ("-", [-c + 0.0 for c in v])) if w == unit), None) + return unit, named or "(%s)" % ", ".join("%g" % round(v, 4) for v in unit) + + +def _angle(quarter_turns: int | None, angle: float | None) -> float: + if (quarter_turns is None) == (angle is None): + raise CommandError("angle: give quarter_turns or angle in degrees, one of them.") + degrees = 90.0 * quarter_turns if quarter_turns is not None else float(angle) + if abs(degrees) > transform.ANGLE_LIMIT: + raise CommandError("angle must be within %d degrees either way." % int(transform.ANGLE_LIMIT)) + return degrees + + +def centre_of(doc, chosen: list) -> list: + box = placing.pivot_box(doc, chosen) + if box is None: + return transform.centre(args.placement(doc, pid)["position"] for pid in chosen) + return transform.settle_place([(box[0][i] + box[1][i]) / 2 for i in range(3)]) + + @command( "part.rotate", "Rotate", - "Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins.", + "Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given." + " What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step.", params=( args.ids_param(), - Param("axis", "string", "x, y or z: the LDraw axis to turn about (y is the up and down axis).", True, 1), - Param("quarter_turns", "integer", "How many quarter turns, right-handed about the positive axis; negative turns the other way.", True), - args.vector_param("about", "The point to turn about, in LDU; the centre of the placements' origins when left out.", False), + Param("axis", "string", "x, y or z: the LDraw axis to turn about (y is the up and down axis). Give this or axis_vector.", False, 1), + Param("quarter_turns", "integer", "How many quarter turns, right-handed about the positive axis; negative turns the other way. Give this or angle.", False), + Param("angle", "number", "The angle in degrees, right-handed about the axis; negative turns the other way. Give this or quarter_turns.", False), + args.vector_param("axis_vector", "A direction in LDraw axes to turn about, such as a hinge's axis, in place of axis.", False), + args.vector_param("about", "The point to turn about, in LDU; the centre of the box around the placements' shapes when left out.", False), ), ) -def rotate(doc, axis: str, quarter_turns: int, ids: list | None = None, about: list | None = None) -> dict: +def rotate(doc, axis: str | None = None, quarter_turns: int | None = None, ids: list | None = None, about: list | None = None, angle: float | None = None, axis_vector: list | None = None) -> dict: chosen = args.ids(doc, ids) - axis = axis.lower() - if axis not in transform.AXES: - raise CommandError("axis must be x, y or z, not %s." % axis) - pivot = args.position(about, "about") if about is not None else transform.centre(args.placement(doc, pid)["position"] for pid in chosen) - turn = transform.quarter_turn(axis, quarter_turns) - for pid in chosen: - p = args.placement(doc, pid) - matrix, where = transform.turn_about(p["rotation"], p["position"], turn, pivot) + direction, named = _axis(axis, axis_vector) + degrees = _angle(quarter_turns, angle) + pivot = args.position(about, "about") if about is not None else centre_of(doc, chosen) + found = placing.turn(doc, chosen, direction, degrees, pivot, fitting.stamp_of(doc)) + ground = next((o for o in found.clashes if o.b == "ground"), None) + if ground is not None: + raise CommandError("ids: %s turns on its hinge and would go %s LDU into the ground, which a hinge cannot be lifted off, so nothing was turned." % (ground.a, round(ground.depth, 1))) + if found.blocked: + raise CommandError("ids: the turn would overlap %s with the overlap check on, so nothing was turned." % ", ".join("%s with %s by %s LDU" % (o.a, o.b, round(o.depth, 1)) for o in found.clashes)) + for pid, (matrix, where) in found.moves.items(): args.position(where, "about") + for pid, (matrix, where) in found.moves.items(): p = doc.model.edit_placement(pid) p["rotation"], p["position"] = matrix, where - doc.label = "Rotate %s about %s" % (args.count(len(chosen)), axis.upper()) - return _moved(doc, chosen) | {"about": pivot} + doc.label = "Rotate %s about %s" % (args.count(len(chosen)), named) + return _moved(doc, chosen) | {"about": pivot, "angle": degrees, "axis": direction, "lifted": found.lifted} + + +CONNECTOR_REACH = 8.0 + + +def _on_connector(doc, pid: str | None, point: list) -> list: + record = doc.model.placement(pid) if pid else None + if record is None or doc.model.find(record["part"]) is not None: + return point + pose = connect_host.pose_of(record) + near = [pose.point(c.position) for c in connect_host.service().info(record["part"]).connectors] + best = min(near, key=lambda c: float(np.linalg.norm(np.subtract(c, point))), default=None) + return list(best) if best is not None and float(np.linalg.norm(np.subtract(best, point))) <= CONNECTOR_REACH else point + + +def _scene(vector: list) -> list: + return [round(float(v), 6) + 0.0 for v in to_scene(np.asarray([vector], dtype=np.float64))[0]] + + +@command( + "part.pivot", + "Pivot", + "Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone;" + " with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point.", + params=( + args.ids_param(), + args.vector_param("origin", "A pointer ray's start in the window's scene axes (+Y up, LDU), to turn about the point it meets on a part.", False), + args.vector_param("direction", "That pointer ray's direction in the window's scene axes.", False), + ), + kind="read", +) +def pivot(doc, ids: list | None = None, origin: list | None = None, direction: list | None = None) -> dict: + chosen = args.ids(doc, ids) + box = placing.pivot_box(doc, chosen) + reach = 0.0 if box is None else round(float(np.linalg.norm(np.subtract(box[1], box[0]))) / 2, 3) + if (origin is None) != (direction is None): + raise CommandError("origin: give a pointer ray as origin and direction, both or neither.") + found = None if origin is None else picking.pick(doc.model, doc.editing, origin, direction, skip=connect_host.hidden(doc.model, doc.editing, fitting.stamp_of(doc)), stamp=fitting.stamp_of(doc), ground=False) + hinge = None if found is not None else placing.hinge_of(doc, chosen) + if found is not None: + point = transform.settle_place(_on_connector(doc, found.key, list(found.ldraw().point))) + if box is not None: + lo, hi = box + reach = round(max(float(np.linalg.norm(np.subtract((x, y, z), point))) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])), 3) + axes = [{"name": k, "axis": v, "scene": _scene(v)} for k, v in AXIS_VECTORS.items()] + return {"ids": chosen, "kind": "point", "about": point, "scene": _scene(point), "axes": axes, "reach": reach, "on": found.key} + if hinge is not None: + point, axis = transform.settle_place(hinge[0]), transform.unit(hinge[1]) + axes = [{"name": "hinge", "axis": axis}] + else: + point, axes = centre_of(doc, chosen), [{"name": k, "axis": v} for k, v in AXIS_VECTORS.items()] + for entry in axes: + entry["scene"] = _scene(entry["axis"]) + return {"ids": chosen, "kind": "hinge" if hinge is not None else "centre", "about": point, "scene": _scene(point), "axes": axes, "reach": reach} + + +@command( + "angle.step", + "Angle Step", + "Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting.", + params=(Param("step", "number", "90, 45, 22.5, 15, 5 or 1."),), + kind="view", +) +def angle_step(doc, step: float) -> dict: + from app.core import settings + + try: + now = settings.store().update({"angle_step": step}) + except settings.SettingsError as exc: + raise CommandError(str(exc).replace("angle_step", "step", 1)) from None + return {"angle_step": now["angle_step"]} @command( diff --git a/backend/app/cmd/commands/switches.py b/backend/app/cmd/commands/switches.py index c9453f1..17bd942 100644 --- a/backend/app/cmd/commands/switches.py +++ b/backend/app/cmd/commands/switches.py @@ -7,7 +7,7 @@ def _set(name: str, value, field: str) -> dict: now = settings.store().update({name: value}) except settings.SettingsError as exc: raise CommandError(str(exc).replace(name, field, 1)) from None - return {"snap": now["snap"], "grid_step": now["grid_step"], "overlap": now["overlap"]} + return {"snap": now["snap"], "grid_step": now["grid_step"], "overlap": now["overlap"], "overlap_nested": now["overlap_nested"]} @command( @@ -35,9 +35,21 @@ def grid_step(doc, step: str) -> dict: @command( "overlap.set", "Overlap Check", - "Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting.", + "Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting.", params=(Param("on", "boolean", "true to check, false to let parts share space."),), kind="view", ) def overlap_set(doc, on: bool) -> dict: return _set("overlap", on, "on") + + +@command( + "overlap.nested", + "Nested Pairs", + "Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole." + " Nested pairs never block placing or moving either way. Kept as the person's setting.", + params=(Param("on", "boolean", "true to report nested pairs too, false to report only real overlaps."),), + kind="view", +) +def overlap_nested(doc, on: bool) -> dict: + return _set("overlap_nested", on, "on") diff --git a/backend/app/cmd/placing.py b/backend/app/cmd/placing.py index 6411b55..b895923 100644 --- a/backend/app/cmd/placing.py +++ b/backend/app/cmd/placing.py @@ -8,7 +8,8 @@ from app.cmd import args, fitting from app.cmd.registry import CommandError, Param -from app.connect import Fit, Overlap, Placed, Pose, box_overlap, joined, neighbours, placed_box +from app.connect import Fit, Overlap, Placed, Pose, box_overlap, joined, neighbours, overlap_check, placed_box +from app.doc import transform from app.mesh import from_scene, hit_placed, placement_from_scene, placement_to_scene, to_scene from app.services import connect_host, picking @@ -227,3 +228,142 @@ def answer(found: Attempt) -> dict: out["joined"] = 0 if seat is None else len(seat.pairs) out["overlaps"] = [] if found.final is None else [item.as_dict() for item in found.final.overlaps] return out + + +DEPTH = 32 + + +def _corners(lo, hi, matrix, position) -> np.ndarray: + points = np.asarray([(x, y, z) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])], dtype=np.float64) + return points @ np.asarray(matrix, dtype=np.float64).reshape(3, 3).T + np.asarray(position, dtype=np.float64) + + +def _points(doc, part: str, matrix, position, depth: int = 0, exact: bool = True) -> np.ndarray: + key = doc.model.find(part) + if key is not None: + if depth > DEPTH: + return np.zeros((0, 3)) + found = [_points(doc, p["part"], transform.mat_mul(matrix, p["rotation"]), transform.add(transform.mat_vec(matrix, p["position"]), position), depth + 1, exact) for p in (doc.model.placement(i) for i in doc.model.ids(key)) if not p["hidden"]] + return np.concatenate(found) if found else np.zeros((0, 3)) + shape = picking.triangles(part) if exact else None + if shape is not None and len(shape): + local = np.concatenate([shape.first, shape.first + shape.one, shape.first + shape.two]) + return local @ np.asarray(matrix, dtype=np.float64).reshape(3, 3).T + np.asarray(position, dtype=np.float64) + try: + bounds = connect_host.service().info(part).shape.bounds + except Exception: + bounds = None + if bounds is None: + return np.asarray([position], dtype=np.float64) + return _corners(bounds[0], bounds[1], matrix, position) + + +def _lowest(doc, poses: dict) -> float | None: + lows = [float(found[:, 1].max()) for pid, (matrix, position) in poses.items() if len(found := _points(doc, doc.model.placement(pid)["part"], matrix, position))] + return max(lows) if lows else None + + +def pivot_box(doc, ids: list) -> tuple[list, list] | None: + found = [_points(doc, doc.model.placement(pid)["part"], doc.model.placement(pid)["rotation"], doc.model.placement(pid)["position"], exact=False) for pid in ids] + found = [f for f in found if len(f)] + if not found: + return None + every = np.concatenate(found) + return [float(v) for v in every.min(axis=0)], [float(v) for v in every.max(axis=0)] + + +def hinge_of(doc, ids: list) -> tuple[list, list] | None: + try: + from app.connect import hinge_axes + except ImportError: + return None + if len(ids) != 1 or doc.model.find(doc.model.placement(ids[0])["part"]) is not None: + return None + key = doc.model.where(ids[0])[0] + found = hinge_axes(connect_host.hash_of(doc.model, key, fitting.stamp_of(doc)), ids[0]) + if not found: + return None + return [float(v) for v in found[0].point_ldraw], [float(v) for v in found[0].direction_ldraw] + + +@dataclass(frozen=True) +class Turned: + ids: list + axis: list + degrees: float + about: list + moves: dict + lifted: float + clashes: tuple + + @property + def blocked(self) -> bool: + return bool(self.clashes) + + +def turn(doc, ids: list, axis: list, degrees: float, about: list, stamp=None) -> Turned: + spin = transform.turn_by(axis, degrees) + exact = transform.exact(axis, degrees) + before = {pid: (doc.model.placement(pid)["rotation"], doc.model.placement(pid)["position"]) for pid in ids} + after = {} + for pid, (matrix, position) in before.items(): + turned, where = transform.turn_about(matrix, position, spin, about) + after[pid] = (turned if exact else transform.settle(turned), where) + was, now = _lowest(doc, before), _lowest(doc, after) + floor = max(0.0, was if was is not None else 0.0) + lifted = now - floor if now is not None and now > floor + 1e-6 else 0.0 + if lifted and on_hinge(doc, ids, axis, about): + moves = {pid: (matrix, transform.settle_place(where)) for pid, (matrix, where) in after.items()} + return Turned(list(ids), list(axis), float(degrees), list(about), moves, 0.0, (Overlap(ids[0], "ground", round(lifted, 3)),)) + moves = {pid: (matrix, transform.settle_place(transform.add(where, (0.0, -lifted, 0.0)))) for pid, (matrix, where) in after.items()} + return Turned(list(ids), list(axis), float(degrees), list(about), moves, round(lifted, 3) + 0.0, _turn_clashes(doc, moves, stamp)) + + +def on_hinge(doc, ids: list, axis: list, about: list) -> bool: + hinge = hinge_of(doc, ids) + if hinge is None: + return False + point, direction = hinge + line = transform.unit(direction) + offset = transform.sub(about, point) + along = sum(offset[i] * line[i] for i in range(3)) + off_line = math.sqrt(max(0.0, sum(v * v for v in offset) - along * along)) + return off_line < 0.5 and abs(abs(sum(transform.unit(axis)[i] * line[i] for i in range(3))) - 1.0) < 1e-6 + + +def _turn_clashes(doc, moves: dict, stamp) -> tuple: + if not connect_host.options().overlap.enabled: + return () + held = connect_host.service() + opts = connect_host.options().overlap + found = [] + for key in {doc.model.where(pid)[0] for pid in moves}: + hash_ = connect_host.hash_of(doc.model, key, stamp) + skip = list(moves) + connect_host.hidden(doc.model, key, stamp) + for pid, (matrix, position) in moves.items(): + part = doc.model.placement(pid)["part"] + if doc.model.where(pid)[0] != key or doc.model.find(part) is not None: + continue + info = held.info(part) + pose = Pose.from_ldraw(position, matrix) + placed = Placed.of(pid, 0, pose, info) + around = neighbours(hash_, info, pose, reach=0.0, exclude=skip) + found.extend(Overlap(pid, o.b, o.depth) for o in overlap_check(info, pose, around, opts, [o.key for o in around if joined(placed, o)])) + return tuple(found) + + +def turn_answer(found: Turned) -> dict: + moves = [] + for pid, (matrix, position) in found.moves.items(): + scene = placement_to_scene(tuple(position), tuple(matrix)) + moves.append({ + "id": pid, + "position": [round(float(v), 4) + 0.0 for v in scene[:3, 3]], + "rotation": [round(float(v), 9) + 0.0 for v in scene[:3, :3].reshape(9)], + "ldraw": {"position": list(position), "rotation": list(matrix)}, + }) + return { + "ids": found.ids, "axis": found.axis, "angle": found.degrees, "about": found.about, + "lifted": found.lifted, "up": _scene_point((0.0, -found.lifted, 0.0)), + "blocked": found.blocked, "overlaps": [item.as_dict() for item in found.clashes], "moves": moves, + } diff --git a/backend/app/connect/HASHOUT_LOG.md b/backend/app/connect/HASHOUT_LOG.md index 6ab3adb..80398e0 100644 --- a/backend/app/connect/HASHOUT_LOG.md +++ b/backend/app/connect/HASHOUT_LOG.md @@ -2,6 +2,147 @@ Reasons behind the connection service, newest first. The rules themselves are in `spec/CONNECTIONS.md`; this log holds the choices made while writing the code and the places where the specification was silent or had to be read one way. +## A fitted pair whose solids cut into each other is still an overlap · 0.5.0 (overlap.py) + +The clip and bar mate puts the clip's centre on the bar's line and does not ask which side of the bar the clip's own part lies on. So in the window a Plate 1 x 1 with Clip Horizontal (`6019.dat`) held over a Plate 1 x 2 with Handle (`2540.dat`) seated with its plate inside the other plate, and because a joined pair was skipped by the overlap check, even with the check on nothing refused it or reported it. Joined pairs are now measured by their solids too: `check` and `check_model` report a joined pair whose solids share more than 1 LDU, and never report one as nested. The test is safe for real joints because a seated stud stands in the hollow it fits, hinge fingers interleave and a clip's jaws close round the bar, so their solids do not cut into each other: measured on the sample car, the pyramid, a 2,013 placement set of 33 cars and a 2,000 placement stack (the overlap check's own test models, kept outside the repository), and a model of a clip seated on a Bar 3L and two seated hinge pairs, no joined pair's solids overlapped, and every count stayed as it was (car 0 overlaps and 19 nested, 33 cars 0 and 627, 2,000 stack 0 and 0). Where a solid is missing (a part the library lacks) a joined pair is still skipped, as before, since the outline alone would flag every seated stud. With the check on, `part.fit` of the 6019 over the 2540 is now blocked at 8 LDU, and the 6019 turned a half turn in front of the handle seats with one pair. Whole-model checks after a fresh open took 72, 10, 110 and 158 ms on those four models, against 136 ms for the 33 cars and 178 ms for the stack when the check was written. + +## A clip on a bar is a fitted pair, not a nested one · 0.5.0 (overlap.py) + +`joined` looked for two connectors within 0.5 LDU of each other before asking the kinds whether they mate. A bar is a line: its connector's position is one end, so a clip seated in the middle of a bar was never within reach of it, the pair was not joined, and the check listed it as nested. SPEC.md 8.2 says parts joined through seated connectors are never reported, nested or not. The reach is now the distance to the bar's segment whenever either connector is of a kind that spans (`Registry.spans`), the same distance the snapping index uses; point connectors keep the squared distance test. Checked on an engine on 9270 with the 2026-10 library: a Bar 3L at (0, -100, 0) with a Plate 1 x 1 with Clip seated on it at y -70 went from 1 nested pair to 0; the sample car stays at 0 overlaps and 19 nested pairs, the pyramid at 0 and 0. +SPEC.md 8.2 now calls such a pair fitted and says nested means a pair whose outlines meet, whose solids do not, and which no seated connector joins. Question for the owner, unchanged in substance: should a part that sits in another's hollow with no connector holding it there (a rim in its tyre, a pin in a hole) be reported as an overlap, or only counted apart unless asked, as the proposed default does? + +## What the check finds in the library's models, and the rule chosen from it · 0.5.0 (overlap.py, solid.py) + +The owner has not decided what counts as an overlap. +Proposed default, awaiting that decision: a pair is an overlap only when the parts' real solids share a region more than 1 LDU thick; a pair whose outlines meet without that is nested, is never counted, never blocks, and is reported apart (`nested_count` always, the pairs themselves when `overlap_nested` or the command's `nested` asks). +The question for the owner: should a part that sits inside another's hollow without cutting into it (a rim in its tyre, a pin in its hole, two hinge halves) be reported as an overlap, or only counted apart unless asked? + +The library's models folder holds two models, `car.ldr` and `pyramid.ldr` (`car.dat` and `pyramid.dat` are one-line pointers to them). +The pyramid's 13 bricks give no pair under any rule below. +The car's 20 pairs of 0.4.0, measured on the 2026-10 library with `overlap.check nested=true` and the grids of `solid.py`; box and slabs are the 0.3.0 and 0.4.0 depths, real depth is the intersection's thickness and real volume its size: + +| Pairs | Parts | Box | Slabs | Real depth | Real volume | A person would say | +| --- | --- | --- | --- | --- | --- | --- | +| p2 and p56, p57; p4 and p54, p55 | 4600 wheel holder, 4624 rim | 11 | 5.5 | 1 | 40 | not a fault: the holder's pin in the rim's hole, faces touching | +| p2 and p60, p61; p4 and p58, p59 | 4600, 3641 tyre | 11 | 5.5 | 0 | 0 | not a fault: the pin passes through the tyre's open middle | +| p54 and p58, p55 and p59, p56 and p60, p57 and p61 | 4624 rim, 3641 tyre | 15 | 4 | 1 | 85 | not a fault: the rim seated in its tyre, faces touching | +| p19 and p60, p61; p20 and p58, p59 | 3788 mudguard, 3641 | 3 | 3 | 0 | 0 | not a fault: the tyre turns under the arch with room to spare | +| p23 and p24 | 3937 hinge base, 3938 hinge top | 13 | 4 | 0 | 0 | not a fault: the two halves interlock as made; joined since lane B2's hinge kinds | +| p50 and p52 | 4214 roof holder, 4213 roof | 7 | 3.5 | 0 | 0 | not a fault: the holder's lugs in the roof's slots | +| p15 and p50 | 4079 seat, 4214 | 4 | 4 | 0 | 0 | not a fault: the seat's back under the holder's frame, not touching | +| p18 and p49 | 3829c01 steering wheel, 3823 windscreen | 13.7 | 7.5 | 0 | 0 | not a fault: the wheel in the hollow under the windscreen | + +None of the 20 is a fault; 8 touch (depth 1, a sheet one cell thick where two faces meet), 12 do not touch at all. Since the slab test sees only outlines, every one of them was a hollow it could not see. + +Two models are too few to choose a rule from, so the library itself was used as a second set of parts put together by design: its shortcut files that place two or more whole parts (5,056 of them), every 25th taken from two starting points, 405 assemblies, of which 314 have parts whose whole bounds meet, 1,200 such pairs not joined through connectors. +And a set of faults was constructed (`faults.ldr`, kept in the lane's scratch folder, not here): a 2 by 4 brick pushed half way into another along x, down and along z, with both turned and with one turned against the other, at 0, 15, 30, 45, 60, 90 and 135 degrees about y, x, z, (1, 1, 1) and (1, 2, 3), 140 pairs; +a brick sunk 1, 2, 3, 4 and 12 LDU into the top of another; a 1 by 1 plate pushed 1, 2, 4 and 10 LDU into a brick's side; a tyre half into a brick; a rim moved 3 LDU across inside its tyre; +a brick on its side with its studs pushed 4 LDU into another's wall; a brick and a 1 by 1 plate clipping a brick's corner by 2, 3 and 4 LDU both ways; 158 pairs. What each candidate did: + +| Candidate | Car's 20 | 1,200 assembly pairs | 158 faults found | +| --- | --- | --- | --- | +| Body box, 0.3.0 | 20 | 1,182 | 155: misses the 1 LDU pushes and the studs pushed into a wall | +| Slabs, 0.4.0 | 20 | 1,102 | 155, the same three missed | +| Real solids, any shared cell | 8 | 298 | 158 | +| Real solids, thicker than 1 LDU (chosen) | 0 | 53 | 156: misses only the two 1 LDU pushes | +| Real solids, thicker than 2 LDU | 0 | 23 | 152: also misses the 2 LDU sink, push and both 2 LDU corner clips | +| Real solids, thicker than 3 LDU | 0 | 19 | 149 | +| Thicker than 1 LDU and at least 1 percent of the smaller part's volume | 0 | 29 | 153: misses the 2, 3 and 4 LDU corner clips between two bricks | +| Joined through connectors, on top of any of these | drops the hinge pair, 1 | already left out | none of the faults is joined | + +Every half-way brick is found at every turn tried, the shallowest at 5 LDU deep (one brick turned 90 degrees about (1, 1, 1) against the other), well above the tolerance. +The tolerance of 1 LDU is the smallest the 1 LDU cells can honour: two faces that touch fill one cell on each side at most, and the car's 8 touching pairs all measure exactly 1. +A larger tolerance lets real 2 LDU faults through for 30 fewer assembly pairs; a volume share drops corner clips that a person would call faults, so neither was taken. +A convex decomposition was not tried: a tyre's convex hull is a solid disc, so the rim in it would still overlap unless the tyre were cut into many pieces, which needs a decomposition library the engine does not have, and the cells already follow the hollow exactly. +The 53 assembly pairs left over are parts drawn into each other in the library itself: the inside parts of electric housings (IR remote, pole reverser, distance sensor), a rim's pinhole insert, figure parts, a gearbox's halves, a few rims and tyres modelled 2 or 3 LDU into each other; `SPEC.md` 8.3 says such parts can show an overlap that is there by design. + +## The check on 2,000 placements, before and after · 0.5.0 (overlap.py) + +A model repeats itself: every wheel sits in its tyre the same way, every brick on the one below it the same way. +The answers of `measure` and of `joined` are therefore kept by the two part names and the second placement's pose seen from the first (rounded to a millionth, with the first's determinant for a scaled placement), not by the two poses in the model, so 33 copies of a car cost one car, and a ghost moved along a wall meets the same relative poses again. +The joined memo also keys on the parts' connector tuples, so an overrides edit that moves a connector is not answered from before. + +Measured with `check_model` over every placement, nested pairs included, best of three, in processor time of one engine process (the machine runs a dozen agents on two processors, so wall time swung by a factor of three between runs; the processor times below repeated within 10 percent), on the 2026-10 library with all grids already in the disk cache, and each memo emptied before every "new" run: + +| Model | Placements | Pairs found | 0.4.0 slabs | 0.5.0 solids | 0.5.0 asked again | +| --- | --- | --- | --- | --- | --- | +| a wall of 2 by 4 bricks, ten courses of 200 in running bond | 2,000 | 0 | 301 ms | 178 ms | 165 ms | +| 33 sample cars side by side | 2,013 | 627 (0.4.0: overlaps; 0.5.0: 0 overlaps, 627 nested) | 396 ms | 136 ms | 129 ms | +| the sample car | 61 | 19 | 10 ms | 12 ms | 3 ms | + +The pairs are 19 and not 20 per car because lane B2's hinge kinds, registered this turn, join the hinge 3937 to 3938, and joined pairs are never reported. +Filling the grids is the cost the table leaves out: the car's 26 distinct parts take 0.6 s the first time a library is used (their meshes already flattened) and are read from `cache/solids` after that, 2 ms each. Through the command line against an engine, `overlap.check` reports its own time as `ms`: 30 ms for the car once warm. + +## Probing bars no longer doubles the derivation time · 0.5.0 (kinds/_probe.py, kinds/clip.py) + +Measured on 300 parts (every 83rd file of the 2026-10 `parts` folder, no cache, the code before this lane's work unpacked beside it with `git archive` and run in turn with the current code): before the change 7.6 and 8.9 s, with the bar probes 18.5 and 16.8 s. A profile put half of it in `Slices`, which projected every triangle of the part onto every candidate line, though most candidates are the 4 LDU solid bars under 1 x N plates and the short pins of round parts. Two cuts: a stretch shorter than the least free length (6) is not probed at all, since it can never give a bar, and `Slices` drops triangles whose box lies outside the stretch's box grown by the probe's reach before projecting anything. After: 11.6 and 8.9 s against 13.0 and 8.9 s for the old code in the same runs, so within the machine's noise, with the same 56 bars, 2 clips and 7 hinge halves on the sample, and the bars of 87994, 2540, 60478 and 18649 and the stud examples unchanged. + +## An override matches a line either way round · 0.5.0 (overrides.py, kinds) + +A matcher with an axis removed a connector only when the two axes agreed within 5 degrees. For a clip, a bar or a hinge half the axis is a line whose sign the derivation picks from the primitive (the two halves of a dual click finger even give opposite signs), so an author writing `[0, -1, 0]` for a bar the walk wrote as `[0, 1, 0]` would see the entry reported stale for no reason. Kinds now say whether their axis is a line (`Kind.line`), and a matcher accepts the opposite axis for those kinds only; studs and anti-studs match as before. The reader looks the kind up in the registry when it matches, so it still names no kind. Checked: a throwaway overrides file removing 87994's bar with the axis written downward leaves the part with no connectors and no stale matcher. + +## The hinge axes a placement is joined on, for the rotation lane · 0.5.0 (held.py, __init__.py) + +Lane B3's turn by the pointer and the fine angle needs, for a placement, the lines it may turn about. The interface was agreed in writing before it was built (`hinge_axes`, `HingeAxis`, `hinge_motion`, `turn_about`) and is kept as written. `hinge_axes` never names a kind: it asks each paired connector's mate for its freedom and keeps the joined pairs whose freedom is a hinge, so a clip on a bar is reported as well as the hinge halves, and a later hinge kind is reported with no change. The point is the half's own point, or for a segment kind the partner's (a clip on a bar turns about the clip's centre on the bar's line). The axis goes out in the scene's axes through `app.mesh.scene.to_scene`, imported only when the function runs, so the conversion stays in its one place and the package still imports without the array library. `angle` is signed about the placement's own axis, from the partner's ref to its own, so the lane can show the opening and limit it later. `hinge_motion` is a turn about a line through the axis point (Rodrigues' formula); composed before a pose it moves the placement and anything moved with it rigidly, and the joined point stays where it was. Checked on a scratch model built from the 2026-10 library: 44301a joined to 44302a reports one axis at scene (30, 98, 0) along z, opening 180; turned by 90, -45 and 30.5 degrees it is still joined, reading -90, 135 and -149.5; a 4085c on a 87994 reports the bar's line and stays joined after the same turns. + +## A part held by a clip or a hinge half is anchored by it · 0.5.0 (held.py) + +A bar is seen from the side, so the face the pointer meets on it looks sideways, where the raw pose used the centre of the part's bottom face: a 1 x 1 plate with a clip then had its clip 20 LDU or more from the bar and never came within reach. "The anchor" in `CONNECTIONS.md` adds the case: a connector of a kind that does not rest on a face (neither the ground's kind nor a partner of it, so the rule names no kind) is the anchor when the person holds the part by it, whatever the face, and, for a part from the palette over a face looking sideways, its nearest such connector to the bottom centre is. `face_kinds` gives that set from the registry. A stud-only part has no such connector, so its anchor is what it was. The quarter turn of a part held by such a connector is about the vertical, since turning a clip about its own axis never lines it up with a bar. Checked through the engine on port 9220: a 4085c pointed at the side of a standing 87994 at heights 50, 33 and 62 in the scene seats at y = -50, -30 and -70; a 3001 pointed at the same spot falls to the grid as before. + +## The snap reaches to a bar's whole length and shares it between clips · 0.5.0 (snap.py, fit.py) + +The snap's own index kept each connector in the 20 LDU cell of its `position`, and looked partners up by distance to that point; a bar's position is one end, so a clip held over the far end of a 60 LDU bar found nothing. Connectors of kinds that `spans` now live in a short list beside the cells, are found by their segment's box, and are measured by distance to the segment (`to_segment`), which is "Reach to a line". `around` asks the right question for either shape of the held connector too, so a part carrying a bar finds clips along it. Occupancy keeps a list of taken stretches per bar from each mate's `at` and `span` instead of taking the bar whole; a proposal or a pair whose stretch overlaps a taken one by more than the mating distance is dropped. Proposals pass the grid step to the mate (`SnapSettings.slide_step`); counting pairs passes none, so a second clip of the same part that lies on the bar between two steps still counts as joined, as it physically is. `fit` fills `slide_step` from the grid step's across value when the caller left it at 0, so the window and `part.fit` slide in Stud, Plate or Fine steps without either knowing about bars. Checked through `./formblocks cli` on an engine on port 9220 with the 2026-10 library: a 87994 bar standing from y = -80 to -20 and a 4085c held with its clip near it at y = -55, -37, -26 and -73 seats at y = -50, -30, -30 and -70 (the middle of the bar and 20 either side); with one 4085c placed at -50 the same fit is refused, a turned one at -30 seats. + +## Clips by name, bars by shape · 0.5.0 (kinds/clip.py, kinds/clip.json, kinds/_probe.py, connector.py) + +Clips are found as studs are, by exact primitive name with the grip's centre, axis, opening and width per file in `clip.json`. Bars have no primitive, so `BarKind` claims the three whole-circle cylinders and makes one provisional piece per radius 4 reference (`source` `cylinder:`, from its start along its run); claiming them is safe because a cylinder file holds no connectors, and it keeps the stud and tube walk exactly as it was. `settle` then joins pieces on one line and keeps only the runs where eight probes from radius 4.25 to 7.75 cross no triangle of the part, which is where the specification's free length is. The probes test only the triangles whose run along the bar covers the sample (`_probe.Slices`, binned per LDU) and that come within the probe's reach of the line, so a 60 LDU bar costs 480 probes against a handful of triangles each. `_probe.py` starts with `_` so `kinds.load` does not import it as a kind. `merge` used to fold any two connectors of a kind closer than 0.5 LDU; two bar pieces that start at one point and run different ways are not the same bar, so connectors with a length now merge only when their lengths agree and their axes are parallel; for length 0, studs, anti-studs and hinge halves, nothing changed. The clip's mate is `place_on_bar`: the projection of the clip's centre on the bar, moved to the nearest grid step from the bar's middle inside the stretch the jaws fit in; the bar's mate is the same seen the other way round. Checked on the 2026-10 library: 87994 gives one bar of 60, 2540 three (the 12 between the handle's legs and the 8 beyond each leg), 60478 one of 8 on the end, 4085c a clip at (0, 4, -20) and 63868 one at (30, 2, 0) along z; 15712, whose jaws are drawn from cylinders, gives none, as the specification says. 3001, 3023, 3068b, 3039 and 3003 give exactly the studs and anti-studs they gave before. + +## Hinge halves: one class, six kinds, one data file · 0.5.0 (kinds/hinge.py, kinds/hinge.json) + +`CONNECTIONS.md` "Hinges" makes each half of a joint its own kind so a half never seats on its twin, and keeps the click, plate and arm systems apart because their sizes differ. So `hinge.py` is one `HingeHalf` class registered six times from the `families` of `hinge.json`, each instance claiming only the files whose `kind` is its own; adding a family is a data change. The per-file point, axis and ref were measured in the 2026-10 library with a scratch script outside the repository (the pins, click positions, knuckles or discs give the axis; the middle of the knuckles the point; the side the file meets its part the ref) and are the numbers of the specification's table. A file in `halves` that names a kind no family has stops the engine, as a broken stud list does. The refs must be 30 degrees apart for a mate; the check projects both into the plane at right angles to the first half's axis, so a slightly tilted partner is judged on its turn about the axis only. Checked against the library: 44301a and 44302a, the locking 1 x 2 hinge plates with one and two fingers, both give their half at (30, 2, 0) on the z axis with the ref pointing back along -x, so one turned half round about the vertical and moved 60 along x meets the other; 4275b and 4276b give (30, 4, 0); the arm pieces 3612 and 30015 give a two finger half at z = -12 and a three finger half at z = 12. + +## A mate can say where along a bar it sits, and a kind can take the grid step · 0.5.0 (kinds/__init__.py) + +A clip on a bar needs two things the stud's mate never did: the grid step, because `CONNECTIONS.md` "The mate of a clip on a bar" moves the clip in grid steps from the bar's middle, and a way to say which stretch of the bar it took, because "What a bar can still take" lets several clips share one bar. `Registry.mate` now takes an optional `step` and hands it only to kinds that set `takes_step`, so `stud.py` keeps its two-argument `mate` and its version, and `Mate` carries `at` (where along the sliding partner the mate sits) and `span` (half the stretch it takes), both kept when the mate is turned round. `spans` marks kinds whose connector is a segment from `position` along `axis` for `length`, so the snap can measure reach to a line without naming a kind. `parallel` and `line_mate` are the mate of two lines either way round with a hinge freedom, which the hinge kinds use. Checked with the selfcheck; the stud mate is unchanged. + +## Depths and volumes are rounded to a millionth · 0.5.0 (solid.py) + +A placement read from a file carries a turn written to nine places, whose determinant is 1 only to about 1e-10, and `meet` scales its cell size by the cube root of that determinant. +A one-cell intersection then measured 1.0000000002 LDU and passed the 1 LDU tolerance: five pairs of a palm tree's trunk segments and two curved track pieces in the library's own assemblies were reported as overlaps for that alone. Both answers are now rounded to six places, which is far below a cell. + +## Overlap, nested, or neither: the rule the measurements chose · 0.5.0 (overlap.py) + +`measure` decides a pair in four steps, cheapest first. The whole bounding boxes (studs included), shrunk by the 0.5 LDU margin and placed as oriented boxes, must meet, or there is nothing to say. +Pairs joined through mated connectors are dropped, as before, before anything costly. The two grids of `solid.py` are then compared: an intersection thicker than `TOLERANCE`, 1 LDU, is an overlap, with its depth and shared volume. +Otherwise, when the body slabs of 0.4.0 still meet, one part is inside the other's outline without cutting into it, and the pair is `nested`. Anything else is neither. +When either part has no grid (missing from the library, or no store installed, as for a caller that builds the package without the engine), the 0.4.0 slab test answers alone and every hit is an overlap, so nothing is lost where the real shape is not known. + +The broad test takes the whole bounds and not the body box because studs are solid in the grids: the body box test let through a brick turned on its side with its studs pushed 4 LDU into another's wall (it found nothing, the grids find 4 LDU). +The cost is that a stacked pair now reaches the joined test; that test was rewritten without a function call per connector pair, and `check_model` now tests the placements' world boxes and skips the oriented test when both turns are whole quarter turns, where the two are the same. +Answers are kept by part names and poses in a memo of 50,000 pairs, so a second check over an unchanged model, and a ghost held still, cost almost nothing. + +Nested pairs never block placing, moving or turning, whatever `overlap_nested` says: blocking them would make the sample car unbuildable with the check on, since every rim has to go into its tyre. +`check` (the fit) and `overlaps` therefore answer real overlaps only, and `check_model` hands nested pairs back only when asked. `Overlap` gained `kind` and `volume` with defaults, so the callers in other lanes that build one from three values keep working. + +## A part's real shape as a grid of 1 LDU cells · 0.5.0 (solid.py, services/connect_host.py) + +The boxes and slabs of 0.4.0 cannot see a hollow: a slab spans the walls on both sides of a tyre's hole, so whatever sits in the hole is inside the slab. The overlap check needs the part's own solid, and it needs it in a form two parts can be compared in quickly. +`solid.py` fills a grid of 1 LDU cells, in the part's own axes, with the inside of the part's triangles, from the mesh lane's flattened mesh (`app.mesh.part_mesh`, studs included, turned back into LDraw axes through `from_scene`, the one conversion). +A cell is inside when its centre is: rays are cast along x, y and z through the cell centres, each triangle crossed adds one when the ray enters the part through it and takes one away when it leaves (the mesh lane already turns every certified triangle to face out, through INVERTNEXT and mirrored placements), and a cell is inside for that axis when the sum is above zero; +a triangle with no certified winding toggles inside and outside instead. +The three axes vote and two of three wins, so a ray that grazes a shared edge, or a part whose surface is not quite closed, costs a few cells and not a streak. Cell centres are moved off the whole and half LDU by a few hundredths (`JITTER`), because LDraw coordinates sit on those values and a ray through a vertex would be counted twice. +Faces of zero thickness (a sticker, a flag) have no inside and give an empty grid. + +The grid is the inside of the surface as LDraw draws it, so a closed body comes out right: 3001 gives 39,344 cubic LDU against about 39,600 worked by hand from its walls, top, three tubes and eight studs, 3024 gives 3,072 against 3,076, 3811 2,097,104. +A part with more than 24 million cells is filled at 2 LDU, then 4, and the step is kept with the grid. +Filling takes 20 to 200 ms for ordinary parts and 4 s for a 32 by 32 baseplate on this machine, so a grid is written once to `cache/solids//v1/` in the data folder as packed, compressed bits (1.8 kB for a 2 by 4 brick, 7.4 kB for the 32 by 32 baseplate) and kept in memory for the last 512 parts. +The key is the mesh lane's library key, so a new library or a new flattener makes new grids. numpy was already the engine's dependency for meshes; `app.connect` imports it here, and the mesh lane only inside `for_library`, so the package still loads without a library. + +`meet` compares two grids: the cells of the smaller part that fall inside the other part's box are turned into the other part's axes and looked up there, one numpy pass. +Its answer is the volume shared, in cubic LDU, and a depth: for every shared cell the length of the run of shared cells through it along each of the part's three axes, the least of the three taken, and the largest of those over the whole intersection. +That is how thick the intersection is at its thickest, across its thinnest direction, so a sheet one cell thick where two faces touch measures 1 whatever its area, and a brick sunk 12 LDU into another measures 12. +The store is installed once, when `connect_host` makes the connection service for a library, through `solid.use`, so every caller of the overlap check (the fit, a drag, a turn, the command) sees the same grids without passing anything. + ## A held part rests on what is under its footprint · 0.4.0 (support.py, fit.py) Seen in the 0.3.0 window: a plate held over the open top of a house fell to the floor, because the raw pose puts the anchor where the ray meets, and the ray met the floor between the walls; the wall studs, 96 LDU up, were far beyond the 15 LDU reach. `CONNECTIONS.md` now has "Resting on what is under the whole footprint", and `fit` follows it: the usual seat first, then, only when that pose cuts into another part, the slab tops under the footprint from the lowest up, each tried as a face looking up at the pointer's x and z, the first clear one taken, the first answer kept when none is. "Clear" is the overlap check's own slab test with the switch forced on and the seat's partners left out, so it agrees with what the person sees when they turn the check on. Only slabs, not studs, give levels: a stud's base and its part's top slab are the same plane. The column is taken from the hash with a 960 LDU ceiling, 40 bricks, so a tall model is not walked whole on every pointer move, and at most six levels are tried. `FitOptions.rest` turns the search off for a caller that wants the old answer; nothing sets it yet. Checked on the 2026-10 library with the driving pack's house up to its fourth course: a 4 by 6 plate and a 6 by 6 plate pointed at the floor in the middle seat on the wall tops at y = -104 with 8 and 16 pairs (54 and 68 ms), a 2 by 4 brick pointed there stands on the floor, one pointed near the side wall goes onto the wall; on a lone brick, on top, one stud over, the ground beside it, its side face, a 1 x 2 plate on top and a 1 x 1 beside it answer as before. diff --git a/backend/app/connect/__init__.py b/backend/app/connect/__init__.py index a568e49..06f3fd2 100644 --- a/backend/app/connect/__init__.py +++ b/backend/app/connect/__init__.py @@ -3,7 +3,7 @@ from .connector import Connector, ConnectorError, make from .fit import Fit, FitOptions, fit, seat_on, settle from .grid import STEPS, GridStep, Step, grid_snap -from .held import Held, Hit, first_hit, ground_hit, raw_pose, turn, turn_step +from .held import HingeAxis, Held, Hit, first_hit, ground_hit, hinge_axes, hinge_motion, raw_pose, turn, turn_about, turn_step from .kinds import Freedom, Kind, KindError, Mate, Registry, axial_mate, register from .kinds import load as load_kinds from .overlap import Overlap, OverlapSettings, check_model, joined @@ -116,4 +116,8 @@ def overlaps( "table", "turn", "turn_step", + "HingeAxis", + "hinge_axes", + "hinge_motion", + "turn_about", ] diff --git a/backend/app/connect/connector.py b/backend/app/connect/connector.py index 242d194..d08dd0c 100644 --- a/backend/app/connect/connector.py +++ b/backend/app/connect/connector.py @@ -121,7 +121,11 @@ def sort(connectors: Iterable[Connector]) -> list[Connector]: def same_place(a: Connector, b: Connector, tolerance: float = MATE_DISTANCE) -> bool: - return distance(a.position, b.position) < tolerance + if distance(a.position, b.position) >= tolerance: + return False + if a.length == 0 and b.length == 0: + return True + return abs(a.length - b.length) < tolerance and abs(dot(a.axis, b.axis)) >= MATE_COS def merge(connectors: Iterable[Connector], tolerance: float = MATE_DISTANCE) -> list[Connector]: diff --git a/backend/app/connect/fit.py b/backend/app/connect/fit.py index 50e1a27..ebb241f 100644 --- a/backend/app/connect/fit.py +++ b/backend/app/connect/fit.py @@ -1,9 +1,9 @@ from __future__ import annotations from collections.abc import Iterable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace -from .grid import DEFAULT, GridStep, grid_snap +from .grid import DEFAULT, GridStep, grid_snap, step_of from .held import FACE_COS, Held, Hit, raw_pose from .kinds import Registry, load from .overlap import Overlap, OverlapSettings, check @@ -68,7 +68,10 @@ def settle( near = neighbours(hash_, info, pose, reach=options.settings.reach, exclude=skip) seat = None if options.snap and info.connectors: - seat = snap(info, pose, near, registry=registry, under=under, current=current, settings=options.settings) + snapping = options.settings + if snapping.slide_step <= 0: + snapping = replace(snapping, slide_step=step_of(options.step).across) + seat = snap(info, pose, near, registry=registry, under=under, current=current, settings=snapping) placed = seat.pose if seat is not None else grid_snap(info, pose, options.step) if not options.overlap.enabled: return Fit(placed, seat, held) diff --git a/backend/app/connect/held.py b/backend/app/connect/held.py index 4010a6d..89a9ea3 100644 --- a/backend/app/connect/held.py +++ b/backend/app/connect/held.py @@ -8,6 +8,7 @@ from .connector import MATE_DISTANCE, Connector from .kinds import Registry, load from .shape import PartInfo, Placed +from .spatial import SpatialHash, placed_box from .vec import ( UP, Mat3, @@ -15,14 +16,18 @@ Vec3, add, apply, + cross, distance, dot, inverse, + length, matmul, normalise, rotation_about, + round_vec, scale, sub, + tidy, transpose, ) @@ -127,7 +132,16 @@ def anchor( looks_up = dot(normal, UP) >= FACE_COS looks_down = dot(normal, UP) <= -FACE_COS centre = _bottom_centre(info, rotation) + resting = face_kinds(registry) + if grip is not None: + gripped = min(info.connectors, key=lambda c: (distance(c.position, grip), c.sort_key()), default=None) + if gripped is not None and gripped.kind not in resting and distance(gripped.position, grip) <= MATE_DISTANCE: + return gripped, gripped.position if not (looks_up or looks_down): + others = [c for c in info.connectors if c.kind not in resting] + if grip is None and others: + best = min(others, key=lambda c: (distance(c.position, centre), c.sort_key())) + return best, best.position return None, centre offered = {ground.KIND} if looks_down: @@ -179,8 +193,12 @@ def turn_step( return QUARTER +def face_kinds(registry: Registry) -> frozenset[str]: + return frozenset({ground.KIND, *registry.partners(ground.KIND)}) + + def turn_axis(pose: Pose, held: Held) -> Vec3: - if held.anchor is None: + if held.anchor is None or held.anchor.kind not in face_kinds(load()): return (0.0, 1.0, 0.0) axis = pose.direction(held.anchor.axis) if abs(axis[1]) > 1e-9 and axis[1] < 0: @@ -196,3 +214,113 @@ def turn(pose: Pose, held: Held, quarter_turns: int) -> Pose: rotation = matmul(spin, pose.rotation) translation = add(apply(spin, sub(pose.translation, pivot)), pivot) return Pose(rotation, translation) + + +@dataclass(frozen=True, slots=True) +class HingeAxis: + placement: str + connector: int + partner: str + partner_connector: int + kind: str + partner_kind: str + point: Vec3 + direction: Vec3 + point_ldraw: Vec3 + direction_ldraw: Vec3 + angle: float + low: float + high: float + + def as_dict(self) -> dict[str, object]: + return { + "placement": self.placement, + "connector": self.connector, + "partner": self.partner, + "partner_connector": self.partner_connector, + "kind": self.kind, + "partner_kind": self.partner_kind, + "point": list(self.point), + "direction": list(self.direction), + "point_ldraw": list(self.point_ldraw), + "direction_ldraw": list(self.direction_ldraw), + "angle": self.angle, + "low": self.low, + "high": self.high, + } + + +def _to_scene(v: Vec3) -> Vec3: + from app.mesh.scene import to_scene + + import numpy as np + + x, y, z = to_scene(np.asarray([v], dtype=np.float64))[0].tolist() + return tidy(round_vec((x, y, z), 1e-9), 9) + + +def _signed(start: Vec3, end: Vec3, axis: Vec3) -> float: + a = sub(start, scale(axis, dot(start, axis))) + b = sub(end, scale(axis, dot(end, axis))) + if length(a) < 1e-9 or length(b) < 1e-9: + return 0.0 + angle = math.degrees(math.atan2(dot(cross(a, b), axis), dot(a, b))) + return 180.0 if angle <= -180.0 + 1e-9 else round(angle, 6) + 0.0 + + +def hinge_axes(hash_: SpatialHash, key: str, *, exclude: Iterable[str] = (), registry: Registry | None = None) -> list[HingeAxis]: + registry = registry or load() + placed = hash_.get(key) + if placed is None: + return [] + box = placed_box(placed.pose, placed.shape.bounds) + if box is None: + return [] + skip = {key, *exclude} + found: list[HingeAxis] = [] + for other in hash_.placements_near(box, MATE_DISTANCE): + if other.key in skip: + continue + for i, a in enumerate(placed.model_connectors): + for j, b in enumerate(other.model_connectors): + if not registry.pair(a.kind, b.kind): + continue + mate = registry.mate(a, b) + if mate is None or mate.residual > MATE_DISTANCE or mate.freedom.motion != "hinge": + continue + point = b.position if registry.spans(a.kind) else a.position + direction = normalise(a.axis) + angle = 0.0 if a.ref is None or b.ref is None else _signed(b.ref, a.ref, direction) + found.append( + HingeAxis( + key, i, other.key, j, a.kind, b.kind, + _to_scene(point), _to_scene(direction), point, direction, + angle, mate.freedom.low, mate.freedom.high, + ) + ) + found.sort(key=lambda h: (hash_.get(h.partner).order if hash_.get(h.partner) is not None else 0, h.partner, h.partner_connector, h.connector)) # type: ignore[union-attr] + return found + + +def turning(direction: Vec3, degrees: float) -> Mat3: + x, y, z = normalise(direction) + c = math.cos(math.radians(degrees)) + s = math.sin(math.radians(degrees)) + k = 1.0 - c + return ( + c + x * x * k, x * y * k - z * s, x * z * k + y * s, + y * x * k + z * s, c + y * y * k, y * z * k - x * s, + z * x * k - y * s, z * y * k + x * s, c + z * z * k, + ) + + +def hinge_motion(axis: HingeAxis, degrees: float) -> Pose: + spin = turning(axis.direction_ldraw, degrees) + p = axis.point_ldraw + return Pose(spin, sub(p, apply(spin, p))) + + +def turn_about(pose: Pose, axis: HingeAxis, degrees: float) -> Pose: + moved = hinge_motion(axis, degrees).compose(pose) + rotation = tuple(round(v, 9) + 0.0 for v in moved.rotation) + return Pose(rotation, tidy(round_vec(moved.translation, 0.001), 9)) # type: ignore[arg-type] diff --git a/backend/app/connect/kinds/__init__.py b/backend/app/connect/kinds/__init__.py index b6591dc..b07161f 100644 --- a/backend/app/connect/kinds/__init__.py +++ b/backend/app/connect/kinds/__init__.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any from ..connector import MATE_COS, Connector, opposed -from ..vec import IDENTITY, Pose, Vec3, distance, sub +from ..vec import IDENTITY, Pose, Vec3, distance, dot, sub if TYPE_CHECKING: from ..geometry import Mesh @@ -44,6 +44,8 @@ class Mate: correction: Pose residual: float freedom: Freedom + at: float | None = None + span: float = 0.0 class Kind: @@ -51,6 +53,9 @@ class Kind: mates_with: frozenset[str] = frozenset() version: str = "1" body: bool = True + takes_step: bool = False + spans: bool = False + line: bool = False def claims(self, file_name: str) -> bool: return False @@ -77,6 +82,16 @@ def axial_mate(a: Connector, b: Connector, spin_step: float, cos_limit: float = return Mate(Pose(IDENTITY, sub(b.position, a.position)), distance(a.position, b.position), Freedom.spin(spin_step)) +def parallel(a: Vec3, b: Vec3, cos_limit: float = MATE_COS) -> bool: + return abs(dot(a, b)) >= cos_limit + + +def line_mate(a: Connector, b: Connector, low: float = -180.0, high: float = 180.0, cos_limit: float = MATE_COS) -> Mate | None: + if not parallel(a.axis, b.axis, cos_limit): + return None + return Mate(Pose(IDENTITY, sub(b.position, a.position)), distance(a.position, b.position), Freedom.hinge(a.axis, low, high)) + + class KindError(ValueError): pass @@ -116,18 +131,22 @@ def partners(self, name: str) -> frozenset[str]: def pair(self, a: str, b: str) -> bool: return b in self.partners(a) + def spans(self, name: str) -> bool: + kind = self.kinds.get(name) + return kind is not None and kind.spans + def claimants(self, file_name: str) -> list[Kind]: return [kind for kind in self.all() if kind.claims(file_name)] - def mate(self, a: Connector, b: Connector) -> Mate | None: + def mate(self, a: Connector, b: Connector, step: float = 0.0) -> Mate | None: first = self.kinds.get(a.kind) second = self.kinds.get(b.kind) if first is None or second is None: return None if b.kind in first.mates_with: - return first.mate(a, b) + return first.mate(a, b, step) if first.takes_step else first.mate(a, b) # type: ignore[call-arg] if a.kind in second.mates_with: - return _flip(second.mate(b, a)) + return _flip(second.mate(b, a, step) if second.takes_step else second.mate(b, a)) # type: ignore[call-arg] return None def versions(self) -> dict[str, str]: @@ -141,7 +160,7 @@ def _flip(found: Mate | None) -> Mate | None: if found is None: return None back = found.correction.inverse() - return Mate(back, found.residual, found.freedom) + return Mate(back, found.residual, found.freedom, found.at, found.span) REGISTRY = Registry() diff --git a/backend/app/connect/kinds/_probe.py b/backend/app/connect/kinds/_probe.py new file mode 100644 index 0000000..8f42517 --- /dev/null +++ b/backend/app/connect/kinds/_probe.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +import math +from collections.abc import Iterable, Sequence + +from ..vec import Vec3, add, cross, dot, length, normalise, scale, sub + +EPS = 1e-9 + +Tri = Sequence[float] + + +def crosses(start: Vec3, end: Vec3, t: Tri) -> bool: + a = (t[0], t[1], t[2]) + b = (t[3], t[4], t[5]) + c = (t[6], t[7], t[8]) + d = sub(end, start) + e1 = sub(b, a) + e2 = sub(c, a) + p = cross(d, e2) + det = dot(e1, p) + if abs(det) < EPS: + return False + inv = 1.0 / det + s = sub(start, a) + u = dot(s, p) * inv + if u < 0.0 or u > 1.0: + return False + q = cross(s, e1) + v = dot(d, q) * inv + if v < 0.0 or u + v > 1.0: + return False + h = dot(e2, q) * inv + return 0.0 <= h <= 1.0 + + +def basis(axis: Vec3) -> tuple[Vec3, Vec3]: + helper = (1.0, 0.0, 0.0) if abs(axis[0]) < 0.9 else (0.0, 1.0, 0.0) + v = normalise(cross(axis, helper)) + w = normalise(cross(axis, v)) + return v, w + + +def ring(axis: Vec3, count: int) -> list[Vec3]: + v, w = basis(axis) + out: list[Vec3] = [] + for k in range(count): + angle = 2.0 * math.pi * k / count + out.append(add(scale(v, math.cos(angle)), scale(w, math.sin(angle)))) + return out + + +def along(origin: Vec3, axis: Vec3, t: Tri) -> tuple[float, float]: + values = [dot(sub((t[i], t[i + 1], t[i + 2]), origin), axis) for i in (0, 3, 6)] + return min(values), max(values) + + +def off_line(point: Vec3, origin: Vec3, axis: Vec3) -> float: + d = sub(point, origin) + return length(sub(d, scale(axis, dot(d, axis)))) + + +class Slices: + def __init__(self, origin: Vec3, axis: Vec3, low: float, high: float, reach: float, triangles: Iterable[Tri]) -> None: + self.origin = origin + self.axis = axis + self.bins: dict[int, list[Tri]] = {} + ends = (add(origin, scale(axis, low)), add(origin, scale(axis, high))) + lo = [min(e[i] for e in ends) - reach - 1.0 for i in range(3)] + hi = [max(e[i] for e in ends) + reach + 1.0 for i in range(3)] + for t in triangles: + if ( + max(t[0], t[3], t[6]) < lo[0] or min(t[0], t[3], t[6]) > hi[0] + or max(t[1], t[4], t[7]) < lo[1] or min(t[1], t[4], t[7]) > hi[1] + or max(t[2], t[5], t[8]) < lo[2] or min(t[2], t[5], t[8]) > hi[2] + ): + continue + t0, t1 = along(origin, axis, t) + if t1 < low - 1.0 or t0 > high + 1.0: + continue + if min(off_line((t[i], t[i + 1], t[i + 2]), origin, axis) for i in (0, 3, 6)) > reach and not _spans_line(t, origin, axis, reach): + continue + for k in range(math.floor(t0), math.floor(t1) + 1): + self.bins.setdefault(k, []).append(t) + + def near(self, t: float) -> list[Tri]: + return self.bins.get(math.floor(t), []) + + +def _spans_line(t: Tri, origin: Vec3, axis: Vec3, reach: float) -> bool: + v, w = basis(axis) + xs = [] + ys = [] + for i in (0, 3, 6): + d = sub((t[i], t[i + 1], t[i + 2]), origin) + xs.append(dot(d, v)) + ys.append(dot(d, w)) + return min(xs) <= reach and max(xs) >= -reach and min(ys) <= reach and max(ys) >= -reach diff --git a/backend/app/connect/kinds/clip.json b/backend/app/connect/kinds/clip.json new file mode 100644 index 0000000..0547419 --- /dev/null +++ b/backend/app/connect/kinds/clip.json @@ -0,0 +1,34 @@ +{ + "version": "1", + "unit_tolerance": 0.01, + "clips": { + "clip1.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Vertical Clip for Flags"}, + "clip2.dat": {"centre": [0, 0, -10], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Vertical Clip for Bricks"}, + "clip3.dat": {"centre": [0, 2, 0], "axis": [1, 0, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Horizontal with Parallel Sides"}, + "clip5.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Symmetrical with Rounded Sides"}, + "clip6.dat": {"centre": [0, 2, 0], "axis": [1, 0, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Horizontal with Rounded Sides"}, + "clip7.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip for Round Arm 4 LDU"}, + "clip8.dat": {"centre": [0, -6, 0], "axis": [0, 0, 1], "opening": [0, -1, 0], "width": 8, "description": "Top Clip with Rounded Tips and Centre Notch"}, + "clip9.dat": {"centre": [0, 0, -10], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Vertical (Thin C-Clip)"}, + "clip10.dat": {"centre": [0, 0, -10], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Vertical (Thin U-Clip)"}, + "clip11.dat": {"centre": [0, -5.994, 0], "axis": [0, 0, 1], "opening": [0, -1, 0], "width": 8, "description": "Top Clip with Rounded Tips"}, + "clip12.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip without Attachment (Thick C-Clip)"}, + "clip13.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Minimal (Thick C-Clip)"}, + "clip14.dat": {"centre": [0, 0, -10], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip Vertical (Thick U-Clip) with Centre Notch"}, + "clip15.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Clip for Round Arm 4 LDU without Adapter"}, + "clip16.dat": {"centre": [0, 0, 0], "axis": [0, 1, 0], "opening": [0, 0, -1], "width": 8, "description": "Vertical Thick Clip for Flags"} + }, + "bar": { + "cylinders": ["4-4cyli.dat", "4-4cylo.dat", "4-4cylc.dat"], + "radius": 4, + "radius_tolerance": 0.05, + "least_piece": 1, + "line_tolerance": 0.05, + "join_gap": 0.5, + "sample_step": 1, + "probe_from": 4.25, + "probe_to": 7.75, + "probes": 8, + "least_free": 6 + } +} diff --git a/backend/app/connect/kinds/clip.py b/backend/app/connect/kinds/clip.py new file mode 100644 index 0000000..f63b288 --- /dev/null +++ b/backend/app/connect/kinds/clip.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +from ..connector import Connector, make +from ..geometry import Mesh +from ..vec import IDENTITY, Pose, Vec3, add, apply, column, dot, length, normalise, scale, sub +from . import Freedom, Kind, Mate, parallel, register +from ._probe import Slices, crosses, off_line, ring + +DATA_FILE = Path(__file__).with_name("clip.json") + + +def _load(path: Path = DATA_FILE) -> dict[str, Any]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise RuntimeError(f"the clip kind's data file {path.name} cannot be read: {error}") from error + for key in ("version", "unit_tolerance", "clips", "bar"): + if key not in data: + raise RuntimeError(f"the clip kind's data file {path.name} has no '{key}'") + return data + + +DATA = _load() +VERSION = str(DATA["version"]) + + +def _vec(values: list[float]) -> Vec3: + return (float(values[0]), float(values[1]), float(values[2])) + + +def place_on_bar(clip: Connector, bar: Connector, step: float) -> Mate | None: + if not parallel(clip.axis, bar.axis): + return None + u = bar.axis + full = bar.length + half = clip.length / 2 + middle = full / 2 + low, high = half, full - half + projected = dot(sub(clip.position, bar.position), u) + if high < low: + t = middle + elif step <= 0: + t = min(max(projected, low), high) + else: + most = math.floor((high - middle) / step + 1e-9) + k = max(-most, min(most, round((projected - middle) / step))) + t = middle + k * step + d = sub(add(bar.position, scale(u, t)), clip.position) + return Mate(Pose(IDENTITY, d), length(d), Freedom.hinge(u, -180.0, 180.0), t, half) + + +class ClipKind(Kind): + name = "clip" + mates_with = frozenset({"bar"}) + version = VERSION + body = True + takes_step = True + line = True + + def __init__(self, data: dict[str, Any] = DATA) -> None: + self.clips = {file.lower(): clip for file, clip in data["clips"].items()} + self.tolerance = float(data["unit_tolerance"]) + + def claims(self, file_name: str) -> bool: + return file_name in self.clips + + def from_reference(self, file_name: str, transform: Pose) -> list[Connector]: + if not all(abs(length(column(transform.rotation, i)) - 1.0) <= self.tolerance for i in range(3)): + return [] + clip = self.clips[file_name] + axis = apply(transform.rotation, _vec(clip["axis"])) + opening = apply(transform.rotation, _vec(clip["opening"])) + return [make(self.name, transform.point(_vec(clip["centre"])), axis, ref=opening, length=float(clip["width"]), source=file_name)] + + def mate(self, a: Connector, b: Connector, step: float = 0.0) -> Mate | None: + return place_on_bar(a, b, step) + + +class BarKind(Kind): + name = "bar" + mates_with = frozenset({"clip"}) + version = VERSION + body = True + takes_step = True + spans = True + line = True + + def __init__(self, data: dict[str, Any] = DATA) -> None: + bar = data["bar"] + self.cylinders = frozenset(name.lower() for name in bar["cylinders"]) + self.radius = float(bar["radius"]) + self.radius_tolerance = float(bar["radius_tolerance"]) + self.least_piece = float(bar["least_piece"]) + self.line = float(bar["line_tolerance"]) + self.gap = float(bar["join_gap"]) + self.step = float(bar["sample_step"]) + self.probe_from = float(bar["probe_from"]) + self.probe_to = float(bar["probe_to"]) + self.probes = int(bar["probes"]) + self.least_free = float(bar["least_free"]) + + def claims(self, file_name: str) -> bool: + return file_name in self.cylinders + + def from_reference(self, file_name: str, transform: Pose) -> list[Connector]: + r = transform.rotation + if any(abs(length(column(r, i)) - self.radius) > self.radius_tolerance for i in (0, 2)): + return [] + run = column(r, 1) + size = length(run) + if size < self.least_piece: + return [] + return [make(self.name, transform.translation, run, length=size, source=f"cylinder:{file_name}")] + + def settle(self, mesh: Mesh, own: list[Connector]) -> list[Connector]: + pieces = [c for c in own if c.source.startswith("cylinder:")] + kept = [c for c in own if not c.source.startswith("cylinder:")] + for origin, axis, stretches in self._lines(pieces): + for low, high in stretches: + if high - low >= self.least_free: + kept.extend(self._free(mesh, origin, axis, low, high)) + return kept + + def _lines(self, pieces: list[Connector]) -> list[tuple[Vec3, Vec3, list[tuple[float, float]]]]: + lines: list[tuple[Vec3, Vec3, list[tuple[float, float]]]] = [] + for piece in pieces: + end = add(piece.position, scale(piece.axis, piece.length)) + for origin, axis, spans in lines: + if parallel(axis, piece.axis) and off_line(piece.position, origin, axis) <= self.line and off_line(end, origin, axis) <= self.line: + a = dot(sub(piece.position, origin), axis) + b = dot(sub(end, origin), axis) + spans.append((min(a, b), max(a, b))) + break + else: + lines.append((piece.position, piece.axis, [(0.0, piece.length)])) + out: list[tuple[Vec3, Vec3, list[tuple[float, float]]]] = [] + for origin, axis, spans in lines: + spans.sort() + joined: list[tuple[float, float]] = [] + for low, high in spans: + if joined and low <= joined[-1][1] + self.gap: + joined[-1] = (joined[-1][0], max(joined[-1][1], high)) + else: + joined.append((low, high)) + out.append((origin, axis, joined)) + return out + + def _free(self, mesh: Mesh, origin: Vec3, axis: Vec3, low: float, high: float) -> list[Connector]: + slices = Slices(origin, axis, low, high, self.probe_to + 0.5, mesh.triangles) + directions = ring(axis, self.probes) + half = self.step / 2 + samples: list[tuple[float, bool]] = [] + t = low + half + while t <= high - half + 1e-9: + centre = add(origin, scale(axis, t)) + near = slices.near(t) + free = not any( + crosses(add(centre, scale(d, self.probe_from)), add(centre, scale(d, self.probe_to)), tri) + for d in directions + for tri in near + ) + samples.append((t, free)) + t += self.step + bars: list[Connector] = [] + run: list[float] = [] + for t, free in [*samples, (math.inf, False)]: + if free: + run.append(t) + continue + if run and len(run) * self.step >= self.least_free: + start = add(origin, scale(axis, run[0] - half)) + bars.append(make(self.name, start, axis, length=len(run) * self.step, source="bar")) + run = [] + return bars + + def mate(self, a: Connector, b: Connector, step: float = 0.0) -> Mate | None: + found = place_on_bar(b, a, step) + if found is None: + return None + back = found.correction.translation + return Mate(Pose(IDENTITY, (-back[0], -back[1], -back[2])), found.residual, found.freedom, found.at, found.span) + + +CLIP = register(ClipKind()) +BAR = register(BarKind()) diff --git a/backend/app/connect/kinds/hinge.json b/backend/app/connect/kinds/hinge.json new file mode 100644 index 0000000..b1f86e4 --- /dev/null +++ b/backend/app/connect/kinds/hinge.json @@ -0,0 +1,36 @@ +{ + "version": "1", + "unit_tolerance": 0.01, + "min_opening_degrees": 30, + "families": { + "click": ["hinge_click_1", "hinge_click_2"], + "plate": ["hinge_plate_2", "hinge_plate_3"], + "arm": ["hinge_arm_2", "hinge_arm_3"], + "brick": ["hinge_brick_top", "hinge_brick_base"], + "swivel": ["hinge_swivel_top", "hinge_swivel_base"] + }, + "halves": { + "clh1.dat": {"kind": "hinge_click_1", "point": [0, 0, -10], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Bricks"}, + "clh2.dat": {"kind": "hinge_click_1", "point": [0, -7, 0], "axis": [1, 0, 0], "ref": [0, 1, 0], "description": "Click Lock Hinge Single Finger for Plate Top"}, + "clh3.dat": {"kind": "hinge_click_1", "point": [0, 0, -10], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Arms Narrow Slot"}, + "clh6.dat": {"kind": "hinge_click_1", "point": [0, 0, -10], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Plate Ends"}, + "clh6d.dat": {"kind": "hinge_click_1", "point": [0, 0, -10], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Plate Ends - Opening Downwards"}, + "clh6u.dat": {"kind": "hinge_click_1", "point": [0, 0, -10], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Plate Ends - Opening Upwards"}, + "clh8.dat": {"kind": "hinge_click_1", "point": [0, 0, -7], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Crevices and Ledges"}, + "clh9.dat": {"kind": "hinge_click_1", "point": [0, -7, 0], "axis": [1, 0, 0], "ref": [0, 1, 0], "description": "Click Lock Hinge Single Finger for Plate Top with Groove"}, + "clh12.dat": {"kind": "hinge_click_1", "point": [0, -7, 0], "axis": [1, 0, 0], "ref": [0, 1, 0], "description": "Click Lock Hinge Single Finger Tall"}, + "clh13.dat": {"kind": "hinge_click_1", "point": [0, -7, 0], "axis": [1, 0, 0], "ref": [0, 1, 0], "description": "Click Lock Hinge Single Finger for Plate Top with Wide Groove 2L"}, + "clh15.dat": {"kind": "hinge_click_1", "point": [0, 0, -10], "axis": [1, 0, 0], "ref": [0, 0, 1], "description": "Click Lock Hinge Single Finger for Arms Wide Slot"}, + "clh4.dat": {"kind": "hinge_click_2", "point": [0, 0, 4], "axis": [1, 0, 0], "ref": [0, 0, -1], "description": "Click Lock Hinge Half Dual Finger - 4.5LDU"}, + "clh5.dat": {"kind": "hinge_click_2", "point": [0, 0, 10], "axis": [1, 0, 0], "ref": [0, 0, -1], "description": "Click Lock Hinge Half Dual Finger for Arms"}, + "clh7.dat": {"kind": "hinge_click_2", "point": [0, 0, 4], "axis": [1, 0, 0], "ref": [0, 0, -1], "description": "Click Lock Hinge Half Dual Finger 3-Position Type 1"}, + "clh10.dat": {"kind": "hinge_click_2", "point": [0, 0, 4], "axis": [1, 0, 0], "ref": [0, 0, -1], "description": "Click Lock Hinge Half Dual Finger 7-Position"}, + "clh11.dat": {"kind": "hinge_click_2", "point": [0, 0, 4], "axis": [1, 0, 0], "ref": [0, 0, -1], "description": "Click Lock Hinge Half Dual Finger - Missing Clicks 2 and 4"}, + "clh14.dat": {"kind": "hinge_click_2", "point": [0, 0, 10], "axis": [1, 0, 0], "ref": [0, 0, -1], "description": "Click Lock Hinge Half Dual Finger 7-Position for Arms"}, + "h1.dat": {"kind": "hinge_plate_2", "point": [0, 10, 0], "axis": [0, 0, 1], "ref": [0, -1, 0], "description": "Hinge Plate 2 Fingers"}, + "h2.dat": {"kind": "hinge_plate_3", "point": [0, 10, 0], "axis": [0, 0, 1], "ref": [0, -1, 0], "description": "Hinge Plate 3 Fingers"}, + "arm1.dat": {"kind": "hinge_arm_2", "point": [0, 0, -10], "axis": [0, 1, 0], "ref": [0, 0, 1], "description": "Hinge Arm 2 Finger"}, + "arm2.dat": {"kind": "hinge_arm_3", "point": [0, 0, -10], "axis": [0, 1, 0], "ref": [0, 0, 1], "description": "Hinge Arm 3 Finger without Ribs with Round Middle Finger"}, + "arm3.dat": {"kind": "hinge_arm_3", "point": [0, 0, -10], "axis": [0, 1, 0], "ref": [0, 0, 1], "description": "Hinge Arm 3 Finger without Ribs with Truncated Middle Finger"} + } +} diff --git a/backend/app/connect/kinds/hinge.py b/backend/app/connect/kinds/hinge.py new file mode 100644 index 0000000..6642c4e --- /dev/null +++ b/backend/app/connect/kinds/hinge.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any + +from ..connector import Connector, make +from ..vec import Pose, Vec3, apply, column, dot, length, scale, sub +from . import Kind, Mate, line_mate, register + +DATA_FILE = Path(__file__).with_name("hinge.json") + + +def _load(path: Path = DATA_FILE) -> dict[str, Any]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise RuntimeError(f"the hinge kind's data file {path.name} cannot be read: {error}") from error + for key in ("version", "unit_tolerance", "min_opening_degrees", "families", "halves"): + if key not in data: + raise RuntimeError(f"the hinge kind's data file {path.name} has no '{key}'") + names = {name for pair in data["families"].values() for name in pair} + for file, half in data["halves"].items(): + if half.get("kind") not in names: + raise RuntimeError(f"the hinge kind's data file {path.name} gives {file} a kind no family names") + return data + + +DATA = _load() +VERSION = str(DATA["version"]) + + +def _vec(values: list[float]) -> Vec3: + return (float(values[0]), float(values[1]), float(values[2])) + + +def flat(v: Vec3, axis: Vec3) -> Vec3 | None: + out = sub(v, scale(axis, dot(v, axis))) + size = length(out) + if size < 1e-9: + return None + return scale(out, 1.0 / size) + + +def opening(a: Connector, b: Connector) -> float | None: + if a.ref is None or b.ref is None: + return None + first = flat(a.ref, a.axis) + second = flat(b.ref, a.axis) + if first is None or second is None: + return None + return math.degrees(math.acos(max(-1.0, min(1.0, dot(first, second))))) + + +class HingeHalf(Kind): + body = True + version = VERSION + line = True + + def __init__(self, name: str, partner: str, data: dict[str, Any] = DATA) -> None: + self.name = name + self.mates_with = frozenset({partner}) + self.halves = {file.lower(): half for file, half in data["halves"].items() if half["kind"] == name} + self.tolerance = float(data["unit_tolerance"]) + self.least = float(data["min_opening_degrees"]) + + def claims(self, file_name: str) -> bool: + return file_name in self.halves + + def from_reference(self, file_name: str, transform: Pose) -> list[Connector]: + if not all(abs(length(column(transform.rotation, i)) - 1.0) <= self.tolerance for i in range(3)): + return [] + half = self.halves[file_name] + axis = apply(transform.rotation, _vec(half["axis"])) + ref = apply(transform.rotation, _vec(half["ref"])) + return [make(self.name, transform.point(_vec(half["point"])), axis, ref=ref, source=file_name)] + + def mate(self, a: Connector, b: Connector) -> Mate | None: + angle = opening(a, b) + if angle is not None and angle < self.least: + return None + return line_mate(a, b) + + +def _register(data: dict[str, Any] = DATA) -> list[Kind]: + made: list[Kind] = [] + for first, second in data["families"].values(): + made.append(register(HingeHalf(first, second, data))) + made.append(register(HingeHalf(second, first, data))) + return made + + +HALVES = _register() diff --git a/backend/app/connect/overlap.py b/backend/app/connect/overlap.py index 1530fd6..fdd5539 100644 --- a/backend/app/connect/overlap.py +++ b/backend/app/connect/overlap.py @@ -1,23 +1,31 @@ from __future__ import annotations import math +import threading +from collections import OrderedDict from collections.abc import Iterable, Sequence from dataclasses import dataclass -from .connector import MATE_DISTANCE +from . import solid +from .connector import MATE_DISTANCE, Connector from .geometry import Box from .kinds import Registry, load from .shape import PartInfo, Placed from .spatial import SpatialHash, placed_box -from .vec import Pose, Vec3, column, cross, distance, dot, length, scale, sub +from .vec import Pose, Vec3, add, column, cross, determinant, dot, length, scale, sub MARGIN = 0.5 +TOLERANCE = 1.0 +OVERLAP = "overlap" +NESTED = "nested" @dataclass(frozen=True, slots=True) class OverlapSettings: enabled: bool = False margin: float = MARGIN + tolerance: float = TOLERANCE + shapes: bool = True @dataclass(frozen=True, slots=True) @@ -32,9 +40,14 @@ class Overlap: a: str b: str depth: float + kind: str = OVERLAP + volume: float | None = None def as_dict(self) -> dict[str, object]: - return {"a": self.a, "b": self.b, "depth": round(self.depth, 3)} + out: dict[str, object] = {"a": self.a, "b": self.b, "depth": round(self.depth, 3), "kind": self.kind} + if self.volume is not None: + out["volume"] = round(self.volume, 1) + return out def body_box(info: PartInfo, margin: float = MARGIN) -> Box | None: @@ -109,7 +122,106 @@ def body_slabs(info: PartInfo, margin: float = MARGIN) -> tuple[Box, ...]: return tuple(shrunk) or (whole,) +def _shrunk(box: Box | None, margin: float) -> Box | None: + if box is None: + return None + lo, hi = box + a = [lo[i] + margin if lo[i] + margin <= hi[i] - margin else (lo[i] + hi[i]) / 2 for i in range(3)] + b = [hi[i] - margin if lo[i] + margin <= hi[i] - margin else (lo[i] + hi[i]) / 2 for i in range(3)] + return ((a[0], a[1], a[2]), (b[0], b[1], b[2])) + + +def _bounds_meet(a_info: PartInfo, a_pose: Pose, b_info: PartInfo, b_pose: Pose, margin: float) -> bool: + a_box = _shrunk(a_info.shape.bounds, margin) + b_box = _shrunk(b_info.shape.bounds, margin) + return a_box is not None and b_box is not None and depth(oriented(a_box, a_pose), oriented(b_box, b_pose)) is not None + + +def _square(pose: Pose) -> bool: + return all(v in (0.0, 1.0, -1.0) for v in pose.rotation) + + +def _solid(store: solid.SolidStore | None, info: PartInfo) -> solid.Solid | None: + if store is None or not info.found: + return None + return store.get(info.name) + + +def _solids_known(settings: OverlapSettings, a: PartInfo, b: PartInfo) -> bool: + store = solid.current() if settings.shapes else None + return _solid(store, a) is not None and _solid(store, b) is not None + + +_MEMO: OrderedDict[tuple, Overlap | None] = OrderedDict() +_JOINED: OrderedDict[tuple, bool] = OrderedDict() +_MEMO_LOCK = threading.Lock() +MEMO_LIMIT = 50_000 + + +def _relative(a_pose: Pose, b_pose: Pose) -> tuple: + try: + rel = a_pose.inverse().compose(b_pose) + except ValueError: + return (a_pose, b_pose) + return (round(determinant(a_pose.rotation), 6), *(round(v, 6) + 0.0 for v in (*rel.rotation, *rel.translation))) + + +def _remember(memo: OrderedDict, key: tuple, value: object) -> None: + with _MEMO_LOCK: + memo[key] = value + while len(memo) > MEMO_LIMIT: + memo.popitem(last=False) + + +def measure(a_info: PartInfo, a_pose: Pose, b_info: PartInfo, b_pose: Pose, settings: OverlapSettings = OverlapSettings(enabled=True)) -> Overlap | None: + store = solid.current() if settings.shapes else None + key = (id(store), a_info.name, a_info.found, b_info.name, b_info.found, _relative(a_pose, b_pose), settings.margin, settings.tolerance) + with _MEMO_LOCK: + if key in _MEMO: + _MEMO.move_to_end(key) + return _MEMO[key] + found = _measure(store, a_info, a_pose, b_info, b_pose, settings) + _remember(_MEMO, key, found) + return found + + +def _measure(store: solid.SolidStore | None, a_info: PartInfo, a_pose: Pose, b_info: PartInfo, b_pose: Pose, settings: OverlapSettings) -> Overlap | None: + a_solid = _solid(store, a_info) + b_solid = _solid(store, b_info) if a_solid is not None else None + if a_solid is None or b_solid is None: + found = slab_depth(a_info, a_pose, b_info, b_pose, settings.margin) + return None if found is None else Overlap("", "", found) + if not _bounds_meet(a_info, a_pose, b_info, b_pose, settings.margin): + return None + if b_solid.grid.size < a_solid.grid.size: + met = solid.meet(b_solid, b_pose, a_solid, a_pose) + else: + met = solid.meet(a_solid, a_pose, b_solid, b_pose) + if met.depth > settings.tolerance: + return Overlap("", "", met.depth, OVERLAP, met.volume) + if not _slabs_meet(a_info, a_pose, b_info, b_pose, settings.margin): + return None + return Overlap("", "", met.depth, NESTED, met.volume) + + +def _slabs_meet(a_info: PartInfo, a_pose: Pose, b_info: PartInfo, b_pose: Pose, margin: float) -> bool: + if not (_square(a_pose) and _square(b_pose)): + return slab_depth(a_info, a_pose, b_info, b_pose, margin) is not None + mine = [placed_box(a_pose, slab) for slab in body_slabs(a_info, margin)] + theirs = [placed_box(b_pose, slab) for slab in body_slabs(b_info, margin)] + for p in mine: + for q in theirs: + if p is not None and q is not None and all(p[0][i] < q[1][i] - 1e-9 and q[0][i] < p[1][i] - 1e-9 for i in range(3)): + return True + return False + + def overlaps(a_info: PartInfo, a_pose: Pose, b_info: PartInfo, b_pose: Pose, margin: float = MARGIN) -> float | None: + found = measure(a_info, a_pose, b_info, b_pose, OverlapSettings(enabled=True, margin=margin)) + return found.depth if found is not None and found.kind == OVERLAP else None + + +def slab_depth(a_info: PartInfo, a_pose: Pose, b_info: PartInfo, b_pose: Pose, margin: float = MARGIN) -> float | None: a_box = body_box(a_info, margin) b_box = body_box(b_info, margin) if a_box is None or b_box is None: @@ -140,19 +252,42 @@ def check( skip = set(joined) found = [] for placed in near: - if placed.key in skip or placed.key == key: + if placed.key == key or (placed.key in skip and not _solids_known(settings, held, placed.info)): continue - found_depth = overlaps(held, pose, placed.info, placed.pose, settings.margin) - if found_depth is not None: - found.append(Overlap(key, placed.key, found_depth)) + met = measure(held, pose, placed.info, placed.pose, settings) + if met is not None and met.kind == OVERLAP: + found.append(Overlap(key, placed.key, met.depth, OVERLAP, met.volume)) return found def joined(a: Placed, b: Placed, registry: Registry | None = None) -> bool: registry = registry or load() + key = (id(registry), a.info.name, hash(a.info.connectors), b.info.name, hash(b.info.connectors), _relative(a.pose, b.pose)) + with _MEMO_LOCK: + if key in _JOINED: + _JOINED.move_to_end(key) + return _JOINED[key] + found = _joined(a, b, registry) + _remember(_JOINED, key, found) + return found + + +def _to_line(point: Vec3, c: Connector) -> float: + t = max(0.0, min(c.length, dot(sub(point, c.position), c.axis))) + return length(sub(point, add(c.position, scale(c.axis, t)))) + + +def _joined(a: Placed, b: Placed, registry: Registry) -> bool: + limit = MATE_DISTANCE * MATE_DISTANCE + theirs = [(y, y.position, y.length > 0 and registry.spans(y.kind)) for y in b.model_connectors] for x in a.model_connectors: - for y in b.model_connectors: - if distance(x.position, y.position) > MATE_DISTANCE: + px, py, pz = x.position + long = x.length > 0 and registry.spans(x.kind) + for y, (qx, qy, qz), along in theirs: + if along or long: + if (_to_line(x.position, y) if along else _to_line(y.position, x)) > MATE_DISTANCE: + continue + elif (px - qx) * (px - qx) + (py - qy) * (py - qy) + (pz - qz) * (pz - qz) > limit: continue found = registry.mate(x, y) if found is not None and found.residual <= MATE_DISTANCE: @@ -165,6 +300,7 @@ def check_model( settings: OverlapSettings = OverlapSettings(), only: Sequence[str] | None = None, registry: Registry | None = None, + nested: bool = False, ) -> list[Overlap]: if not settings.enabled: return [] @@ -172,11 +308,19 @@ def check_model( wanted = set(only) if only is not None else None seen: set[tuple[str, str]] = set() found: list[Overlap] = [] + boxes: dict[str, Box | None] = {} + + def box_of(item: Placed) -> Box | None: + if item.key not in boxes: + boxes[item.key] = placed_box(item.pose, _shrunk(item.shape.bounds, settings.margin)) + return boxes[item.key] + for placed in hash_.all(): if wanted is not None and placed.key not in wanted: continue - box = placed_box(placed.pose, placed.shape.body) - if box is None: + box = placed_box(placed.pose, placed.shape.bounds) + mine = box_of(placed) + if box is None or mine is None: continue for other in hash_.placements_near(box): if other.key == placed.key: @@ -185,9 +329,17 @@ def check_model( if pair in seen: continue seen.add(pair) - value = overlaps(placed.info, placed.pose, other.info, other.pose, settings.margin) - if value is None or joined(placed, other, registry): + theirs = box_of(other) + if theirs is None or any(mine[0][i] >= theirs[1][i] or theirs[0][i] >= mine[1][i] for i in range(3)): + continue + square = _square(placed.pose) and _square(other.pose) + if not (square or _bounds_meet(placed.info, placed.pose, other.info, other.pose, settings.margin)): + continue + met = measure(placed.info, placed.pose, other.info, other.pose, settings) + if met is None or (met.kind == NESTED and not nested): + continue + if joined(placed, other, registry) and (met.kind == NESTED or not _solids_known(settings, placed.info, other.info)): continue - found.append(Overlap(pair[0], pair[1], value)) + found.append(Overlap(pair[0], pair[1], met.depth, met.kind, met.volume)) found.sort(key=lambda item: (item.a, item.b)) return found diff --git a/backend/app/connect/overrides.json b/backend/app/connect/overrides.json index d401647..bff10fd 100644 --- a/backend/app/connect/overrides.json +++ b/backend/app/connect/overrides.json @@ -3,5 +3,71 @@ "version": 1, "license": "Apache-2.0", "copyright": "FormBlocks contributors", - "entries": [] + "entries": [ + { + "file": "15712.dat", + "description": "Tile 1 x 1 with Clip (Thick C-Clip)", + "checked_against": "2026-10", + "author": "nodemode-ai", + "date": "2026-11-27", + "license": "Apache-2.0", + "reason": "The jaws are drawn from cylinders, not a clip primitive, so no clip is derived. Measured: a 5-8 cylinder of radius 4 runs along z from (0, -6, -4) to (0, -6, 4), its open arc facing -y, 8 LDU wide like every clip primitive.", + "mode": "patch", + "add": [ + { "kind": "clip", "position": [0, -6, 0], "axis": [0, 0, 1], "ref": [0, -1, 0], "length": 8 } + ] + }, + { + "file": "2429.dat", + "description": "Hinge Plate 1 x 4 Base", + "checked_against": "2026-10", + "author": "nodemode-ai", + "date": "2026-11-27", + "license": "Apache-2.0", + "reason": "The plate's round end turns flat about a vertical axis and is drawn from cylinders, so no hinge half is derived. Measured: the end's radius 8 rim and radius 4 pin stand on the y axis from y 4 to 8, the lower half of the plate's thickness; the plate runs to x -40.", + "mode": "patch", + "add": [ + { "kind": "hinge_swivel_base", "position": [0, 4, 0], "axis": [0, 1, 0], "ref": [-1, 0, 0] } + ] + }, + { + "file": "2430.dat", + "description": "Hinge Plate 1 x 4 Top", + "checked_against": "2026-10", + "author": "nodemode-ai", + "date": "2026-11-27", + "license": "Apache-2.0", + "reason": "The plate's round end turns flat about a vertical axis and is drawn from cylinders, so no hinge half is derived. Measured: the end's radius 8 rim stands on the y axis from y 0 to 4, the upper half of the plate's thickness, over a hole round the base's pin; the plate runs to x 40.", + "mode": "patch", + "add": [ + { "kind": "hinge_swivel_top", "position": [0, 4, 0], "axis": [0, 1, 0], "ref": [1, 0, 0] } + ] + }, + { + "file": "3937.dat", + "description": "Hinge 1 x 2 Base", + "checked_against": "2026-10", + "author": "nodemode-ai", + "date": "2026-11-27", + "license": "Apache-2.0", + "reason": "The base's knuckles are drawn from cylinders and boxes, so no hinge half is derived. Measured: its two outer knuckles, radius 8, and their radius 4 bores run along x through (0, 10, 0) at x 16 to 20 and -20 to -16; the base's body lies below the axis.", + "mode": "patch", + "add": [ + { "kind": "hinge_brick_base", "position": [0, 10, 0], "axis": [1, 0, 0], "ref": [0, 1, 0] } + ] + }, + { + "file": "3938.dat", + "description": "Hinge 1 x 2 Top", + "checked_against": "2026-10", + "author": "nodemode-ai", + "date": "2026-11-27", + "license": "Apache-2.0", + "reason": "The top's pins are drawn from cylinders, so no hinge half is derived. Measured: its radius 4 pins run along x through (0, 10, 0) from x 16 to 20 and -20 to -16, into the base's bores; the top's body lies above the axis.", + "mode": "patch", + "add": [ + { "kind": "hinge_brick_top", "position": [0, 10, 0], "axis": [1, 0, 0], "ref": [0, -1, 0] } + ] + } + ] } diff --git a/backend/app/connect/overrides.py b/backend/app/connect/overrides.py index dd6ec97..459df2f 100644 --- a/backend/app/connect/overrides.py +++ b/backend/app/connect/overrides.py @@ -51,7 +51,12 @@ def matches(self, connector: Connector) -> bool: return False if distance(connector.position, self.position) >= MATE_DISTANCE: return False - return self.axis is None or aligned(connector.axis, self.axis) + if self.axis is None or aligned(connector.axis, self.axis): + return True + from .kinds import load + + kind = load().get(connector.kind) + return kind is not None and kind.line and aligned(connector.axis, (-self.axis[0], -self.axis[1], -self.axis[2])) def as_dict(self) -> dict[str, object]: found: dict[str, object] = {"kind": self.kind, "position": list(self.position)} diff --git a/backend/app/connect/snap.py b/backend/app/connect/snap.py index 15026b9..974d54b 100644 --- a/backend/app/connect/snap.py +++ b/backend/app/connect/snap.py @@ -7,11 +7,11 @@ from . import ground from .connector import MATE_DISTANCE, Connector from .geometry import Box -from .kinds import Registry, load +from .kinds import Mate, Registry, load from .overlap import body_box from .shape import PartInfo, Placed from .spatial import SpatialHash, cell_of, placed_box -from .vec import Pose, Vec3, add, distance, length, round_vec, sub, tidy +from .vec import Pose, Vec3, add, distance, dot, length, round_vec, scale, sub, tidy REACH = 15.0 CORRECTION_STEP = 0.5 @@ -29,6 +29,7 @@ class SnapSettings: strict: bool = True ground: bool = True hysteresis: float = HYSTERESIS + slide_step: float = 0.0 @dataclass(frozen=True, slots=True) @@ -108,22 +109,52 @@ def as_dict(self) -> dict[str, object]: } +def _end(connector: Connector) -> Vec3: + return add(connector.position, scale(connector.axis, connector.length)) + + +def _segment_box(connector: Connector, margin: float = 0.0) -> Box: + a, b = connector.position, _end(connector) + return ( + (min(a[0], b[0]) - margin, min(a[1], b[1]) - margin, min(a[2], b[2]) - margin), + (max(a[0], b[0]) + margin, max(a[1], b[1]) + margin, max(a[2], b[2]) + margin), + ) + + +def to_segment(point: Vec3, connector: Connector) -> float: + t = max(0.0, min(connector.length, dot(sub(point, connector.position), connector.axis))) + return distance(point, add(connector.position, scale(connector.axis, t))) + + class _Index: - def __init__(self, near: Iterable[Placed], size: float = 20.0) -> None: + def __init__(self, near: Iterable[Placed], size: float = 20.0, registry: Registry | None = None) -> None: self.size = size self.placed = list(near) + self.registry = registry or load() self.cells: dict[tuple[int, int, int], list[tuple[Placed, int, Connector]]] = {} + self.long: list[tuple[Placed, int, Connector]] = [] + self.slots: dict[tuple[str, int], list[tuple[float, float]]] = {} for placed in self.placed: for index, connector in enumerate(placed.model_connectors): - self.cells.setdefault(cell_of(connector.position, size), []).append((placed, index, connector)) + if connector.length > 0 and self.registry.spans(connector.kind): + self.long.append((placed, index, connector)) + else: + self.cells.setdefault(cell_of(connector.position, size), []).append((placed, index, connector)) def near(self, point: Vec3, radius: float) -> list[tuple[Placed, int, Connector]]: found = [] for item in self.in_box(((point[0] - radius, point[1] - radius, point[2] - radius), (point[0] + radius, point[1] + radius, point[2] + radius))): - if distance(item[2].position, point) <= radius: + c = item[2] + gap = to_segment(point, c) if c.length > 0 and self.registry.spans(c.kind) else distance(c.position, point) + if gap <= radius: found.append(item) return found + def around(self, connector: Connector, radius: float) -> list[tuple[Placed, int, Connector]]: + if connector.length > 0 and self.registry.spans(connector.kind): + return [item for item in self.in_box(_segment_box(connector, radius)) if to_segment(item[2].position, connector) <= radius] + return self.near(connector.position, radius) + def in_box(self, box: Box) -> list[tuple[Placed, int, Connector]]: lo, hi = box a = cell_of(lo, self.size) @@ -136,9 +167,17 @@ def in_box(self, box: Box) -> list[tuple[Placed, int, Connector]]: p = item[2].position if lo[0] <= p[0] <= hi[0] and lo[1] <= p[1] <= hi[1] and lo[2] <= p[2] <= hi[2]: found.append(item) + for item in self.long: + if _meets(_segment_box(item[2]), box): + found.append(item) found.sort(key=lambda item: (item[0].order, item[0].key, item[1])) return found + def free_at(self, key: str, index: int, found: Mate, margin: float) -> bool: + if found.at is None: + return True + return all(abs(found.at - at) >= found.span + span - margin for at, span in self.slots.get((key, index), ())) + def occupy(self, registry: Registry, settings: SnapSettings, zone: Box | None = None) -> None: self.taken: set[tuple[str, int]] = set() self.ground_taken: set[tuple[int, int]] = set() @@ -147,11 +186,15 @@ def occupy(self, registry: Registry, settings: SnapSettings, zone: Box | None = else: items = self.in_box(zone) for placed, j, a in items: - for other, _k, b in self.near(a.position, settings.mate_distance): + for other, _k, b in self.around(a, settings.mate_distance): if other.key == placed.key: continue found = registry.mate(a, b) - if found is not None and found.residual <= settings.mate_distance: + if found is None or found.residual > settings.mate_distance: + continue + if found.at is not None and a.length > 0 and registry.spans(a.kind): + self.slots.setdefault((placed.key, j), []).append((found.at, found.span)) + else: self.taken.add((placed.key, j)) if registry.pair(a.kind, ground.KIND): lattice, b = ground.nearest(a.position) @@ -201,11 +244,11 @@ def propose(d: Vec3, rank: tuple[float, str, int, tuple[int, int]]) -> None: proposals[key] = (rank, d) for a in held: - for placed, j, b in index.near(a.position, settings.reach): + for placed, j, b in index.around(a, settings.reach): if (placed.key, j) in index.taken: continue - found = registry.mate(a, b) - if found is not None: + found = registry.mate(a, b, settings.slide_step) + if found is not None and index.free_at(placed.key, j, found, settings.mate_distance): propose(found.correction.translation, (placed.order, placed.key, j, (0, 0))) if settings.ground and registry.pair(a.kind, ground.KIND): for lattice, b in ground.studs_near(a.position, settings.reach): @@ -220,11 +263,11 @@ def propose(d: Vec3, rank: tuple[float, str, int, tuple[int, int]]) -> None: def _pairs(moved: Sequence[Connector], index: _Index, registry: Registry, settings: SnapSettings) -> list[Pair]: pairs: list[Pair] = [] for i, a in enumerate(moved): - for placed, j, b in index.near(a.position, settings.mate_distance): + for placed, j, b in index.around(a, settings.mate_distance): if (placed.key, j) in index.taken: continue found = registry.mate(a, b) - if found is not None and found.residual <= settings.mate_distance: + if found is not None and found.residual <= settings.mate_distance and index.free_at(placed.key, j, found, settings.mate_distance): pairs.append(Pair(i, placed.key, placed.order, j)) if settings.ground and registry.pair(a.kind, ground.KIND): lattice, b = ground.nearest(a.position) @@ -281,7 +324,7 @@ def candidates( settings: SnapSettings = SnapSettings(), ) -> list[Candidate]: registry = registry or load() - index = _Index(near) + index = _Index(near, registry=registry) box = placed_box(pose, held.shape.bounds) zone = None if box is None else _grow(box, settings.reach + settings.mate_distance + 0.01) index.occupy(registry, settings, zone) diff --git a/backend/app/connect/solid.py b/backend/app/connect/solid.py new file mode 100644 index 0000000..26d87d8 --- /dev/null +++ b/backend/app/connect/solid.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import hashlib +import io +import os +import re +import threading +from collections import OrderedDict +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from .vec import Pose + +VERSION = 1 +STEP = 1.0 +MOST_CELLS = 24_000_000 +JITTER = (0.0137, 0.0071, 0.0193) +FOLDER = ("cache", "solids") +CHUNK = 2_000_000 +_UNSAFE = re.compile(r"[^a-z0-9_.-]+") + +Triangles = Callable[[str], tuple[np.ndarray, np.ndarray] | None] + + +@dataclass(frozen=True, eq=False) +class Solid: + origin: np.ndarray + step: float + grid: np.ndarray + + @property + def cells(self) -> int: + return int(self.grid.sum()) + + @property + def volume(self) -> float: + return self.cells * self.step**3 + + def centre(self, index: np.ndarray) -> np.ndarray: + return self.origin + (index + 0.5) * self.step + np.asarray(JITTER) + + def index(self, points: np.ndarray) -> np.ndarray: + return np.floor((points - self.origin - np.asarray(JITTER)) / self.step).astype(np.int64) + + def inside(self, points: np.ndarray) -> np.ndarray: + found = np.zeros(len(points), dtype=bool) + if not len(points): + return found + index = self.index(points) + shape = np.asarray(self.grid.shape) + ok = np.all((index >= 0) & (index < shape), axis=1) + good = index[ok] + found[ok] = self.grid[good[:, 0], good[:, 1], good[:, 2]] + return found + + def window(self, lo: np.ndarray, hi: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None: + a = np.maximum(self.index(lo[None])[0], 0) + b = np.minimum(self.index(hi[None])[0] + 1, np.asarray(self.grid.shape)) + if np.any(b <= a): + return None + return a, b + + +def _signed_axis(corners: np.ndarray, sided: np.ndarray, origin: np.ndarray, step: float, shape: tuple[int, int, int], axis: int) -> np.ndarray: + b, c = (axis + 1) % 3, (axis + 2) % 3 + na, nb, nc = shape[axis], shape[b], shape[c] + ob, oc, oa = origin[b] + JITTER[b], origin[c] + JITTER[c], origin[axis] + JITTER[axis] + pb, pc, pa = corners[:, :, b], corners[:, :, c], corners[:, :, axis] + e1b, e1c = pb[:, 1] - pb[:, 0], pc[:, 1] - pc[:, 0] + e2b, e2c = pb[:, 2] - pb[:, 0], pc[:, 2] - pc[:, 0] + area = e1b * e2c - e1c * e2b + use = np.abs(area) > 1e-12 + j0 = np.ceil((pb.min(axis=1) - ob) / step - 0.5).astype(np.int64) + j1 = np.floor((pb.max(axis=1) - ob) / step - 0.5).astype(np.int64) + k0 = np.ceil((pc.min(axis=1) - oc) / step - 0.5).astype(np.int64) + k1 = np.floor((pc.max(axis=1) - oc) / step - 0.5).astype(np.int64) + j0, k0 = np.maximum(j0, 0), np.maximum(k0, 0) + j1, k1 = np.minimum(j1, nb - 1), np.minimum(k1, nc - 1) + wide = np.maximum(j1 - j0 + 1, 0) + deep = np.maximum(k1 - k0 + 1, 0) + count = np.where(use, wide * deep, 0) + winding = np.zeros((na + 1) * nb * nc, dtype=np.int32) + parity = np.zeros((na + 1) * nb * nc, dtype=np.int32) + tris = np.flatnonzero(count) + if not len(tris): + return np.zeros(shape, dtype=bool) + total = np.cumsum(count[tris]) + start = 0 + while start < len(tris): + stop = int(np.searchsorted(total, (total[start - 1] if start else 0) + CHUNK, side="right")) + stop = max(stop, start + 1) + chunk = tris[start:stop] + n = count[chunk] + which = np.repeat(chunk, n) + offset = np.arange(int(n.sum())) - np.repeat(np.cumsum(n) - n, n) + j = j0[which] + offset // deep[which] + k = k0[which] + offset % deep[which] + qb = ob + (j + 0.5) * step + qc = oc + (k + 0.5) * step + tb, tc = pb[which], pc[which] + d0 = (tb[:, 1] - tb[:, 0]) * (qc - tc[:, 0]) - (tc[:, 1] - tc[:, 0]) * (qb - tb[:, 0]) + d1 = (tb[:, 2] - tb[:, 1]) * (qc - tc[:, 1]) - (tc[:, 2] - tc[:, 1]) * (qb - tb[:, 1]) + d2 = (tb[:, 0] - tb[:, 2]) * (qc - tc[:, 2]) - (tc[:, 0] - tc[:, 2]) * (qb - tb[:, 2]) + hit = ((d0 >= 0) & (d1 >= 0) & (d2 >= 0)) | ((d0 <= 0) & (d1 <= 0) & (d2 <= 0)) + which, j, k, qb, qc = which[hit], j[hit], k[hit], qb[hit], qc[hit] + u = ((qb - pb[which, 0]) * e2c[which] - (qc - pc[which, 0]) * e2b[which]) / area[which] + v = (e1b[which] * (qc - pc[which, 0]) - e1c[which] * (qb - pb[which, 0])) / area[which] + at = pa[which, 0] + u * (pa[which, 1] - pa[which, 0]) + v * (pa[which, 2] - pa[which, 0]) + i = np.clip(np.ceil((at - oa) / step - 0.5).astype(np.int64), 0, na) + flat = (i * nb + j) * nc + k + two = sided[which] + sign = np.where(area[which] > 0, -1, 1) + winding += np.bincount(flat[~two], weights=sign[~two], minlength=len(winding)).astype(np.int32) + parity += np.bincount(flat[two], minlength=len(parity)).astype(np.int32) + start = stop + w = np.cumsum(winding.reshape(na + 1, nb, nc), axis=0)[:na] + p = np.cumsum(parity.reshape(na + 1, nb, nc), axis=0)[:na] % 2 == 1 + inside = (w > 0) ^ p + return np.moveaxis(inside, (0, 1, 2), (axis, b, c)) + + +def voxelise(corners: np.ndarray, two_sided: np.ndarray | None = None, step: float = STEP) -> Solid: + corners = np.asarray(corners, dtype=np.float64).reshape(-1, 3, 3) + sided = np.zeros(len(corners), dtype=bool) if two_sided is None else np.asarray(two_sided, dtype=bool) + if not len(corners): + return Solid(np.zeros(3), step, np.zeros((0, 0, 0), dtype=bool)) + lo = corners.min(axis=(0, 1)) + hi = corners.max(axis=(0, 1)) + while True: + origin = np.floor(lo / step) * step - step + shape = tuple(int(v) for v in np.ceil((hi - origin) / step).astype(np.int64) + 2) + if shape[0] * shape[1] * shape[2] <= MOST_CELLS: + break + step *= 2 + votes = np.zeros(shape, dtype=np.int8) + for axis in range(3): + votes += _signed_axis(corners, sided, origin, step, shape, axis) + return Solid(origin, step, votes >= 2) + + +def _entry(name: str) -> str: + normal = re.sub(r"[\\/]+", "/", name.strip()).lower() + safe = _UNSAFE.sub("_", normal)[:64].strip("._") or "part" + return f"{safe}-{hashlib.sha256(normal.encode('utf-8')).hexdigest()[:12]}.npz" + + +class SolidStore: + def __init__(self, triangles: Triangles, folder: Path | None = None, key: Callable[[], str] = lambda: "", limit: int = 512) -> None: + self.triangles = triangles + self.folder = folder + self.key = key + self.limit = limit + self._memory: OrderedDict[tuple[str, str], Solid | None] = OrderedDict() + self._lock = threading.Lock() + + def _path(self, key: str, name: str) -> Path | None: + if self.folder is None or not key: + return None + return self.folder / key[:24] / f"v{VERSION}" / _entry(name) + + def _read(self, path: Path | None) -> Solid | None: + if path is None: + return None + try: + with np.load(path) as data: + shape = tuple(int(v) for v in data["shape"]) + grid = np.unpackbits(data["bits"], count=shape[0] * shape[1] * shape[2]).astype(bool).reshape(shape) + return Solid(data["origin"].astype(np.float64), float(data["step"]), grid) + except (OSError, ValueError, KeyError): + return None + + def _write(self, path: Path | None, solid: Solid) -> None: + if path is None: + return + buffer = io.BytesIO() + np.savez_compressed(buffer, origin=solid.origin, step=np.float64(solid.step), shape=np.asarray(solid.grid.shape), bits=np.packbits(solid.grid.reshape(-1))) + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident()}.tmp") + temporary.write_bytes(buffer.getvalue()) + os.replace(temporary, path) + except OSError: + return + + def get(self, name: str) -> Solid | None: + try: + key = self.key() + except Exception: + return None + memo = (key, name.lower()) + with self._lock: + if memo in self._memory: + self._memory.move_to_end(memo) + return self._memory[memo] + path = self._path(key, name) + found = self._read(path) + if found is None: + try: + made = self.triangles(name) + except Exception: + made = None + if made is not None: + found = voxelise(*made) + self._write(path, found) + with self._lock: + self._memory[memo] = found + while len(self._memory) > self.limit: + self._memory.popitem(last=False) + return found + + +_CURRENT: list[SolidStore | None] = [None] + + +def use(store: SolidStore | None) -> None: + _CURRENT[0] = store + + +def current() -> SolidStore | None: + return _CURRENT[0] + + +def for_library(library, data_dir: Path | None) -> SolidStore: + from app.mesh import from_scene, part_mesh + from app.mesh.cachekey import library_key + + def triangles(name: str) -> tuple[np.ndarray, np.ndarray] | None: + mesh = part_mesh(library, name) + if not mesh.triangle_count: + return None + corners = from_scene(np.asarray(mesh.positions, dtype=np.float64)).reshape(-1, 3, 3) + return corners, np.asarray(mesh.two_sided, dtype=bool) + + def key() -> str: + return library_key(library, library.require()) + + folder = Path(data_dir).joinpath(*FOLDER) if data_dir is not None else None + return SolidStore(triangles, folder, key) + + +def _matrix(pose: Pose) -> tuple[np.ndarray, np.ndarray]: + return np.asarray(pose.rotation, dtype=np.float64).reshape(3, 3), np.asarray(pose.translation, dtype=np.float64) + + +def _runs(mask: np.ndarray, axis: int) -> np.ndarray: + moved = np.moveaxis(mask, axis, -1) + rows = moved.reshape(-1, moved.shape[-1]).astype(np.int8) + padded = np.zeros((rows.shape[0], rows.shape[1] + 2), dtype=np.int8) + padded[:, 1:-1] = rows + step = np.diff(padded, axis=1) + r0, s = np.nonzero(step == 1) + _, e = np.nonzero(step == -1) + size = e - s + marks = np.zeros((rows.shape[0], rows.shape[1] + 1), dtype=np.int64) + np.add.at(marks, (r0, s), size) + np.add.at(marks, (r0, e), -size) + filled = np.cumsum(marks, axis=1)[:, :-1] * rows + return np.moveaxis(filled.reshape(moved.shape), -1, axis) + + +@dataclass(frozen=True, slots=True) +class Meeting: + depth: float + volume: float + + +def meet(a: Solid, a_pose: Pose, b: Solid, b_pose: Pose) -> Meeting: + if not a.grid.size or not b.grid.size: + return Meeting(0.0, 0.0) + ra, ta = _matrix(a_pose) + rb, tb = _matrix(b_pose) + to_b = np.linalg.inv(rb) @ ra + shift = np.linalg.inv(rb) @ (ta - tb) + blo = b.origin + bhi = b.origin + np.asarray(b.grid.shape) * b.step + corners = np.array([[x, y, z] for x in (blo[0], bhi[0]) for y in (blo[1], bhi[1]) for z in (blo[2], bhi[2])]) + back = np.linalg.inv(to_b) + in_a = (corners - shift) @ back.T + found = a.window(in_a.min(axis=0), in_a.max(axis=0)) + if found is None: + return Meeting(0.0, 0.0) + lo, hi = found + part = a.grid[lo[0]:hi[0], lo[1]:hi[1], lo[2]:hi[2]] + cells = np.argwhere(part) + if not len(cells): + return Meeting(0.0, 0.0) + points = a.centre(cells + lo) @ to_b.T + shift + hit = b.inside(points) + count = int(hit.sum()) + if not count: + return Meeting(0.0, 0.0) + both = np.zeros(part.shape, dtype=bool) + chosen = cells[hit] + both[chosen[:, 0], chosen[:, 1], chosen[:, 2]] = True + thin = np.minimum(np.minimum(_runs(both, 0), _runs(both, 1)), _runs(both, 2)) + scale = float(np.cbrt(abs(np.linalg.det(ra)))) + return Meeting(round(float(thin.max()) * a.step * scale, 6), round(count * (a.step * scale) ** 3, 6)) diff --git a/backend/app/core/settings.py b/backend/app/core/settings.py index bade24b..5b22ac8 100644 --- a/backend/app/core/settings.py +++ b/backend/app/core/settings.py @@ -30,8 +30,18 @@ "grid_step": "stud", "snap": True, "overlap": False, + "overlap_nested": False, + "angle_step": 90, } +ANGLE_STEPS = (90, 45, 22.5, 15, 5, 1) + + +def _angle(name: str, value): + if isinstance(value, bool) or not isinstance(value, (int, float)) or value not in ANGLE_STEPS: + raise SettingsError(f"{name} is one of {', '.join(str(v) for v in ANGLE_STEPS)} degrees.") + return int(value) if float(value).is_integer() else float(value) + class SettingsError(ValueError): pass @@ -106,8 +116,38 @@ def _folder(name: str, value) -> str | None: "grid_step": lambda n, v: _choice(n, v, GRID_STEPS), "snap": _switch, "overlap": _switch, + "overlap_nested": _switch, + "angle_step": _angle, } +COLUMN_SECTIONS = ("colours", "tabs", "details") +COLUMN_TABS = ("model", "steps", "parts", "info") +COLUMN_SIZE_MAX = 4000 + + +def _column(name: str, value) -> dict: + if not isinstance(value, dict) or set(value) - {"colours", "details", "closed", "tab"}: + raise SettingsError(f"{name} is an object with colours, details, closed and tab.") + kept = {"colours": None, "details": None, "closed": [], "tab": None} + for size in ("colours", "details"): + given = value.get(size) + if given is not None and (isinstance(given, bool) or not isinstance(given, int) or not 0 < given <= COLUMN_SIZE_MAX): + raise SettingsError(f"{name}.{size} is a height in pixels from 1 to {COLUMN_SIZE_MAX}, or null for the window's own.") + kept[size] = given + closed = value.get("closed", []) + if not isinstance(closed, list) or any(c not in COLUMN_SECTIONS for c in closed): + raise SettingsError(f"{name}.closed lists sections of {', '.join(COLUMN_SECTIONS)}.") + kept["closed"] = [c for c in COLUMN_SECTIONS if c in closed] + tab = value.get("tab") + if tab is not None and tab not in COLUMN_TABS: + raise SettingsError(f"{name}.tab is one of {', '.join(COLUMN_TABS)}, or null.") + kept["tab"] = tab + return kept + + +DEFAULTS["right_column"] = {"colours": None, "details": None, "closed": [], "tab": None} +CHECKS["right_column"] = _column + def clean(changes: dict) -> dict: if not isinstance(changes, dict): diff --git a/backend/app/doc/transform.py b/backend/app/doc/transform.py index 161de2f..4285097 100644 --- a/backend/app/doc/transform.py +++ b/backend/app/doc/transform.py @@ -1,7 +1,10 @@ from __future__ import annotations +import math from collections.abc import Iterable, Sequence +import numpy as np + IDENTITY = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) LIMIT = 1_000_000.0 SINGULAR = 1e-9 @@ -51,6 +54,59 @@ def quarter_turn(axis: str, turns: int) -> list[float]: return out +TURN_PLACES = 6 +PLACE_PLACES = 3 +ANGLE_LIMIT = 3600.0 + + +def unit(axis: Sequence[float]) -> list[float]: + size = math.sqrt(sum(float(v) * float(v) for v in axis)) + if not math.isfinite(size) or size < SINGULAR: + raise ValueError("an axis needs a direction that is not zero") + out = [float(v) / size for v in axis] + return [tidy(round(v)) if abs(v - round(v)) < 1e-12 else v for v in out] + + +def principal(axis: Sequence[float]) -> bool: + return sum(1 for v in axis if v != 0) == 1 + + +def quarters(degrees: float) -> int | None: + count = float(degrees) / 90.0 + return int(round(count)) if abs(count - round(count)) < 1e-9 else None + + +def exact(axis: Sequence[float], degrees: float) -> bool: + return quarters(degrees) is not None and principal(unit(axis)) + + +def turn_by(axis: Sequence[float], degrees: float) -> list[float]: + x, y, z = unit(axis) + whole = quarters(degrees) + if whole is not None: + c, s = (1.0, 0.0, -1.0, 0.0)[whole % 4], (0.0, 1.0, 0.0, -1.0)[whole % 4] + else: + c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees)) + t = 1.0 - c + return vec(( + t * x * x + c, t * x * y - s * z, t * x * z + s * y, + t * x * y + s * z, t * y * y + c, t * y * z - s * x, + t * x * z - s * y, t * y * z + s * x, t * z * z + c, + )) + + +def settle(matrix: Sequence[float]) -> list[float]: + m = np.asarray(matrix, dtype=np.float64).reshape(3, 3) + u, sizes, vt = np.linalg.svd(m) + if np.all(np.abs(sizes - 1.0) < 1e-3): + m = u @ vt + return [tidy(round(float(v), TURN_PLACES)) for v in m.reshape(9)] + + +def settle_place(position: Sequence[float]) -> list[float]: + return [tidy(round(float(v), PLACE_PLACES)) for v in position] + + def centre(points: Iterable[Sequence[float]]) -> list[float]: found = list(points) if not found: diff --git a/backend/app/routers/doc.py b/backend/app/routers/doc.py index d4e310c..2c331f1 100644 --- a/backend/app/routers/doc.py +++ b/backend/app/routers/doc.py @@ -30,15 +30,13 @@ async def tree() -> dict: return await run_in_threadpool(_tree) -def _info() -> dict: - doc = document() - with doc.lock: - return model_info.info(doc) +def _info(table: bool) -> dict: + return runner.run("model.info", {"table": table})["result"] @router.get("/doc/info") -async def info() -> dict: - return await run_in_threadpool(_info) +async def info(table: bool = Query(True)) -> dict: + return await run_in_threadpool(_info, table) def _parts_csv(scope: str, group: str, separator: str) -> str: diff --git a/backend/app/routers/place.py b/backend/app/routers/place.py index 3049cf0..66ba0cb 100644 --- a/backend/app/routers/place.py +++ b/backend/app/routers/place.py @@ -7,6 +7,7 @@ from app.cmd import args, fitting, placing from app.cmd.registry import CommandError +from app.doc import transform from app.doc.document import document from app.services import connect_host, picking, warmer @@ -98,6 +99,33 @@ def pick(body: PickBody) -> dict: return {"hit": None if found is None else found.as_dict(), "revision": doc.revision} +class TurnBody(BaseModel): + ids: list[str] = Field(min_length=1, max_length=args.ID_MAX) + axis: Vector + angle: float = Field(ge=-3600, le=3600) + about: Vector + + +def turn(body: TurnBody) -> dict: + doc = document() + with doc.lock: + chosen = args.ids(doc, body.ids) + try: + axis = transform.unit(body.axis) + except ValueError: + raise CommandError("axis needs a direction that is not zero.") from None + found = placing.turn(doc, chosen, axis, body.angle, args.position(body.about, "about"), fitting.stamp_of(doc)) + return placing.turn_answer(found) | {"revision": doc.revision} + + +@router.post("/turn") +async def read_turn(body: TurnBody) -> dict: + try: + return await run_in_threadpool(turn, body) + except CommandError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + + @router.post("/preview") async def read_preview(body: PreviewBody) -> dict: try: diff --git a/backend/app/services/agent_programs.py b/backend/app/services/agent_programs.py index 2a29996..86fc8d8 100644 --- a/backend/app/services/agent_programs.py +++ b/backend/app/services/agent_programs.py @@ -8,7 +8,7 @@ from pathlib import Path from app.core import config, guard -from app.services import agent_lookup, terminal +from app.services import agent_lookup, terminal, windows_start CONTRACT = "2.2.1" KINDS = ("claude", "codex", "cursor", "antigravity") @@ -208,6 +208,38 @@ def codex_args(port: int) -> list[str]: "-c", f"developer_instructions={json.dumps(NOTE)}"] +TYPE_QUIET, TYPE_LIMIT = 0.8, 30.0 + + +def through_interpreter(path: str) -> bool: + return agent_lookup.windows() and windows_start.needs_interpreter(path) + + +def start_words(path: str, extra: list[str], env: dict | None = None) -> list[str]: + if agent_lookup.windows(): + return windows_start.argv(path, extra, env) + return agent_lookup.start_argv([path, *extra]) + + +def as_typed(prompt: str) -> str: + return prompt.replace("\r\n", "\n").replace("\r", "\n") + "\r" + + +def type_when_ready(session, prompt: str) -> None: + def wait() -> None: + start = time.monotonic() + seen, still = -1, start + while time.monotonic() - start < TYPE_LIMIT and session.alive and terminal.SESSIONS.get(session.id) is session: + if session.size != seen: + seen, still = session.size, time.monotonic() + elif seen > 0 and time.monotonic() - still >= TYPE_QUIET: + terminal.write(session.id, as_typed(prompt)) + return + time.sleep(0.1) + + threading.Thread(target=wait, name=f"first-message-{session.id}", daemon=True).start() + + def open_terminal(kind: str, port: int, cols: int, rows: int, prompt: str | None = None, resume: str | None = None) -> dict: if kind not in KINDS: raise ValueError(f"No agent program called {kind}") @@ -215,19 +247,20 @@ def open_terminal(kind: str, port: int, cols: int, rows: int, prompt: str | None if kind == "claude" and prompt and not resume: running = terminal.live("claude") if running is not None: - terminal.write(running.id, prompt.replace("\r\n", "\n").replace("\r", "\n") + "\r") + terminal.write(running.id, as_typed(prompt)) return running.describe() found = usable(kind) if found.state != "runs" or not found.path: raise LookupError(said(found)) - extra = claude_args(port, prompt, resume) if kind == "claude" else codex_args(port) if kind == "codex" else [] - argv = agent_lookup.start_argv([found.path, *extra]) + typed = prompt if kind == "claude" and prompt and through_interpreter(found.path) else None + extra = claude_args(port, None if typed else prompt, resume) if kind == "claude" else codex_args(port) if kind == "codex" else [] own = tab_folder(kind) if kind in OWN_FOLDER else None folder = own or Path(terminal.workdir()) token = guard.issue_run_token(SCOPE, kind) env = agent_lookup.child_env(found.path, base=terminal.base_env(), extra={TOKEN_VAR: token, MCP_URL_VAR: mcp_url(port)}, shell_timeout=SHELL_WAIT) filed = kind == "antigravity" try: + argv = start_words(found.path, extra, env) if own: write_guide(kind, own) if kind == "cursor": @@ -241,7 +274,9 @@ def open_terminal(kind: str, port: int, cols: int, rows: int, prompt: str | None remove_antigravity(own, token) raise if kind == "claude" and prompt: - session.argv = agent_lookup.start_argv([found.path, *claude_args(port, None, resume)]) + session.argv = start_words(found.path, claude_args(port, None, resume), env) + if typed: + type_when_ready(session, typed) session.on_close.append(lambda: guard.revoke_run_token(token)) if filed: session.on_close.append(lambda: remove_antigravity(own, token)) diff --git a/backend/app/services/chat.py b/backend/app/services/chat.py index b344d7a..eac3be7 100644 --- a/backend/app/services/chat.py +++ b/backend/app/services/chat.py @@ -267,8 +267,8 @@ def start(mode: str = "ask", fresh: bool = False, port: int | None = None) -> di CHAT.token = guard.issue_run_token(agent_programs.SCOPE, "chat") env = agent_lookup.child_env(found.path, base=terminal.base_env(), extra={agent_programs.TOKEN_VAR: CHAT.token, agent_programs.MCP_URL_VAR: url}, shell_timeout=agent_programs.SHELL_WAIT) try: - proc = subprocess.Popen(agent_lookup.start_argv(args), cwd=terminal.workdir(), env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) - except OSError as exc: + proc = subprocess.Popen(agent_programs.start_words(args[0], args[1:], env), cwd=terminal.workdir(), env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) + except (OSError, ValueError) as exc: _drop_token() set_state("exited") raise RuntimeError(f"Claude Code could not start: {exc}") diff --git a/backend/app/services/connect_host.py b/backend/app/services/connect_host.py index 182403f..b5ae421 100644 --- a/backend/app/services/connect_host.py +++ b/backend/app/services/connect_host.py @@ -14,6 +14,9 @@ def service() -> ConnectService: with _LOCK: if _HELD["library"] is not library: _HELD.update(library=library, service=ConnectService(library, config.data_dir()), hashes={}) + from app.connect import solid + + solid.use(solid.for_library(library, config.data_dir())) return _HELD["service"] diff --git a/backend/app/services/model_info.py b/backend/app/services/model_info.py index 8eaf282..f9a6548 100644 --- a/backend/app/services/model_info.py +++ b/backend/app/services/model_info.py @@ -149,7 +149,7 @@ def info(doc) -> dict: "licence": _header_line(main, "!LICENSE").removeprefix("Licensed under ").strip(), "path": doc.file, "kind": doc.file_kind, - "builtWith": project.get("library"), + "builtWith": doc.report.get("savedWith", project.get("library")), "library": status["update"] if status["installed"] else None, "counts": { "parts": sum(r["count"] for r in rows), diff --git a/backend/app/services/windows_start.py b/backend/app/services/windows_start.py new file mode 100644 index 0000000..0f58cb3 --- /dev/null +++ b/backend/app/services/windows_start.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import os +import re +import shutil +from pathlib import Path + +BATCH = (".cmd", ".bat") +NEVER = frozenset('"%^!\r\n\x00') +SPACED_ONLY = frozenset("&|<>()") +SCRIPT_ENDINGS = (".js", ".cjs", ".mjs") +PROGRAM_ENDINGS = (".exe", ".com") +TARGET = re.compile(r'"(%~?dp0%?[^"]*)"') + + +def is_batch(path: str) -> bool: + return str(path).lower().endswith(BATCH) + + +def shim_target(path: str) -> Path | None: + try: + text = Path(path).read_text(encoding="utf-8", errors="replace") + except OSError: + return None + found = None + for line in text.splitlines(): + if "%*" in line: + hits = TARGET.findall(line.split("%*", 1)[0]) + if hits: + found = hits[-1] + if not found: + return None + rest = re.sub(r"^%~?dp0%?", "", found).lstrip("\\/") + target = Path(os.path.normpath(Path(path).parent / rest.replace("\\", os.sep))) + if not target.is_file() or not target.name.lower().endswith(SCRIPT_ENDINGS + PROGRAM_ENDINGS): + return None + return target + + +def needs_interpreter(path: str) -> bool: + return is_batch(path) and shim_target(path) is None + + +def interpreter_safe(word: str) -> bool: + if NEVER & set(word): + return False + return " " in word or "\t" in word or not (SPACED_ONLY & set(word)) + + +def argv(path: str, words: list[str], env: dict | None = None) -> list[str]: + if not is_batch(path): + return [path, *words] + target = shim_target(path) + if target is not None and target.name.lower().endswith(PROGRAM_ENDINGS): + return [str(target), *words] + if target is not None: + beside = Path(path).parent / "node.exe" + node = str(beside) if beside.is_file() else shutil.which("node", path=(env or os.environ).get("PATH")) + if node: + return [node, str(target), *words] + bad = next((w for w in words if not interpreter_safe(w)), None) + if bad is not None: + raise ValueError(f"{Path(path).name} is a batch file the Windows command interpreter must run, and it would act on a character in one of the words for it, so it was not started.") + return [(env or os.environ).get("COMSPEC") or "cmd.exe", "/d", "/v:off", "/c", "call", path, *words] diff --git a/backend/formblocks_engine.py b/backend/formblocks_engine.py index 791008a..16341a4 100644 --- a/backend/formblocks_engine.py +++ b/backend/formblocks_engine.py @@ -11,7 +11,7 @@ def resource_dir() -> str: def selfcheck() -> int: info = {"python": sys.version.split()[0]} - for name in ("fastapi", "uvicorn", "pydantic", "winpty" if os.name == "nt" else "ptyprocess"): + for name in ("fastapi", "uvicorn", "pydantic", "numpy", "winpty" if os.name == "nt" else "ptyprocess"): try: module = __import__(name) info[name] = getattr(module, "__version__", "ok") @@ -35,11 +35,22 @@ def selfcheck() -> int: info["commands"] = len(registry.catalogue()) info["tools"] = len(mcp.tool_list()) from app.connect import overrides - from app.connect.kinds import stud + from app.connect.kinds import clip, hinge, stud from app.library import categories - gone = [str(p) for p in (stud.DATA_FILE, overrides.DEFAULT_PATH, categories.DATA_FILE) if not p.is_file()] + gone = [str(p) for p in (stud.DATA_FILE, clip.DATA_FILE, hinge.DATA_FILE, overrides.DEFAULT_PATH, categories.DATA_FILE) if not p.is_file()] info["data_files"] = "missing: " + ", ".join(gone) if gone else "ok" + import pkgutil + + import app as package + + broken = [] + for module in pkgutil.walk_packages(package.__path__, "app."): + try: + importlib.import_module(module.name) + except Exception as exc: + broken.append(f"{module.name}: {exc}") + info["modules"] = "missing: " + "; ".join(broken)[:800] if broken else "ok" except Exception as exc: info["app"] = f"failed: {exc!r}" print(json.dumps(info)) diff --git a/docs/AGENT_DOCK.md b/docs/AGENT_DOCK.md index 8e04f15..5350126 100644 --- a/docs/AGENT_DOCK.md +++ b/docs/AGENT_DOCK.md @@ -1,6 +1,6 @@ # The agent dock in FormBlocks -FormBlocks carries the Form family's agent dock, the shared module in `frontend/src/dock/` (version 2.2.1, the same bytes in every app, checked against its `MANIFEST.json` by `./formblocks agents check`). The dock is a panel at the bottom or the right of the window with terminal tabs, Chat, and a tab for each of four agent programs: Claude Code (`claude`), Codex (`codex`), Cursor (`cursor-agent`) and Antigravity (`agy`). The module never talks to the engine itself; `frontend/src/dock-adapter.ts` turns its calls into the engine's routes, and the engine meets the module's `CONTRACT.md`. This page says what each program gets, clause by clause, and what was run in this build to show it. It was written for 0.4.0. +FormBlocks carries the Form family's agent dock, the shared module in `frontend/src/dock/` (version 2.2.1, the same bytes in every app, checked against its `MANIFEST.json` by `./formblocks agents check`). The dock is a panel at the bottom or the right of the window with terminal tabs, Chat, and a tab for each of four agent programs: Claude Code (`claude`), Codex (`codex`), Cursor (`cursor-agent`) and Antigravity (`agy`). The module never talks to the engine itself; `frontend/src/dock-adapter.ts` turns its calls into the engine's routes, and the engine meets the module's `CONTRACT.md`. This page says what each program gets, clause by clause, and what was run in this build to show it. It was written for 0.4.0 and brought up to date on 27 November 2026 for 0.5.0. ## Each program @@ -16,7 +16,7 @@ FormBlocks carries the Form family's agent dock, the shared module in `frontend/ | Outside the window | `./formblocks claude`: `--mcp-config` naming `./formblocks mcp`, `--allowedTools mcp__formblocks`, `--append-system-prompt` naming the driving skill's path | `./formblocks codex`: `-c mcp_servers.formblocks.command`, `args`, `startup_timeout_sec`, `tool_timeout_sec` and `developer_instructions` with the same note as Claude Code's; no file is changed | `./formblocks cursor`: adds `formblocks` to `.cursor/mcp.json` of the current folder when missing, every other entry kept | `./formblocks antigravity`: adds `formblocks` to `.agents/mcp_config.json` of the current folder when missing, every other entry kept | | Repository files | `.mcp.json`, `CLAUDE.md`, `.claude/skills` | `.codex/config.toml`, `AGENTS.md`, `.agents/skills` | `.cursor/mcp.json`, `.cursor/rules/formblocks.mdc`, `AGENTS.md` | `.agents/mcp_config.json`, `AGENTS.md`, `.agents/skills` | | For this user everywhere (`./formblocks agents install`) | `claude mcp add --scope user formblocks`, skill in `~/.claude/skills` | `[mcp_servers.formblocks]` in `~/.codex/config.toml`, skill in `~/.agents/skills` | `~/.cursor/mcp.json`, skill in `~/.agents/skills` | `~/.gemini/config/mcp_config.json`, skill in `~/.gemini/config/skills` | -| Proven here | Real program, version 2.1.332, not signed in | Real program from the npm registry, version 0.172.0, in a scratch `CODEX_HOME`, not signed in | A stand-in script named `cursor-agent` | A stand-in script named `agy` | +| Proven here on 27 November 2026 (0.5.0) | Real program, version 2.1.332, not signed in | Real program from the npm registry, version 0.172.0, in a scratch npm prefix, not signed in | Real program from Cursor's installer, version 2026.11.22-e9042b2, in a scratch home, not signed in | Real program from Antigravity's installer, version 1.5.18, in a scratch home, not signed in | `./formblocks agents status` prints the same per program for the computer it runs on: found or not, the path and version, where a `formblocks` server is registered (the repository's file and the user's own), where the driving skill is, which instruction files the repository gives it, and how it is started in the dock and outside it (`--json` for one object). @@ -29,7 +29,7 @@ A tab's token is made when the tab opens, is good only for `/mcp`, and is revoke | 1. The caller | The holder of the window key; a tab's token is refused (403) on every dock route | `backend/app/core/guard.py` | | 2. Stream authentication | The window key as `?token=` on the websocket; no tickets | `frontend/src/io/api.ts`, `guard.py` | | 3. The record | `{id, title, alive, kind, tip}`; kinds `shell`, `claude`, `codex`, `cursor`, `antigravity` and `agent` | `backend/app/services/terminal.py` | -| 4. Open | `POST /api/terminal` and `/api/terminal/agent`; sizes clamped; a prompt is typed into a running Claude Code tab; `resume` always makes a new tab | `backend/app/routers/terminal.py`, `agent_programs.py` | +| 4. Open | `POST /api/terminal` and `/api/terminal/agent`; sizes clamped; a prompt is typed into a running Claude Code tab, and on Windows, when the program is a `.cmd` or `.bat` file, into the new tab once the program has started, never onto the command interpreter's line; `resume` always makes a new tab | `backend/app/routers/terminal.py`, `agent_programs.py` | | 5. Restart | Same id, program started again, screen cleared; a Claude Code tab's first prompt is not sent again | `terminal.py`, `agent_programs.py` | | 6. Close | Kills the program, safe to repeat | `terminal.py` | | 7 to 9. The channel | Scrollback replayed on every attach, `exit` frame at once for an ended program, input and resize frames, a slow reader loses output | `routers/terminal.py` | @@ -48,6 +48,19 @@ A tab's token is made when the tab opens, is good only for `/mcp`, and is revoke An agent outside the window (any of the four started in a terminal, through `./formblocks ` or its own configuration) reaches the engine through the stdio bridge, `./formblocks mcp`, which posts to `/mcp` with the person's window key read from the data folder. A call that changes the model waits for the person's answer in the window, unless the standing choice is allowed or blocked. Each call and its outcome is written into a read-only Outside agents tab in the dock, made at the first call; while that tab is in front, the head says how many calls are still running, which includes a change waiting for the person's answer. The Outside agents entry of the dock's More agents menu opens a dialog with the standing choice and the agents allowed by name. +## What was run for 0.5.0, on 27 November 2026 + +All four programs were real this time; none was signed in, and no turn was taken with a model. Claude Code 2.1.332 was already on the computer; Codex 0.172.0 was installed from the npm registry into a scratch prefix; Cursor's agent 2026.11.22-e9042b2 and Antigravity 1.5.18 were installed by their own installers (both hosts answered this time) into a scratch home folder, which the engine was given as `HOME`, so the finder found them in their known install folders and not through an override. The engine ran from source on 127.0.0.1:9250 with a scratch data folder; each step was a request to the engine's own routes and a read of `/proc` for the process the tab started. + +- Status: `GET /api/agents/status?fresh=true` found all four, with the path, the version from `--version`, how it was found and the install line. +- Each program's tab, opened with `POST /api/terminal/agent`: Claude Code and Codex started in the terminal folder (the repository), Cursor's agent in `agent-tabs/cursor` and Antigravity in `agent-tabs/antigravity` of the data folder (read from `/proc//cwd`). The tab's token was in the program's environment for all four, and for Antigravity also in `.agents/mcp_config.json` there, mode 0600; it was on no command line of any process in the tab (`/proc//cmdline`), and the window key was in no environment. With the tab open the token got 200 from `/mcp` (`initialize`) and 403 from `/api/settings`; after `DELETE /api/terminal/` it got 401, the program's process was gone, and Antigravity's file no longer held it. +- Each program through the launcher arm (`./formblocks claude`, `codex`, `cursor`, `antigravity`, in a pseudo-terminal, from a scratch folder, with a tab token and a window key planted in the caller's environment): each program started in that folder with neither in its environment or command line; the Cursor and Antigravity arms wrote the `formblocks` entry into that folder's `.cursor/mcp.json` and `.agents/mcp_config.json`. With a short PATH and an empty home, the Codex, Cursor and Antigravity arms said where they had looked and gave the install line, exit 1. +- A first message with quotes, `&`, `%`, `|`, `<`, `^`, `!`, `%PATH%`, two line breaks and a leading dash, through a stand-in `claude` that records what it is given: from a dock tab it arrived unchanged as the last argument, in a folder named `odd & 50% folder`; with the start made to take the Windows path for a `.cmd` program, it was not on the command line and arrived as three typed lines instead. Through the launcher arm, from a folder named `arm & 50% dir`, the same kind of message (with `$HOME` and a backquoted command added) arrived unchanged. The arm's Windows check refused a `.cmd` program given such a message and let plain words through. +- An arm's first message (the words after `--`, `FORMBLOCKS_MESSAGE`, or an owner-only file named by `FORMBLOCKS_MESSAGE_FILE`) went to stand-ins for all four as each reads one: `-- ` for Claude Code and Codex, `agent -- ` for Cursor's agent, `--prompt-interactive=` for Antigravity, a message starting with `-p` included. +- On Windows a program is started without the command interpreter when it is an npm or pnpm shim (its node script or its `.exe` is run directly), and FormBlocks' server is registered as the engine's Python with `formblocks_engine.py mcp`, since Node programs cannot start a `.bat`. Both were exercised only by making the code take its Windows path on Linux with shims written in npm's and pnpm's forms. + +Not run: any `.bat` file and Windows itself, so the Windows paths were reasoned through and exercised only by making the code take them on Linux (`setup/HASHOUT_LOG.md`, `backend/HASHOUT_LOG.md`); macOS; a signed-in session of any program; the window's dock with these four real programs in a browser (the dock module and its adapter did not change in this version). + ## What was run for 0.4.0 All against an engine on 127.0.0.1:8341 with its own data folder and the window on 5341, headless Chrome through Playwright: diff --git a/docs/MANUAL.md b/docs/MANUAL.md index 4be6e9f..0e579a8 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -1,8 +1,8 @@ # FormBlocks manual -This manual is for a person who wants to build with bricks on a computer. It describes FormBlocks 0.4.0 as it runs in its window, and it says plainly at the end what does not work yet. Nothing here needs you to read code. Words in **bold** are the names you see on screen; keys are written as Ctrl+S (on a Mac read Ctrl as Cmd and Alt as Option). +This manual is for a person who wants to build with bricks on a computer. It describes FormBlocks 0.5.0 as it runs in its window, and it says plainly at the end what does not work yet. Nothing here needs you to read code. Words in **bold** are the names you see on screen; keys are written as Ctrl+S (on a Mac read Ctrl as Cmd and Alt as Option). -Contents: [Starting](#starting-and-the-parts-library) · [The window](#the-window) · [Finding parts and colours](#finding-parts-and-colours) · [Placing, snapping and the grid](#placing-snapping-and-the-grid) · [Moving, turning and deleting](#moving-turning-and-deleting) · [Selecting](#selecting) · [Submodels](#submodels) · [Steps](#steps) · [The Parts tab](#the-parts-tab-and-its-csv) · [Save Picture](#save-picture) · [Files](#files) · [Preferences and themes](#preferences-and-themes) · [Keys and mouse](#keys-and-mouse) · [The agent dock](#the-agent-dock) · [What does not work yet](#what-does-not-work-yet) +Contents: [Starting](#starting-and-the-parts-library) · [The window](#the-window) · [Finding parts and colours](#finding-parts-and-colours) · [Placing, snapping and the grid](#placing-snapping-and-the-grid) · [Moving, turning and deleting](#moving-turning-and-deleting) · [Selecting](#selecting) · [Submodels](#submodels) · [Steps](#steps) · [The Parts tab](#the-parts-tab-and-its-csv) · [The Info tab](#the-info-tab) · [Save Picture](#save-picture) · [Files](#files) · [Preferences and themes](#preferences-and-themes) · [Keys and mouse](#keys-and-mouse) · [The agent dock](#the-agent-dock) · [What does not work yet](#what-does-not-work-yet) ## Starting and the parts library @@ -17,7 +17,7 @@ On the first start FormBlocks has no library, so the viewport shows a card calle 1. **Use a library folder on this computer.** If you already have an LDraw library, type the folder's full path (it must hold `parts`, `p` and `LDConfig.ldr`) and press **Use this folder**. FormBlocks reads it where it is and never writes into it. 2. **Fetch the library.** The card shows exactly what will happen before it happens: - **From**: `https://library.ldraw.org/library/updates/complete.zip`, the only address it will contact. - - **Size**: unknown until you press **Ask the server**, which asks `library.ldraw.org` how big the archive is and downloads nothing. The archive is about 147 MB. + - **Size**: "147 MB at the last check", the size FormBlocks was last told, until you press **Ask the server**, which asks `library.ldraw.org` how big the archive is now and downloads nothing. - **Licence**: CC BY 2.0 and CC BY 4.0. The parts are the work of the library's many authors; each part's own file names its author and licence, and the card ends with the credit line, which is also in Preferences under Library and agents. - A paragraph in plain words saying that FormBlocks will download the library and keep it on this computer, and that it fetches nothing else. @@ -41,9 +41,13 @@ The window has five regions, and each one is where it is whatever you are doing, **Viewport (the middle).** The 3D view of the model on a ground grid, with the red X axis and the blue Z axis drawn through the origin. A path at its top left (for example "Main model › Base") appears while you edit a submodel, and a **Show all** button at its top right appears while anything is hidden. Under it is the **step strip**: first, previous, next and last buttons, "Step 2 of 3", one chip for each step, a button that dims earlier steps, and the **New Step** button. -**Right column.** From the top: the **current colour** (a large swatch with its name and LDraw number), a colour search, hue families, and the colours themselves. Under that, three tabs: **Model** (the model tree and the list of submodels), **Steps** and **Parts**. At the bottom, **Details**, which describes the selected part. The dividers between these panels can be dragged, or moved with the Up and Down keys when focused; a double-click restores them. +**Right column.** Three sections, each with a header. At the top the **Colours** section: the **current colour** (a large swatch with its name and LDraw number), a colour search, hue families, and the colours themselves. In the middle the tabs, **Model** (the model tree and the list of submodels), **Steps**, **Parts** and **Info** (the model's own facts, see "The Info tab"). At the bottom **Details**, which describes the selected part. -**Status bar.** From the left: a dot that is green while the window is connected to the engine and red when it is not; a summary of the selection ("2 parts selected in 2 colours"); notices such as "Holding 3001: click or Space to drop, R to turn, Esc to stop"; the step and submodel shown ("Step 2 of 3 · Main model"); the pointer's place in LDU while a part is held or dragged; and three switches you can click, **Snap**, the **grid step** (Stud, Plate or Fine) and **Overlap**. The version is at the far right. +The middle section is the one that grows: it takes all the height the other two leave, because the list you are working in is the one that needs rows. The Colours and Details sections keep the height you drag them to, between a least and a greatest height. A divider between sections is dragged, or moved 16 pixels at a time with Up and Down when it has the focus, and a double-click puts it back to its first height (the Colours section starts 256 pixels high; dragging its divider 60 pixels down made it 316, and a double-click made it 256 again). + +Click a section's header, or press Enter on it, to fold the section to its header. The Colours header says the current colour ("Red · 4") and the Details header names the selection, so a folded section still tells you what is in it. The tab bar is the middle section's header: the fold button at its right end folds the tabs down to the bar, and a click on any tab opens them again. A folded section gives its height to the sections still open, and the tabs take it first. When the window is too short for every open section, Details and then Colours are shown folded without losing your choice. The heights, the folded sections and the tab shown are kept from one start to the next and are in place before the window first draws, so nothing moves when it opens. **Reset Right Column** in Search Commands puts the heights and the folds back to their first values. + +**Status bar.** From the left: a dot that is green while the window is connected to the engine and red when it is not; a summary of the selection ("2 parts selected in 2 colours"); notices such as "Holding 3001: click or Space to drop, R to turn, Esc to stop"; the step and submodel shown ("Step 2 of 3 · Main model"); the pointer's place in LDU while a part is held or dragged; and five switches you can click, **Snap**, the **grid step** (Stud, Plate or Fine), the **angle step** (90°, 45°, 22.5°, 15°, 5° or 1°), **Overlap** and **Nested**. The version is at the far right. Everything you see is the engine's model. The window draws it and sends your clicks and keys to the engine, which does the work. That is why the model is still there after you reload the page, and why an agent program's changes appear at once. @@ -119,7 +123,34 @@ Stud is the step at the first start; the last one you chose is kept. Up and down ### Snap, grid and the overlap check -The three switches in the status bar are also keys: **S** turns snapping on and off, **G** goes to the next grid step, **O** turns the **overlap check** on and off. The overlap check is off at the first start. With it on, a place where the held part (or a dragged part) would go inside another part is not taken: the ghost stays at the last free place, its outline turns to the warning colour, and a click there says "That place overlaps another part." The check is coarse, a guide and not a proof that a model can be built. Holding Ctrl while you drag a part turns snapping off for that drag only. +The switches in the status bar are also keys: **S** turns snapping on and off, **G** goes to the next grid step, **O** turns the **overlap check** on and off. The overlap check is off at the first start. With it on, a place where the held part (or a dragged part) would go inside another part is not taken: the ghost stays at the last free place, its outline turns to the warning colour, and a click there says "That place overlaps another part." Holding Ctrl while you drag a part turns snapping off for that drag only. + +The check compares the parts' real shapes, studs included. Two parts overlap when they cut more than 1 LDU into each other; parts that only touch, parts joined through their connectors, and a stud standing in the hollow of the part above never count. A part resting in a hollow it fits with no connector holding it, such as a rim in its tyre or a pin in its hole, is a **nested pair**: it never blocks placing, dragging or turning, and it is counted apart so nothing is hidden. Two hinge halves or a clip on a bar, seated, are joined by their connectors and are neither. While the check is on, every part of a real overlap already in the model is drawn washed out with edges in the warning colour, and is drawn as before once the overlap is gone or the check is off. The check is still a guide and not a proof that a model can be built: a part whose surface is not closed, or a part the library lacks, can be reported wrongly. + +**Show Overlaps** (Model menu, or Search Commands) looks over the whole model, selects the parts of every overlapping pair and says the result in the status bar, for example "1 overlap, 24 LDU deep · 0 nested". It works whether or not the overlap check is on. The **Nested** switch at the right of the status bar, and **Report nested pairs** on the General page of Preferences, choose whether nested pairs are listed too; it is off at the first start, and only changes what is reported. The sample car in the library's `models` folder has 0 overlaps and 19 nested pairs (rims in tyres, pins and hinge halves); before this version its check reported 20 pairs. + +### Clips, bars and hinges + +Besides studs, FormBlocks seats three more kinds of join, found from the shapes of the parts themselves: clips on bars, and hinge halves on each other. They are not drawn as marks of their own; the small violet marks show where parts join, as for studs. Nothing here needs a setting. + +**A clip on a bar.** A clip is a pair of jaws that closes round a rod 8 LDU across, and a bar is any free rod of that size with room round it for the jaws: the handle of a plate with a handle, the arm of a Bar 3L (`87994`), the rods many accessories carry. +Hold a part with a clip (a Plate 1 x 1 with Clip, `4085c`) with its clip at the side of a bar and it seats with the clip's centre on the bar's line. The clip then slides: along the bar it takes the places that are whole grid steps from the bar's middle. On the Bar 3L, whose free length is 60 LDU, a clip held near the bar's middle seats there or 20 LDU either side of it at the Stud step, in steps of 10 at the Plate step, and anywhere along the free part at the Fine step (a clip held 63 LDU up the bar came to rest at 70 at Stud, 60 at Plate and 63 at Fine). One bar holds several clips side by side, but two clips cannot share the same stretch: a second clip held where the first sits is not seated. A clip turns on its bar: select it and the pivot dial shows one ring about the bar. + +**Hinge halves.** A hinge is two halves on one pivot line, the fingers of one between the fingers of the other. FormBlocks knows five families, and a half seats only on the other half of its own family: + +| Family | The two halves | Example parts | +| --- | --- | --- | +| Click hinge | single finger, dual finger | the click-lock hinge plates, `44301a` and `44302a` | +| Plate hinge | two fingers, three fingers | `4276b` and `4275b` | +| Arm hinge | two fingers, three fingers | the hinge arms with discs of radius 10 | +| Brick hinge | base, top | the 1 x 2 hinge brick, `3937` and `3938` | +| Swivel plate | base, top | the 1 x 4 swivel hinge plates, `2429` and `2430` | + +Two halves of the same kind never seat (two three-finger halves would occupy the same places). Snapping never turns a part, so turn the half first until its pivot line runs the same way as its partner's, then bring it up: it moves so the two pivot lines meet, the middles of the fingers together, and small marks show where they join. A half whose pivot line runs the other way, or that would fold flat onto its partner, does not seat. A `44301a` held near a `44302a`, turned a half turn about the up axis, came to rest against it with one pair of joins and the two parts side by side, 60 LDU apart. + +Once seated, a hinge half turns about the hinge, not about the middle of its box: select the half and the pivot dial shows one ring about the hinge's own line, and dragging it opens or closes the hinge in angle steps (the status bar says "Turning 1 part 45° about the hinge: let go to put down, Shift for whole degrees, Esc to put back."). A hinge turns all the way round; the overlap check, when on, is what stops a half cutting into another part. Parts joined through a seated hinge are not reported as overlapping each other. The parts FormBlocks finds hinge halves and clips on are those drawn with the library's own hinge and clip pieces, together with a short list of corrections kept in FormBlocks for the 1 x 2 hinge brick, the swivel plates and the 1 x 1 tile with a clip; a hinge or clip drawn some other way is not found and simply does not snap. + +What is not here yet: pins and the holes that take them, axles, ball joints, a bar into a hole made for it, limits on how far a hinge opens, click positions on a click hinge, and flexible parts. ## Moving, turning and deleting @@ -142,7 +173,17 @@ Hold **Alt** at the press to drag copies instead: the status bar says "Copying 1 ### Turning -**R** turns a quarter turn about the vertical axis (clockwise seen from above), **Shift+R** the other way. **T** tips a quarter turn about the left to right axis, **Shift+T** back. **Y** rolls a quarter turn about the front to back axis, **Shift+Y** back. They work on a held part, on a dragged selection and on a selection that is standing still. Turns are whole quarter turns only; there are no finer angles yet. Details shows a single part's turn as three angles, and "Several turns" when more than one part is selected. +**R** turns a quarter turn about the vertical axis (clockwise seen from above), **Shift+R** the other way. **T** tips a quarter turn about the left to right axis, **Shift+T** back. **Y** rolls a quarter turn about the front to back axis, **Shift+Y** back. They work on a held part, on a dragged selection and on a selection that is standing still. Details shows a single part's turn as three angles, and "Several turns" when more than one part is selected. + +Those keys turn by the **angle step**, which starts at 90°, a quarter turn, because a quarter turn leaves a part where its studs can seat again. The step is one of 90°, 45°, 22.5°, 15°, 5° and 1°. Press **A**, or click the angle in the status bar, to go to the next one; it is your setting like the grid step and is kept from one start to the next. Hold **Alt** with R, T or Y (Alt+Shift reverses) to turn by the angle step instead of a quarter turn, on a part you hold, a selection you are dragging or a selection standing still. Each key press on a standing selection is one step you can undo. + +### Turning with the pointer + +Whenever parts are selected and nothing is held or dragged, a **pivot dial** shows in the viewport: one green ring lying flat about the vertical axis through the middle of the selection, a little wider than the selection. Press on the ring and drag along it to turn the selection about that axis in angle steps; hold **Shift** to turn in whole degrees. The parts turn in place as you drag, and the status bar says "Turning 1 part 45° about Y: let go to put down, Shift for whole degrees, Esc to put back." Letting go is one undo step, "Rotate"; Esc, or losing the pointer, puts the parts back and leaves no step. + +**J**, the pivot tool, shows three rings, about LDraw's X, Y and Z, each in its own colour, so a part can be tipped or rolled; J again, or Esc with no drag, goes back to the one ring. With the pivot tool on, a click on a part sets the pivot there: on the nearest connector, a stud for example, when there is one within 8 LDU of the click, else on the point itself. The rings move to that point and stay there for that selection; they go back to the middle of the parts when you select something else. A selection that is one part joined by a hinge turns about the hinge's own axis, see the next part. Typing an angle on the dial is not built. + +Two rules hold for every turn, by key, by pointer or from an agent. A turn never leaves a part below the ground: if it would, the whole turned selection is lifted straight up until it rests on the ground (a brick tipped a quarter turn on its side is raised by the difference). And with the overlap check on, a turn that would push a turning part into a part that does not turn is refused, and while you drag a ring the parts stay at the last free angle, drawn in the warning colour, until the pointer comes back to a free one. Snapping never turns a part and a turn never seats one: a turned part stays where the turn puts it. ### Copying, deleting and undoing @@ -228,6 +269,19 @@ Part,Description,Colour,Colour name,Count The **Part** and **Colour** columns are LDraw part and colour numbers, the numbers every LDraw program uses; there are no shop numbers yet. The file is UTF-8 with a byte order mark so spreadsheet programs read the characters correctly, and its lines end in CR LF. A cell that starts with `=`, `+`, `-` or `@` is written after an apostrophe so a spreadsheet reads it as text and never as a formula. The save uses whatever the tab is set to count, so choose **Whole model** first if you want the whole list. +## The Info tab + +The **Info** tab, the fourth tab of the right column after Parts, is the model's own information: what the model is called, who made it and how big it is. It is about the model, not the app; **About FormBlocks** in the Help group of the menu is about the app. The tab has four groups, and every value has its place from the start, so a value arriving or changing moves nothing else. + +- **Model**: **Name**, **Description**, **Author** and **Licence**, which you can change in place. The name is the main model's `Name:` line (renaming it renames every use of it too); the description is the title line an LDraw file starts with; the licence is chosen from a list (None, CC BY 4.0, CC BY-SA 4.0, CC BY-NC 4.0, CC BY-NC-SA 4.0, CC BY-ND 4.0, CC BY-NC-ND 4.0 and CC0 1.0). Press Enter or leave the field to set it, Esc to put the old value back. Each change is one undo step ("Change model information"), so Ctrl+Z takes it back. The licence line describes your model only; the parts keep their own. +- **Counts**: **Placements** (as written in the file), **Parts in all** (counting through every use of a submodel), **Different parts**, **Colours**, **Parts list rows** (a part in a colour is one row), **Submodels**, **Steps** (of the main model), **Not in library** and **Overlaps** (pairs, counted as the overlap check counts them, so nested pairs are not in it). The library's sample car reads 61 placements, 26 different parts, 7 colours, 32 parts list rows, 8 steps and 0 overlaps. +- **Size**: **Across**, **Deep** and **High** in studs, in studs and bricks or plates, and in millimetres (an LDU is 0.4 mm). The sample car is 4.5 studs (36 mm) across, 10.8 studs (86.4 mm) deep and 5.17 bricks, 15.5 plates or 49.6 mm high. +- **File**: the **Path** the model was opened from or saved to, its **Format**, the library update it was last saved with ("Not recorded in the file" for an LDraw file that did not come from FormBlocks), and the library update now in use. + +Under the groups, **Not in this library** names each part number the library lacks and how many the model needs of it, or says "Every part is in the library." A model of one 2 x 4 brick and two copies of an unknown `99999x.dat` listed "99999x · 2 needed". + +The same values come from `model.info` and are changed with `model.set_info` and `submodel.rename`, so an agent reads and edits what the tab shows. The values are counted by the engine and the tab only shows them. + ## Save Picture **Save Picture** writes a PNG picture of the viewport. Open it from the camera button in the top bar, from the **File** group of the menu, or with **Ctrl+Shift+P**. The panel asks: @@ -309,6 +363,9 @@ On a Mac read **Ctrl** as **Cmd** and **Alt** as **Option**. All of these work w | R, Shift+R | Turn a quarter turn about the vertical axis, and back | | T, Shift+T | Tip a quarter turn about the left to right axis, and back | | Y, Shift+Y | Roll a quarter turn about the front to back axis, and back | +| Alt+R, Alt+T, Alt+Y (with Shift to reverse) | The same turns by the angle step instead of a quarter turn | +| A | Next angle step: 90°, 45°, 22.5°, 15°, 5°, 1° | +| J | Pivot tool: three rings, and a click sets the pivot; J again goes back to one ring | | Left, Right | Nudge one grid step left or right | | Up, Down | Nudge one grid step away from you or towards you | | Shift+Up, Shift+Down | Nudge up or down (8 LDU at the Stud and Plate steps) | @@ -344,6 +401,7 @@ Keys that have no key of their own are reached through **Search Commands**: Swit | Drag from empty space | Draw a selection box (left to right: wholly inside; right to left: touching) | | Press on a part and pull | Move it, or the selection it is in | | Alt+press on a part and pull | Drag copies | +| Press on a ring of the pivot dial and drag along it | Turn the selection about that ring's axis in angle steps; Shift for whole degrees; Esc puts it back | | Ctrl while dragging a part | No snapping for that drag | | Right button drag, or Alt+left drag | Orbit the camera | | Shift+right drag, Alt+Shift+left drag, or middle drag | Pan the camera | @@ -398,28 +456,28 @@ Every call an outside agent makes is written into a read-only **Outside agents** ### What was tried -Claude Code was a real program on the machine where this manual was written, not signed in, and Codex was the real package from the npm registry run from a scratch folder, also not signed in, so no model turn was run with either. Cursor and Antigravity were not installed, so a small stand-in program played each, to check what FormBlocks gives them (the arguments, the folder, the configuration entry and the pass). How well the real Cursor and Antigravity programs then behave has not been seen. `docs/AGENT_DOCK.md` has the full table. +All four programs were real programs when this manual was checked, and none was signed in, so no turn with a model was run with any of them: Claude Code 2.1.332 was on the computer, Codex 0.172.0 came from the npm registry into a scratch folder, and Cursor's agent (2026.11.22) and Antigravity (1.5.18) came from their own installers into a scratch home folder. For each, FormBlocks found it and said its version, started it from a dock tab and from the launcher in the right folder, gave it a token that was in its environment and on no command line, and that token opened the engine's `/mcp` and was refused everywhere else and after its tab closed. How well each program then works with FormBlocks once you sign in has not been seen. `docs/AGENT_DOCK.md` has the full table. ## What does not work yet -This is 0.4.0, in active development and functional. Here is what is not there, and what is not proven. +This is 0.5.0, in active development and functional. Here is what is not there, and what is not proven. **Not built in the window yet** -- The tools that need a tool bar: the stamp, the pivot, the brush, the colour sampler and the hide tool. You recolour by choosing a colour with parts selected, and hide with H. +- The tools that need a tool bar: the stamp, the brush, the colour sampler and the hide tool (the pivot tool is on the J key). You recolour by choosing a colour with parts selected, and hide with H. - Move handles (arrows along one axis) on the selection. Use the arrow keys or the Details fields. -- Turns finer than a quarter turn, and a preference for them. +- Typing an angle on the pivot dial, and any limit on how far a hinge opens. +- Pins and the holes that take them, axles, ball joints, a bar into a hole made for it, the click positions of a click hinge, and flexible parts such as hoses and strings. Clips, bars and hinges are the joins added in this version (see "Clips, bars and hinges"). - Packing and unpacking submodels by a key (Ctrl+G); use the command palette. Double-clicking a use of a submodel does not enter it (select it and press Enter) and there is no "Open alone" view of a submodel by itself. -- A panel for the model's name, author, description and licence (the engine answers `model.info` and `model.set_info`, and an agent or the command line can use them), and the model's size in studs and millimetres. - Safety copies of a model that was not saved, and an Export LDraw command with its own key; Save As with an `.ldr` or `.mpd` path is the export. - Saving the parts list in another catalogue's numbers: the list has LDraw part and colour numbers only. - Instruction pages, photoreal rendering, a check that a model could stand, a part designer and flexible parts. These are described in `spec/SPEC.md` as later work. **Not proven** -- Only Linux has run FormBlocks from source. macOS and Windows are made to work and have not been run, no `.bat` file has been run, and no desktop (Tauri) build has been made. +- Only Linux has run FormBlocks from source. macOS and Windows are made to work and have not been run, and no `.bat` file has been run. One desktop (Tauri) build has been made, on Linux only, unsigned (a deb and an AppImage); it started its engine and drew the window under a virtual display. No macOS or Windows desktop build, signing or updater has been run. - The window was run headless with software drawing, so how fast it draws on a real graphics card is not measured. -- Cursor and Antigravity were tested only through stand-in programs, and no agent program has been run signed in, so no real conversation has been seen with any of the four. +- No agent program has been run signed in, so no real conversation has been seen with any of the four. The launcher and the dock's terminal on Windows, and a first message typed into a tab there, were made to work and checked only by taking the Windows paths on Linux; no `.bat` file has run. - A very large model has not been tried. **Rough edges** diff --git a/docs/NEW_APP.md b/docs/NEW_APP.md index 9baecba..e03dec4 100644 --- a/docs/NEW_APP.md +++ b/docs/NEW_APP.md @@ -36,6 +36,6 @@ A command added to `backend/app/cmd/commands/` is followed by `./formblocks agen ## What FormBlocks writes for itself -- Its own `README.md` sections, `CHANGELOG.md` and the icons in `src-tauri/icons`, which the owner is drawing. +- Its own `README.md` sections and `CHANGELOG.md`. The icons in `src-tauri/icons` and `assets/app-icon/` are the owner's art and are never redrawn. - Its `NOTICE.md` rows for every dependency it adds, the LDraw Parts Library's attribution, and the credit to the family apps it came from, which stays. - `notes_for_owner` in `apps/formblocks.json`. diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 5fba3b6..2d1c19f 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -13,9 +13,9 @@ Nothing in this repository pushes, signs or publishes a release. The family's co ## A release, step by step 1. Bump the version by hand at every site in one commit: `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`, `src-tauri/Cargo.lock` (the shell's own package), `frontend/package.json`, `frontend/package-lock.json` (both fields), `frontend/src/version.ts`, `backend/app/__init__.py`, and a new `## X.Y.Z` section at the top of `CHANGELOG.md`. A version is three numbers `x.yy.z`: the first and last one digit, the middle 0 to 99; after 0.9.9 comes 0.10.0. -2. Write the changelog section plainly: what changed for the person, then what changed for developers. formcompiler publishes it as the release notes. -3. Land it on `main` through a pull request; `ci.yml` must pass. -4. An owner starts the build. formcompiler creates `compile_vX.Y.Z` at that commit, checks that the version file names the version and that `ci.yml` passed, and runs on each runner, from the root of a fresh checkout: +2. Write the changelog section plainly: what changed for the person, then what changed for developers. formcompiler publishes it as the release notes, so the section is written in the words of someone using the app, one change to a bullet, saying what happens now and, for a fix, what went wrong before. It names nothing private, no machine, person, token, bucket or project, and holds no emoji, no long dash and no attribution line. Say what was run for the version and what was not. +3. The release commit comes last on the branch, with the subject `chore(release): version x.y.z (x.y.z)`, and it moves every version site, because the build is made from the version found on `main` after the merge. Land the branch through a pull request with a merge commit, never a squash or a rebase, so each commit stays; `ci.yml` must pass first. Times written anywhere are US Eastern. +4. An owner starts the build, after checking the merged commit; nobody else creates, moves or pushes a `compile_vX.Y.Z` branch or starts the release workflow by hand. formcompiler creates `compile_vX.Y.Z` at that commit, checks that the version file names the version and that `ci.yml` passed, and runs on each runner, from the root of a fresh checkout: ``` ./formblocks install --lite @@ -25,6 +25,7 @@ Nothing in this repository pushes, signs or publishes a release. The family's co (On Windows the same in Git Bash; `windows_shell: "cmd"` in the entry switches to `formblocks.bat`.) These three run with no question asked and fail with a non-zero exit when they fail. 5. formcompiler signs the installers, makes a draft release tagged `vX.Y.Z` on this repository, and an owner publishes it. +6. After the build, the release page gets its "What's new" text and a table saying which file is for which computer. The notes cover everything since the last version people could download, not only the last version number; a version that was never published is folded in and the first sentence says so. They use the headings New, Improved, Changed, Fixed, Removed, Known issues and Under the hood, in that order, leaving out any that is empty, and say nothing about a weakness that is still open. They claim only what the changelog and the commits of that range say, and never that something was tested unless the repository says so. The table of files, the line saying what the computer needs and the checksums are made from the files really on the release, not written by hand. Pages for a version already published can be corrected afterwards. ## Secrets @@ -32,7 +33,8 @@ This repository holds no signing key, certificate or release token, and its work ## Before the first release -- The desktop bundle needs the app's icons in `src-tauri/icons`; there are none yet, and the owner is drawing them. +- The desktop bundle takes the app's icons from `src-tauri/icons`, made from the owner's art in `assets/app-icon/`; nobody redraws them. Check that they are present and unchanged. +- A desktop build has been made and run on each system the release names. Until then the release page says which systems it was not run on. - The app installs and starts on macOS, Windows and Linux from the installers of the family's candidate build. - No installer, release asset or extra carries any part of the LDraw Parts Library. A release is checked for it: the frozen engine and the bundle hold no `parts/`, `p/` or `LDConfig.ldr`. The person fetches the library after consent on first run, or points FormBlocks at a copy they have. - `.fblk` is added to formcompiler's registry of project files, and the owner has approved the trademark notice in `README.md` and `NOTICE.md` and the "instead of" line. diff --git a/formblocks.bat b/formblocks.bat index 2679fa7..2dd31e9 100644 --- a/formblocks.bat +++ b/formblocks.bat @@ -1,8 +1,14 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion if not defined FORMBLOCKS_CALLER_DIR set "FORMBLOCKS_CALLER_DIR=%CD%" cd /d "%~dp0" set "CMD=%~1" +if /i "%CMD%"=="claude" goto :agent +if /i "%CMD%"=="codex" goto :agent +if /i "%CMD%"=="cursor" goto :agent +if /i "%CMD%"=="antigravity" goto :agent +if /i "%CMD%"=="cli" goto :engine +if /i "%CMD%"=="mcp" goto :engine set "ARG=%~2" if "%CMD%"=="" set "CMD=boot" if /i "%CMD%"=="boot" ( call setup\boot_all.bat & goto :done ) @@ -19,13 +25,7 @@ if /i "%CMD%"=="desktop" ( goto :done ) if /i "%CMD%"=="doctor" ( call setup\doctor.bat & goto :done ) -if /i "%CMD%"=="mcp" ( call setup\mcp.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) -if /i "%CMD%"=="cli" ( call setup\cli.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) if /i "%CMD%"=="agents" ( call setup\agents.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) -if /i "%CMD%"=="claude" ( call setup\claude.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) -if /i "%CMD%"=="codex" ( call setup\codex.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) -if /i "%CMD%"=="cursor" ( call setup\cursor.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) -if /i "%CMD%"=="antigravity" ( call setup\antigravity.bat %2 %3 %4 %5 %6 %7 %8 %9 & goto :done ) if /i "%CMD%"=="clean" ( call setup\clean.bat %ARG% & goto :done ) if /i "%CMD%"=="version" ( call :version & goto :done ) if /i "%CMD%"=="--version" ( call :version & goto :done ) @@ -35,6 +35,17 @@ call :usage exit /b 2 :done exit /b %ERRORLEVEL% +:agent +if not exist backend\venv\Scripts\activate.bat ( echo [formblocks] error: engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) +call backend\venv\Scripts\activate.bat +python setup\agent_launch.py %* +exit /b %ERRORLEVEL% +:engine +cd /d backend +if not exist venv\Scripts\activate.bat ( echo [formblocks] engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) +call venv\Scripts\activate.bat +python formblocks_engine.py %* +exit /b %ERRORLEVEL% :version for /f "tokens=2 delims='" %%v in ('findstr /b /c:"export const VERSION" frontend\src\version.ts') do echo FormBlocks %%v exit /b 0 diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 86e0540..d67a010 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,6 +2,72 @@ Why the window is the way it is. Newest entry first. +## A part picked from the search field leaves the field · 0.5.0 (src/ui/side-panel.ts) + +Typing a number in the parts palette's search and pressing Enter picks the first match and holds it, but the cursor stayed in the search field, and the window's keys act only when the cursor is not in a text field. So R, T, Y, A and O typed letters into the search instead of turning the held part, and Esc cleared the search instead of putting the part down; a person had to click somewhere first, and a click in the viewport drops the part. Choosing a part now takes the cursor out of a text field inside the palette, so the next key turns, drops or cancels the held part; the search keeps its words for the next pick. Checked in headless Chrome on 7270: "3004", Enter, R turned the held ghost a quarter turn (the preview's rotation became the turn about Y), the search still read "3004" and the focus was on the page. + +## Overlapping parts are drawn in the warning colour while the check is on · 0.5.0 (src/ui/overlaps.ts, src/view/model-scene.ts, src/view/index.ts, src/ui/mounts.ts) + +`SPEC.md` 8.1 asks for overlapping parts drawn as wireframe in the warning colour with the check on; 0.5.0 built the check by real solids but not this mark, so an overlap already in a model was seen only through Show Overlaps. The engine decides: whenever the overlap switch is turned on, a model is opened or the model changes, the window asks `overlap.check` with `nested` false (one request at a time, a change during one asks once more after it) and hands the ids of every real overlapping pair to the viewport's `setOverlaps`, which patches only the instances whose state changed. A part so marked keeps its shape with its face tint washed 0.82 toward the background and its edge lines in `--view-blocked` (the warning colour); a true wireframe would need a second material for every batch, which the instanced drawing does not have, and the washed face with bright edges reads the same way. The mark wins over selection, so Show Overlaps' selection does not hide it. Turning the switch off clears every mark at once. Checked in headless Chrome on 7270: two 2 x 4 bricks pushed 8 LDU into each other and a third apart, O on: the two were washed with warning edges and the third drawn as before; O off: all three as before. + +## The arrow keys nudge along the axes nearest the screen's · 0.5.0 (src/ui/edit-keys.ts, src/ui/mounts.ts, src/view/index.ts) + +`SPEC.md` 5.3 asks Left and Right to move the selection along the horizontal axis nearest the screen's left and right and Up and Down along the one nearest into the screen; they moved along LDraw's X and Z from every view, so from the back Right moved a part to the left. They now use the same choice as T and Y (below): Right moves toward the screen's right, Up away from the person, Shift with Up and Down still moves up and down, Alt still moves 1 LDU. Checked in headless Chrome on 7270 with one brick at the stud step: Right and Up moved it by +X and +Z from the front, +Z and -X from the right, -X and -Z from the back, -Z and +X from the left, +X and +Z from the top and the corner view. + +## T and Y tip and roll about the axes nearest the screen's · 0.5.0 (src/ui/edit-keys.ts, src/ui/mounts.ts, src/view/index.ts) + +`SPEC.md` 5.2 asks T to tip about the horizontal axis that runs most nearly left to right on the screen and Y to roll about the one that runs most nearly into it; since 0.3.0 they turned about LDraw's X and Z whatever the camera did, so from the right or the back the keys tipped the wrong way or rolled instead. The viewport now answers `facing()`, the camera's right and forward directions in scene axes, and the keys take whichever of LDraw's X and Z is nearer each, with the sign that points to the screen's right or into the screen, so a tip always looks the same to the person. From the front the keys do what they did before (X and Z, positive). The tip axis is the one of X and Z nearer the camera's right, the roll axis always the other one, with its sign from the camera's forward plus up direction, so looking straight down (the top view), where forward has no horizontal part, Y still rolls away from the person. The held ghost, a drag and Alt with T or Y go through the same choice. Checked in headless Chrome on 7270 with a 1 x 2 brick: from the front T turned about +X and Y about +Z, from the right about +Z and +X, from the back about -X and -Z, from the left about -Z and +X, and each Shift key turned back to the start. + +## The Parts tab's controls take one row, Copy and Save sit in its foot · 0.5.0 (src/ui/parts-list.ts, src/styles/partslist.css) + +Measured headless: the tab spent 122 pixels on a filter row with Copy and Save, a scope row, the sort row and the foot before any part, so even with the column's new layout the list had five and a half rows at 1440 by 900. The filter, the scope choice and the submodel switch now share the first row (the filter keeps every pixel the choice does not need, the choice is at most one and a half cells wide), and Copy and Save are the last two cells of the foot, beside the total they act on. The filter's placeholder is the short "Filter rows" because the long one was cut at this width; the long words are still its label and tooltip. The list is 249 pixels, 6.2 rows, at 1440 by 900 (three rows at 0.4.0) and 165 pixels at 1280 by 720. Walked headless under 4x CPU: showing the tab, a scope change, a filter (16 of 32 rows), the submodel switch twice and Copy (32 rows copied), with no layout shift. + +## The pivot tool sets the pivot where the person clicks · 0.5.0 (src/ui/placing.ts) + +`SPEC.md` 5.2: with the pivot tool on (J) and parts selected, a plain click asks `part.pivot` with the selection and the click's ray; the engine answers the point on the part it meets, or the stud or other connector within 8 LDU of it, and the dial moves there with its three rings. The chosen point stays for turns of the same selection, so a part can be turned about one corner again and again; a new selection, leaving the tool, or a click that meets no part goes back to the engine's centre. Checked headless on 7230: with a 3001 selected and the tool on, a click on its front face moved the rings to that point without changing the selection, a quarter turn on the Y ring turned the brick about it as one Rotate step, and a click on the ground put the rings back about the brick's centre. + +## The column writes nothing to the engine before it has heard the engine · 0.5.0 (src/ui/splits.ts) + +Checked headless with a fresh browser profile against an engine holding a layout (palette 300, details folded, the Parts tab): the tab bar's first `show` keeps the tab, which scheduled a write of the window's default layout 400 ms later, and the engine's answer, which comes after the window is shown even unthrottled (the fonts are ready first), was kept for the next start and then overwritten by that write, so the person's layout was lost. `keep` now writes only the local mirror until the engine's first settings answer has been read; after it, every change is written as before. Walked again under 4x CPU and a slow network and without throttling: the first load showed the defaults and left the engine's layout alone, the reload opened with the palette at 300, details folded and the Parts tab, with no layout shift. + +## A turn about a hinge waits for the engine before it shows an angle · 0.5.0 (src/ui/placing.ts) + +With the overlap check off the dial shows each step at once, because nothing could then block it. A turn about a hinge can be blocked with the check off, by the ground, which stops it rather than lifting it off its hinge (`SPEC.md` 5.2, decided in 0.5.0), so the angle would show and then jump back. A hinge ring now waits for `/api/place/turn`'s answer as the check does. Checked headless on 7230 with a Hinge Plate 1 x 2 with 2 Fingers joined to one with 3: the dial showed one ring in the selection colour about the hinge, a drag folded the plate up 90 degrees about the hinge, and `part.pivot` still found it hinged afterwards. + +## Reset Right Column, and the headers' summaries · 0.5.0 (src/ui/splits.ts, src/ui/colours-host.ts, src/ui/details.ts) + +`SPEC.md` 1.5 lists `view.layout_reset`; the engine has no layout command yet, so the window registers the id as a window command in the View group: it forgets which sections the person opened last, opens every section and puts both heights back to the tokens' defaults, keeping the tab shown, and the change is kept like any other. The headers carry what a folded section would otherwise hide: the palette's names the current colour with its swatch (`colours-host.ts`, which already followed the current colour), the details panel's names the selection, which moved there from the panel's own title row, so the open panel is one row shorter and the folded one still says what is selected; with nothing selected it is empty rather than repeating "Details". Both are left aligned in the header so a longer name grows to the right and moves nothing. Walked headless at 1440 by 900: with the palette and details folded, Reset Right Column from the command palette opened both at 256 and 204. + +## Alt with R, T and Y turn a held part and a drag by the angle step too · 0.5.0 (src/ui/placing.ts, src/ui/edit-keys.ts) + +This replaces the last sentence but two of "The pivot dial turns the selection, asking the engine once per step": held parts and drags first kept turning a quarter with Alt, on the thought that a ghost seats only at quarter turns. But `SPEC.md` 5.2 (decided in 0.5.0) makes Alt with the keys turn by the angle step wherever they act, and the engine places a part turned by any angle on the grid or the surface under it (a single anti-stud may even seat). The held turn helper now takes a fraction of a quarter turn: whole quarter turns still come from the exact table, anything else from the cosine and sine, rounded to six places as before. Checked headless on 7230 with the angle step at 45: Ctrl+D held a copy of a 3001, Alt+R turned the copy's ghost 45 degrees, and the click dropped it with the matrix 0.707107, 0, 0.707107 / 0, 1, 0 / -0.707107, 0, 0.707107. + +## The nested pairs switch and Show Overlaps · 0.5.0 (src/ui/overlaps.ts, src/main.ts, src/ui/prefs.ts) + +The engine's overlap check now tells real overlaps from nested pairs and keeps the choice of whether nested pairs are reported in the `overlap_nested` setting (backend/app/connect/HASHOUT_LOG.md has the rule and the measurements). +The setting is shown where the overlap switch lives: a fourth status bar switch, "Nested on" or "Nested off", and a row under the overlap check in Preferences, General. Both run `overlap.nested`; Reset this page puts it back off, the proposed default. +The switch is built by `overlaps.ts` in its own shell-mounted hook, which `main.ts` imports right after `status.ts` so the hook runs after the status bar's container exists and before the first paint; it uses the status bar's own switch classes, whose grid columns are fixed, so the wider status bar is there from the first frame and the text changing between on and off moves nothing. + +The window had no way to see the check's answer: the catalogue's "Check Overlaps" runs and drops its result. +"Show Overlaps" (Model menu and the palette, titled apart from the engine command so the palette's first match is not the argument form) runs `overlap.check`, +selects both parts of every real overlap, and the nested pairs too when they are listed, and says in the status bar how many of each there are and how deep the deepest overlap is ("0 overlaps · 20 nested apart"). +A selection is the one highlight the view already draws, so no view code changed; drawing overlapping parts as wireframe in the warning colour (`SPEC.md` 8.1) is still to build. +The selection is always replaced, emptied when there is nothing to show, so an old selection is never read as an answer. +Checked in headless Chrome against an engine on a scratch port with the CPU slowed 4 times and a 1.6 Mbit/s, 562 ms network, over a hard reload and every interaction: the sample car gives "0 overlaps · 20 nested apart" and nothing selected, then 19 parts selected with nested on; +the car with a 2 by 4 brick sunk into its chassis gives "4 overlaps, deepest 8 LDU" with 5 parts selected; layout shift 0 without recent input and 0 with it. + +## The pivot dial turns the selection, asking the engine once per step · 0.5.0 (src/ui/placing.ts, src/ui/edit-keys.ts) + +`SPEC.md` 5.2 (decided in 0.5.0). The placing module asks `part.pivot` for the visible selected parts whenever the selection changes or a selected part changes, and hands the view the point, the axes in the scene's axes and the reach; one ring (Y) normally, all three with the pivot tool (J), the hinge's alone when the engine answers a hinge. Nothing about the pivot is worked out in the window. While a ring is dragged the raw angle from the view is rounded to the angle step (to whole degrees with Shift); only when that rounded angle changes does anything happen: the parts are turned in place at once (with the overlap check off, since nothing can then block it), and `POST /api/place/turn` is asked, one request at a time with only the newest angle waiting, for the lift and whether the angle is blocked. The answer moves the parts and the dial up by the lift, or, blocked, puts them back at the last free angle in the warning colour (with the check on, the window waits for the answer before showing an angle, so a blocked one never flashes). So a drag uploads nothing per pointer frame, and one 60 to 90 byte request per step. The release waits for the last answer and sends one `part.rotate` with `axis_vector`, `angle` and `about` exactly as the engine gave them, so the command runs the same rule; the preview ends when the change has arrived (or 600 ms), as for a move. Esc, a lost pointer or the Step Back command put the parts back. Alt with R, T or Y turns a still selection by the angle step with `part.rotate`'s `angle`; on a held ghost or a drag they still turn a quarter, since a ghost only seats at quarter turns. A changes the angle step through `angle.step`; Esc with nothing else to step back from leaves the pivot tool (18.1). + +## The Info tab shows the model information the engine counts · 0.5.0 (src/ui/model-info.ts, src/ui/model-info-strings.ts, src/styles/info.css) + +`SPEC.md` 13.1 (decided in 0.5.0): model information is a fourth tab, Info, because the tab section is the part of the right column that grows, so the panel's twenty values have room without taking rows from the lists, and a dialog would hide the view. The panel is built whole when the tab mounts, every value a `dd` of its own with a line's height reserved, and each answer of `model.info` (asked with `table: false`, so the parts list is not sent) is written into those nodes with `setText`, one text node per value; the missing parts are a keyed list patched in place at the panel's end, so a part appearing there moves nothing above it. Nothing is counted here, not even a sum: placements, parts, different parts, colours, pairs, submodels, steps, missing parts and overlapping pairs come from the engine, the overlap count from `overlap.check` through the engine, and the licence choices from the answer's `licences`. Like the Parts tab it asks again only while shown and only when the counts can have changed (an edit recorded by the store, which includes a header change since the engine sends the main submodel back, the path or format after a save, the library update or index). Name, description and author are fields: Enter or leaving the field runs `submodel.rename` (which renames every use) or `model.set_info`, each one undo step, and Esc puts the field back; a field being typed in is never overwritten by an answer. The licence is a choice of None and the engine's list. Values are left aligned so a longer number or name never moves its neighbours. Its words live in `model-info-strings.ts` beside it, like the palette's, to keep a twenty-line block out of the shared strings. A window command, Model Information, shows the tab from the menu and the command palette. Looked at headless at 1440 by 900 and 1280 by 720 with the car: 61 placements, 61 parts, 26 different, 7 colours, 32 pairs, 8 steps, 0 overlaps (what `overlap.check` answered at that moment), 4.5 by 10.8 studs and 5.17 bricks. + +## The right column gives its room to the list being worked in · 0.5.0 (src/ui/shell.ts, src/ui/splits.ts, src/styles/shell.css) + +Looked at headless with the car at 0.4.0: at 1440 by 900 the palette (320 pixels) and the details panel (228) left the tab section 286, so the Parts tab showed three rows and the tree four; at 1280 by 720 the tree showed none. `SPEC.md` 1.2 now has the rule this implements. The column is three sections, `.ui-sec` with `data-sec` colours, tabs and details, each in the shell's markup from the first frame: the palette and the details panel with a header (a button with a chevron, the name and a summary the section's module fills), the tab section with its tab bar as header. The grid's three rows are custom properties on `.ui-right` (`--ui-colours-row`, `--ui-tabs-row`, `--ui-details-row`), so a drag, a fold or a window resize writes three values and a `data-fold` attribute and builds nothing. One section grows (`minmax(0, 1fr)`): the tab section, or the palette when the tabs are folded, or the details panel when both are; the others take the height the person dragged them to, clamped to the least and greatest heights in `tokens.css`. When the least heights do not fit, the palette and the details panel shrink to them, and then one is shown folded (`data-fold="squeezed"`), details first, the one the person opened last kept longest, without touching what the person chose; at 1280 by 720 the least heights fit with 8 pixels to spare, so this happens only with the dock at the bottom or a shorter window. A folded section's body is `inert` and hidden, so its controls leave the tab order. The layout (`ColumnLayout`: the two heights or null for the token default, the folded sections, the tab) is kept in the engine's `right_column` setting, written 400 ms after the last change, and mirrored in local storage under `formblocks.rightColumn`, which is read when the shell mounts, before the window is revealed, so a reload opens at the remembered sizes with nothing moving. The engine is the record: its first answer replaces the mirror when it differs and the window is not yet shown; when it comes after the window is shown it is kept for the next start rather than moving the column under the person; when the engine holds no layout yet the mirror is written to it, which also carries over the 0.4.0 divider heights (`formblocks.split.*`) once. The dividers keep their keys (Up, Down, double-click) and are hidden where they would move nothing (beside a folded or the growing section). Walked headless at 1440 by 900 with the car: the palette dragged 60 pixels down and the details divider 40 down changed only the three heights, folding the palette gave the tabs 642 pixels, a reload kept all three and the engine's `settings.json` held them, folding the tabs grew the details panel, a click on the Parts tab opened the section again, and double-clicks put both heights back to 256 and 204. + ## Preferences reach the Outside agents dialog and list Ctrl+J · 0.4.0 (src/ui/prefs.ts, src/ui/strings.ts) The page named "Library and agents" had nothing about agents, and the Keys page lists the catalogue's commands only, while the dock's own chord, Ctrl+J (Cmd+J), belongs to the dock module and is not a window command. The page now ends with an Outside agents row whose Open button closes Preferences and opens the same dialog as the dock's menu, so there is one place where the standing choice is kept; the Keys page shows the dock's chord first, written with the same key label as every other row and found by the search. The chord is not registered as a command, which would toggle the dock twice. Checked headless: the Keys page's first row read "Show or Hide the Agent Dock = Ctrl+J", Open on the library page left the Outside agents dialog as the one dialog shown, and no layout shift was recorded. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 775aa1e..368d354 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,23 +1,23 @@ { "name": "formblocks", - "version": "0.4.0", + "version": "0.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formblocks", - "version": "0.4.0", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "@fontsource/inter": "5.3.0", "@fontsource/jetbrains-mono": "5.3.0", - "@tauri-apps/api": "2.12.4", + "@tauri-apps/api": "2.12.5", "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "three": "0.186.1" }, "devDependencies": { - "@tauri-apps/cli": "2.11.4", + "@tauri-apps/cli": "2.12.5", "@types/three": "0.186.0", "typescript": "7.0.2", "vite": "8.3.5" @@ -399,9 +399,9 @@ "license": "MIT" }, "node_modules/@tauri-apps/api": { - "version": "2.12.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz", - "integrity": "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.5.tgz", + "integrity": "sha512-G9QIMt5fzED+aS4QhVK3w1HWLKpLIwH/MnpCr9z1ugGEHnS2ORmqrLkc0uALOjRK4qXJy+4Yiw8LDl/KicC1Hg==", "license": "Apache-2.0 OR MIT", "funding": { "type": "opencollective", @@ -409,9 +409,9 @@ } }, "node_modules/@tauri-apps/cli": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.11.4.tgz", - "integrity": "sha512-R8xGtMpwyetawSqm9kYOuMmEqkhUbvcUy8n0aNXIxollKBLESUu5f4Fx+64hgASYm1H+jSWq6jCW6zqTnH6hqQ==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.5.tgz", + "integrity": "sha512-Dm8s/4aiE52HsBh+Gz3uSrh+fEykRICA1VoAnQA80IqHoTRncPg+q4rGvuhmyNsHUPg3QrPjUrTUSfWmXLVVEw==", "dev": true, "license": "Apache-2.0 OR MIT", "bin": { @@ -425,23 +425,23 @@ "url": "https://opencollective.com/tauri" }, "optionalDependencies": { - "@tauri-apps/cli-darwin-arm64": "2.11.4", - "@tauri-apps/cli-darwin-x64": "2.11.4", - "@tauri-apps/cli-linux-arm-gnueabihf": "2.11.4", - "@tauri-apps/cli-linux-arm64-gnu": "2.11.4", - "@tauri-apps/cli-linux-arm64-musl": "2.11.4", - "@tauri-apps/cli-linux-riscv64-gnu": "2.11.4", - "@tauri-apps/cli-linux-x64-gnu": "2.11.4", - "@tauri-apps/cli-linux-x64-musl": "2.11.4", - "@tauri-apps/cli-win32-arm64-msvc": "2.11.4", - "@tauri-apps/cli-win32-ia32-msvc": "2.11.4", - "@tauri-apps/cli-win32-x64-msvc": "2.11.4" + "@tauri-apps/cli-darwin-arm64": "2.12.5", + "@tauri-apps/cli-darwin-x64": "2.12.5", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.5", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.5", + "@tauri-apps/cli-linux-arm64-musl": "2.12.5", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.5", + "@tauri-apps/cli-linux-x64-gnu": "2.12.5", + "@tauri-apps/cli-linux-x64-musl": "2.12.5", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.5", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.5", + "@tauri-apps/cli-win32-x64-msvc": "2.12.5" } }, "node_modules/@tauri-apps/cli-darwin-arm64": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.11.4.tgz", - "integrity": "sha512-1ryOF3ZhpZ/nemHV5zVwBQBz9jDGKmKPvWPADOhc83ig0P4bMc2iER4NbC6r9sjeIZ6RVQ4g3RZIYvezhcl4TQ==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.5.tgz", + "integrity": "sha512-VVvBRBdTFF7BP7RqGeItp9yDiyXj0DI1laRCEN2q6GLrNkw4wrHeWAxHp23PwtQtn/XET+yTN1jOKrq+Yor5PQ==", "cpu": [ "arm64" ], @@ -456,9 +456,9 @@ } }, "node_modules/@tauri-apps/cli-darwin-x64": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.11.4.tgz", - "integrity": "sha512-uFsGQAAfuyz1k/yGLmkWfkBlgKAqZfxqlHmLWx81QU27RJWfmbNHCIq8T8w1e+VClleIuZUjpHWfoE4E3DLo3A==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.5.tgz", + "integrity": "sha512-A84QYNj93kaG06N2mIFBRZM/X3lf9TyAVQeQwOmP2AJZ2wCt1WLDJgHRCvjeJmwJjJ5Ud0jUbIKbXg8NEGvsVQ==", "cpu": [ "x64" ], @@ -473,9 +473,9 @@ } }, "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.11.4.tgz", - "integrity": "sha512-IaHZn5CdBL21oUmjiVOS1ctw6Ip1O0pjp70FwOWmYz1myWe0SY96ZIj2FYf7pT0m8bI2h/hrs5ZbEXXh44/MkQ==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.5.tgz", + "integrity": "sha512-tb/5xG5HV6CJR9AZBmTyI2GCi05vcH8XUjUIjBquAx7x+AE4f1vMWngvq7JW2AqYK8nNl79LJH1GR9Hf5QQc5g==", "cpu": [ "arm" ], @@ -490,9 +490,9 @@ } }, "node_modules/@tauri-apps/cli-linux-arm64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.11.4.tgz", - "integrity": "sha512-N41/ukTRVe6XSuUTESuFdGeOW2i7k62tK+6gHK5Kd5/q5RPvvi19GaWAVPPb9u95HSGmTChSolBfzynUsssFaA==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.5.tgz", + "integrity": "sha512-Vb7SlbIWlmIqekfsGYT64wH1cQNg5MET8XFyT6pUlVJ7Y/z6LsOIh4MUal0Z5FCPL83GMuEUNxpYUHpt36teHQ==", "cpu": [ "arm64" ], @@ -507,9 +507,9 @@ } }, "node_modules/@tauri-apps/cli-linux-arm64-musl": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.11.4.tgz", - "integrity": "sha512-v277UnT/fB64xAfSroL5N3Km3tLmvATWqJJw/wRI+g6o+HkeD0slyE7gOhNs1MbjE41R7bQOTxMVoL3aomUJmw==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.5.tgz", + "integrity": "sha512-b/YfVGueoTOtENQHY1STBF9XlU4uZDtOiMUErp2Nao/YrDWCKggjxxBZU3ycbeDWUYxl8U8M9seE4HYag1xjiQ==", "cpu": [ "arm64" ], @@ -524,9 +524,9 @@ } }, "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.11.4.tgz", - "integrity": "sha512-qqgNkQ2u1yZHxjhxsZaxUtRDW8dIqIYm33rx/mzwQv0SfY9x1B+iraj8vWeFiXjjSVVhEMepXSOts1TqPzvXNQ==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.5.tgz", + "integrity": "sha512-/EXbTfE9FM9GKSSRL9YTRHcMglTVNzbcwegXM0MBR3ozVgoE+pFq46Ej/InJBs1l+sjSpu6jyi38MZ+xyU/3NQ==", "cpu": [ "riscv64" ], @@ -541,9 +541,9 @@ } }, "node_modules/@tauri-apps/cli-linux-x64-gnu": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.11.4.tgz", - "integrity": "sha512-2VRNWl84FOH0m2giiDkO2h0QXlcMJeX+zJDpI5kDIQAx6s+geF3v48F4DXfJez4GS/FdoDGnPnw1C2iYGbQ7bQ==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.5.tgz", + "integrity": "sha512-OIun574QsULxaZ5SmPDX4D8bO95RBmYJshu8yGFy0RSyCMKEs/y+o3BThot4fbCv4ttC1Tq6Hzt0QRHXCIgp7w==", "cpu": [ "x64" ], @@ -558,9 +558,9 @@ } }, "node_modules/@tauri-apps/cli-linux-x64-musl": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.11.4.tgz", - "integrity": "sha512-o9GyhYor/nc7xarmwDE3ka2szuW3uuZzXjHWh64Q8YX5AtSgxdQkFWzrY4O8KiGtVNvFBI14H3Q49Qj5TOIP/A==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.5.tgz", + "integrity": "sha512-GDzWcb/6OzJrHnVGQ/n3XndLan67bZ7cu4zJN9+zFmV10nBgKz5jDDm8sRQO4sGb7bu6Ztiy+Al2XY2ptRY0RQ==", "cpu": [ "x64" ], @@ -575,9 +575,9 @@ } }, "node_modules/@tauri-apps/cli-win32-arm64-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.11.4.tgz", - "integrity": "sha512-ld5Ehb598m0VkYyylRPNeCFsBe/km0jxis6KgMpl3IGY6I/i1RwQXO05I1AsXUXO2WC6AvB/Lw4qTf/asiuEiQ==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.5.tgz", + "integrity": "sha512-61KCX5vo0vex7P/P7sbXdfFhHqs+rFaG+UXK/UBwz/VlLveDx6vgpHkF+rfUIfCqj0VvLArpxR3+rQIzRwxKgw==", "cpu": [ "arm64" ], @@ -592,9 +592,9 @@ } }, "node_modules/@tauri-apps/cli-win32-ia32-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.11.4.tgz", - "integrity": "sha512-12Hxi0XX/H5VFxO/bGgHkFWhml9VMgEOu9CidjeCeTNQ1l6fpUlbiGgSP7CLI3PFtW9/FfbeHieZ+kyWK5H7CA==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.5.tgz", + "integrity": "sha512-mGujjR/MlXwJiQcue4wlXrBYlIEdDCoap0g+GNPlLCb75ilSbWMC8qTsXVuGcLIMumIJvc2v+veDnCHnels/Zg==", "cpu": [ "ia32" ], @@ -609,9 +609,9 @@ } }, "node_modules/@tauri-apps/cli-win32-x64-msvc": { - "version": "2.11.4", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.11.4.tgz", - "integrity": "sha512-+vDiqBIU5dMISg/wNvX3sF+ZHfgJGJ5T0AcO+EHNXV9GGAG+P5fzodlDXD3QdKCRgZxMoCm5PPvj3BqLNjBthw==", + "version": "2.12.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.5.tgz", + "integrity": "sha512-o1+EOjvi/nFwKx5XamCXSr+GUr2ko8TH7+0wnWuZjE+lZwE+/VWCbE49HPHa3/V59M3bJ0dlK1yhogGQ15OVPg==", "cpu": [ "x64" ], diff --git a/frontend/package.json b/frontend/package.json index 6534298..074a633 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formblocks", "private": true, - "version": "0.4.0", + "version": "0.5.0", "description": "FormBlocks · an open brick building app on the LDraw parts library", "license": "Apache-2.0", "type": "module", @@ -18,13 +18,13 @@ "dependencies": { "@fontsource/inter": "5.3.0", "@fontsource/jetbrains-mono": "5.3.0", - "@tauri-apps/api": "2.12.4", + "@tauri-apps/api": "2.12.5", "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "three": "0.186.1" }, "devDependencies": { - "@tauri-apps/cli": "2.11.4", + "@tauri-apps/cli": "2.12.5", "@types/three": "0.186.0", "typescript": "7.0.2", "vite": "8.3.5" diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 25a143a..044339e 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -5,6 +5,7 @@ import './ui/menu'; import './ui/side-panel'; import './ui/model-view'; import './ui/status'; +import './ui/overlaps'; import './dock-adapter'; startApp(); diff --git a/frontend/src/styles/details.css b/frontend/src/styles/details.css index 025a1f8..7f4ba18 100644 --- a/frontend/src/styles/details.css +++ b/frontend/src/styles/details.css @@ -1,10 +1,9 @@ -.ui-details-box { display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100%; min-height: 0; padding: var(--space-2) var(--space-3); } -.ui-details-head { display: grid; grid-template-rows: auto auto; row-gap: var(--hair-gap); min-width: 0; padding-bottom: var(--space-2); } -.ui-details-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-primary); font-size: var(--fs-13); font-weight: var(--fw-bold); } +.ui-details-box { display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100%; min-height: 0; padding: 0 var(--space-3) var(--space-2); } +.ui-details-head { display: grid; min-width: 0; padding-bottom: var(--space-1); } .ui-details-id { min-height: calc(var(--fs-11) * var(--lh)); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-muted); font-family: var(--font-mono); font-size: var(--fs-11); } .ui-details-empty { grid-area: 2 / 1 / 3 / 2; margin: 0; } .ui-details-empty[hidden], .ui-details-body[hidden] { display: none; } -.ui-details-body { grid-area: 2 / 1 / 3 / 2; display: grid; align-content: start; row-gap: var(--space-2); min-height: 0; overflow: hidden; } +.ui-details-body { grid-area: 2 / 1 / 3 / 2; display: grid; align-content: start; row-gap: var(--space-1); min-height: 0; overflow-x: hidden; overflow-y: auto; scrollbar-gutter: stable; } .ui-details-row { display: grid; grid-template-columns: var(--num-w) minmax(0, 1fr); align-items: center; column-gap: var(--space-2); min-height: var(--ctl-sm); font-size: var(--fs-12); } .ui-details-label { color: var(--text-muted); font-size: var(--fs-11); } .ui-details-colour { display: inline-flex; align-items: center; gap: var(--space-2); min-width: 0; color: var(--text-primary); } diff --git a/frontend/src/styles/info.css b/frontend/src/styles/info.css new file mode 100644 index 0000000..637879e --- /dev/null +++ b/frontend/src/styles/info.css @@ -0,0 +1,40 @@ +.ui-info { + --info-label-w: calc(var(--num-w) + var(--space-6)); + display: grid; + align-content: start; + row-gap: var(--space-3); + height: 100%; + min-height: 0; + overflow-x: hidden; + overflow-y: auto; + scrollbar-gutter: stable; + overscroll-behavior: contain; + padding: var(--space-2) var(--space-2) var(--space-3) var(--space-3); +} +.ui-info-group { display: grid; row-gap: var(--space-1); min-width: 0; } +.ui-info-h { margin: 0; color: var(--text-secondary); font-size: var(--fs-11); font-weight: var(--fw-bold); } +.ui-info-field { display: grid; grid-template-columns: var(--info-label-w) minmax(0, 1fr); align-items: center; column-gap: var(--space-2); min-height: var(--ctl-sm); } +.ui-info-label, .ui-info-facts dt { overflow: hidden; color: var(--text-muted); font-size: var(--fs-11); text-overflow: ellipsis; white-space: nowrap; } +.ui-info-field .ui-input { width: 100%; height: var(--ctl-sm); padding: 0 var(--space-1); font-size: var(--fs-12); } +.ui-info-field select.ui-input { padding-right: 0; } +.ui-info-facts dt { line-height: calc(var(--fs-12) * var(--lh)); } +.ui-info-facts { display: grid; grid-template-columns: var(--info-label-w) minmax(0, 1fr); align-items: start; column-gap: var(--space-2); row-gap: var(--hair-gap); margin: 0; } +.ui-info-facts dd { + min-width: 0; + min-height: calc(var(--fs-12) * var(--lh)); + margin: 0; + overflow: hidden; + color: var(--text-primary); + font-size: var(--fs-12); + font-variant-numeric: tabular-nums; + text-overflow: ellipsis; + white-space: nowrap; + user-select: text; + -webkit-user-select: text; +} +.ui-info-none { margin: 0; min-height: calc(var(--fs-11) * var(--lh)); } +.ui-info-none[hidden] { display: none; } +.ui-info-missing { display: grid; row-gap: var(--hair-gap); margin: 0; padding: 0; list-style: none; } +.ui-info-lost { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: var(--space-2); min-height: calc(var(--fs-12) * var(--lh)); font-size: var(--fs-12); } +.ui-info-lost-num { min-width: 0; overflow: hidden; color: var(--warn); font-family: var(--font-mono); text-overflow: ellipsis; white-space: nowrap; } +.ui-info-lost-count { color: var(--text-secondary); font-variant-numeric: tabular-nums; } diff --git a/frontend/src/styles/partslist.css b/frontend/src/styles/partslist.css index d89032b..e45670d 100644 --- a/frontend/src/styles/partslist.css +++ b/frontend/src/styles/partslist.css @@ -1,9 +1,7 @@ -.ui-plist { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto; height: 100%; min-height: 0; } -.ui-plist-tools, .ui-plist-scope { display: grid; align-items: center; column-gap: var(--space-1); padding: 0 var(--space-2); } -.ui-plist-tools { grid-template-columns: minmax(0, 1fr) var(--ctl-md) var(--ctl-md); padding-top: var(--space-2); } -.ui-plist-scope { grid-template-columns: minmax(0, 1fr) var(--ctl-md); padding-top: var(--space-1); } -.ui-plist-tools .ui-input, .ui-plist-scope .ui-input { width: 100%; height: var(--ctl-md); font-size: var(--fs-12); } -.ui-plist-scope select.ui-input { padding-right: var(--space-1); } +.ui-plist { display: grid; grid-template-rows: auto auto minmax(0, 1fr) auto; height: 100%; min-height: 0; } +.ui-plist-tools { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, calc(var(--cell-w) * 1.5)) var(--ctl-md); align-items: center; column-gap: var(--space-1); padding: var(--space-2) var(--space-2) 0; } +.ui-plist-tools .ui-input { width: 100%; height: var(--ctl-md); font-size: var(--fs-12); } +.ui-plist-tools select.ui-input { padding-right: 0; padding-left: var(--space-1); } .ui-plist .ui-icon-btn .ui-icon { width: var(--icon-sm); height: var(--icon-sm); } .ui-plist-sort { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; column-gap: var(--space-1); align-items: center; height: var(--ctl-sm); margin-top: var(--space-1); padding: 0 var(--space-2); border-bottom: var(--line-w) solid var(--line-1); } @@ -16,8 +14,8 @@ .ui-plist-sort-btn.is-on .ui-plist-dir { visibility: visible; } .ui-plist-sort-btn.is-up .ui-plist-dir { transform: rotate(180deg); } -.ui-plist-list { grid-area: 4 / 1 / 5 / 2; min-height: 0; padding: 0 var(--space-1); } -.ui-plist-empty { grid-area: 4 / 1 / 5 / 2; align-self: start; margin: 0; padding: var(--space-3); pointer-events: none; } +.ui-plist-list { grid-area: 3 / 1 / 4 / 2; min-height: 0; padding: 0 var(--space-1); } +.ui-plist-empty { grid-area: 3 / 1 / 4 / 2; align-self: start; margin: 0; padding: var(--space-3); pointer-events: none; } .ui-plist-empty[hidden] { display: none; } .ui-plist-row { display: grid; grid-template-columns: var(--plist-thumb) minmax(0, 1fr) var(--plist-count-w); grid-template-rows: minmax(0, 1fr) minmax(0, 1fr); column-gap: var(--space-2); height: var(--plist-row-h); padding: 0 var(--space-2) 0 var(--space-1); border-radius: var(--radius-sm); color: var(--text-primary); font-size: var(--fs-12); cursor: default; } @@ -40,7 +38,8 @@ .ui-plist-row.is-missing .ui-plist-desc, .ui-plist-row.is-missing .ui-plist-mark { color: var(--warn); } .ui-plist-row.is-use .ui-plist-mark { color: var(--accent-ink); } -.ui-plist-foot { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); column-gap: var(--space-2); align-items: center; height: var(--ctl-sm); padding: 0 var(--space-3); border-top: var(--line-w) solid var(--line-1); color: var(--text-secondary); font-size: var(--fs-11); } +.ui-plist-foot { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) var(--ctl-sm) var(--ctl-sm); column-gap: var(--space-1); align-items: center; height: var(--ctl-md); padding: 0 var(--space-1) 0 var(--space-3); border-top: var(--line-w) solid var(--line-1); color: var(--text-secondary); font-size: var(--fs-11); } +.ui-plist-foot .ui-icon-btn { width: var(--ctl-sm); height: var(--ctl-sm); } .ui-plist-left { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .ui-plist-lost { color: var(--warn); } .ui-plist-lost:not(:empty)::before { content: " · "; color: var(--text-muted); } diff --git a/frontend/src/styles/shell.css b/frontend/src/styles/shell.css index 11353c6..ece602b 100644 --- a/frontend/src/styles/shell.css +++ b/frontend/src/styles/shell.css @@ -32,13 +32,57 @@ button { font: inherit; } .ui-main > .ui-viewport { position: absolute; inset: 0; } .ui-main > .ui-hud { position: absolute; inset: 0; z-index: var(--z-hud); pointer-events: none; } .ui-hud > * { pointer-events: auto; } -.ui-right { --ui-colours-h: var(--colours-h); --ui-details-h: var(--details-h); position: relative; display: grid; grid-template-rows: var(--ui-colours-h) minmax(0, 1fr) var(--ui-details-h); min-width: 0; min-height: 0; overflow: hidden; border-left: var(--line-w) solid var(--line-1); background: var(--bg-secondary); } +.ui-right { + --ui-colours-h: var(--colours-h); + --ui-details-h: var(--details-h); + --ui-colours-row: var(--ui-colours-h); + --ui-tabs-row: minmax(0, 1fr); + --ui-details-row: var(--ui-details-h); + position: relative; + display: grid; + grid-template-rows: var(--ui-colours-row) var(--ui-tabs-row) var(--ui-details-row); + align-content: start; + min-width: 0; + min-height: 0; + overflow: hidden; + border-left: var(--line-w) solid var(--line-1); + background: var(--bg-secondary); +} .ui-split { position: absolute; left: 0; right: 0; height: var(--split-h); z-index: var(--z-raised); cursor: row-resize; touch-action: none; } +.ui-split[hidden] { display: none; } .ui-split-colours { top: calc(var(--ui-colours-h) - var(--split-h) / 2); } .ui-split-details { bottom: calc(var(--ui-details-h) - var(--split-h) / 2); } .ui-split:hover, .ui-split:focus-visible, .ui-split.is-dragging { background: var(--accent-line); outline: none; } -.ui-colours, .ui-tabs, .ui-details { min-width: 0; min-height: 0; overflow: hidden; } -.ui-tabs, .ui-details { border-top: var(--line-w) solid var(--line-1); } +.ui-sec { display: grid; grid-template-rows: var(--sec-head-h) minmax(0, 1fr); min-width: 0; min-height: 0; overflow: hidden; } +.ui-sec[data-sec="tabs"] { grid-template-rows: minmax(0, 1fr); } +.ui-sec + .ui-sec { border-top: var(--line-w) solid var(--line-1); } +.ui-sec-head { min-width: 0; margin: 0; font: inherit; } +.ui-sec-toggle { + display: grid; + grid-template-columns: var(--icon) auto minmax(0, 1fr); + align-items: center; + column-gap: var(--space-2); + width: 100%; + height: var(--sec-head-h); + padding: 0 var(--space-3) 0 var(--space-2); + border: 0; + background: transparent; + color: var(--text-secondary); + font-size: var(--fs-11); + font-weight: var(--fw-bold); + text-align: left; + cursor: pointer; +} +.ui-sec-toggle:hover { background: var(--bg-hover); color: var(--text-primary); } +.ui-sec-toggle:focus-visible { outline: var(--focus-w) solid var(--accent-line); outline-offset: calc(var(--focus-w) * -1); } +.ui-sec-chev { display: inline-grid; place-items: center; width: var(--icon); height: var(--icon); color: var(--text-muted); } +.ui-sec-chev .ui-icon { width: var(--icon-sm); height: var(--icon-sm); } +.ui-sec:not([data-fold="open"]) .ui-sec-chev { transform: rotate(-90deg); } +.ui-sec-sum { display: flex; justify-content: flex-start; align-items: center; gap: var(--space-1); min-width: 0; overflow: hidden; color: var(--text-muted); font-weight: var(--fw-regular); white-space: nowrap; } +.ui-sec-sum-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.ui-sec-sum .ui-tree-swatch { flex: none; } +.ui-sec-body { min-width: 0; min-height: 0; overflow: hidden; } +.ui-sec:not([data-fold="open"]) > .ui-sec-body:not(.ui-tabs) { visibility: hidden; } .ui-strip { min-width: 0; overflow: hidden; border-top: var(--line-w) solid var(--line-1); background: var(--surface-1); } :root[data-clear="on"] .ui-app { --ui-left-w: 0px; --ui-right-w: 0px; } diff --git a/frontend/src/styles/tabs.css b/frontend/src/styles/tabs.css index 4027299..9a487d2 100644 --- a/frontend/src/styles/tabs.css +++ b/frontend/src/styles/tabs.css @@ -1,6 +1,10 @@ .ui-tabs { display: grid; grid-template-rows: var(--tab-h) minmax(0, 1fr); } -.ui-tabbar { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); border-bottom: var(--line-w) solid var(--line-1); } -.ui-tab { height: var(--tab-h); padding: 0 var(--space-3); border: 0; border-bottom: var(--focus-w) solid transparent; background: transparent; color: var(--text-muted); font-size: var(--fs-12); font-weight: var(--fw-medium); cursor: pointer; } +.ui-tabhead { display: grid; grid-template-columns: minmax(0, 1fr) var(--tab-h); border-bottom: var(--line-w) solid var(--line-1); } +.ui-tabbar { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); min-width: 0; } +.ui-tabhead .ui-tabfold { width: var(--tab-h); height: var(--tab-h); border-radius: 0; } +.ui-sec[data-sec="tabs"]:not([data-fold="open"]) .ui-tabhead { border-bottom-color: transparent; } +.ui-sec[data-sec="tabs"]:not([data-fold="open"]) .ui-tab[aria-selected="true"] { border-bottom-color: transparent; } +.ui-tab { height: var(--tab-h); min-width: 0; padding: 0 var(--space-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: var(--focus-w) solid transparent; background: transparent; color: var(--text-muted); font-size: var(--fs-12); font-weight: var(--fw-medium); cursor: pointer; } .ui-tab:hover { color: var(--text-primary); } .ui-tab[aria-selected="true"] { border-bottom-color: var(--accent-color); color: var(--text-primary); } .ui-tabpanel { grid-area: 2 / 1 / 3 / 2; min-width: 0; min-height: 0; overflow: hidden; } diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index 61ab7c2..e42cb77 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -127,11 +127,15 @@ --parts-w: 272px; --right-w: 296px; --viewport-min-w: 320px; - --colours-h: 320px; - --details-h: 228px; + --sec-head-h: 28px; + --colours-h: 256px; + --colours-min: 208px; + --colours-max: 440px; + --details-h: 204px; + --details-min: 148px; + --details-max: 204px; + --tabs-min: 290px; --split-h: 6px; - --split-min: 120px; - --split-tabs-min: 120px; --tab-h: 32px; --strip-h: 40px; --step-chip-w: 32px; @@ -164,6 +168,7 @@ --view-ghost: var(--text-secondary); --view-blocked: var(--warn); --view-axis-x: #d0504a; + --view-axis-y: #4fae5c; --view-axis-z: #4a7fd0; --view-frame: var(--accent-color); --view-frame-shade: color-mix(in srgb, var(--bg-primary) 55%, transparent); diff --git a/frontend/src/styles/tree.css b/frontend/src/styles/tree.css index 53ef7e5..50c3039 100644 --- a/frontend/src/styles/tree.css +++ b/frontend/src/styles/tree.css @@ -1,4 +1,4 @@ -.ui-tree { display: grid; grid-template-rows: auto auto minmax(0, 3fr) minmax(calc(var(--tree-row-h) * 3), 1fr); height: 100%; min-height: 0; } +.ui-tree { display: grid; grid-template-rows: auto auto minmax(0, 4fr) minmax(calc(var(--tree-row-h) * 3), 1fr); height: 100%; min-height: 0; } .ui-tree-filter { padding: var(--space-2) var(--space-2) var(--space-1); } .ui-tree-filter .ui-input { width: 100%; height: var(--ctl-sm); font-size: var(--fs-12); } .ui-tree-head { display: grid; grid-template-columns: minmax(0, 1fr) var(--num-w); column-gap: var(--space-2); padding: var(--space-1) var(--space-3); color: var(--text-secondary); font-size: var(--fs-11); font-weight: var(--fw-bold); } diff --git a/frontend/src/ui/colours-host.ts b/frontend/src/ui/colours-host.ts index 8245f29..fc37dd9 100644 --- a/frontend/src/ui/colours-host.ts +++ b/frontend/src/ui/colours-host.ts @@ -1,6 +1,8 @@ import { api } from '../io/api'; +import { colourOf, colourTable, onColours } from '../io/lookup'; import { currentColour, onCurrentColour, setCurrentColour } from './current-colour'; import { docStore } from './doc-store'; +import { q, setText } from './dom'; import type { PaletteModule } from './mounts'; import { noticeError } from './notice'; import { runCommand } from './run'; @@ -17,6 +19,21 @@ export function chooseColour(code: number): void { } onShellMounted(({ hosts }) => { + const sum = hosts.summaries.colours; + sum.innerHTML = ''; + const swatch = q(sum, '.ui-tree-swatch'); + const name = q(sum, '.ui-sec-sum-text'); + const paintSum = (): void => { + const code = currentColour(); + const c = colourOf(code); + const value = c?.value ?? ''; + if (swatch.dataset.value !== value) { swatch.dataset.value = value; swatch.style.background = value; } + setText(name, c ? `${c.label} · ${code}` : String(code)); + }; + paintSum(); + onCurrentColour(paintSum); + onColours(paintSum); + void colourTable().catch(() => undefined); const m = palettes['./palette/index.ts']; if (typeof m?.mountColourPalette !== 'function') return; try { diff --git a/frontend/src/ui/details.ts b/frontend/src/ui/details.ts index af3e4f0..4075889 100644 --- a/frontend/src/ui/details.ts +++ b/frontend/src/ui/details.ts @@ -39,7 +39,7 @@ function centreOf(list: Placement[]): number[] { } const VIEW = `

-
+

${T.colour}
@@ -53,7 +53,8 @@ const VIEW = `
onShellMounted(({ hosts }) => { const box = hosts.details; box.innerHTML = VIEW; - const title = q(box, '.ui-details-title'); + hosts.summaries.details.innerHTML = ''; + const title = q(hosts.summaries.details, '.ui-sec-sum-text'); const idText = q(box, '.ui-details-id'); const empty = q(box, '.ui-details-empty'); const body = q(box, '.ui-details-body'); @@ -73,7 +74,7 @@ onShellMounted(({ hosts }) => { setHidden(empty, list.length > 0); setHidden(body, list.length === 0); setText(empty, T.none); - if (!list.length) { setText(title, T.title); setText(idText, ''); return; } + if (!list.length) { setText(title, ''); setTitle(title, ''); setText(idText, ''); return; } const one = list.length === 1 ? list[0] : undefined; if (one) { const info = one.use ? undefined : partInfo(one.part); diff --git a/frontend/src/ui/edit-keys.ts b/frontend/src/ui/edit-keys.ts index 2b32aa2..2fb6a2e 100644 --- a/frontend/src/ui/edit-keys.ts +++ b/frontend/src/ui/edit-keys.ts @@ -1,8 +1,9 @@ import { GRID_LDU, settings } from '../io/settings'; import { commands, type WindowCommand } from './commands'; import { docStore } from './doc-store'; +import { viewport } from './model-view'; import { notice } from './notice'; -import { cancelDrag, cancelPick, drop, holdCopies, holding, turnDrag, turnHeld, type Axis } from './placing'; +import { angleStep, cancelDrag, cancelPick, cancelTurn, drop, holdCopies, holding, nextAngleStep, togglePivotTool, turnDrag, turnHeld, type Axis } from './placing'; import { runCommand } from './run'; import { S } from './strings'; @@ -14,7 +15,11 @@ function nudge(dx: number, dy: number, dz: number, fine: boolean): void { const g = GRID_LDU[settings.value.grid_step]; const across = fine ? 1 : g.across; const up = fine ? 1 : g.up; - void runCommand('part.move', { ids: selected(), delta: [dx * across, dy * up, dz * across] }); + const delta = [0, dy * up, 0]; + for (const [amount, a] of [[dx, along('right')], [dz, along('forward')]] as const) { + if (amount) delta[a.axis === 'x' ? 0 : 2] = amount * a.sign * across; + } + void runCommand('part.move', { ids: selected(), delta }); } function turn(axis: Axis, turns: number): void { @@ -24,6 +29,38 @@ function turn(axis: Axis, turns: number): void { void runCommand('part.rotate', { ids: selected(), axis, quarter_turns: turns }); } +function turnByStep(axis: Axis, sign: number): void { + const turns = (sign * angleStep()) / 90; + if (turnDrag(axis, turns)) return; + if (holding()) { turnHeld(axis, turns); return; } + if (!some()) return; + void runCommand('part.rotate', { ids: selected(), axis, angle: sign * angleStep() }); +} + +interface Along { axis: Axis; sign: number } + +const sideOf = (v: number[], axis: Axis): number => ((axis === 'x' ? v[0] ?? 0 : -(v[2] ?? 0)) < 0 ? -1 : 1); + +function along(which: 'right' | 'forward'): Along { + const f = viewport()?.facing(); + if (!f) return { axis: which === 'right' ? 'x' : 'z', sign: 1 }; + const r = f.right; + const across: Axis = Math.abs(r[0] ?? 0) >= Math.abs(r[2] ?? 0) ? 'x' : 'z'; + if (which === 'right') return { axis: across, sign: sideOf(r, across) }; + const deep: Axis = across === 'x' ? 'z' : 'x'; + return { axis: deep, sign: sideOf(f.into, deep) }; +} + +function tipOrRoll(which: 'right' | 'forward', sign: number, byStep: boolean): void { + const a = along(which); + if (byStep) turnByStep(a.axis, sign * a.sign); + else turn(a.axis, sign * a.sign); +} + +function nextAngle(): void { + void runCommand('angle.step', { step: nextAngleStep() }).then(() => settings.refresh()); +} + function duplicate(): void { const ids = selected(); if (!ids.length || holdCopies()) return; @@ -31,10 +68,11 @@ function duplicate(): void { } function escape(): void { - if (cancelDrag()) return; + if (cancelTurn() || cancelDrag()) return; if (holding()) { cancelPick(); return; } if (some()) { void runCommand('select.clear'); return; } - if (docStore.state.editing.length > 1) void runCommand('submodel.leave'); + if (docStore.state.editing.length > 1) { void runCommand('submodel.leave'); return; } + togglePivotTool(false); } function enter(): void { @@ -48,6 +86,7 @@ const c = (id: string, words: { title: string; summary: string }, group: string, ({ id, title: words.title, summary: words.summary, group, icon, ...(keys ? { keys } : {}), ...(also ? { also } : {}), ...(enabled ? { enabled } : {}), run }); const E = S.edit; +const TS = S.turn; const sel = S.group.select; const ed = S.group.edit; @@ -60,10 +99,18 @@ commands.add( c('place.drop', E.drop, ed, 'brick', 'Space', () => { void drop(); }, undefined, holding), c('edit.turn', E.turn, ed, 'rotate', 'R', () => turn('y', 1)), c('edit.turnBack', E.turnBack, ed, 'rotate', 'Shift+R', () => turn('y', -1)), - c('edit.tip', E.tip, ed, 'rotate', 'T', () => turn('x', 1)), - c('edit.tipBack', E.tipBack, ed, 'rotate', 'Shift+T', () => turn('x', -1)), - c('edit.roll', E.roll, ed, 'rotate', 'Y', () => turn('z', 1)), - c('edit.rollBack', E.rollBack, ed, 'rotate', 'Shift+Y', () => turn('z', -1)), + c('edit.tip', E.tip, ed, 'rotate', 'T', () => tipOrRoll('right', 1, false)), + c('edit.tipBack', E.tipBack, ed, 'rotate', 'Shift+T', () => tipOrRoll('right', -1, false)), + c('edit.roll', E.roll, ed, 'rotate', 'Y', () => tipOrRoll('forward', 1, false)), + c('edit.rollBack', E.rollBack, ed, 'rotate', 'Shift+Y', () => tipOrRoll('forward', -1, false)), + c('edit.turnStep', TS.by, ed, 'rotate', 'Alt+R', () => turnByStep('y', 1)), + c('edit.turnStepBack', TS.byBack, ed, 'rotate', 'Alt+Shift+R', () => turnByStep('y', -1)), + c('edit.tipStep', TS.tip, ed, 'rotate', 'Alt+T', () => tipOrRoll('right', 1, true)), + c('edit.tipStepBack', TS.tipBack, ed, 'rotate', 'Alt+Shift+T', () => tipOrRoll('right', -1, true)), + c('edit.rollStep', TS.roll, ed, 'rotate', 'Alt+Y', () => tipOrRoll('forward', 1, true)), + c('edit.rollStepBack', TS.rollBack, ed, 'rotate', 'Alt+Shift+Y', () => tipOrRoll('forward', -1, true)), + c('angle.next', TS.next, S.group.view, 'rotate', 'A', nextAngle), + c('edit.pivotTool', TS.pivot, ed, 'rotate', 'J', () => togglePivotTool()), c('edit.nudgeLeft', E.left, ed, 'prev', 'ArrowLeft', () => nudge(-1, 0, 0, false)), c('edit.nudgeRight', E.right, ed, 'next', 'ArrowRight', () => nudge(1, 0, 0, false)), c('edit.nudgeIn', E.in, ed, 'next', 'ArrowUp', () => nudge(0, 0, 1, false)), diff --git a/frontend/src/ui/features.ts b/frontend/src/ui/features.ts index 07c5e34..64a1796 100644 --- a/frontend/src/ui/features.ts +++ b/frontend/src/ui/features.ts @@ -6,6 +6,7 @@ import './tabs'; import './model-tree'; import './steps-tab'; import './parts-list'; +import './model-info'; import './details'; import './file-actions'; import './library-card'; diff --git a/frontend/src/ui/icons.ts b/frontend/src/ui/icons.ts index 6c5e3fc..243ef75 100644 --- a/frontend/src/ui/icons.ts +++ b/frontend/src/ui/icons.ts @@ -29,6 +29,7 @@ export const ICONS: Record = { snap: s(''), grid: s(''), overlap: s(''), + nested: s(''), rotate: s(''), duplicate: s(''), gear: s(''), diff --git a/frontend/src/ui/model-info-strings.ts b/frontend/src/ui/model-info-strings.ts new file mode 100644 index 0000000..c01cb9e --- /dev/null +++ b/frontend/src/ui/model-info-strings.ts @@ -0,0 +1,43 @@ +export const I = { + label: 'Model information', + model: 'Model', + file: 'File', + counts: 'Counts', + size: 'Size', + missing: 'Not in this library', + name: 'Name', + nameHint: 'The main model\'s Name: line; every use of it is renamed too', + description: 'Description', + descriptionHint: 'The first line of the file, its title', + author: 'Author', + licence: 'Licence', + noLicence: 'None', + path: 'Path', + format: 'Format', + savedWith: 'Saved with', + library: 'Library', + placements: 'Placements', + parts: 'Parts in all', + different: 'Different parts', + colours: 'Colours', + pairs: 'Parts list rows', + submodels: 'Submodels', + steps: 'Steps', + missingCount: 'Not in library', + overlaps: 'Overlaps', + across: 'Across', + deep: 'Deep', + high: 'High', + studs: '{n} studs · {mm} mm', + bricks: '{n} bricks · {plates} plates · {mm} mm', + nothing: 'Nothing placed', + notSaved: 'Not saved yet', + notRecorded: 'Not recorded in the file', + noLibrary: 'No library in use', + needsLibrary: 'Needs the library', + kinds: { ldr: 'LDraw model (.ldr)', mpd: 'LDraw multi-part (.mpd)', fblk: 'FormBlocks project (.fblk)' } as Record, + noneMissing: 'Every part is in the library.', + needs: '{n} needed', + enterToSet: 'Enter to set, Esc to put back', + cmdShow: { title: 'Model Information', summary: 'Show the Info tab with the model\'s name, description, author, file, counts and size.' }, +}; diff --git a/frontend/src/ui/model-info.ts b/frontend/src/ui/model-info.ts new file mode 100644 index 0000000..5a41e01 --- /dev/null +++ b/frontend/src/ui/model-info.ts @@ -0,0 +1,208 @@ +import '../styles/info.css'; +import { api, ApiError } from '../io/api'; +import { library } from '../io/library'; +import { commands } from './commands'; +import { docStore } from './doc-store'; +import { el, escapeHtml, patchList, q, setHidden, setText, setTitle } from './dom'; +import { I } from './model-info-strings'; +import { noticeError } from './notice'; +import { runCommand } from './run'; +import { S, fill } from './strings'; +import { currentTab, onTabShown, showTab, tabHost } from './tabs'; + +interface Size { studs: { across: number; deep: number }; bricks: number; plates: number; mm: { across: number; deep: number; high: number } } +interface Missing { part: string; file: string; count: number } +interface Info { + name: string; + title: string; + author: string; + licence: string; + path: string | null; + kind: string | null; + builtWith: string | null; + library: string | null; + counts: Record; + size: Size | null; + missingParts: Missing[]; + licences: string[]; +} + +type Field = 'name' | 'title' | 'author'; +const FIELDS: Array<[Field, string, string]> = [['name', I.name, I.nameHint], ['title', I.description, I.descriptionHint], ['author', I.author, '']]; +const FACTS: Array<[string, string]> = [['path', I.path], ['format', I.format], ['savedWith', I.savedWith], ['library', I.library]]; +const COUNTS: Array<[string, string]> = [ + ['placements', I.placements], ['parts', I.parts], ['differentParts', I.different], ['colours', I.colours], ['pairs', I.pairs], + ['submodels', I.submodels], ['steps', I.steps], ['missing', I.missingCount], ['overlaps', I.overlaps], +]; +const SIZES: Array<[string, string]> = [['across', I.across], ['deep', I.deep], ['high', I.high]]; + +const fact = (key: string, label: string): string => `
${label}
`; + +function panel(): string { + const field = ([key, label, hint]: [Field, string, string]): string => [ + '', + ].join(''); + return [ + `
`, + `

${I.model}

`, + FIELDS.map(field).join(''), + ``, + '
', + `

${I.counts}

${COUNTS.map(([k, l]) => fact(k, l)).join('')}
`, + `

${I.size}

${SIZES.map(([k, l]) => fact(k, l)).join('')}
`, + `

${I.file}

${FACTS.map(([k, l]) => fact(k, l)).join('')}
`, + `

${I.missing}

    `, + '
    ', + ].join(''); +} + +const number = (n: number): string => (Number.isInteger(n) ? String(n) : String(Math.round(n * 100) / 100)); + +function sizeText(s: Size | null, axis: string): string { + if (!s) return I.nothing; + if (axis === 'high') return fill(I.bricks, { n: number(s.bricks), plates: number(s.plates), mm: number(s.mm.high) }); + const a = axis as 'across' | 'deep'; + return fill(I.studs, { n: number(s.studs[a]), mm: number(s.mm[a]) }); +} + +commands.add({ id: 'info.show', title: I.cmdShow.title, summary: I.cmdShow.summary, icon: 'info', group: S.group.model, run: () => showTab('info') }); + +tabHost('info', (host) => { + host.innerHTML = panel(); + const inputs = Object.fromEntries(FIELDS.map(([k]) => [k, q(host, `input[data-field="${k}"]`)])) as Record; + const licence = q(host, 'select[data-field="licence"]'); + const values = new Map(Array.from(host.querySelectorAll('dd[data-v]')).map((d) => [d.dataset.v ?? '', d])); + const none = q(host, '.ui-info-none'); + const missing = q(host, '.ui-info-missing'); + let info: Info | null = null; + + const put = (key: string, text: string): void => { + const node = values.get(key); + if (!node) return; + setText(node, text); + setTitle(node, text); + }; + + const paintField = (k: Field): void => { + const input = inputs[k]; + const v = info ? info[k] : ''; + if (document.activeElement !== input && input.value !== v) input.value = v; + input.disabled = !info; + }; + + const paintLicences = (list: string[]): void => { + const have = Array.from(licence.options).slice(1).map((o) => o.value); + if (have.join('|') !== list.join('|')) { + for (const o of Array.from(licence.options).slice(1)) o.remove(); + for (const name of list) licence.append(el(``)); + } + const v = info?.licence ?? ''; + const known = list.find((n) => n.toLowerCase() === v.toLowerCase()) ?? ''; + if (document.activeElement !== licence && licence.value !== known) licence.value = known; + licence.disabled = !info; + }; + + const paint = (): void => { + for (const [k] of FIELDS) paintField(k); + paintLicences(info?.licences ?? []); + const a = info; + put('path', a ? a.path ?? I.notSaved : ''); + put('format', a ? (a.kind ? I.kinds[a.kind] ?? a.kind : I.notSaved) : ''); + put('savedWith', a ? a.builtWith ?? I.notRecorded : ''); + put('library', a ? a.library ?? I.noLibrary : ''); + for (const [k] of COUNTS) { + const n = a?.counts[k]; + put(k, !a ? '' : n === null || n === undefined ? I.needsLibrary : String(n)); + } + for (const [k] of SIZES) put(k, a ? sizeText(a.size, k) : ''); + const lost = a?.missingParts ?? []; + setText(none, a && !lost.length ? I.noneMissing : ''); + setHidden(none, !a || lost.length > 0); + patchList(missing, lost, { + key: (m) => m.part.toLowerCase(), + create: () => el('
  • '), + update: (node, m) => { + setText(q(node, '.ui-info-lost-num'), m.part); + setText(q(node, '.ui-info-lost-count'), fill(I.needs, { n: m.count })); + setTitle(node, `${m.file} · ${fill(I.needs, { n: m.count })}`); + }, + }); + }; + + let busy = false; + let again = false; + let loaded = ''; + let edits = 0; + const want = (): string => { + const s = docStore.state; + return JSON.stringify([edits, s.path, s.kind, library.status?.update ?? '', !!library.status?.index_ready]); + }; + + const load = async (): Promise => { + if (busy) { again = true; return; } + busy = true; + try { + do { + again = false; + const asked = want(); + const got = await api.run('model.info', { table: false }); + info = got.result as Info; + loaded = asked; + paint(); + } while (again); + } catch (err) { + loaded = ''; + if (!(err instanceof ApiError && err.status === 0)) noticeError(err); + } finally { + busy = false; + } + }; + + const refresh = (): void => { + if (currentTab() !== 'info' || !docStore.ready) return; + if (want() !== loaded) void load(); + }; + + const commit = async (k: Field): Promise => { + const input = inputs[k]; + if (!info) return; + const next = input.value.trim(); + const was = info[k]; + if (next === was) { input.value = was; return; } + const ok = k === 'name' + ? await runCommand('submodel.rename', { name: info.name, new_name: next }) + : await runCommand('model.set_info', { [k]: next }); + if (!ok) { input.value = info[k]; return; } + edits++; + refresh(); + }; + + for (const [k] of FIELDS) { + const input = inputs[k]; + input.addEventListener('keydown', (e) => { + e.stopPropagation(); + if (e.key === 'Enter') { e.preventDefault(); input.blur(); } + if (e.key === 'Escape') { e.preventDefault(); input.value = info ? info[k] : ''; input.blur(); } + }); + input.addEventListener('change', () => { void commit(k); }); + } + licence.addEventListener('change', () => { + void runCommand('model.set_info', { licence: licence.value }).then((ok) => { + if (!ok) paintLicences(info?.licences ?? []); + edits++; + refresh(); + }); + }); + + docStore.onChange((change) => { + if (change.reset || change.submodels || change.touched.size || change.removed.size) edits++; + refresh(); + }); + library.onChange(() => refresh()); + onTabShown((tab) => { if (tab === 'info') refresh(); }); + paint(); + refresh(); +}); diff --git a/frontend/src/ui/mounts.ts b/frontend/src/ui/mounts.ts index 020b076..9693759 100644 --- a/frontend/src/ui/mounts.ts +++ b/frontend/src/ui/mounts.ts @@ -17,10 +17,12 @@ export interface Viewport { setDoc(doc: ModelDoc): void; applyChanges(changes: DocChanges): void; setSelection(ids: string[]): void; + setOverlaps(ids: string[]): void; setStep(index: number | null): void; setGhost(g: Ghost | null): void; fit(): void; setView(name: ViewName): void; + facing(): { right: number[]; into: number[] }; thumbnail(part: string, colour: number, px: number): Promise; refreshColours(): void; resize(): void; diff --git a/frontend/src/ui/overlaps.ts b/frontend/src/ui/overlaps.ts new file mode 100644 index 0000000..3ca896d --- /dev/null +++ b/frontend/src/ui/overlaps.ts @@ -0,0 +1,90 @@ +import { api } from '../io/api'; +import { settings } from '../io/settings'; +import { commands } from './commands'; +import { docStore } from './doc-store'; +import { el, q, setAttr, setClass, setText, setTitle } from './dom'; +import { icon } from './icons'; +import { viewport, whenViewport } from './model-view'; +import { notice, noticeError } from './notice'; +import { runCommand } from './run'; +import { onShellMounted } from './shell'; +import { S, fill } from './strings'; + +const T = S.status; + +interface Pair { a: string; b: string; depth: number; kind: string } +interface Checked { overlaps: Pair[]; count: number; nested_count: number; nested_listed: boolean; nested?: Pair[] } + +const nestedOn = (): boolean => settings.value.overlap_nested === true; + +function summary(found: Checked): string { + const deepest = Math.max(0, ...found.overlaps.map((p) => p.depth)); + const depth = Math.round(deepest * 10) / 10; + const real = found.count === 0 ? T.check.none : fill(found.count === 1 ? T.check.one : T.check.some, { n: found.count, depth }); + if (!found.nested_count) return `${real} · ${T.check.nestedNone}`; + return `${real} · ${fill(T.check.nested, { n: found.nested_count })} ${found.nested_listed ? T.check.counted : T.check.apart}`; +} + +async function review(): Promise { + try { + const found = (await api.run('overlap.check', {})).result as Checked; + const shown = [...found.overlaps, ...(found.nested ?? [])]; + await runCommand('select.set', { ids: [...new Set(shown.flatMap((p) => [p.a, p.b]))] }); + notice(summary(found), found.count ? 'info' : 'ok'); + } catch (err) { + noticeError(err); + } +} + +let marking = false; +let again = false; +let wasOn = false; + +async function mark(): Promise { + if (!settings.value.overlap) { viewport()?.setOverlaps([]); return; } + if (!viewport() || !docStore.ready) return; + if (marking) { again = true; return; } + marking = true; + try { + do { + again = false; + const found = (await api.run('overlap.check', { nested: false })).result as Checked; + viewport()?.setOverlaps(settings.value.overlap ? [...new Set(found.overlaps.flatMap((p) => [p.a, p.b]))] : []); + } while (again); + } catch { + viewport()?.setOverlaps([]); + } finally { + marking = false; + } +} + +docStore.onChange((c) => { + if (c.reset) viewport()?.setOverlaps([]); + if (c.reset || c.submodels || c.touched.size || c.removed.size) void mark(); +}); +settings.onChange(() => { + if (settings.value.overlap === wasOn) return; + wasOn = settings.value.overlap; + void mark(); +}); +whenViewport(() => { void mark(); }); + +commands.add( + { id: 'overlap.nested.toggle', title: T.nested.title, summary: T.nested.summary, icon: 'nested', group: S.group.view, run: () => { void runCommand('overlap.nested', { on: !nestedOn() }).then(() => settings.refresh()); } }, + { id: 'overlap.review', title: T.check.title, summary: T.check.summary, icon: 'overlap', group: S.group.model, run: () => { void review(); } }, +); + +onShellMounted(({ hosts }) => { + const b = el(``); + b.setAttribute('aria-label', T.nested.title); + q(hosts.status, '.ui-status-switches').append(b); + const paint = (): void => { + const on = nestedOn(); + setClass(b, 'is-on', on); + setAttr(b, 'aria-pressed', String(on)); + setText(q(b, '.ui-status-switch-text'), on ? T.nested.on : T.nested.off); + setTitle(b, T.nested.summary); + }; + paint(); + settings.onChange(paint); +}); diff --git a/frontend/src/ui/parts-list.ts b/frontend/src/ui/parts-list.ts index cc69bbd..84b0054 100644 --- a/frontend/src/ui/parts-list.ts +++ b/frontend/src/ui/parts-list.ts @@ -147,12 +147,8 @@ function panel(): string { return [ '
    ', '
    ', - ``, - actButton('copy', T.copy, 'duplicate'), - actButton('save', T.save, 'save'), - '
    ', - '
    ', - ``, + ``, + ``, ``, '
    ', `
    ${COLUMNS.map(sortButton).join('')}
    `, @@ -161,6 +157,8 @@ function panel(): string { '
    ', '', '', + actButton('copy', T.copy, 'duplicate'), + actButton('save', T.save, 'save'), '
    ', '
    ', ].join(''); diff --git a/frontend/src/ui/placing.ts b/frontend/src/ui/placing.ts index 1a345eb..707031f 100644 --- a/frontend/src/ui/placing.ts +++ b/frontend/src/ui/placing.ts @@ -1,5 +1,7 @@ import { api, call, type Pose, type Ray } from '../io/api'; +import { settings } from '../io/settings'; import { setDragPort, setHoldingCopies, showDragGhosts, type DragGhost } from '../view/drag-hub'; +import { previewTurn, setDialState, setPointPick, setTurnPort, showDial, type DialAxis } from '../view/turn-hub'; import { currentColour, onCurrentColour } from './current-colour'; import { docStore } from './doc-store'; import { store, stored } from './dom'; @@ -46,8 +48,9 @@ export function onPointerPlace(fn: (at: number[] | null) => void): void { where. function quarter(axis: Axis, turns: number): number[] { const t = ((turns % 4) + 4) % 4; - const c = [1, 0, -1, 0][t] ?? 1; - const s = [0, 1, 0, -1][t] ?? 0; + const whole = Number.isInteger(t); + const c = whole ? [1, 0, -1, 0][t] ?? 1 : Math.cos((t * Math.PI) / 2); + const s = whole ? [0, 1, 0, -1][t] ?? 0 : Math.sin((t * Math.PI) / 2); if (axis === 'x') return [1, 0, 0, 0, c, -s, 0, s, c]; if (axis === 'y') return [c, 0, s, 0, 1, 0, -s, 0, c]; return [c, -s, 0, s, c, 0, 0, 0, 1]; @@ -250,6 +253,7 @@ function pump(d: Dragging): void { function endDrag(d: Dragging): void { if (drag !== d) return; drag = null; + paintDial(); d.token = ++serial; d.show(null); for (const fn of where) fn(null); @@ -328,6 +332,7 @@ export function holdCopies(): boolean { drag = { grab, ids, copy: true, hold: true, rotation: sceneRotation(grabbed.matrix), turned: false, token: ++serial, ray: null, press: null, held: null, free: false, blocked: false, show: showDragGhosts, shown: null, busy: null, queued: false }; setHoldingCopies(true); setPicking(true); + paintDial(); tell(fill(S.place.holdingCopies, { count: countOf(ids.length) })); return true; } @@ -352,6 +357,7 @@ setDragPort({ } const d: Dragging = { grab: how.grab, ids, copy: how.copy, rotation: sceneRotation(grabbed.matrix), turned: false, token: ++serial, ray: null, press: how.press, held: null, free: false, blocked: false, show, shown: null, busy: null, queued: false }; drag = d; + paintDial(); tell(fill(how.copy ? S.place.copying : S.place.moving, { count: countOf(ids.length) })); return { move(ray, free) { @@ -369,3 +375,197 @@ setDragPort({ }; }, }); + +export const ANGLE_STEPS = [90, 45, 22.5, 15, 5, 1]; + +export function angleStep(): number { + const v = Number(settings.value['angle_step']); + return ANGLE_STEPS.includes(v) ? v : 90; +} + +export function nextAngleStep(): number { + const at = ANGLE_STEPS.indexOf(angleStep()); + return ANGLE_STEPS[(at + 1) % ANGLE_STEPS.length] ?? 90; +} + +interface PivotAxis { name: string; axis: number[]; scene: number[] } +interface Pivot { ids: string[]; kind: string; about: number[]; scene: number[]; axes: PivotAxis[]; reach: number } +interface TurnAnswer { blocked: boolean; lifted: number; up: number[] } + +interface Turning { + ids: string[]; + axis: PivotAxis; + about: number[]; + point: number[]; + shown: number; + good: number; + up: number[]; + blocked: boolean; + asking: number | null; + queued: number | null; + token: number; +} + +let tool = false; +let pivot: Pivot | null = null; +let pivotToken = 0; +let turning: Turning | null = null; +const NO_LIFT = [0, 0, 0]; + +export const pivotTool = (): boolean => tool; + +function dialAxes(p: Pivot): PivotAxis[] { + if (p.kind !== 'centre' || tool) return p.axes; + return p.axes.filter((a) => a.name === 'y'); +} + +function paintDial(): void { + const p = pivot; + if (!p || held || drag) { showDial(null); return; } + const axes: DialAxis[] = dialAxes(p).map((a) => ({ name: a.name, axis: a.scene })); + showDial({ point: p.scene, axes, reach: p.reach }); +} + +async function askPivot(): Promise { + const ids = docStore.state.selection.filter((id) => docStore.placements.get(id)?.hidden === false); + const token = ++pivotToken; + if (!ids.length) { + pivot = null; + paintDial(); + return; + } + try { + const answer = await api.run('part.pivot', { ids }); + if (token !== pivotToken || turning) return; + pivot = answer.result as Pivot; + } catch { + if (token !== pivotToken) return; + pivot = null; + } + paintDial(); +} + +export function togglePivotTool(on = !tool): void { + if (on === tool) return; + tool = on; + if (!on && pivot?.kind === 'point') void askPivot(); + else paintDial(); +} + +async function askPivotAt(ray: Ray): Promise { + const ids = pivot?.ids ?? []; + const token = ++pivotToken; + try { + const answer = await api.run('part.pivot', { ids, origin: ray.origin, direction: ray.dir }); + if (token !== pivotToken || turning) return; + pivot = answer.result as Pivot; + paintDial(); + } catch { + if (token === pivotToken) void askPivot(); + } +} + +setPointPick((ray) => { + if (!tool || !pivot || turning || held || drag) return false; + void askPivotAt(ray); + return true; +}); + +docStore.onChange((c) => { + if (turning) return; + const chosen = docStore.state.selection; + const was = c.before?.selection ?? []; + const same = chosen.length === was.length && chosen.every((id, i) => id === was[i]); + if (same && !c.reset && pivot?.kind === 'point' && !chosen.some((id) => c.removed.has(id))) return; + const moved = chosen.some((id) => c.touched.has(id) || c.removed.has(id)); + if (c.reset || moved || !same) void askPivot(); +}); + +onPick(() => paintDial()); + +function showTurn(t: Turning, degrees: number, up: number[]): void { + previewTurn({ ids: t.ids, axis: t.axis.scene, point: t.point, degrees, up }); + setDialState({ up, blocked: t.blocked }); + const words = { count: countOf(t.ids.length), angle: Math.round(degrees * 100) / 100, axis: S.turn.axes[t.axis.name] ?? t.axis.name }; + tell(fill(t.blocked ? S.turn.blocked : S.turn.turning, words)); +} + +async function askTurn(t: Turning, degrees: number): Promise { + t.asking = degrees; + try { + const answer = await call('POST', '/api/place/turn', { ids: t.ids, axis: t.axis.axis, angle: degrees, about: t.about }); + if (turning !== t || t.shown !== degrees) return; + if (!answer.blocked) { + t.good = degrees; + t.up = answer.up; + } + t.blocked = answer.blocked; + showTurn(t, t.good, t.up); + } catch (err) { + if (turning === t) { noticeError(err); endTurn(t); } + } finally { + t.asking = null; + const next = t.queued; + t.queued = null; + if (next !== null && turning === t) void askTurn(t, next); + } +} + +function endTurn(t: Turning): void { + if (turning !== t) return; + turning = null; + t.token = ++serial; + previewTurn(null); + setDialState(null); + noticeOver(told); + if (pivot?.kind === 'point') paintDial(); + else void askPivot(); +} + +async function putTurn(t: Turning): Promise { + while (t.asking !== null || t.queued !== null) await new Promise((r) => window.setTimeout(r, 16)); + if (turning !== t) return; + const angle = t.good; + if (Math.abs(angle % 360) < 1e-9) { endTurn(t); return; } + if (t.blocked && t.shown !== t.good) notice(fill(S.turn.blocked, { count: countOf(t.ids.length), angle }), 'error'); + const changed = settled(); + if (await runCommand('part.rotate', { ids: t.ids, axis_vector: t.axis.axis, angle, about: t.about })) await changed; + endTurn(t); +} + +export function cancelTurn(): boolean { + if (!turning) return false; + endTurn(turning); + return true; +} + +setTurnPort({ + begin(ring) { + const p = pivot; + if (!p || turning || held || drag) return null; + const axis = dialAxes(p)[ring]; + if (!axis) return null; + const t: Turning = { ids: p.ids.slice(), axis, about: p.about, point: p.scene, shown: 0, good: 0, up: NO_LIFT, blocked: false, asking: null, queued: null, token: ++serial }; + turning = t; + setDialState({ active: ring, blocked: false, up: NO_LIFT }); + showTurn(t, 0, NO_LIFT); + return { + move(raw, free) { + if (turning !== t) return; + const step = free ? 1 : angleStep(); + const degrees = Math.round(raw / step) * step + 0; + if (degrees === t.shown) return; + t.shown = degrees; + if (!settings.value.overlap && t.axis.name !== 'hinge') showTurn(t, degrees, t.up); + if (t.asking !== null) t.queued = degrees; + else void askTurn(t, degrees); + }, + drop() { + void putTurn(t); + }, + cancel() { + endTurn(t); + }, + }; + }, +}); diff --git a/frontend/src/ui/prefs.ts b/frontend/src/ui/prefs.ts index fc20d94..e03300e 100644 --- a/frontend/src/ui/prefs.ts +++ b/frontend/src/ui/prefs.ts @@ -91,23 +91,27 @@ class Preferences extends Dialog { grid.addEventListener('change', () => { void runCommand('grid.step', { step: grid.value }).then(() => settings.refresh()); }); const overlap = toggle(T.overlap.label); overlap.addEventListener('change', () => { void runCommand('overlap.set', { on: overlap.checked }).then(() => settings.refresh()); }); + const nested = toggle(T.nested.label); + nested.addEventListener('change', () => { void runCommand('overlap.nested', { on: nested.checked }).then(() => settings.refresh()); }); this.rows('general').append( row('drop', T.keep.label, T.keep.note, keep), row('snap', T.snap.label, T.snap.note, snap), row('grid', T.grid.label, T.grid.note, grid), row('overlap', T.overlap.label, T.overlap.note, overlap), + row('overlap nested hollow', T.nested.label, T.nested.note, nested), ); const paint = (): void => { keep.checked = keepHolding(); snap.checked = settings.value.snap; grid.value = settings.value.grid_step; overlap.checked = settings.value.overlap; + nested.checked = settings.value.overlap_nested === true; }; settings.onChange(paint); paint(); this.reset('general', () => { setKeepHolding(true); - void Promise.all([runCommand('snap.set', { on: true }), runCommand('grid.step', { step: 'stud' }), runCommand('overlap.set', { on: false })]).then(() => settings.refresh()); + void Promise.all([runCommand('snap.set', { on: true }), runCommand('grid.step', { step: 'stud' }), runCommand('overlap.set', { on: false }), runCommand('overlap.nested', { on: false })]).then(() => settings.refresh()); paint(); }); } diff --git a/frontend/src/ui/shell.ts b/frontend/src/ui/shell.ts index ed0fe53..3b19bf4 100644 --- a/frontend/src/ui/shell.ts +++ b/frontend/src/ui/shell.ts @@ -1,6 +1,17 @@ import { q } from './dom'; import { icon } from './icons'; -import { S } from './strings'; +import { S, fill } from './strings'; + +const head = (sec: 'colours' | 'details', label: string): string => [ + `
    `, + '

    ', + `', + '

    ', +].join(''); const SHELL = `
    @@ -15,9 +26,9 @@ const SHELL = `
    +
    +${head('details', S.region.details)}
    @@ -39,6 +50,7 @@ export interface ShellHosts { colours: HTMLElement; tabs: HTMLElement; details: HTMLElement; + summaries: { colours: HTMLElement; details: HTMLElement }; strip: HTMLElement; status: HTMLElement; } @@ -75,6 +87,7 @@ export function mountShell(appHost: HTMLElement): AppContext { colours: q(root, '.ui-colours'), tabs: q(root, '.ui-tabs'), details: q(root, '.ui-details'), + summaries: { colours: q(root, '[data-sec="colours"] .ui-sec-sum'), details: q(root, '[data-sec="details"] .ui-sec-sum') }, strip: q(root, '.ui-strip'), status: q(root, '.ui-status'), }; diff --git a/frontend/src/ui/side-panel.ts b/frontend/src/ui/side-panel.ts index 995146d..05cde3b 100644 --- a/frontend/src/ui/side-panel.ts +++ b/frontend/src/ui/side-panel.ts @@ -35,7 +35,11 @@ onShellMounted(({ hosts }) => { get: (path) => api.get(path), put: (path, body) => api.put(path, body), thumbnail, - onChoose: (part) => pick(part), + onChoose: (part) => { + pick(part); + const typing = document.activeElement; + if (typing instanceof HTMLInputElement && hosts.panel.contains(typing)) typing.blur(); + }, }); } catch (err) { noticeError(err); diff --git a/frontend/src/ui/splits.ts b/frontend/src/ui/splits.ts index ef34b17..7ce03fa 100644 --- a/frontend/src/ui/splits.ts +++ b/frontend/src/ui/splits.ts @@ -1,15 +1,108 @@ -import { store, stored } from './dom'; +import { settings } from '../io/settings'; +import { commands } from './commands'; +import { setAttr, setHidden, setTitle, store, stored } from './dom'; import { onShellMounted } from './shell'; -import { S } from './strings'; +import { S, fill } from './strings'; -interface Edge { name: 'colours' | 'details'; prop: string; key: string; grows: 1 | -1; node: HTMLElement } +export type Section = 'colours' | 'tabs' | 'details'; +type Sized = 'colours' | 'details'; +export interface ColumnLayout { colours: number | null; details: number | null; closed: Section[]; tab: string | null } +interface Edge { name: Sized; prop: string; grows: 1 | -1; node: HTMLElement } const STEP = 16; +const SECTIONS: Section[] = ['colours', 'tabs', 'details']; +const GROWERS: Section[] = ['tabs', 'colours', 'details']; +const MIRROR = 'formblocks.rightColumn'; +const FIRST: ColumnLayout = { colours: null, details: null, closed: [], tab: null }; +const SAVE_MS = 400; function length(el: HTMLElement, prop: string): number { return parseFloat(getComputedStyle(el).getPropertyValue(prop)) || 0; } +const height = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v > 0 && v <= 4000 ? v : null); + +function readLayout(raw: unknown): ColumnLayout { + if (!raw || typeof raw !== 'object') return { ...FIRST, closed: [] }; + const r = raw as Record; + const closed = Array.isArray(r.closed) ? SECTIONS.filter((s) => (r.closed as unknown[]).includes(s)) : []; + return { colours: height(r.colours), details: height(r.details), closed, tab: typeof r.tab === 'string' ? r.tab : null }; +} + +function fromMirror(): ColumnLayout { + try { + const kept = stored(MIRROR); + if (kept) return readLayout(JSON.parse(kept)); + } catch { return { ...FIRST, closed: [] }; } + const old = (key: string): number | null => height(Math.round(parseFloat(stored(key) ?? ''))); + return { ...FIRST, closed: [], colours: old('formblocks.split.colours'), details: old('formblocks.split.details') }; +} + +const sameLayout = (a: ColumnLayout, b: ColumnLayout): boolean => JSON.stringify(a) === JSON.stringify(b); + +let layout = fromMirror(); +const opened: Section[] = []; +let squeezed = new Set
    (); +let apply: () => void = () => undefined; +const listeners = new Set<(l: ColumnLayout) => void>(); +let saving = 0; +let synced = false; + +export const columnLayout = (): ColumnLayout => layout; +export const isFolded = (s: Section): boolean => layout.closed.includes(s) || squeezed.has(s); + +export function onColumn(fn: (l: ColumnLayout) => void): void { listeners.add(fn); } + +function keep(next: ColumnLayout, engine = true): void { + layout = next; + store(MIRROR, JSON.stringify(next)); + if (!engine || !synced) return; + window.clearTimeout(saving); + saving = window.setTimeout(() => { void settings.set({ right_column: layout }); }, SAVE_MS); +} + +export function keepTab(tab: string): void { + if (layout.tab !== tab) keep({ ...layout, tab }); +} + +export function openSection(s: Section): void { + if (!isFolded(s)) return; + opened.splice(0, opened.length, ...opened.filter((o) => o !== s), s); + if (layout.closed.includes(s)) keep({ ...layout, closed: layout.closed.filter((c) => c !== s) }); + apply(); +} + +export function toggleSection(s: Section): void { + if (isFolded(s)) { openSection(s); return; } + keep({ ...layout, closed: SECTIONS.filter((c) => c === s || layout.closed.includes(c)) }); + apply(); +} + +commands.add({ + id: 'view.layout_reset', + title: S.column.reset.title, + summary: S.column.reset.summary, + icon: 'columns', + group: S.group.view, + run: () => { + opened.splice(0); + keep({ ...FIRST, closed: [], tab: layout.tab }); + apply(); + }, +}); + +settings.onChange((s) => { + if (synced) return; + synced = true; + const theirs = readLayout(s.right_column); + if (sameLayout(theirs, layout)) return; + if (sameLayout(theirs, FIRST)) { keep(layout); return; } + if (document.body.classList.contains('app-ready')) { store(MIRROR, JSON.stringify(theirs)); return; } + keep(theirs, false); + apply(); + for (const fn of listeners) fn(layout); +}); + onShellMounted(({ hosts }) => { const right = hosts.right; const edge = (name: Edge['name'], grows: Edge['grows'], label: string): Edge => { @@ -21,34 +114,91 @@ onShellMounted(({ hosts }) => { node.setAttribute('aria-label', label); node.title = S.split.hint; right.append(node); - return { name, prop: `--ui-${name}-h`, key: `formblocks.split.${name}`, grows, node }; + return { name, prop: `--ui-${name}-h`, grows, node }; }; const edges = [edge('colours', 1, S.split.colours), edge('details', -1, S.split.details)]; - const host = (e: Edge): HTMLElement => (e.name === 'colours' ? hosts.colours : hosts.details); - const other = (e: Edge): Edge => (e === edges[0] ? edges[1]! : edges[0]!); + const sections = Object.fromEntries(SECTIONS.map((s) => [s, right.querySelector(`.ui-sec[data-sec="${s}"]`)!])) as Record; + const bodies = Object.fromEntries(SECTIONS.map((s) => [s, sections[s].querySelector('.ui-sec-body')!])) as Record; + const host = (e: Edge): HTMLElement => sections[e.name]; + + const measure = (): { size: Record; least: Record; grow: Section | null; squeeze: Set
    } => { + const tall = right.clientHeight; + const headH = length(right, '--sec-head-h'); + const head: Record = { colours: headH, tabs: length(right, '--tab-h'), details: headH }; + const least: Record = { colours: length(right, '--colours-min'), tabs: length(right, '--tabs-min'), details: length(right, '--details-min') }; + const most: Record = { colours: length(right, '--colours-max'), tabs: Infinity, details: length(right, '--details-max') }; + const want: Record = { colours: layout.colours ?? length(right, '--colours-h'), tabs: 0, details: layout.details ?? length(right, '--details-h') }; + const open = SECTIONS.filter((s) => !layout.closed.includes(s)); + const grow = GROWERS.find((s) => open.includes(s)) ?? null; + const size = {} as Record; + for (const s of SECTIONS) size[s] = !open.includes(s) ? head[s] : s === grow ? least[s] : Math.min(most[s], Math.max(least[s], want[s])); + const order = (['details', 'colours'] as Section[]).filter((s) => open.includes(s) && s !== grow).sort((a, b) => opened.indexOf(a) - opened.indexOf(b)); + let over = SECTIONS.reduce((sum, s) => sum + size[s], 0) - tall; + for (const s of order) { + if (over <= 0) break; + const cut = Math.min(over, size[s] - least[s]); + size[s] -= cut; + over -= cut; + } + const squeeze = new Set
    (); + for (const s of order) { + if (over <= 0) break; + over -= size[s] - head[s]; + size[s] = head[s]; + squeeze.add(s); + } + return { size, least, grow, squeeze }; + }; - const limits = (e: Edge): [number, number] => { - const least = length(right, '--split-min'); - const room = right.clientHeight - host(other(e)).offsetHeight - length(right, '--split-tabs-min'); - return [least, Math.max(least, room)]; + const setVar = (prop: string, value: string): void => { + if (right.style.getPropertyValue(prop) !== value) right.style.setProperty(prop, value); }; - const set = (e: Edge, size: number, keep: boolean): void => { - const [lo, hi] = limits(e); - const value = `${Math.round(Math.min(hi, Math.max(lo, size)))}px`; - if (right.style.getPropertyValue(e.prop) !== value) right.style.setProperty(e.prop, value); - e.node.setAttribute('aria-valuenow', String(parseInt(value, 10))); - if (keep) store(e.key, value); + apply = (): void => { + const { size, grow, squeeze } = measure(); + squeezed = squeeze; + for (const s of SECTIONS) { + const fold = layout.closed.includes(s) ? 'closed' : squeeze.has(s) ? 'squeezed' : 'open'; + setVar(`--ui-${s}-row`, s === grow ? 'minmax(0, 1fr)' : `${Math.round(size[s])}px`); + setAttr(sections[s], 'data-fold', fold); + const name = S.column[s]; + for (const b of sections[s].querySelectorAll(`[data-fold="${s}"]`)) { + setAttr(b, 'aria-expanded', String(fold === 'open')); + setTitle(b, fill(fold === 'open' ? S.column.fold : fold === 'closed' ? S.column.open : S.column.squeezed, { name })); + } + const panes = s === 'tabs' ? Array.from(bodies.tabs.querySelectorAll('.ui-tabpanel')) : [bodies[s]]; + for (const p of panes) if (p.inert !== (fold !== 'open')) p.inert = fold !== 'open'; + } + for (const e of edges) { + setVar(e.prop, `${Math.round(size[e.name])}px`); + setHidden(e.node, isFolded(e.name) || e.name === grow); + setAttr(e.node, 'aria-valuenow', String(Math.round(size[e.name]))); + } + }; + + const set = (e: Edge, want: number, persist: boolean): void => { + const { size, least, grow } = measure(); + const others = SECTIONS.reduce((sum, s) => (s === e.name ? sum : sum + (s === grow ? least[s] : size[s])), 0); + const lo = length(right, `--${e.name}-min`); + const hi = Math.min(length(right, `--${e.name}-max`), right.clientHeight - others); + const next = Math.round(Math.max(lo, Math.min(hi, want))); + if (layout[e.name] !== next) layout = { ...layout, [e.name]: next }; + apply(); + if (persist) keep(layout); }; const reset = (e: Edge): void => { - right.style.removeProperty(e.prop); - store(e.key, ''); + keep({ ...layout, [e.name]: null }); + apply(); }; + right.addEventListener('click', (event) => { + const s = (event.target as HTMLElement).closest('button[data-fold]')?.dataset.fold as Section | undefined; + if (s && SECTIONS.includes(s)) toggleSection(s); + }); + + apply(); for (const e of edges) { - const saved = parseFloat(stored(e.key) ?? ''); - if (Number.isFinite(saved) && saved > 0) set(e, saved, false); let start = 0; let from = 0; e.node.addEventListener('pointerdown', (event) => { @@ -80,7 +230,5 @@ onShellMounted(({ hosts }) => { set(e, host(e).offsetHeight + by * e.grows, true); }); } - new ResizeObserver(() => { - for (const e of edges) if (right.style.getPropertyValue(e.prop)) set(e, host(e).offsetHeight, false); - }).observe(right); + new ResizeObserver(() => apply()).observe(right); }); diff --git a/frontend/src/ui/status.ts b/frontend/src/ui/status.ts index a4dda17..280d8d5 100644 --- a/frontend/src/ui/status.ts +++ b/frontend/src/ui/status.ts @@ -10,7 +10,7 @@ import { el, q, setAttr, setClass, setText, setTitle } from './dom'; import { icon } from './icons'; import { onViewportHover } from './model-view'; import { onNotice, type Tone } from './notice'; -import { onPointerPlace } from './placing'; +import { angleStep, onPointerPlace } from './placing'; import { runCommand } from './run'; import { S, fill, plural } from './strings'; @@ -80,7 +80,8 @@ onShellMounted(({ hosts }) => { const snap = switchButton('snap.toggle', 'is-snap'); const grid = switchButton('grid.next', 'is-grid'); const overlap = switchButton('overlap.toggle', 'is-overlap'); - q(bar, '.ui-status-switches').append(snap, grid, overlap); + const angle = switchButton('angle.next', 'is-angle'); + q(bar, '.ui-status-switches').append(snap, grid, angle, overlap); setText(q(bar, '.ui-status-version'), `${S.app} ${VERSION}`); const paintLink = (s: LinkState): void => { @@ -99,6 +100,8 @@ onShellMounted(({ hosts }) => { setTitle(snap, `${T.snap.summary} · ${keyLabel('S')}`); setText(q(grid, '.ui-status-switch-text'), T.gridSteps[v.grid_step]); setTitle(grid, `${T.grid.summary} · ${keyLabel('G')}`); + setText(q(angle, '.ui-status-switch-text'), fill(S.turn.degrees, { n: angleStep() })); + setTitle(angle, `${S.turn.next.summary} · ${keyLabel('A')}`); setClass(overlap, 'is-on', v.overlap); setAttr(overlap, 'aria-pressed', String(v.overlap)); setText(q(overlap, '.ui-status-switch-text'), v.overlap ? T.overlap.on : T.overlap.off); diff --git a/frontend/src/ui/strings.ts b/frontend/src/ui/strings.ts index 2ce45bf..3ba6dda 100644 --- a/frontend/src/ui/strings.ts +++ b/frontend/src/ui/strings.ts @@ -7,7 +7,7 @@ export const S = { viewport: 'Viewport', right: 'Colours, model and details', colours: 'Colour palette', - tabs: 'Model, steps and parts', + tabs: 'Model, steps, parts and information', details: 'Details', strip: 'Steps', status: 'Status', @@ -19,6 +19,15 @@ export const S = { details: 'Height of the details panel', hint: 'Drag to resize, or use the Up and Down keys; double-click to restore', }, + column: { + colours: 'Colours', + tabs: 'Tabs', + details: 'Details', + fold: 'Fold {name} to its header', + open: 'Open {name}', + squeezed: '{name} is folded for lack of height; open it to fold another section instead', + reset: { title: 'Reset Right Column', summary: 'Open the colour palette, the tabs and the details panel again at their first heights.' }, + }, keys: { ArrowLeft: 'Left', ArrowRight: 'Right', ArrowUp: 'Up', ArrowDown: 'Down', ',': 'Comma', '.': 'Full stop', '\\': 'Backslash', Escape: 'Esc', Delete: 'Delete', Backspace: 'Backspace', Enter: 'Enter', Home: 'Home', End: 'End', Space: 'Space' } as Record, keyMod: { mac: 'Cmd', other: 'Ctrl' }, keyAlt: { mac: 'Option', other: 'Alt' }, @@ -74,12 +83,15 @@ export const S = { gridSteps: { stud: 'Stud', plate: 'Plate', fine: 'Fine' } as Record, snap: { title: 'Snap', summary: 'Let parts seat on each other\'s studs. With it off, parts follow the grid only.', on: 'Snap on', off: 'Snap off' }, grid: { title: 'Next Grid Step', summary: 'The size of a move when a part does not seat: Stud, Plate or Fine.' }, - overlap: { title: 'Overlap Check', summary: 'Keep parts from being put inside each other. The check is coarse: a guide, not a proof that a model can be built.', on: 'Overlap on', off: 'Overlap off' }, + overlap: { title: 'Overlap Check', summary: 'Keep parts from being put inside each other: a part may not cut more than 1 LDU into another. A guide, not a proof that a model can be built.', on: 'Overlap on', off: 'Overlap off' }, + nested: { title: 'Report Nested Pairs', summary: 'Also report parts that sit in another part\'s hollow by design, such as a rim in its tyre or a pin in its hole. They never block placing either way. Off is the proposed default.', on: 'Nested on', off: 'Nested off' }, + check: { title: 'Show Overlaps', summary: 'Check the whole model, select the parts that overlap, and say how many nested pairs there are; with Report Nested Pairs on, select those too.', none: '0 overlaps', some: '{n} overlaps, deepest {depth} LDU', one: '1 overlap, {depth} LDU deep', nested: '{n} nested', nestedNone: '0 nested', counted: 'selected', apart: 'apart' }, }, - tabs: { model: 'Model', steps: 'Steps', parts: 'Parts' }, + tabs: { model: 'Model', steps: 'Steps', parts: 'Parts', info: 'Info' }, partsList: { label: 'Parts list', filter: 'Filter by name, number or colour', + filterShort: 'Filter rows', scope: 'Which parts to count', scopes: { model: 'Whole model', submodel: 'This submodel', step: 'Up to this step', this_step: 'This step only' } as Record, asRows: 'Count each submodel as one row', @@ -144,7 +156,8 @@ export const S = { keep: { label: 'Another copy waits after a drop', note: 'After a part is dropped, another of the same part stays under the pointer until Esc.' }, snap: { label: 'Snap', note: 'Parts seat on each other\'s studs. Kept for new models.' }, grid: { label: 'Grid step', note: 'How far a part moves when it does not seat: Stud 20 LDU, Plate 10, Fine 1.' }, - overlap: { label: 'Overlap check', note: 'Keep parts from being put inside each other. The check is coarse: a guide, not a proof.' }, + overlap: { label: 'Overlap check', note: 'Keep parts from being put inside each other: a part may not cut more than 1 LDU into another. A guide, not a proof.' }, + nested: { label: 'Report nested pairs', note: 'Also report parts that sit in another part\'s hollow by design, such as a rim in its tyre. Off reports only real overlaps, the proposed default.' }, theme: { label: 'Theme', note: 'The window\'s colours.', dark: 'Dark', light: 'Light' }, keysLead: 'The keys every command answers to. They work when the cursor is not in a text field.', dockKey: 'Show or Hide the Agent Dock', @@ -329,6 +342,20 @@ export const S = { one: '1 part', many: '{n} parts', }, + turn: { + turning: 'Turning {count} {angle}° about {axis}: let go to put down, Shift for whole degrees, Esc to put back.', + blocked: 'Turning {count} stopped at {angle}°: further would overlap another part.', + axes: { x: 'X', y: 'Y', z: 'Z', hinge: 'the hinge' } as Record, + degrees: '{n}°', + next: { title: 'Next Angle Step', summary: 'The step a turn on the pivot dial moves in, and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees.' }, + pivot: { title: 'Pivot Tool', summary: 'Show the pivot dial\'s three rings, one for each axis, to turn the selection about any of them; again to go back to the one ring about the up axis.' }, + by: { title: 'Turn by the Angle Step', summary: 'Turn the selection clockwise, seen from above, by the angle step shown in the status bar.' }, + byBack: { title: 'Turn Back by the Angle Step', summary: 'Turn the selection anticlockwise, seen from above, by the angle step.' }, + tip: { title: 'Tip by the Angle Step', summary: 'Tip the selection about the left to right axis by the angle step.' }, + tipBack: { title: 'Tip Back by the Angle Step', summary: 'Tip the selection back about the left to right axis by the angle step.' }, + roll: { title: 'Roll by the Angle Step', summary: 'Roll the selection about the front to back axis by the angle step.' }, + rollBack: { title: 'Roll Back by the Angle Step', summary: 'Roll the selection back about the front to back axis by the angle step.' }, + }, refused: '{why} ({command}).', common: { theme: { title: 'Switch Theme', summary: 'Switch the window between the dark and the light theme. The choice is kept for the next start.' }, diff --git a/frontend/src/ui/tabs.ts b/frontend/src/ui/tabs.ts index 63a7327..d520d3c 100644 --- a/frontend/src/ui/tabs.ts +++ b/frontend/src/ui/tabs.ts @@ -1,16 +1,17 @@ -import { q, setAttr, setHidden, store, stored } from './dom'; +import { q, setAttr, setHidden, stored } from './dom'; +import { icon } from './icons'; import { onShellMounted } from './shell'; -import { S } from './strings'; +import { columnLayout, isFolded, keepTab, onColumn, openSection } from './splits'; +import { S, fill } from './strings'; -export type TabName = 'model' | 'steps' | 'parts'; +export type TabName = 'model' | 'steps' | 'parts' | 'info'; -const KEY = 'formblocks.rightTab'; -const NAMES: TabName[] = ['model', 'steps', 'parts']; +const NAMES: TabName[] = ['model', 'steps', 'parts', 'info']; const isTab = (v: string | null | undefined): v is TabName => NAMES.includes(v as TabName); const hosts = new Map(); const waiting = new Map void>>(); const shown = new Set<(tab: TabName) => void>(); -const kept = stored(KEY); +const kept = columnLayout().tab ?? stored('formblocks.rightTab'); let current: TabName = isTab(kept) ? kept : 'model'; export const currentTab = (): TabName => current; @@ -27,18 +28,26 @@ export function tabHost(name: TabName, fn: (host: HTMLElement) => void): void { let show: (name: TabName) => void = () => undefined; -export function showTab(name: TabName): void { show(name); } +export function showTab(name: TabName): void { + openSection('tabs'); + show(name); +} onShellMounted(({ hosts: shell }) => { const box = shell.tabs; const bar = NAMES.map((n) => ``).join(''); const panels = NAMES.map((n) => `
    `).join(''); - box.innerHTML = `
    ${bar}
    ${panels}`; + const fold = [ + `', + ].join(''); + box.innerHTML = `
    ${bar}
    ${fold}
    ${panels}`; const panes = Object.fromEntries(NAMES.map((n) => [n, q(box, `.ui-tabpanel[data-tab="${n}"]`)])) as Record; const tabs = Object.fromEntries(NAMES.map((n) => [n, q(box, `.ui-tab[data-tab="${n}"]`)])) as Record; show = (name: TabName): void => { current = name; - store(KEY, name); + keepTab(name); for (const n of NAMES) { setHidden(panes[n], n !== name); setAttr(tabs[n], 'aria-selected', String(n === name)); @@ -48,7 +57,7 @@ onShellMounted(({ hosts: shell }) => { }; q(box, '.ui-tabbar').addEventListener('click', (e) => { const t = (e.target as HTMLElement).closest('.ui-tab')?.dataset.tab; - if (isTab(t)) show(t); + if (isTab(t)) showTab(t); }); q(box, '.ui-tabbar').addEventListener('keydown', (e) => { const step = { ArrowLeft: -1, ArrowRight: 1 }[e.key]; @@ -56,10 +65,12 @@ onShellMounted(({ hosts: shell }) => { if (step === undefined && edge === undefined) return; e.preventDefault(); const next: TabName = edge ?? (NAMES[(NAMES.indexOf(current) + (step ?? 0) + NAMES.length) % NAMES.length] as TabName); - show(next); + showTab(next); tabs[next].focus(); }); + onColumn((l) => { if (isTab(l.tab) && l.tab !== current) show(l.tab); }); show(current); + if (isFolded('tabs')) for (const n of NAMES) panes[n].inert = true; for (const n of NAMES) { hosts.set(n, panes[n]); for (const fn of waiting.get(n) ?? []) fn(panes[n]); diff --git a/frontend/src/version.ts b/frontend/src/version.ts index 465e390..243bfad 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.4.0'; +export const VERSION = '0.5.0'; diff --git a/frontend/src/view/HASHOUT_LOG.md b/frontend/src/view/HASHOUT_LOG.md index 9a4ff1c..1be804e 100644 --- a/frontend/src/view/HASHOUT_LOG.md +++ b/frontend/src/view/HASHOUT_LOG.md @@ -2,6 +2,18 @@ Why the 3D view is the way it is. Newest entry first. +## A plain click can be taken by the pivot tool before it selects · 0.5.0 (gestures.ts, turn-wire.ts, turn-hub.ts) + +With the pivot tool on, `SPEC.md` 5.2 sets the pivot where the person clicks. A plain left click (no Shift, no Ctrl, not placing) is first offered to the hub as a pointer ray through the gestures' `turn` handler with the phase `point`; the window's placing module takes it only while the pivot tool is on and something is selected, and then the click selects nothing. The view hands over the ray in the scene's axes and nothing else, since the engine picks the part and the point. Shift and Ctrl clicks still add and toggle as before, so the selection can be changed without leaving the tool. + +## The pivot dial is three fat lines made once, hit in screen pixels, and read by the plane of its ring · 0.5.0 (turn-dial.ts, turn-hub.ts, turn-wire.ts, gestures.ts, viewport.css) + +`SPEC.md` 5.2 (decided in 0.5.0). The dial is three `Line2` circles with `LineMaterial` from three's own examples (no new dependency), made once with one shared 96 segment unit circle, and placed for each selection by position, rotation and scale only, so showing it, hiding it or changing the selection allocates nothing; a fat line keeps a width in screen pixels (2.5, 4.5 when pointed at or dragged) whatever the zoom, where a torus would vanish far away and fill the view close up. They draw over the parts with no depth test, in the axis colours from the tokens (X, Y, Z; the selection colour for a hinge; the warning colour when the engine blocks the angle), and the picture leaves them out. The engine says where the dial is (`part.pivot`); the window only draws it a little wider than the box's half diagonal. A press is on a ring when it falls within 9 pixels of the ring's projected outline, tested before the part under the pointer, so pressing on a ring that passes over a part turns rather than drags; Alt or Ctrl at the press go to the part as before. The angle comes from where the pointer's ray meets the ring's plane, measured about the axis from the press point and unwrapped across half turns, so going round the ring any number of times counts; when the ring is seen nearly edge on (the ray within about 12 degrees of its plane) the plane is no use, and the angle is the pointer's travel along the ring's tangent on screen at the press point instead. Shift during the drag is sent at once, without a move, as Ctrl is for a part drag; Escape, losing the pointer or the window's focus put everything back. `turn-hub` carries the dial's spec and state from the window's placing module to the view and the drag back, as `drag-hub` does for moves, so the view imports nothing of the window. Pointing at a ring gives the canvas the grab cursor by a class, which moves nothing. + +## A turn is previewed by patching the turned parts' instance matrices · 0.5.0 (model-scene.ts) + +`SPEC.md` 5.2 (decided in 0.5.0) turns the selected parts in place while the pivot dial is dragged; unlike a move there are no ghosts, because a turn about the selection's own centre leaves the parts where they are and a second set drawn over them would hide the turn. `ModelScene.setTurn(ids, matrix)` keeps one matrix and the set of placements it applies to; every instance whose pick is in the set is written as that matrix times its own world matrix, nothing else is touched and no batch, node or geometry is made, so a drag frame costs one 64 byte instance write per turned part (a use of a submodel turns every instance under it). `refresh` writes the same posed matrix, so a selection or hover tint during the drag keeps the turn. When the engine's change for a turned placement arrives, `applyChanges` takes it out of the set before patching it, so the new world matrix is drawn once and never turned a second time, whatever the order of the command's answer and the live channel's change. Checked headless on 7230: a 3001 turned on the dial showed turned while the button was down and was drawn once in its new place after the drop. + ## Thumbnails are drawn at twice their size · 0.4.0 (thumbnails.ts) Mixing a dark part's edges toward its colour was not enough for a part covered in studs: a black Plate 6 x 8 at 32 pixels is mostly outlines, and still read grey in the Parts tab. A line is always one device pixel wide, so the only way to make it lighter in the picture is to draw the picture larger and let the image be shown at its CSS size, which every place that shows a thumbnail already sets (`.ui-plist-img`, `.pp-thumb img`). Thumbnails are now drawn at twice the pixels asked for. Checked headless on the house of the 0.4.0 walk: the black plate's picture averaged 66, 71, 75 drawn at size and 55, 62, 68 drawn at twice; the red and yellow bricks lost their speckled studs. diff --git a/frontend/src/view/gestures.ts b/frontend/src/view/gestures.ts index a0e5b87..af3220c 100644 --- a/frontend/src/view/gestures.ts +++ b/frontend/src/view/gestures.ts @@ -23,9 +23,13 @@ export interface GestureHandlers { partAt?(x: number, y: number): string | null; rayAt?(x: number, y: number): PointerRay; showDrag?(ghosts: DragGhost[] | null, moving: boolean): void; + ringAt?(x: number, y: number): number | null; + turn?(phase: TurnPhase, ring: number, x: number, y: number, free: boolean): boolean; } -type Drag = 'orbit' | 'pan' | 'box' | 'click' | 'part' | 'spent'; +export type TurnPhase = 'begin' | 'move' | 'drop' | 'cancel' | 'point'; + +type Drag = 'orbit' | 'pan' | 'box' | 'click' | 'part' | 'ring' | 'spent'; interface Press { id: number; @@ -41,6 +45,7 @@ interface Press { copy: boolean; free: boolean; session: DragSession | null; + ring: number; } const SLOP = 4; @@ -75,7 +80,7 @@ export class Gestures { window.removeEventListener('keyup', key, true); window.removeEventListener('blur', blur); }); - this.on('lostpointercapture', () => { if (this.press?.session) this.cancel(); }); + this.on('lostpointercapture', () => { if (this.press?.session || this.press?.kind === 'ring') this.cancel(); }); const show = h.showDrag; if (show) { setDragDisplay((ghosts) => show(ghosts, false)); @@ -99,7 +104,12 @@ export class Gestures { this.steer(p, e.type === 'keydown'); return; } - if (e.type !== 'keydown' || e.key !== 'Escape' || !p || !(p.session || (p.kind === 'box' && p.moved))) return; + if (p?.kind === 'ring' && p.moved && e.key === 'Shift') { + p.free = e.type === 'keydown'; + this.h.turn?.('move', p.ring, p.lastX, p.lastY, p.free); + return; + } + if (e.type !== 'keydown' || e.key !== 'Escape' || !p || !(p.session || (p.kind === 'box' && p.moved) || (p.kind === 'ring' && p.moved))) return; e.preventDefault(); e.stopImmediatePropagation(); this.drop(); @@ -117,7 +127,8 @@ export class Gestures { p.session?.cancel(); p.session = null; if (p.kind === 'box') this.h.boxing(null); - if (p.kind === 'part' || p.kind === 'box') p.kind = 'spent'; + if (p.kind === 'ring' && p.moved) this.h.turn?.('cancel', p.ring, p.lastX, p.lastY, p.free); + if (p.kind === 'part' || p.kind === 'box' || p.kind === 'ring') p.kind = 'spent'; } private ray(e: MouseEvent): PointerRay | null { @@ -147,15 +158,17 @@ export class Gestures { if (this.press) return; const { x, y } = this.at(e); const mods: Mods = { shift: e.shiftKey, toggle: e.ctrlKey || e.metaKey }; - const grab = e.button === 0 && !this.placing() && !(e.altKey && e.shiftKey) ? this.h.partAt?.(x, y) ?? null : null; + const ring = e.button === 0 && !this.placing() && !e.altKey && !mods.toggle ? this.h.ringAt?.(x, y) ?? null : null; + const grab = ring === null && e.button === 0 && !this.placing() && !(e.altKey && e.shiftKey) ? this.h.partAt?.(x, y) ?? null : null; let kind: Drag; if (e.button === 2) kind = e.shiftKey ? 'pan' : 'orbit'; else if (e.button === 1) kind = 'pan'; + else if (ring !== null) kind = 'ring'; else if (grab) kind = 'part'; else if (e.button === 0 && e.altKey) kind = e.shiftKey ? 'pan' : 'orbit'; else if (e.button === 0) kind = this.placing() ? 'click' : 'box'; else return; - this.press = { id: e.pointerId, button: e.button, x, y, lastX: x, lastY: y, kind, moved: false, mods, grab, copy: e.altKey, free: mods.toggle, session: null }; + this.press = { id: e.pointerId, button: e.button, x, y, lastX: x, lastY: y, kind, moved: false, mods, grab, copy: e.altKey, free: kind === 'ring' ? e.shiftKey : mods.toggle, session: null, ring: ring ?? -1 }; this.el.setPointerCapture(e.pointerId); if (e.button === 1) e.preventDefault(); } @@ -179,7 +192,11 @@ export class Gestures { else if (p.kind === 'pan') this.h.pan(dx, dy); else if (p.kind === 'box') this.h.boxing(this.rect(p, x, y)); else if (p.kind === 'click' && this.placing()) this.h.place(x, y, 'move'); - else if (p.kind === 'part') { + else if (p.kind === 'ring') { + if (first) this.h.turn?.('begin', p.ring, p.x, p.y, p.free); + p.free = e.shiftKey; + this.h.turn?.('move', p.ring, x, y, p.free); + } else if (p.kind === 'part') { if (first) this.begin(p); p.free = e.ctrlKey || e.metaKey; const ray = this.ray(e); @@ -204,10 +221,14 @@ export class Gestures { else p.session?.cancel(); return; } + if (p.kind === 'ring') { + if (p.moved) this.h.turn?.('drop', p.ring, x, y, e.shiftKey); + return; + } if (p.moved && p.kind !== 'click') return; if (p.button === 0 && !p.copy) { if (this.placing()) this.h.place(x, y, 'commit'); - else this.h.click(x, y, p.mods); + else if (p.mods.shift || p.mods.toggle || !this.h.turn?.('point', -1, x, y, false)) this.h.click(x, y, p.mods); } else if (p.button === 1) { this.h.focusAt(x, y); } else if (p.button === 2 && this.placing()) { @@ -235,6 +256,7 @@ export class Gestures { } const p = this.press; if (p?.session) this.steer(p, p.free); + if (p?.kind === 'ring' && p.moved) this.h.turn?.('move', p.ring, p.lastX, p.lastY, p.free); } private rect(p: Press, x: number, y: number): ScreenRect { diff --git a/frontend/src/view/index.ts b/frontend/src/view/index.ts index 78c4944..a113f5c 100644 --- a/frontend/src/view/index.ts +++ b/frontend/src/view/index.ts @@ -16,6 +16,7 @@ import { groundHit, pickBox, pickRay, type Hit, type ScreenRect } from './pick'; import { ShapeStore } from './shapes'; import { Thumbnails } from './thumbnails'; import { readInk } from './tokens'; +import { attachDial } from './turn-wire'; export type { GhostSpec, PointerPhase, PointerRay, ViewChanges, ViewColour, ViewDoc, ViewName } from './doc-types'; export { missingTokens } from './tokens'; @@ -34,10 +35,12 @@ export interface Viewport { setDoc(doc: ViewDoc): void; applyChanges(changes: ViewChanges): void; setSelection(ids: string[]): void; + setOverlaps(ids: string[]): void; setStep(index: number | null): void; setGhost(g: GhostSpec | null): void; fit(): void; setView(name: ViewName): void; + facing(): { right: number[]; into: number[] }; thumbnail(part: string, colour: number, px: number): Promise; refreshColours(): void; resize(): void; @@ -152,9 +155,12 @@ export function createViewport(host: HTMLElement, deps: ViewportDeps): Viewport let boxStartX = 0; const drags = Ghost.many(shapes, table, materials, () => ink, invalidate, tableReady); scene.add(drags.group); + const dial = attachDial({ host, canvas, scene, rig, model, ink, size: () => ({ width, height }), invalidate }); const gestures = new Gestures(canvas, { partAt: (x, y) => (ghost.active ? null : hitAt(x, y)?.id ?? null), + ringAt: (x, y) => (ghost.active ? null : dial.ringAt(x, y)), + turn: (phase, ring, x, y, free) => dial.turn(phase, ring, x, y, free), rayAt: (x, y) => { rig.ray(x, y, ray); return { origin: [ray.origin.x, ray.origin.y, ray.origin.z], dir: [ray.direction.x, ray.direction.y, ray.direction.z] }; @@ -236,7 +242,7 @@ export function createViewport(host: HTMLElement, deps: ViewportDeps): Viewport bindExtras({ renderer, scene, rig, model, ground, lights, - hide: [ghost.group], + hide: [ghost.group, dial.group], ink: () => ink, fullBox: () => model.hiddenBox(), redraw: touched, @@ -266,6 +272,9 @@ export function createViewport(host: HTMLElement, deps: ViewportDeps): Viewport setSelection(ids) { model.setSelection(ids); }, + setOverlaps(ids) { + model.setOverlaps(ids); + }, setStep(index) { model.setStep(index); }, @@ -280,6 +289,9 @@ export function createViewport(host: HTMLElement, deps: ViewportDeps): Viewport const aim = aimOf(name); rig.look(aim.from, aim.up, frameBox(), true); }, + facing() { + return { right: rig.right.toArray(), into: rig.forward.add(rig.up).toArray() }; + }, thumbnail(part, colour, px) { return thumbs.get(part, colour, px); }, @@ -300,6 +312,7 @@ export function createViewport(host: HTMLElement, deps: ViewportDeps): Viewport canvas.removeEventListener('webglcontextrestored', restored); themeWatch.disconnect(); gestures.dispose(); + dial.dispose(); model.dispose(); ghost.dispose(); ground.dispose(); diff --git a/frontend/src/view/model-scene.ts b/frontend/src/view/model-scene.ts index dcc511e..46441f1 100644 --- a/frontend/src/view/model-scene.ts +++ b/frontend/src/view/model-scene.ts @@ -13,6 +13,7 @@ const FADE = 0.55; const LEFT_BEHIND = 0.7; const SELECT_FACE = 0.38; const HOVER_LINE = 0.85; +const CLASH_FACE = 0.82; interface Context { world: THREE.Matrix4; @@ -86,6 +87,10 @@ export class ModelScene { private fadeInk: THREE.Color | null = null; private lines = true; private readonly scratch = new THREE.Matrix4(); + private turned = new Set(); + private clashing = new Set(); + private readonly turn = new THREE.Matrix4(); + private readonly posed = new THREE.Matrix4(); constructor( private readonly shapes: ShapeStore, @@ -173,6 +178,7 @@ export class ModelScene { if (!structural) for (const key of [...(this.byId.get(p.id) ?? [])]) this.removeSubtree(key); if (!structural) this.expandNew(p); } else if (!structural) { + this.turned.delete(p.id); for (const key of [...(this.byId.get(p.id) ?? [])]) this.patch(key, p); } } @@ -270,6 +276,37 @@ export class ModelScene { this.changed(); } + setOverlaps(ids: string[]): void { + const next = new Set(ids); + const touched = [...this.clashing].filter((id) => !next.has(id)).concat(ids.filter((id) => !this.clashing.has(id))); + if (!touched.length) return; + this.clashing = next; + for (const id of touched) { + for (const key of this.byId.get(id) ?? []) { + const node = this.nodes.get(key); + if (node) this.refresh(node); + } + } + this.changed(); + } + + setTurn(ids: string[], matrix: THREE.Matrix4 | null): void { + const before = this.turned; + this.turned = matrix ? new Set(ids) : new Set(); + if (matrix) this.turn.copy(matrix); + for (const id of new Set([...before, ...this.turned])) { + for (const key of this.byPick.get(id) ?? []) { + const node = this.nodes.get(key); + if (node?.batch) node.batch.setMatrix(node.slot, this.poseOf(node)); + } + } + this.changed(); + } + + private poseOf(node: Node): THREE.Matrix4 { + return node.pick && this.turned.has(node.pick) ? this.posed.multiplyMatrices(this.turn, node.world) : node.world; + } + setHover(id: string | null): void { if (id === this.hover) return; const old = this.hover; @@ -503,6 +540,10 @@ export class ModelScene { const faded = (this.edited !== this.top && node.pick === null) || (this.fade && current !== null && node.step !== null && node.step < current); if (node.pick && this.dragged.has(node.pick)) return [[bg.r, bg.g, bg.b, LEFT_BEHIND], [bg.r, bg.g, bg.b, LEFT_BEHIND]]; if (this.plain) return [faded ? [bg.r, bg.g, bg.b, FADE] : NONE, faded ? [bg.r, bg.g, bg.b, FADE] : NONE]; + if (this.clashing.has(node.id)) { + const w = this.ink.blocked; + return [[bg.r, bg.g, bg.b, CLASH_FACE], [w.r, w.g, w.b, 1]]; + } if (node.pick && this.selection.has(node.pick)) { const s = this.ink.select; return [[s.r, s.g, s.b, SELECT_FACE], [s.r, s.g, s.b, 1]]; @@ -532,7 +573,7 @@ export class ModelScene { return; } const [face, line] = this.tints(node); - node.batch.setMatrix(node.slot, node.world); + node.batch.setMatrix(node.slot, this.poseOf(node)); node.batch.setTint(node.slot, face, line); this.changed(); } diff --git a/frontend/src/view/tokens.ts b/frontend/src/view/tokens.ts index 5195d41..aa25da7 100644 --- a/frontend/src/view/tokens.ts +++ b/frontend/src/view/tokens.ts @@ -9,6 +9,7 @@ export interface SceneInk { ghost: THREE.Color; blocked: THREE.Color; axisX: THREE.Color; + axisY: THREE.Color; axisZ: THREE.Color; } @@ -21,6 +22,7 @@ const WANTED: Array<[keyof SceneInk, string, string]> = [ ['ghost', '--view-ghost', '--text-secondary'], ['blocked', '--view-blocked', '--warn'], ['axisX', '--view-axis-x', '--danger'], + ['axisY', '--view-axis-y', '--ok'], ['axisZ', '--view-axis-z', '--accent-color'], ]; diff --git a/frontend/src/view/turn-dial.ts b/frontend/src/view/turn-dial.ts new file mode 100644 index 0000000..00b302f --- /dev/null +++ b/frontend/src/view/turn-dial.ts @@ -0,0 +1,232 @@ +import * as THREE from 'three'; +import { Line2 } from 'three/examples/jsm/lines/Line2.js'; +import { LineGeometry } from 'three/examples/jsm/lines/LineGeometry.js'; +import { LineMaterial } from 'three/examples/jsm/lines/LineMaterial.js'; +import type { DialSpec, DialState } from './turn-hub'; +import type { SceneInk } from './tokens'; + +const SEGMENTS = 96; +const LINE_PX = 2.5; +const HOVER_PX = 4.5; +const HIT_PX = 9; +const DIMMED = 0.25; +const WIDER = 1.15; +const PAD = 8; +const EDGE_ON = 0.2; +const NUDGE = 1e-3; +const Z = new THREE.Vector3(0, 0, 1); + +interface Ring { + line: Line2; + material: LineMaterial; + axis: THREE.Vector3; + name: string; +} + +interface Grip { + ring: number; + plane: boolean; + last: number; + total: number; + ref: THREE.Vector3; + pressX: number; + pressY: number; + slope: THREE.Vector2; +} + +const unit: number[] = []; +for (let i = 0; i <= SEGMENTS; i++) { + const a = (i / SEGMENTS) * Math.PI * 2; + unit.push(Math.cos(a), Math.sin(a), 0); +} + +const at = new THREE.Vector3(); +const next = new THREE.Vector3(); +const lifted = new THREE.Vector3(); +const hitPoint = new THREE.Vector3(); +const plane = new THREE.Plane(); +const spare = new THREE.Vector2(); +const spare2 = new THREE.Vector2(); +const drawn = new THREE.Vector2(); + +export class TurnDial { + readonly group = new THREE.Group(); + private readonly rings: Ring[] = []; + private spec: DialSpec | null = null; + private state: DialState = { active: null, blocked: false, up: [0, 0, 0] }; + private hovered: number | null = null; + private readonly centre = new THREE.Vector3(); + private radius = 0; + private grip: Grip | null = null; + + constructor(private ink: SceneInk, private readonly changed: () => void) { + this.group.name = 'pivot-dial'; + this.group.visible = false; + const geometry = new LineGeometry(); + geometry.setPositions(unit); + for (let i = 0; i < 3; i++) { + const material = new LineMaterial({ linewidth: LINE_PX, worldUnits: false, depthTest: false, depthWrite: false, transparent: true }); + const line = new Line2(geometry, material); + line.renderOrder = 30; + line.frustumCulled = false; + line.visible = false; + line.onBeforeRender = (renderer) => { material.resolution.copy(renderer.getSize(drawn)); }; + this.group.add(line); + this.rings.push({ line, material, axis: new THREE.Vector3(0, 1, 0), name: '' }); + } + } + + get shown(): boolean { + return this.group.visible; + } + + setInk(ink: SceneInk): void { + this.ink = ink; + this.paint(); + } + + show(spec: DialSpec | null): void { + this.spec = spec; + this.grip = null; + this.hovered = null; + if (!spec || !spec.axes.length) { + this.group.visible = false; + this.changed(); + return; + } + this.centre.set(spec.point[0] ?? 0, spec.point[1] ?? 0, spec.point[2] ?? 0); + this.radius = spec.reach * WIDER + PAD; + this.rings.forEach((r, i) => { + const a = spec.axes[i]; + r.line.visible = !!a; + if (!a) return; + r.name = a.name; + r.axis.set(a.axis[0] ?? 0, a.axis[1] ?? 0, a.axis[2] ?? 0).normalize(); + r.line.quaternion.setFromUnitVectors(Z, r.axis); + r.line.position.copy(this.centre); + r.line.scale.setScalar(this.radius); + }); + this.group.visible = true; + this.paint(); + } + + setState(state: DialState): void { + this.state = state; + this.group.position.set(state.up[0] ?? 0, state.up[1] ?? 0, state.up[2] ?? 0); + if (state.active === null) this.grip = null; + this.paint(); + } + + hover(index: number | null): void { + if (index === this.hovered) return; + this.hovered = index; + this.paint(); + } + + hit(x: number, y: number, camera: THREE.Camera, width: number, height: number): number | null { + if (!this.group.visible) return null; + let best: number | null = null; + let near = HIT_PX; + this.rings.forEach((r, index) => { + if (!r.line.visible) return; + const from = this.screen(this.ringPoint(r, 0, at), camera, width, height, spare).clone(); + for (let i = 1; i <= SEGMENTS; i++) { + const to = this.screen(this.ringPoint(r, i, next), camera, width, height, spare2); + const d = segmentDistance(x, y, from, to); + if (d < near) { near = d; best = index; } + from.copy(to); + } + }); + return best; + } + + begin(index: number, x: number, y: number, ray: THREE.Ray, camera: THREE.Camera, width: number, height: number): void { + const r = this.rings[index]; + if (!r) return; + const centre = lifted.copy(this.centre).add(this.group.position); + const facing = Math.abs(ray.direction.dot(r.axis)) > EDGE_ON; + const grip: Grip = { ring: index, plane: false, last: 0, total: 0, ref: new THREE.Vector3(), pressX: x, pressY: y, slope: new THREE.Vector2() }; + if (facing && ray.intersectPlane(plane.setFromNormalAndCoplanarPoint(r.axis, centre), hitPoint)) { + grip.plane = true; + grip.ref.copy(hitPoint).sub(centre); + } else { + let closest = 0; + let near = Infinity; + for (let i = 0; i < SEGMENTS; i++) { + const d = this.screen(this.ringPoint(r, i, at), camera, width, height, spare).distanceTo(spare2.set(x, y)); + if (d < near) { near = d; closest = i; } + } + const p = this.ringPoint(r, closest, new THREE.Vector3()); + const tangent = next.copy(r.axis).cross(at.copy(p).sub(centre)); + const a = this.screen(p, camera, width, height, new THREE.Vector2()); + const b = this.screen(p.clone().addScaledVector(tangent, NUDGE), camera, width, height, new THREE.Vector2()); + grip.slope.copy(b.sub(a)).divideScalar(NUDGE); + } + this.grip = grip; + } + + angle(x: number, y: number, ray: THREE.Ray): number { + const g = this.grip; + const r = g ? this.rings[g.ring] : undefined; + if (!g || !r) return 0; + if (!g.plane) { + const len = g.slope.lengthSq(); + return len > 0 ? THREE.MathUtils.radToDeg(((x - g.pressX) * g.slope.x + (y - g.pressY) * g.slope.y) / len) : 0; + } + const centre = lifted.copy(this.centre).add(this.group.position); + if (!ray.intersectPlane(plane.setFromNormalAndCoplanarPoint(r.axis, centre), hitPoint)) return THREE.MathUtils.radToDeg(g.total); + const v = hitPoint.sub(centre); + const a = Math.atan2(at.copy(g.ref).cross(v).dot(r.axis), g.ref.dot(v)); + let d = a - g.last; + if (d > Math.PI) d -= Math.PI * 2; + else if (d < -Math.PI) d += Math.PI * 2; + g.total += d; + g.last = a; + return THREE.MathUtils.radToDeg(g.total); + } + + axisOf(index: number): number[] | null { + return this.spec?.axes[index]?.axis ?? null; + } + + dispose(): void { + this.rings[0]?.line.geometry.dispose(); + for (const r of this.rings) r.material.dispose(); + } + + private ringPoint(r: Ring, i: number, out: THREE.Vector3): THREE.Vector3 { + out.set(unit[i * 3] ?? 0, unit[i * 3 + 1] ?? 0, 0).multiplyScalar(this.radius).applyQuaternion(r.line.quaternion); + return out.add(this.centre).add(this.group.position); + } + + private screen(p: THREE.Vector3, camera: THREE.Camera, width: number, height: number, out: THREE.Vector2): THREE.Vector2 { + const v = at.copy(p).project(camera); + return out.set(((v.x + 1) / 2) * width, ((1 - v.y) / 2) * height); + } + + private colourOf(name: string): THREE.Color { + if (name === 'x') return this.ink.axisX; + if (name === 'y') return this.ink.axisY; + if (name === 'z') return this.ink.axisZ; + return this.ink.select; + } + + private paint(): void { + const active = this.state.active; + this.rings.forEach((r, i) => { + const lit = active === i || (active === null && this.hovered === i); + r.material.color.copy(this.state.blocked && active === i ? this.ink.blocked : this.colourOf(r.name)); + r.material.linewidth = lit ? HOVER_PX : LINE_PX; + r.material.opacity = active !== null && active !== i ? DIMMED : 1; + }); + this.changed(); + } +} + +function segmentDistance(x: number, y: number, a: THREE.Vector2, b: THREE.Vector2): number { + const dx = b.x - a.x; + const dy = b.y - a.y; + const len = dx * dx + dy * dy; + const t = len > 0 ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / len)) : 0; + return Math.hypot(x - (a.x + t * dx), y - (a.y + t * dy)); +} diff --git a/frontend/src/view/turn-hub.ts b/frontend/src/view/turn-hub.ts new file mode 100644 index 0000000..8f90e08 --- /dev/null +++ b/frontend/src/view/turn-hub.ts @@ -0,0 +1,91 @@ +import type { PointerRay } from './doc-types'; + +export interface DialAxis { + name: string; + axis: number[]; +} + +export interface DialSpec { + point: number[]; + axes: DialAxis[]; + reach: number; +} + +export interface DialState { + active: number | null; + blocked: boolean; + up: number[]; +} + +export interface TurnPreview { + ids: string[]; + axis: number[]; + point: number[]; + degrees: number; + up: number[]; +} + +export interface TurnSession { + move(degrees: number, free: boolean): void; + drop(): void; + cancel(): void; +} + +export interface TurnPort { + begin(axis: number): TurnSession | null; +} + +interface DialView { + show(spec: DialSpec | null): void; + state(state: DialState): void; + preview(turn: TurnPreview | null): void; +} + +const REST: DialState = { active: null, blocked: false, up: [0, 0, 0] }; + +let port: TurnPort | null = null; +let view: DialView | null = null; +let spec: DialSpec | null = null; +let state: DialState = REST; + +export function setTurnPort(next: TurnPort | null): void { + port = next; +} + +export function turnPort(): TurnPort | null { + return port; +} + +export function setDialView(next: DialView | null): void { + view = next; + next?.show(spec); + next?.state(state); +} + +export function showDial(next: DialSpec | null): void { + spec = next; + view?.show(next); +} + +export function dialShown(): DialSpec | null { + return spec; +} + +export function setDialState(next: Partial | null): void { + state = next ? { ...state, ...next } : REST; + view?.state(state); +} + +export function previewTurn(turn: TurnPreview | null): void { + view?.preview(turn); +} + +let pointPick: ((ray: PointerRay) => boolean) | null = null; + +export function setPointPick(next: ((ray: PointerRay) => boolean) | null): void { + pointPick = next; +} + +export function pickPoint(ray: PointerRay): boolean { + return pointPick?.(ray) ?? false; +} diff --git a/frontend/src/view/turn-wire.ts b/frontend/src/view/turn-wire.ts new file mode 100644 index 0000000..5f512d5 --- /dev/null +++ b/frontend/src/view/turn-wire.ts @@ -0,0 +1,115 @@ +import * as THREE from 'three'; +import type { CameraRig } from './camera'; +import type { TurnPhase } from './gestures'; +import type { ModelScene } from './model-scene'; +import { readInk, type SceneInk } from './tokens'; +import { TurnDial } from './turn-dial'; +import { pickPoint, setDialView, turnPort, type TurnPreview, type TurnSession } from './turn-hub'; + +export interface DialHost { + host: HTMLElement; + canvas: HTMLCanvasElement; + scene: THREE.Scene; + rig: CameraRig; + model: ModelScene; + ink: SceneInk; + size(): { width: number; height: number }; + invalidate(): void; +} + +export interface DialHandle { + group: THREE.Group; + ringAt(x: number, y: number): number | null; + turn(phase: TurnPhase, ring: number, x: number, y: number, free: boolean): boolean; + dispose(): void; +} + +const ON_RING = 'is-on-ring'; + +export function attachDial(h: DialHost): DialHandle { + const dial = new TurnDial(h.ink, h.invalidate); + h.scene.add(dial.group); + const ray = new THREE.Ray(); + const matrix = new THREE.Matrix4(); + const spin = new THREE.Matrix4(); + const back = new THREE.Matrix4(); + const axis = new THREE.Vector3(); + let session: TurnSession | null = null; + + const preview = (t: TurnPreview | null): void => { + if (!t) { + h.model.setTurn([], null); + return; + } + const [px = 0, py = 0, pz = 0] = t.point; + const [ux = 0, uy = 0, uz = 0] = t.up; + axis.set(t.axis[0] ?? 0, t.axis[1] ?? 0, t.axis[2] ?? 0).normalize(); + spin.makeRotationAxis(axis, THREE.MathUtils.degToRad(t.degrees)); + matrix.makeTranslation(px + ux, py + uy, pz + uz).multiply(spin).multiply(back.makeTranslation(-px, -py, -pz)); + h.model.setTurn(t.ids, matrix); + }; + setDialView({ show: (spec) => dial.show(spec), state: (s) => dial.setState(s), preview }); + + const ringAt = (x: number, y: number): number | null => { + const { width, height } = h.size(); + return dial.hit(x, y, h.rig.camera, width, height); + }; + + let hoverFrame = 0; + let hoverAt: { x: number; y: number } | null = null; + const hoverNow = (): void => { + hoverFrame = 0; + const found = hoverAt && !session ? ringAt(hoverAt.x, hoverAt.y) : null; + dial.hover(found); + h.canvas.classList.toggle(ON_RING, found !== null); + }; + const moved = (e: PointerEvent): void => { + if (e.buttons || !dial.shown) { + if (!dial.shown && h.canvas.classList.contains(ON_RING)) h.canvas.classList.remove(ON_RING); + return; + } + const r = h.canvas.getBoundingClientRect(); + hoverAt = { x: e.clientX - r.left, y: e.clientY - r.top }; + if (!hoverFrame) hoverFrame = requestAnimationFrame(hoverNow); + }; + h.canvas.addEventListener('pointermove', moved); + + const themeWatch = new MutationObserver(() => dial.setInk(readInk(h.host))); + themeWatch.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + + const turn = (phase: TurnPhase, ring: number, x: number, y: number, free: boolean): boolean => { + if (phase === 'point') { + h.rig.ray(x, y, ray); + return pickPoint({ origin: [ray.origin.x, ray.origin.y, ray.origin.z], dir: [ray.direction.x, ray.direction.y, ray.direction.z] }); + } + if (phase === 'begin') { + if (!dial.shown) return false; + const { width, height } = h.size(); + dial.begin(ring, x, y, h.rig.ray(x, y, ray), h.rig.camera, width, height); + session = turnPort()?.begin(ring) ?? null; + return session !== null; + } + const s = session; + if (!s) return false; + if (phase === 'move') s.move(dial.angle(x, y, h.rig.ray(x, y, ray)), free); + else { + session = null; + if (phase === 'drop') s.drop(); + else s.cancel(); + } + return true; + }; + + return { + group: dial.group, + ringAt, + turn, + dispose() { + if (hoverFrame) cancelAnimationFrame(hoverFrame); + h.canvas.removeEventListener('pointermove', moved); + themeWatch.disconnect(); + setDialView(null); + dial.dispose(); + }, + }; +} diff --git a/frontend/src/view/viewport.css b/frontend/src/view/viewport.css index 13b0087..28dbf9e 100644 --- a/frontend/src/view/viewport.css +++ b/frontend/src/view/viewport.css @@ -13,6 +13,14 @@ outline: none; } +.fb-view-canvas.is-on-ring { + cursor: grab; +} + +.fb-view-canvas.is-on-ring:active { + cursor: grabbing; +} + .fb-view-box { position: absolute; left: 0; diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 8de6873..0b3ee96 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -2,6 +2,50 @@ Why the install, boot, build and check scripts are the way they are, newest first. Read before editing a script, and add an entry in the same commit as the change. +## The batch twin names each agent arm on a line of its own · 0.5.0 (../formblocks.bat) + +The four arms were one `for` line testing `%~1` against each program's name, which works the same but which the family's validator (`formapp.py validate`, clause 6.18) cannot read as an arm, so it reported the twin as having no claude, codex, cursor or antigravity arm. The first word is now kept in `CMD` at once and tested on six lines, `"%CMD%"=="claude"` and the rest, before anything else, as the shell launcher does. The rule of "What the person types reaches an agent program" below still holds: only the first word, the command's own name, is read into a variable or a test; the second argument is set only after every arm and `cli` have gone, and the arms still run `python setup\agent_launch.py %*` with no `call`. Checked: the validator now holds every clause it checks (0 SHOULD not held, it was 1), the file keeps its CRLF line ends. Not run: the `.bat` itself, as nothing on this machine runs one. + +## On Windows the MCP server FormBlocks registers is the engine's Python, not the launcher's batch file · 0.5.0 (agents.py) + +The arms and `agents install` named `formblocks.bat mcp` as the `formblocks` server on Windows. Claude Code, Codex from npm and Cursor's agent are Node programs, and Node refuses to start a `.bat` or `.cmd` without a shell since its 2024 security change (it fails with `EINVAL`), so on Windows none of them could start the server FormBlocks gave them; Antigravity's start of a batch file would again pass through the interpreter. FormAnything's agent lane found the same. On Windows the command is now the venv's `backend\venv\Scripts\python.exe` with `backend\formblocks_engine.py mcp`, which is what `mcp.bat` runs; macOS and Linux keep `./formblocks mcp`. `ours`, which tells FormBlocks' own entry from another, compares the same two values, so an entry written before this is no longer called FormBlocks' own on Windows and is left alone with a sentence. The repository's own files (`.mcp.json`, `.cursor/mcp.json`, `.codex/config.toml`, `.agents/mcp_config.json`) start the launcher through `sh` and are unchanged. Checked on Linux: the engine started as `venv/bin/python /path/backend/formblocks_engine.py mcp --headless` from another folder answered `initialize` and listed 72 tools; `LAUNCH` and `ARGS` are unchanged here. Not run: Windows. + +## Every arm and engine batch file turns delayed expansion off and keeps the caller's folder · 0.5.0 (../formblocks.bat, claude, codex, cursor, antigravity, their .bat twins, cli.bat, mcp.bat) + +`setlocal` alone inherits the computer's choice of delayed expansion, which a registry value can turn on for every `cmd`; with it on, a `!` in the person's words is read as the start of a variable and dropped with what follows. The root launcher, the four arm twins, `cli.bat` and `mcp.bat` now start with `setlocal EnableExtensions DisableDelayedExpansion`. The root launcher sends `mcp` to the engine directly with `%*`, as it already does `cli` and the four arms, so no word of those reaches `call` or an `if`; `agents` keeps its `call`, since its words are the kit's own fixed words. The four arm twins and their shell scripts now set `FORMBLOCKS_CALLER_DIR` to the folder they were started from when no launcher set it, so `setup/claude` run directly starts Claude Code in the person's folder rather than the repository's. Checked: from a scratch folder, `setup/claude --print-config` named that folder; `bash -n` on the four shell scripts. The `.bat` files were not run (no Windows here). + +## An arm takes a first message, and starts the program on Windows the way the dock does · 0.5.0 (agent_launch.py) + +Two changes to the arms, the same idea as FormAnything's agent lane's description of the Windows fault, written here for FormBlocks. First, a first message is its own thing. It comes from the words after `--` (joined by a space), or else `FORMBLOCKS_MESSAGE`, or else a file named by `FORMBLOCKS_MESSAGE_FILE`, which must belong to the person and be writable by nobody else; both variables are taken out of the program's environment. Before, every word went to the program as given, so a message starting with a dash was read as an option, and on Windows the only way to give one was on a command line. Each program gets it where it reads a first prompt and cannot mistake it for an option or a command: `-- ` for Claude Code and Codex, `agent -- ` for Cursor's agent (whose own commands, such as `status` or `login`, would otherwise take a message that is one word), and `--prompt-interactive=` for Antigravity. Second, on Windows the command is built by `backend/app/services/windows_start.py` (loaded from its file, as the finder is): an npm or pnpm shim runs its node script or program directly, and any other batch file goes through the interpreter only with words it cannot act on; otherwise the arm refuses before it writes a file or starts anything. The previous check here, which refused any `.cmd` with such a character, is replaced by it. Checked on Linux, from a folder named `arm & 50% dir`: all four arms with stand-ins that record what they get, `--model x -- ` where the message starts with `-p` and holds quotes, `&`, `%`, `|`, `<`, `^`, `!`, `$HOME` and a line break: Claude Code got `-- `, Codex `--model x -- `, Cursor's agent `--model x agent -- `, Antigravity `--model x --prompt-interactive=`, each in that folder and with neither message variable in its environment; `FORMBLOCKS_MESSAGE` and a 0600 message file gave Claude Code the same, and a 0666 file was refused, exit 1. With the platform made to take the Windows path: npm `codex.cmd` became `node codex.js -- `, an npm `claude.cmd` naming an `.exe` that `.exe`, a pnpm `cursor-agent.cmd` its `node.exe` and `.mjs`, and a plain `.bat` was refused with nothing written. Not run: Windows. + +## The Linux engine carries numpy's libraries once · 0.5.0 (freeze_backend) + +PyInstaller's folder on Linux holds three symbolic links in `_internal/` (`libscipy_openblas64_*.so`, `libgfortran-*.so.5.0.0`, `libquadmath-*.so.0.0.0`), each pointing at the same file in `_internal/numpy.libs/`. Tauri copies resources without links, so the first `deb` carried each library twice: its engine folder was 142 MB against the frozen folder's 116 MB, 27 MB of it the second copies. numpy's own modules find these libraries through their run path (`$ORIGIN/../../numpy.libs`), not through `_internal/`, so on Linux the freeze now removes every link whose target lies inside the engine folder, and the self-check that ends the freeze imports numpy and every engine module without them. macOS keeps its own step (the links become copies there, which the signing needs); Windows has no links. Checked: a copy of the frozen folder with the three links deleted passed `--selfcheck` and flattened 3001 to 700 triangles with `cli part-mesh`; `./formblocks freeze` then removed 3 and passed its self-check; the second desktop build's package is measured in the first desktop build's entry. + +## The freeze carries every JSON file the engine's packages hold · 0.5.0 (freeze_backend, freeze_backend.bat) + +The freeze named three data files one by one (the stud kind's, the overrides and the categories). This branch added the `clip` and `hinge` connector kinds, each with a JSON file read when its module is imported, and the frozen engine had neither, so every connector query in the desktop app ended in an error. The shell script now finds every folder under `backend/app` that holds a `.json` file and passes `--add-data` with a `*.json` glob for each (PyInstaller expands a glob in the source), so a kind added later is carried without an edit here. `cmd` cannot list folders and cut the prefix without delayed expansion, which would mangle a `!` in a path, so the `.bat` twin names the three folders that hold JSON files today with the same glob; a JSON file in a new folder fails the engine's self-check there (`backend/HASHOUT_LOG.md`, "The self-check imports every module"), which the freeze's last step runs. The refusal to freeze when a named file is missing is gone with the names. Checked: `./formblocks freeze` passed its self-check with `"modules": "ok"`; `_internal/app/connect/kinds` holds `clip.json`, `hinge.json` and `stud.json`, with `overrides.json` and `categories.json` in their folders; the frozen `part.connectors part=3001` listed the brick's connectors. The `.bat` twin was not run (no Windows here). + +## The doctor names what a Linux desktop build needs · 0.5.0 (doctor, doctor.bat) + +The doctor looked for WebKitGTK alone, so a computer with it and without GTK's, libsoup's or librsvg's development files, a C compiler or `patchelf` was called ready and the first build stopped inside a `-sys` crate (this machine stopped in `gdk-sys` before those files were installed). It now asks `pkg-config` for each library the shell's crates link (`webkit2gtk-4.1`, `javascriptcoregtk-4.1`, `libsoup-3.0`, `gtk+-3.0`, `librsvg-2.0`), naming the Debian package for a missing one, says when `pkg-config` itself is missing, checks for a C compiler, and for `patchelf` and `file`, which the AppImage step uses. On every system it now also checks the Tauri command line in `frontend/node_modules` and PyInstaller in the engine's venv, which `desktop build` needs and which `install` alone does not bring. Each is a warning, as WebKitGTK was, because a person who never builds the desktop app needs none of them. Checked on Linux: with the libraries present every line is `ok` and the versions are the ones the first build linked against; with `PKG_CONFIG_LIBDIR` pointed at an empty place the five libraries are each named with their package. The `.bat` twin gains the Tauri and PyInstaller lines and was not run (no Windows here). + +## What the person types reaches an agent program, or the engine's command line, as typed · 0.5.0 (../formblocks.bat, cli.bat, agent_launch.py) + +The rule: no message, folder or other text the person or an agent supplies is ever handed to `cmd.exe` to read a second time. Every path where it was, reasoned through, since no `.bat` can run here: + +- `formblocks.bat claude "fix 50% of it & save"` ran `call setup\claude.bat %2 %3 ... %9`. A batch file reads a line once: `%2` is replaced by the argument with its quotes, and the quotes keep `&` from splitting the line. But `call` reads the line a second time for `%`: in a batch file a single `%` with no partner is dropped and a pair names a variable, so the message became `fix 50 of it & save`, and `%PATH%` written by the person reached the program as the computer's path. `%2` to `%9` also dropped a tenth argument. The `.bat` now goes to the four arms and `cli` before anything else, with no `call` and no `set` of an argument: `python setup\agent_launch.py %*` (the program's name is the script's first word, as on the shell side) and `python formblocks_engine.py %*` from `backend` (the engine takes `cli` as its first word and drops it). `%*` is the person's own words, replaced once and read once with their quotes; nothing in it is expanded again. The old lines are gone. Before this, `set "ARG=%~2"` and the `if` tests also ran on every call with the second argument inside them, which a word such as `a"&x"` breaks out of; the arms no longer reach them. +- `setup\cli.bat` ran `if "%~1"=="" ( ... ) else ( python formblocks_engine.py %* )`. `%~1` strips only the outer quotes, so an argument with a quote inside closed the test's quotes, and inside the parenthesised block an unquoted `)` in `%*` (such as `position=(0,0,0)` written without quotes) ended the block early. It now tests `[%1]==[]`, which keeps the argument's own quotes, and runs the engine on a line of its own. +- `agent_launch.py` ran the program with `subprocess.call([path, *arguments])`. When the program is a `.cmd` or `.bat` file (npm installs Claude Code and Codex as `.cmd` shims), Windows starts it through `cmd.exe /c`, which reads the joined line: `&`, `|`, `<`, `>` outside its idea of a quoted stretch, `^`, and `%NAME%` even inside quotes. Python joins the words with the C runtime's quoting, where a quote becomes `\"`, which the interpreter does not understand, so one quote in the message leaves the rest of it bare; and a line break cannot be passed at all. No quoting makes arbitrary text safe there, so the arm refuses before it writes or starts anything when the program is a `.cmd` or `.bat` file on Windows and any argument (FormBlocks' own or the person's) holds `& | < > ^ % !`, a line break or NUL, and says to start the program without that argument and type the text once it runs. FormBlocks' own arguments hold none of them unless the checkout's own folder does. A program that is an `.exe` gets its arguments directly and is not affected. +- The dock: see `backend/HASHOUT_LOG.md`, "On Windows a tab's first message is typed". A tab's folder is the process's working folder, never a word on its command line, and Chat sends every message on standard input. +- Left as they are: `desktop build --config ` is passed through `call` twice, so a `%` in the config file's path would be lost; formcompiler's path is under the runner's temporary folder and holds none. `install`'s `--lite` and `agents`' words are fixed words. + +Checked here, on Linux, for real: `./formblocks claude` with a stand-in that records its arguments, from a folder named `arm & 50% dir`, with the message `it's "quoted" & 50% |
    ^ !x $HOME` and a backquoted `id`, a line break and `line two`, then `-- -p`: the stand-in got the message unchanged, then `--` and `-p`, in that folder, with no window key or token in its environment. The arm's check, called with the platform set to Windows: a `claude.cmd` with `fix 50% & go` refused, with plain words allowed, a `claude.exe` with the same message allowed, Codex's own `-c` settings allowed. Not run: any `.bat` file and Windows itself. + +## A desktop build may name its cargo folder · 0.5.0 (lib.sh, desktop_build, desktop_build.bat) + +`app_rust_env` clears `CARGO_TARGET_DIR` and the other cargo overrides before a build, as FormCAD does, so a value left in a person's shell or set by a runner cannot move the bundles away from `src-tauri/target`, where formcompiler's staging looks for them. That also made it impossible to build into a shared cargo folder on purpose: on a computer that builds several Tauri apps, each first build of the same crates takes most of an hour on two processors. `FORMBLOCKS_CARGO_TARGET_DIR` now names such a folder, and is the only way to: a stray `CARGO_TARGET_DIR` is still cleared. `desktop build` says where the bundles went. The `.bat` twin did not clear `CARGO_TARGET_DIR` at all, so the two twins could build into different places; it now clears it and takes the same override. Checked: `./formblocks desktop build` with `FORMBLOCKS_CARGO_TARGET_DIR` set built into that folder and said so (see the first desktop build's entry). The `.bat` twin was not run (no Windows here). + ## The engine reloads only when asked · 0.4.0 (boot_backend, boot_backend.bat, ../backend/boot_backend, ../backend/boot_backend.bat) Both pairs of boot scripts ran uvicorn with `--reload`, so any edit under `backend/` (another agent's, a skill sync's, a person's) restarted the engine: the open model in memory was reloaded from its store, a held part and any waiting question were lost, and every start wrote a new `session.token`, which cut off the window and the command line until they read it again. Reload is now off unless `FORMBLOCKS_RELOAD=1` is set or `--reload` is the script's first argument; with either it watches `backend/app` only. The shell scripts build the flag as an array so nothing is passed when it is off; the `.bat` twins set `RELOAD` the same way (not run here: no Windows). Checked on port 8349 with a scratch data folder: plain, with `FORMBLOCKS_RELOAD=1` and with `--reload`, the engine answered `/api/health` 200, and only the last two logged that uvicorn was watching for changes. diff --git a/setup/agent_launch.py b/setup/agent_launch.py index 873a06b..f36741d 100755 --- a/setup/agent_launch.py +++ b/setup/agent_launch.py @@ -17,20 +17,26 @@ OVERRIDES = {"claude": "FORMBLOCKS_CLAUDE_BIN", "codex": "FORMBLOCKS_CODEX_BIN", "cursor": "FORMBLOCKS_CURSOR_BIN", "antigravity": "FORMBLOCKS_ANTIGRAVITY_BIN"} FILES = {"cursor": (".cursor", "mcp.json"), "antigravity": (".agents", "mcp_config.json")} SKILL = agents.USE_SKILLS[0] +WINDOWS_START = os.path.join(ROOT, "backend", "app", "services", "windows_start.py") +MESSAGE_VARS = ("FORMBLOCKS_MESSAGE", "FORMBLOCKS_MESSAGE_FILE") def say(text: str) -> None: print(f"[formblocks] {text}", file=sys.stderr) -def lookup(): - spec = importlib.util.spec_from_file_location("formblocks_agent_lookup", LOOKUP) +def load(name: str, path: str): + spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) return module +def lookup(): + return load("formblocks_agent_lookup", LOOKUP) + + def entry() -> dict: return {"command": agents.LAUNCH, "args": list(agents.ARGS)} @@ -53,6 +59,38 @@ def codex_args() -> list[str]: "-c", f"{key}.startup_timeout_sec=90", "-c", f"{key}.tool_timeout_sec=600", "-c", f"developer_instructions={json.dumps(note())}"] +def message_file(name: str) -> str: + path = Path(name).expanduser() + try: + st = path.stat() + if os.name != "nt" and (st.st_uid != os.geteuid() or st.st_mode & 0o022): + raise SystemExit(f"[formblocks] {path} must be yours and writable by you alone to be read as a first message; nothing was started.") + return path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as exc: + raise SystemExit(f"[formblocks] the first message file {path} could not be read ({exc}); nothing was started.") + + +def first_message(rest: list[str]) -> tuple[list[str], str | None]: + if "--" in rest: + at = rest.index("--") + return rest[:at], " ".join(rest[at + 1:]) or None + if os.environ.get(MESSAGE_VARS[0]): + return rest, os.environ[MESSAGE_VARS[0]] + if os.environ.get(MESSAGE_VARS[1]): + return rest, message_file(os.environ[MESSAGE_VARS[1]]) + return rest, None + + +def placed(kind: str, options: list[str], message: str | None) -> list[str]: + if message is None: + return list(options) + if kind == "antigravity": + return [*options, f"--prompt-interactive={message}"] + if kind == "cursor": + return [*options, "agent", "--", message] + return [*options, "--", message] + + def server_file(kind: str, folder: Path) -> Path: return folder.joinpath(*FILES[kind]) @@ -97,27 +135,34 @@ def main(argv: list[str]) -> int: dry = bool(rest) and rest[0] == "--print-config" if dry: rest = rest[1:] + options, message = first_message(rest) folder = Path(os.environ.get("FORMBLOCKS_CALLER_DIR") or os.getcwd()).resolve() finder = lookup() found = finder.check(finder.find(kind, override_vars=(OVERRIDES[kind],))) extra = claude_args() if kind == "claude" else codex_args() if kind == "codex" else [] if dry: print(json.dumps({"program": kind, "found": found.path, "state": found.state, "version": found.version, "folder": str(folder), - "arguments": extra, "file": ensure_file(kind, folder, True) if kind in FILES else None, "skill": skill_hint(kind, folder)}, indent=2)) + "arguments": [*extra, *placed(kind, options, message)], "file": ensure_file(kind, folder, True) if kind in FILES else None, "skill": skill_hint(kind, folder)}, indent=2)) return 0 if found.state != "runs" or not found.path: say(finder.sentence(found, finder.install(kind))) return 1 + env = finder.child_env(found.path) + for name in ("FORMBLOCKS_TOKEN", "FORMBLOCKS_TAB_TOKEN", "FORMBLOCKS_MCP_URL", *MESSAGE_VARS): + env.pop(name, None) + words = [*extra, *placed(kind, options, message)] + try: + command = load("formblocks_windows_start", WINDOWS_START).argv(found.path, words, env) if finder.windows() else [found.path, *words] + except ValueError as exc: + say(f"{exc} Nothing was started: start it without that text and type the text once the program runs.") + return 1 told = ensure_file(kind, folder, False) if kind in FILES else None if told: say(told) hint = skill_hint(kind, folder) if hint: say(hint) - env = finder.child_env(found.path) - for name in ("FORMBLOCKS_TOKEN", "FORMBLOCKS_TAB_TOKEN", "FORMBLOCKS_MCP_URL"): - env.pop(name, None) - return subprocess.call([found.path, *extra, *rest], cwd=str(folder), env=env) + return subprocess.call(command, cwd=str(folder), env=env) if __name__ == "__main__": diff --git a/setup/agents.py b/setup/agents.py index a7cef48..4d595f7 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -35,8 +35,12 @@ DOCK_MANIFEST = os.path.join(DOCK_DIR, "MANIFEST.json") DOCK = {"positions": ["bottom", "right"], "tabs": ["terminal", "chat", "claude-code", "codex", "cursor", "antigravity", "outside-agents"]} EXTENSIONS = None -LAUNCH = os.path.join(ROOT, LAUNCHER + (".bat" if os.name == "nt" else "")) -ARGS = ["mcp"] +if os.name == "nt": + LAUNCH = os.path.join(ROOT, "backend", "venv", "Scripts", "python.exe") + ARGS = [os.path.join(ROOT, "backend", f"{LAUNCHER}_engine.py"), "mcp"] +else: + LAUNCH = os.path.join(ROOT, LAUNCHER) + ARGS = ["mcp"] CLAUDE_BIN = "FORMBLOCKS_CLAUDE_BIN" diff --git a/setup/antigravity b/setup/antigravity index 93be667..854b351 100755 --- a/setup/antigravity +++ b/setup/antigravity @@ -2,5 +2,6 @@ set -e source "$(dirname "$0")/lib.sh" app_venv +export FORMBLOCKS_CALLER_DIR="${FORMBLOCKS_CALLER_DIR:-$PWD}" cd "$FORMBLOCKS_ROOT" exec python setup/agent_launch.py antigravity "$@" diff --git a/setup/antigravity.bat b/setup/antigravity.bat index 240ee87..508502c 100644 --- a/setup/antigravity.bat +++ b/setup/antigravity.bat @@ -1,5 +1,6 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion +if not defined FORMBLOCKS_CALLER_DIR set "FORMBLOCKS_CALLER_DIR=%CD%" cd /d "%~dp0.." if not exist backend\venv\Scripts\activate.bat ( echo [formblocks] error: engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) call backend\venv\Scripts\activate.bat diff --git a/setup/claude b/setup/claude index 631ea87..f0630a3 100755 --- a/setup/claude +++ b/setup/claude @@ -2,5 +2,6 @@ set -e source "$(dirname "$0")/lib.sh" app_venv +export FORMBLOCKS_CALLER_DIR="${FORMBLOCKS_CALLER_DIR:-$PWD}" cd "$FORMBLOCKS_ROOT" exec python setup/agent_launch.py claude "$@" diff --git a/setup/claude.bat b/setup/claude.bat index b9b21bc..160fe04 100644 --- a/setup/claude.bat +++ b/setup/claude.bat @@ -1,5 +1,6 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion +if not defined FORMBLOCKS_CALLER_DIR set "FORMBLOCKS_CALLER_DIR=%CD%" cd /d "%~dp0.." if not exist backend\venv\Scripts\activate.bat ( echo [formblocks] error: engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) call backend\venv\Scripts\activate.bat diff --git a/setup/cli.bat b/setup/cli.bat index d5b8374..e6fdaf3 100644 --- a/setup/cli.bat +++ b/setup/cli.bat @@ -1,8 +1,12 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion if not defined FORMBLOCKS_CALLER_DIR set "FORMBLOCKS_CALLER_DIR=%CD%" cd /d "%~dp0..\backend" if not exist venv\Scripts\activate.bat ( echo [formblocks] engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) call venv\Scripts\activate.bat -if "%~1"=="" ( python formblocks_engine.py help ) else ( python formblocks_engine.py %* ) +if [%1]==[] goto :help +python formblocks_engine.py %* +exit /b %ERRORLEVEL% +:help +python formblocks_engine.py help exit /b %ERRORLEVEL% diff --git a/setup/codex b/setup/codex index 0ae3c29..49d2556 100755 --- a/setup/codex +++ b/setup/codex @@ -2,5 +2,6 @@ set -e source "$(dirname "$0")/lib.sh" app_venv +export FORMBLOCKS_CALLER_DIR="${FORMBLOCKS_CALLER_DIR:-$PWD}" cd "$FORMBLOCKS_ROOT" exec python setup/agent_launch.py codex "$@" diff --git a/setup/codex.bat b/setup/codex.bat index 5c9d0d5..13abd73 100644 --- a/setup/codex.bat +++ b/setup/codex.bat @@ -1,5 +1,6 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion +if not defined FORMBLOCKS_CALLER_DIR set "FORMBLOCKS_CALLER_DIR=%CD%" cd /d "%~dp0.." if not exist backend\venv\Scripts\activate.bat ( echo [formblocks] error: engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) call backend\venv\Scripts\activate.bat diff --git a/setup/cursor b/setup/cursor index 1d1539b..d637b5a 100755 --- a/setup/cursor +++ b/setup/cursor @@ -2,5 +2,6 @@ set -e source "$(dirname "$0")/lib.sh" app_venv +export FORMBLOCKS_CALLER_DIR="${FORMBLOCKS_CALLER_DIR:-$PWD}" cd "$FORMBLOCKS_ROOT" exec python setup/agent_launch.py cursor "$@" diff --git a/setup/cursor.bat b/setup/cursor.bat index a4b1207..83cb9dd 100644 --- a/setup/cursor.bat +++ b/setup/cursor.bat @@ -1,5 +1,6 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion +if not defined FORMBLOCKS_CALLER_DIR set "FORMBLOCKS_CALLER_DIR=%CD%" cd /d "%~dp0.." if not exist backend\venv\Scripts\activate.bat ( echo [formblocks] error: engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) call backend\venv\Scripts\activate.bat diff --git a/setup/desktop_build b/setup/desktop_build index 181b1d3..e2d9a1c 100755 --- a/setup/desktop_build +++ b/setup/desktop_build @@ -9,4 +9,4 @@ command -v cargo >/dev/null 2>&1 || app_die "Rust not found; run ./formblocks in cd "$FORMBLOCKS_ROOT" [ -n "$(ls src-tauri/icons 2>/dev/null)" ] || app_say "src-tauri/icons is empty: the bundle needs the app's icons, see src-tauri/HASHOUT_LOG.md" frontend/node_modules/.bin/tauri build "$@" -app_say "bundles are in src-tauri/target/release/bundle" +app_say "bundles are in ${CARGO_TARGET_DIR:-src-tauri/target}/release/bundle" diff --git a/setup/desktop_build.bat b/setup/desktop_build.bat index f518f3e..e7bc111 100644 --- a/setup/desktop_build.bat +++ b/setup/desktop_build.bat @@ -6,6 +6,9 @@ if not exist frontend\node_modules\.bin\tauri.cmd ( echo [formblocks] the Tauri call setup\build_frontend.bat || exit /b 1 call setup\freeze_backend.bat || exit /b 1 if not exist src-tauri\icons\icon.ico echo [formblocks] src-tauri\icons has no icon.ico: the bundle needs the app's icons, see src-tauri\HASHOUT_LOG.md +set "CARGO_TARGET_DIR=" +if defined FORMBLOCKS_CARGO_TARGET_DIR set "CARGO_TARGET_DIR=%FORMBLOCKS_CARGO_TARGET_DIR%" call frontend\node_modules\.bin\tauri.cmd build %* || exit /b 1 -echo [formblocks] bundles are in src-tauri\target\release\bundle +if defined CARGO_TARGET_DIR echo [formblocks] bundles are in "%CARGO_TARGET_DIR%\release\bundle" +if not defined CARGO_TARGET_DIR echo [formblocks] bundles are in src-tauri\target\release\bundle exit /b 0 diff --git a/setup/doctor b/setup/doctor index c9ed31d..705db39 100755 --- a/setup/doctor +++ b/setup/doctor @@ -13,8 +13,22 @@ if [ -d "$FORMBLOCKS_ROOT/frontend/node_modules" ]; then ok "frontend node_modul app_rust_env if command -v cargo >/dev/null 2>&1; then ok "rust $(rustc --version | awk '{print $2}') for desktop builds"; else warn "rust" "desktop builds need https://rustup.rs"; fi if [ "$(app_os)" = linux ]; then - if pkg-config --exists webkit2gtk-4.1 2>/dev/null; then ok "webkit2gtk-4.1"; else warn "webkit2gtk-4.1" "desktop builds need libwebkit2gtk-4.1-dev"; fi + if ! command -v pkg-config >/dev/null 2>&1; then + warn "pkg-config" "desktop builds need pkg-config to find the system libraries below" + else + for lib in webkit2gtk-4.1:libwebkit2gtk-4.1-dev javascriptcoregtk-4.1:libjavascriptcoregtk-4.1-dev libsoup-3.0:libsoup-3.0-dev gtk+-3.0:libgtk-3-dev librsvg-2.0:librsvg2-dev; do + if pkg-config --exists "${lib%%:*}"; then ok "${lib%%:*} $(pkg-config --modversion "${lib%%:*}")"; else warn "${lib%%:*}" "desktop builds need ${lib#*:}"; fi + done + fi + if command -v cc >/dev/null 2>&1; then ok "c compiler"; else warn "c compiler" "desktop builds need build-essential"; fi + for tool in patchelf:patchelf file:file; do + if command -v "${tool%%:*}" >/dev/null 2>&1; then ok "${tool%%:*}"; else warn "${tool%%:*}" "the AppImage bundle needs ${tool#*:}"; fi + done fi +if [ -x "$FORMBLOCKS_ROOT/frontend/node_modules/.bin/tauri" ]; then ok "tauri command line"; else warn "tauri command line" "desktop builds need ./formblocks install-desktop"; fi +venv_py="$FORMBLOCKS_ROOT/backend/venv/bin/python" +[ -x "$venv_py" ] || venv_py="$FORMBLOCKS_ROOT/backend/venv/Scripts/python.exe" +if [ -x "$venv_py" ] && "$venv_py" -c "import PyInstaller" 2>/dev/null; then ok "pyinstaller in the engine venv"; else warn "pyinstaller" "freezing the engine for a desktop build needs ./formblocks install-desktop"; fi if [ -n "$(ls "$FORMBLOCKS_ROOT/src-tauri/icons" 2>/dev/null)" ]; then ok "desktop icons"; else warn "desktop icons" "src-tauri/icons is empty; the desktop bundle needs the app's icons"; fi for port in "$FORMBLOCKS_WINDOW_PORT" "$FORMBLOCKS_PREVIEW_PORT" "$FORMBLOCKS_PORT"; do if ! app_port_busy "$port"; then ok "port $port free"; else warn "port $port" "already in use"; fi diff --git a/setup/doctor.bat b/setup/doctor.bat index 96c5ec8..4a9ed3c 100644 --- a/setup/doctor.bat +++ b/setup/doctor.bat @@ -9,6 +9,8 @@ where py >nul 2>nul && ( echo ok python launcher ) || ( where python >nul if exist backend\venv\Scripts\activate.bat ( echo ok engine venv ) else ( echo warn engine venv, run formblocks.bat install ) if exist frontend\node_modules ( echo ok frontend node_modules ) else ( echo warn frontend deps, run formblocks.bat install ) where cargo >nul 2>nul && ( echo ok rust for desktop builds ) || ( echo warn rust, desktop builds need https://rustup.rs ) +if exist frontend\node_modules\.bin\tauri.cmd ( echo ok tauri command line ) else ( echo warn tauri command line, desktop builds need formblocks.bat install-desktop ) +if exist backend\venv\Scripts\python.exe ( backend\venv\Scripts\python.exe -c "import PyInstaller" >nul 2>nul && ( echo ok pyinstaller in the engine venv ) || ( echo warn pyinstaller, freezing the engine for a desktop build needs formblocks.bat install-desktop ) ) if exist src-tauri\icons\icon.ico ( echo ok desktop icons ) else ( echo warn desktop icons, src-tauri\icons has no icon.ico ) for %%p in (5330 5331 %FORMBLOCKS_PORT%) do ( netstat -an | findstr /r /c:"127.0.0.1:%%p .*LISTENING" >nul && ( echo warn port %%p already in use ) || ( echo ok port %%p free ) diff --git a/setup/freeze_backend b/setup/freeze_backend index 5aee150..b6959a4 100755 --- a/setup/freeze_backend +++ b/setup/freeze_backend @@ -37,6 +37,16 @@ flatten_engine() { app_say "engine flattened: Python library at _internal/Python, $links links replaced by copies" } +drop_inner_links() { + local dir link real gone=0 + dir="$(cd "$1" && pwd -P)" + while IFS= read -r link; do + real="$(readlink -f "$link")" + case "$real" in "$dir"/*) rm -f "$link"; gone=$((gone + 1)) ;; esac + done < <(find "$dir" -type l) + app_say "engine links into its own folder removed: $gone" +} + app_venv python -c "import PyInstaller" 2>/dev/null || app_die "PyInstaller missing, run ./formblocks install-desktop" [ -f "$FORMBLOCKS_ROOT/frontend/dist/index.html" ] || "$FORMBLOCKS_ROOT/setup/build_frontend" @@ -50,10 +60,9 @@ python -c "import winpty" 2>/dev/null && extra+=(--hidden-import winpty --collec python -c "import ptyprocess" 2>/dev/null && extra+=(--hidden-import ptyprocess) [ -z "${FORMBLOCKS_PYI_ARCH:-}" ] || extra+=(--target-arch "$FORMBLOCKS_PYI_ARCH") [ ! -d "$FORMBLOCKS_ROOT/backend/app/data" ] || extra+=(--add-data "$src/backend/app/data${sep}app/data") -for f in app/connect/kinds/stud.json app/connect/overrides.json app/library/categories.json; do - [ -f "$FORMBLOCKS_ROOT/backend/$f" ] || app_die "engine data file missing: backend/$f" - extra+=(--add-data "$src/backend/$f${sep}$(dirname "$f")") -done +while IFS= read -r d; do + extra+=(--add-data "$src/backend/$d/*.json${sep}$d") +done < <(find app -name '*.json' ! -path '*/__pycache__/*' -exec dirname {} \; | sort -u) rm -rf build/pyinstaller dist-engine PYTHONPATH="$src/backend${PYTHONPATH:+$sep$PYTHONPATH}" pyinstaller --noconfirm --clean --onedir --name formblocks-engine \ --distpath dist-engine --workpath build/pyinstaller --specpath build/pyinstaller \ @@ -66,5 +75,6 @@ rm -rf "$out" cp -R dist-engine/formblocks-engine "$out" [ "$(app_os)" != macos ] || flatten_engine "$out" [ "$(app_os)" != macos ] || sign_engine "$out" +[ "$(app_os)" != linux ] || drop_inner_links "$out" "$out/formblocks-engine${ext}" --selfcheck app_say "engine folder ready: $out" diff --git a/setup/freeze_backend.bat b/setup/freeze_backend.bat index 7cd2845..2610c71 100644 --- a/setup/freeze_backend.bat +++ b/setup/freeze_backend.bat @@ -10,8 +10,7 @@ cd backend set "EXTRA=" python -c "import winpty" >nul 2>nul && set "EXTRA=--hidden-import winpty --collect-binaries winpty" if exist "%ROOT%\backend\app\data" set EXTRA=%EXTRA% --add-data "%ROOT%\backend\app\data;app\data" -for %%F in (connect\kinds\stud.json connect\overrides.json library\categories.json) do if not exist "%ROOT%\backend\app\%%F" ( echo [formblocks] engine data file missing: backend\app\%%F & exit /b 1 ) -set EXTRA=%EXTRA% --add-data "%ROOT%\backend\app\connect\kinds\stud.json;app\connect\kinds" --add-data "%ROOT%\backend\app\connect\overrides.json;app\connect" --add-data "%ROOT%\backend\app\library\categories.json;app\library" +set EXTRA=%EXTRA% --add-data "%ROOT%\backend\app\connect\kinds\*.json;app\connect\kinds" --add-data "%ROOT%\backend\app\connect\*.json;app\connect" --add-data "%ROOT%\backend\app\library\*.json;app\library" if exist build\pyinstaller rmdir /s /q build\pyinstaller if exist dist-engine rmdir /s /q dist-engine set "PYTHONPATH=%ROOT%\backend;%PYTHONPATH%" diff --git a/setup/lib.sh b/setup/lib.sh index 6a8828a..17826b3 100755 --- a/setup/lib.sh +++ b/setup/lib.sh @@ -45,6 +45,7 @@ app_rust_env() { export PATH unset RUSTC RUSTC_WORKSPACE_WRAPPER RUSTFLAGS CARGO_ENCODED_RUSTFLAGS CARGO_BUILD_RUSTFLAGS CARGO_BUILD_TARGET CARGO_TARGET_DIR CARGO_BUILD_TARGET_DIR CARGO_BUILD_RUSTC export RUSTC_WRAPPER="" CARGO_BUILD_RUSTC_WRAPPER="" + [ -z "${FORMBLOCKS_CARGO_TARGET_DIR:-}" ] || export CARGO_TARGET_DIR="$FORMBLOCKS_CARGO_TARGET_DIR" if [ -n "${FORMBLOCKS_RUST_TOOLCHAIN:-}" ]; then export RUSTUP_TOOLCHAIN="$FORMBLOCKS_RUST_TOOLCHAIN"; fi } app_port_busy() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } diff --git a/setup/mcp.bat b/setup/mcp.bat index 610eb7f..b07c001 100644 --- a/setup/mcp.bat +++ b/setup/mcp.bat @@ -1,5 +1,5 @@ @echo off -setlocal +setlocal EnableExtensions DisableDelayedExpansion cd /d "%~dp0..\backend" if not exist venv\Scripts\activate.bat ( echo [formblocks] engine venv missing, run formblocks.bat install 1>&2 & exit /b 1 ) call venv\Scripts\activate.bat diff --git a/skills/formblocks-driving/SKILL.md b/skills/formblocks-driving/SKILL.md index 10c3e7a..906173e 100644 --- a/skills/formblocks-driving/SKILL.md +++ b/skills/formblocks-driving/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-driving -description: "Use when asked to build, stack, change, check, picture or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats bricks on placements or the ground, builds walls in overlapping courses with plates, tiles and slopes, moves, drags, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into building steps and walks them, counts parts and saves the parts list as CSV, saves PNG pictures and reads them back to check a build, checks overlaps and floating parts, and opens, saves and exports .fblk, .ldr and .mpd files. Covers Claude Code, Codex, Cursor and Antigravity in the agent dock or outside it, and the person's approval, which an agent never gives itself. Includes worked examples, coordinates, error codes and scripts. Not for changing FormBlocks' source code, installing or building it (formblocks-harness)." +description: "Use when asked to build, stack, change, check, picture or save a brick model in FormBlocks through its MCP tools or ./formblocks cli: a wall, a tower, a house, a table, any LDraw model. Finds parts and colours in the LDraw parts library, places and seats bricks, clips and hinge halves on placements or the ground, builds walls in overlapping courses with plates, tiles and slopes, moves, turns, duplicates and recolours parts, uses the selection and submodels, splits a model into steps and walks them, counts parts and saves the parts list as CSV, saves PNG pictures and reads them back to check a build, checks overlaps, and opens, saves and exports .fblk, .ldr and .mpd files. Covers Claude Code, Codex, Cursor and Antigravity in the agent dock or outside it, and the person's approval, which an agent never gives itself. Includes worked examples, coordinates, error codes and scripts. Not for changing FormBlocks' source code or installing it (formblocks-harness)." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.4.0" + pack-version: "0.5.0" audience: operating agent --- @@ -20,14 +20,17 @@ FormBlocks keeps one open model in its engine: submodels holding placements of L | Search words, categories, part numbers, moved parts, parts of other systems | `sub-skills/finding-parts/SUB-SKILL.md` | | Colour codes, colour names, finishes, colour 16 inside submodels, recolouring | `sub-skills/colours/SUB-SKILL.md` | | Studs and anti-studs, seating on a part or the ground, part.place, part.fit, on, seated, refused placements | `sub-skills/placing-and-snapping/SUB-SKILL.md` | +| Clips on bars, hinge halves, hinge plates and bricks, swivel plates, sliding a clip, folding a hinge, part.connectors kinds | `sub-skills/clips-and-hinges/SUB-SKILL.md` | | Planning a build, walls in overlapping courses, corners, openings, plates and tiles, roofs of slopes | `sub-skills/building-in-order/SUB-SKILL.md` | | Moving, turning, duplicating, recolouring, hiding, showing and deleting placements, undo and redo | `sub-skills/changing-parts/SUB-SKILL.md` | +| Turning parts by any angle, about a point, an axis or a hinge's axis, part.pivot, the angle step, a turn lifted or refused | `sub-skills/turning-parts/SUB-SKILL.md` | | Moving or copying parts along a pointer ray as the window drags them, part.pick, the scene's axes, resting across a gap, what the person's drags and Ctrl+D do | `sub-skills/moving-parts/SUB-SKILL.md` | | Reading and setting the selection, selecting by colour or part, showing the person which parts | `sub-skills/selection/SUB-SKILL.md` | | Packing repeated units into submodels, placing uses, editing inside one, unpacking, renaming, deleting | `sub-skills/submodels/SUB-SKILL.md` | | Building steps: what a sensible step is, adding, naming, moving and deleting steps, the step shown | `sub-skills/steps/SUB-SKILL.md` | | Walking the steps: step.goto by number or first, previous, next, last, what each step adds, dimmed earlier steps, leaving the step shown right | `sub-skills/step-walking/SUB-SKILL.md` | | New, open, save, save as, LDraw export, inserting a model, what `.fblk`, `.ldr`, `.mpd` and `.dat` keep | `sub-skills/files/SUB-SKILL.md` | +| What a model is: its name, description, author, licence, counts, size, file facts, missing parts, and setting them (the Info tab) | `sub-skills/model-information/SUB-SKILL.md` | | Checking a build: the overlap check, floating parts, reading the model back, counting parts | `sub-skills/checking-a-model/SUB-SKILL.md` | | The parts list: counts per part and colour, scopes, missing and moved parts, selecting a row's parts, saving it as CSV | `sub-skills/parts-list/SUB-SKILL.md` | | A picture of the model or of every step, and looking at your own build by saving a PNG and reading it back | `sub-skills/pictures/SUB-SKILL.md` | diff --git a/skills/formblocks-driving/evals/evals.json b/skills/formblocks-driving/evals/evals.json index 8a56786..5df2ecb 100644 --- a/skills/formblocks-driving/evals/evals.json +++ b/skills/formblocks-driving/evals/evals.json @@ -92,6 +92,36 @@ "Refuses to answer the window's question or change the standing choice, and says the person can choose Always allow or set it in the Outside agents dialog", "Refuses to fetch the library or type the consent words, and names the library card or the command the person runs" ] + }, + { + "id": 9, + "name": "turn-by-45", + "prompt": "Turn the red brick p1 45 degrees about its up axis in FormBlocks and tell me if anything is wrong afterwards.", + "files": [], + "expected_behavior": [ + "Sends part.rotate with ids [p1], axis y and angle 45, not quarter_turns, and passes ids rather than relying on the selection", + "Reads the answer's lifted value, runs overlap.check afterwards, and says a turn that is not a quarter turn seats nothing" + ] + }, + { + "id": 10, + "name": "open-a-hinge", + "prompt": "Put a 44301a hinge half beside the 44302a at the top of my model and open the hinge 90 degrees.", + "files": [], + "expected_behavior": [ + "Turns the half a half turn about y before placing it near its partner, because snapping never turns a part, and reads seated and joined", + "Reads part.pivot for the hinge's point and axis and sends part.rotate with axis_vector, about and angle 90 for that half only" + ] + }, + { + "id": 11, + "name": "who-made-this-model", + "prompt": "How big is the open model, how many different parts and colours does it use, and which parts is the library missing? Put my name as the author.", + "files": [], + "expected_behavior": [ + "Reads model.info with table false and answers from counts, size and missingParts", + "Sets the author with model.set_info and says it is one undo step; does not touch the licence line" + ] } ], "trigger_evals": [ @@ -105,6 +135,9 @@ { "query": "register the formblocks MCP server with my agent", "should_trigger": true }, { "query": "how many bricks does this model need, save the parts list as csv", "should_trigger": true }, { "query": "save a picture of each building step of my brick model", "should_trigger": true }, + { "query": "tilt this brick 22.5 degrees and tell me if it lifted off the ground in FormBlocks", "should_trigger": true }, + { "query": "clip the plate onto the bar and slide it along in my brick model", "should_trigger": true }, + { "query": "what licence and author does my open brick model carry and how many studs across is it", "should_trigger": true }, { "query": "add a new MCP tool to the FormBlocks engine source", "should_trigger": false }, { "query": "fix the typecheck error in the FormBlocks window code", "should_trigger": false }, { "query": "write a parser for LDraw files in Rust", "should_trigger": false }, diff --git a/skills/formblocks-driving/references/command-catalogue.md b/skills/formblocks-driving/references/command-catalogue.md index 3e76eb4..9c9f875 100644 --- a/skills/formblocks-driving/references/command-catalogue.md +++ b/skills/formblocks-driving/references/command-catalogue.md @@ -4,8 +4,8 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never ## Contents -- MCP tools: the 69 tools an agent sees, each with whether it only reads. -- Commands: the 63 catalogue commands with their titles, parameters and summaries, in name order. +- MCP tools: the 72 tools an agent sees, each with whether it only reads. +- Commands: the 66 catalogue commands with their titles, parameters and summaries, in name order. ## MCP tools @@ -17,12 +17,13 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `formblocks_redo` | no | Redo changes that formblocks_undo took back, one step each. A new change after an undo empties what can be redone. Returns {revision, labels, label}. | | `formblocks_status` | yes | Read what this FormBlocks is: its version, the model's revision, placement count, file and unsaved mark, how many commands there are, its data folder, whether the window's engine is running, and the person's standing choice for outside agents (ask, allowed or blocked). Call it first. | | `formblocks_undo` | no | Undo the last changes, one step per command. Returns {revision, labels, label}: the new revision and the titles of the commands taken back, newest first. Nothing to undo answers an empty labels list. | +| `cmd_angle_step` | yes | Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_current` | yes | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_colours_list` | yes | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. Only reads. | | `cmd_colours_used` | yes | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. Only reads. | | `cmd_grid_step` | yes | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | | `cmd_library_status` | yes | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. Only reads. | -| `cmd_model_info` | yes | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. Only reads. | +| `cmd_model_info` | yes | Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use; its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them); the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false. Only reads. | | `cmd_model_insert` | no | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_new` | no | Start a new model named Untitled with one empty step, and a new history. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_open` | no | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | @@ -32,9 +33,10 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_model_save_as` | no | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. Opens, starts or writes a model file; not an undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_set_info` | no | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_model_tree` | yes | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. Only reads. | -| `cmd_overlap_check` | yes | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. Only reads. | -| `cmd_overlap_set` | yes | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | -| `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. Only reads. | +| `cmd_overlap_check` | yes | List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU. Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked. Only reads. | +| `cmd_overlap_nested` | yes | Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole. Nested pairs never block placing or moving either way. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_overlap_set` | yes | Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting. Changes only the view (the selection, the step shown or the submodel being edited); no undo step. | +| `cmd_part_connectors` | yes | List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind. Only reads. | | `cmd_part_delete` | no | Remove placements from the model; deleting the last use of a submodel keeps the submodel. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate` | no | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_duplicate_at_ray` | no | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | @@ -44,10 +46,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `cmd_part_move` | no | Move placements by an offset in LDU, exactly, with no snapping. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_move_at_ray` | no | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers, resting on what lies under its footprint when the place under the pointer would cut into another part; the others keep their places relative to it. Give held as the drag preview answered it so the part lands as previewed. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_pick` | yes | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. Only reads. | +| `cmd_part_pivot` | yes | Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone; with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point. Only reads. | | `cmd_part_place` | no | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_place_at_ray` | no | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers, resting on what lies under its whole footprint when the place under the pointer would cut into another part; it goes into the step shown of the submodel being edited and becomes the selection. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_recolour` | no | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | -| `cmd_part_rotate` | no | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | +| `cmd_part_rotate` | no | Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given. What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_set_transform` | no | Put one placement at an exact position, rotation or both, as the details panel does. Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_part_show` | no | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). Changes the model; one undo step. An outside agent waits for the person to allow it in the window. | | `cmd_parts_list` | yes | Read the parts a model needs, one row per part and colour with its description, colour name, count and the placements of the submodel being edited that hold it; a submodel's parts counted once for each use unless submodels is row, a moved part counted under the number it moved to, parts missing from the library first and marked. With text true the answer also holds the list as tab separated text. Only reads. | @@ -85,12 +88,13 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | Command | Title | Reads only | Parameters | What it does | | --- | --- | --- | --- | --- | +| `angle.step` | Angle Step | yes | `step` (number) | Choose the angle step a turn with the pointer moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees. Kept as the person's setting. | | `colours.current` | Current Colour | yes | `colour` (integer) | Choose the colour the next placed part gets, and put it at the front of the recent colours. Kept as the person's setting; it recolours nothing. | | `colours.list` | Colours | yes | `text` (string, optional), `group` (string, optional), `hue` (string, optional) | List the library's colours with code, name, value, edge and finish, or the swatches of one group, hue family or name words. | | `colours.used` | Colours Used | yes | none | List the colours used in the open model, most used first: each colour's number, name, value, how many parts of the whole model are in it, and whether the library defines it. | | `grid.step` | Grid Step | yes | `step` (string) | Choose the grid step: stud (20 LDU across, 8 up), plate (10 across, 8 up) or fine (1 and 1). Kept as the person's setting. | | `library.status` | Library Status | yes | none | Read whether a parts library is in use, where it was found, its update, whether its index is ready, the fetch in progress if any, and the consent and attribution the library card shows. Reading never fetches; only the person can consent to a fetch. | -| `model.info` | Model Information | yes | none | Read the model's name, author, file and library update, its counts (parts through every use, different parts, part and colour pairs, submodels, steps), its size in LDU, studs, bricks and millimetres, and its parts list. | +| `model.info` | Model Information | yes | `table` (boolean, optional) | Read the model's name, description (its title line), author, file, format and the library update it was saved with and the one in use; its counts (placements, parts through every use, different parts, colours, part and colour pairs, submodels, steps, missing parts, and overlapping pairs as overlap.check counts them); the parts the library lacks by number; its size in LDU, studs, bricks and millimetres; the licences model.set_info accepts; and its parts list unless table is false. | | `model.insert` | Insert LDraw Model | no | `path` (string), `position` (array, optional), `submodel` (string, optional) | Bring another .ldr, .mpd or .fblk file into the open model as new submodels and place one use of its main model. | | `model.new` | New Model | no | `discard` (boolean, optional) | Start a new model named Untitled with one empty step, and a new history. | | `model.open` | Open | no | `path` (string), `discard` (boolean, optional) | Open a .fblk, .ldr, .mpd or .dat file by its full path; a library part file opens as a new model holding one placement of the part. | @@ -100,9 +104,10 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `model.save_as` | Save As | no | `path` (string) | Write the model to a new path: .fblk saves the project file and makes it the model's file; .ldr or .mpd exports LDraw without FormBlocks' own state. | | `model.set_info` | Set Model Information | no | `title` (string, optional), `author` (string, optional), `licence` (string, optional) | Change the main model's title, author or licence, as written in its header: the licence is empty or one of the Creative Commons licences listed in its parameter. | | `model.tree` | Model Tree | yes | `submodel` (string, optional) | Read one submodel's steps and placements, each with its id, part, colour, position, rotation, step and hidden mark, and the submodels with their uses. | -| `overlap.check` | Check Overlaps | yes | `ids` (array, optional) | List each pair of overlapping placements with the depth of the overlap in LDU, for the given placements or the whole model; parts joined through seated connectors never count. | -| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the coarse overlap check on or off: with it on, placing and moving never put a part where its box would overlap another's. Kept as the person's setting. | -| `part.connectors` | Part Connectors | yes | `part` (string) | List a library part's connectors as the connection model derives them: kind, position, axis and where each came from, with the counts, the body box and the footprint. | +| `overlap.check` | Check Overlaps | yes | `ids` (array, optional), `nested` (boolean, optional) | List each pair of overlapping placements, for the given placements or the whole model: two parts whose real shapes cut more than 1 LDU into each other, with the depth in LDU and the shared volume in cubic LDU. Parts joined through seated connectors never count. Nested pairs, one part sitting in another's hollow by design, are counted apart in nested_count and listed under nested when asked. | +| `overlap.nested` | Nested Pairs | yes | `on` (boolean) | Choose what the overlap check reports: false reports only real overlaps (the proposed default), true reports nested pairs too, parts that sit in another's hollow by design, such as a rim in its tyre or a pin in its hole. Nested pairs never block placing or moving either way. Kept as the person's setting. | +| `overlap.set` | Overlap Check | yes | `on` (boolean) | Turn the overlap check on or off: with it on, placing and moving never put a part where its real shape would cut more than 1 LDU into another's. Kept as the person's setting. | +| `part.connectors` | Part Connectors | yes | `part` (string), `kind` (string, optional) | List a library part's connectors as the connection model derives them: kind, position, axis, ref, length, index and where each came from, with the counts, the body box and the footprint; kind keeps only connectors of one kind. | | `part.delete` | Delete | no | `ids` (array, optional) | Remove placements from the model; deleting the last use of a submodel keeps the submodel. | | `part.duplicate` | Duplicate | no | `ids` (array, optional), `delta` (array, optional) | Copy placements, keeping colours and relative places, offset by delta; the copies go into the step shown and become the selection. | | `part.duplicate_at_ray` | Duplicate at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Drop copies of a selection where a pointer ray in the window's scene axes takes the copy of the grabbed placement, seated, on the grid or refused as the drag preview with copy answers; the copies keep their colours and places relative to one another, go into the step shown and become the selection. One undo step. | @@ -112,10 +117,11 @@ Written by `./formblocks agents sync` from the engine's command catalogue; never | `part.move` | Move | no | `ids` (array, optional), `delta` (array) | Move placements by an offset in LDU, exactly, with no snapping. | | `part.move_at_ray` | Move Selection at Pointer | no | `grab` (string), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `ids` (array, optional), `snap` (boolean, optional) | Put down a dragged selection where a pointer ray in the window's scene axes takes the grabbed placement, seated, on the grid or refused exactly as the drag preview answers, resting on what lies under its footprint when the place under the pointer would cut into another part; the others keep their places relative to it. Give held as the drag preview answered it so the part lands as previewed. One undo step. | | `part.pick` | Pick at Pointer | yes | `origin` (array), `direction` (array), `ground` (boolean, optional) | Name the placement of the submodel being edited that a pointer ray in the window's scene axes meets first on its real triangles, with the point and the face's normal, or the ground; hidden parts are passed through. | +| `part.pivot` | Pivot | yes | `ids` (array, optional), `origin` (array, optional), `direction` (array, optional) | Say what placements turn about when the pivot dial turns them: the centre of the box around their shapes with the X, Y and Z axes, or, for one part joined by a hinge, the hinge's point and axis alone; with a pointer ray, the point where it meets a part of the submodel being edited (or the connector within 8 LDU of it), with X, Y and Z, and as without a ray when it meets none. Each point and axis in LDraw's axes and in the window's scene axes, with how far the box reaches from the point. | | `part.place` | Place Part | no | `part` (string), `colour` (integer), `position` (array, optional), `rotation` (array, optional), `submodel` (string, optional), `step` (integer, optional), `on` (string, optional), `snap` (boolean, optional) | Place a part, or a use of a submodel, in a colour: at a position, seated on its connectors when snapping is on, or seated on another placement with on; it goes into the step shown and becomes the selection. | | `part.place_at_ray` | Place Part at Pointer | no | `part` (string), `colour` (integer), `origin` (array), `direction` (array), `rotation` (array, optional), `held` (integer, optional), `step` (integer, optional), `snap` (boolean, optional) | Place a library part where a pointer ray in the window's scene axes puts it, seated, on the grid or refused exactly as the placement preview answers, resting on what lies under its whole footprint when the place under the pointer would cut into another part; it goes into the step shown of the submodel being edited and becomes the selection. | | `part.recolour` | Recolour | no | `ids` (array, optional), `colour` (integer) | Give placements a colour; a use of a submodel in colour 16 passes it to its parts in colour 16. | -| `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string), `quarter_turns` (integer), `about` (array, optional) | Turn placements by quarter turns about the X, Y or Z axis through a point, by default the centre of their origins. | +| `part.rotate` | Rotate | no | `ids` (array, optional), `axis` (string, optional), `quarter_turns` (integer, optional), `angle` (number, optional), `axis_vector` (array, optional), `about` (array, optional) | Turn placements about an axis through a point: by whole quarter turns, or by an angle in degrees, about X, Y, Z or any direction in LDraw axes, about the centre of their box when no point is given. What turned is lifted straight up when it would end below the ground, and with the overlap check on a turn into a part that does not turn is refused. One undo step. | | `part.set_transform` | Set Position and Rotation | no | `id` (string), `position` (array, optional), `rotation` (array, optional) | Put one placement at an exact position, rotation or both, as the details panel does. | | `part.show` | Show | no | `ids` (array, optional) | Show hidden placements again; every hidden placement in the model when no ids are given (Show all). | | `parts.list` | Parts List | yes | `scope` (string, optional), `group` (string, optional), `submodels` (string, optional), `text` (boolean, optional) | Read the parts a model needs, one row per part and colour with its description, colour name, count and the placements of the submodel being edited that hold it; a submodel's parts counted once for each use unless submodels is row, a moved part counted under the number it moved to, parts missing from the library first and marked. With text true the answer also holds the list as tab separated text. | diff --git a/skills/formblocks-driving/references/error-codes.md b/skills/formblocks-driving/references/error-codes.md index 59f5912..be3d89c 100644 --- a/skills/formblocks-driving/references/error-codes.md +++ b/skills/formblocks-driving/references/error-codes.md @@ -53,7 +53,7 @@ A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids | "part: ... is not in the LDraw parts library in use" | Search with `parts.search` and place the number it answers. A number with letters (`3068b`) is a different part from the bare number. | | "No LDraw parts library is installed" | Nothing can be placed. Tell the person; only they can find or fetch the library (`sub-skills/parts-library/SUB-SKILL.md`). | | "position: give a position, a placement to seat on (on), or a pointer ray" | `part.place` needs `position` or `on`. | -| "position: the part would overlap ... with the overlap check on" | The person's overlap check is on and the place is taken. Pick another place; the check is coarse inside arches and hollows, so tell the person if a part is refused where it should fit. | +| "position: the part would overlap ... by ... LDU with the overlap check on, so it was not placed." | The person's overlap check is on and the place is taken by more than 1 LDU of real shape. Pick another place; a part whose surface is not closed can be refused where it should fit, so tell the person if that happens. | | "... must stay within 1000000 LDU of the origin" | A position or offset is out of range: check signs and units. | | "on: ... has no free connector that ... can seat on" | Every stud of that placement is taken. Seat on another placement, or give a position. | | "on: ... is hidden" | Hidden parts offer no connectors. Show it with `part.show` first, or use a position. | @@ -87,6 +87,6 @@ A command's sentence starts with the parameter it is about (`part:`, `on:`, `ids - `part.place` answering `"seated": false`: the part did not join anything. With the overlap check off (its first setting) it was put on the grid step instead and may float in the air or sit inside another part. Undo it and fix the position, unless a loose part is what you meant. - `part.place` with `on` seating on a different part of the target than you wanted: `on` takes the first free studs nearest the target's middle. Give a position for an exact place. -- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. +- `overlap.check` answering a `count` above 0: two parts share space. Undo the newer one or move it. A `nested_count` above 0 is not a fault: those parts sit in each other's hollows by design, and are listed only with `nested: true`. - `model.open` answering an `issueCount` above 0: some lines could not be read; `model.report` lists them. The rest of the file opened. - A JSON-RPC timeout on a `change` sent from outside: the person may still have the question open. Read the model before sending again. diff --git a/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md index e359a5c..22c5308 100644 --- a/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md +++ b/skills/formblocks-driving/sub-skills/building-in-order/SUB-SKILL.md @@ -47,7 +47,7 @@ Where two walls meet, let one wall run through the corner cell in one course and - A half turn about Y, `rotation` `[-1,0,0, 0,1,0, 0,0,-1]`, makes it face the back. - Lay a flat layer of plates on the walls first, so every slope has studs under its whole footprint. - A gable roof: a row of slopes facing front along the front edge and a row facing back along the back edge. Each further row steps in by one stud and up by one brick, standing on the studs of the row below and on filler bricks behind it. Close the ridge with plates or tiles over the last studs. -- The overlap check follows a slope's face in slabs 4 LDU thick, so a part held clear above the face is not refused, but one cutting into the face is. The slabs step by half a plate, so a part within a few LDU of the face can still be reported; tell the person why when it is. +- The overlap check compares real shapes, so a part held clear above a slope's face is not refused and one cutting more than 1 LDU into the face is. Where it still reports a part that fits, such as one tucked under a roof whose surface is not closed, tell the person why. ## After each course diff --git a/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md index 6b42af5..4704707 100644 --- a/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md +++ b/skills/formblocks-driving/sub-skills/changing-parts/SUB-SKILL.md @@ -17,7 +17,7 @@ Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left o | --- | --- | --- | | `part.move` | `ids`, `delta` | Moves by an exact offset in LDU, `[dx, dy, dz]`. No snapping: the parts go exactly where sent. Up is a negative `dy`. | | `part.set_transform` | `id`, `position`, `rotation` | Puts one placement at an exact position, an exact rotation, or both. | -| `part.rotate` | `ids`, `axis`, `quarter_turns`, `about` | Turns by quarter turns about `x`, `y` or `z`, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the placements' origins, and works out the new positions and matrices. | +| `part.rotate` | `ids`, `axis` or `axis_vector`, `quarter_turns` or `angle`, `about` | Turns by whole quarter turns or by an angle in degrees, right-handed about the positive axis; negative turns go the other way. It turns about `about` when given, otherwise about the centre of the box round the placements' shapes. Lifts a turn off the ground and, with the overlap check on, refuses one into a part that stays; `sub-skills/turning-parts/SUB-SKILL.md` has the rest. | | `part.duplicate` | `ids`, `delta` | Copies the placements with their colours and relative places, offset by `delta`. The copies go into the step shown and become the selection; the answer lists their new ids. | | `part.recolour` | `ids`, `colour` | Gives a colour code. Parts already in it are left as they are. | | `part.delete` | `ids` | Removes placements. Deleting the last use of a submodel keeps the submodel itself. | @@ -32,8 +32,9 @@ Each command takes `ids`, a list of placement ids such as `["p3", "p4"]`. Left o ## Turning in place - A quarter turn about Y of one 2 x 4 brick about its own origin turns it crosswise on the same spot; it may then overlap its neighbours. -- To turn a whole group as one, give all their ids: they turn about the centre of their origins and keep their places relative to one another. +- To turn a whole group as one, give all their ids: they turn about the centre of their box and keep their places relative to one another. - To turn about a stud, give `about` as that stud's position. +- Any other angle than a quarter turn is the same command with `angle` (`sub-skills/turning-parts/SUB-SKILL.md`). ## Repeating a row diff --git a/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md index a022c85..a811ab9 100644 --- a/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md +++ b/skills/formblocks-driving/sub-skills/checking-a-model/SUB-SKILL.md @@ -9,16 +9,18 @@ Never report a build as done from memory of the commands you sent. Read the mode ## The overlap check -`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose bodies overlap, with the depth of the overlap in LDU. Give `ids` to check only those placements against the rest; leave it out for the whole model. It works whatever the person's overlap switch says. +`overlap.check` (`cmd_overlap_check`) lists every pair of placements whose real shapes cut into each other, with the depth in LDU and the shared volume in cubic LDU. Give `ids` to check only those placements against their neighbours; leave it out for the whole model. It works whatever the person's overlap switch says. ```json -{"checked": 28, "overlaps": [], "count": 0} -{"checked": 5, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p5", "depth": 23.0}], "count": 1} +{"checked": 28, "overlaps": [], "count": 0, "nested_count": 0, "nested_listed": false} +{"checked": 2, "overlaps": [{"submodel": "untitled.ldr", "a": "p1", "b": "p2", "depth": 24.0, "kind": "overlap", "volume": 16952.0, "parts": ["3001.dat", "3001.dat"]}], "count": 1, "nested_count": 0, "nested_listed": false} ``` - `count` 0 is the goal. -- Parts seated on each other never count, and parts that only touch face to face never count. -- The check is coarse: each part is stood in for by a box round its body, without its studs, shrunk by half an LDU, and a part whose outline changes with height (a slope, a windscreen, a round part) by a stack of slabs 4 LDU thick, so the open wedge over a slope's face is free. The space inside an arch, under a hinge or inside a hollow still counts as solid, so a part tucked there is reported although it fits. Say so to the person rather than moving a part that is right. +- Parts seated on each other never count, and parts that only touch, or cut into each other by 1 LDU or less, never count. +- Since 0.5.0 each part is its real solid, studs included, filled into cells of 1 LDU, so a part tucked into a hollow, an arch or under a hinge without cutting into the walls is not an overlap. A part with a surface that is not closed, or a part the library lacks, can still be reported wrongly; say so to the person rather than moving a part that is right. +- A pair whose outlines meet but whose solids do not, and which no seated connector joins, such as a rim in its tyre or a pin in a hole, is a nested pair. Two hinge halves or a clip on a bar, seated, are fitted and not listed at all. It is counted in `nested_count` and listed only when you pass `nested: true` or the person's setting "Report nested pairs" is on (`nested_listed` says which). Nested pairs are never refused when placing, moving or turning. On the library's sample car the answer is 0 overlaps and 19 nested pairs. +- `overlap.nested` (`on`) is that setting, the person's, like the overlap switch: ask before you change it, and prefer `nested: true` on one call. - A depth near a whole brick (24) or plate (8) usually means a part was placed on top of another at the same height: undo it or move it. ## Seated, or floating @@ -41,7 +43,7 @@ Check the counts against the plan: the number of placements, the number in each ## Counting parts - `parts.list` counts what the model needs, one row per part and colour, a submodel's parts once per use, missing parts first; `parts.list_save` writes it as CSV. `sub-skills/parts-list/SUB-SKILL.md` gives the scopes and the answer. -- `model.info` (read) answers the model's name, author, file and library update, `counts` (`parts`, `differentParts`, `pairs`, `missing`, `submodels`, `steps`, `placements`), its `size` in LDU, studs, bricks and millimetres, and the parts list with it. +- `model.info` (read) answers the model's name, author, file and library update, `counts` (`parts`, `differentParts`, `pairs`, `colours`, `overlaps`, `missing`, `submodels`, `steps`, `placements`), `missingParts` by number, its `size` in LDU, studs, bricks and millimetres, and the parts list with it unless `table` is false (`sub-skills/model-information/SUB-SKILL.md`). - `colours.used` (read) lists each colour of the model with its number, name and how many parts are in it, most used first; `known` false marks a colour the library does not define. Check the counts against the plan: parts in each colour, kinds of part, the number of steps. diff --git a/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md new file mode 100644 index 0000000..a54221b --- /dev/null +++ b/skills/formblocks-driving/sub-skills/clips-and-hinges/SUB-SKILL.md @@ -0,0 +1,66 @@ +--- +name: clips-and-hinges +description: Seats and turns clips on bars and hinge halves on each other in FormBlocks with part.place, part.fit, part.connectors and part.rotate about a hinge axis. Use when asked to build with clips, bars, handles, hinges, hinge plates, hinge bricks or swivel plates, to fold or open a hinge, to slide a clip along a bar, when a clip or hinge half will not seat, or to read which clip, bar or hinge kinds a part has. +--- + +# Clips, bars and hinges + +Besides studs and anti-studs, the engine finds three more kinds of join from a part's own shape and snaps them with the same rule: `part.place`, `part.fit` and the window's drags all use it. Read the kinds of any part with `part.connectors` (`cmd_part_connectors`, read; pass `kind` to list only one kind, such as `clip`, `bar` or `hinge_click_1`). A part with none of them seats as before. + +## The kinds + +| Kind | Pairs with | What it is | +| --- | --- | --- | +| `clip` | `bar` | Jaws that close round a rod 8 LDU across, from the library's clip pieces, such as the one on `4085c`, a Plate 1 x 1 with Clip. | +| `bar` | `clip` | Any free rod of radius 4 with room round it for jaws: the handle of a plate with a handle, `87994` Bar 3L (free length 60 LDU), the rods of many accessories. Found from the shape, so a rod never meant to be gripped can count too. | +| `hinge_click_1`, `hinge_click_2` | each other | Single-finger and dual-finger click hinge halves, such as `44301a` and `44302a`. | +| `hinge_plate_2`, `hinge_plate_3` | each other | Two-finger and three-finger plate hinge halves, `4276b` and `4275b`. | +| `hinge_arm_2`, `hinge_arm_3` | each other | The hinge arm with discs. | +| `hinge_brick_base`, `hinge_brick_top` | each other | The 1 x 2 hinge brick, `3937` and `3938`. | +| `hinge_swivel_base`, `hinge_swivel_top` | each other | The 1 x 4 swivel hinge plates, `2429` and `2430`. | + +A half pairs only with the other half of its own family. A clip does not take a stud, and a bar does not go into an anti-stud. + +## Seating a clip on a bar + +The clip's centre is put on the bar's line, and it slides along the bar in grid steps measured from the bar's middle: at the Stud step the middle and 20 LDU either side of it, at Plate every 10, at Fine anywhere along the free length. One bar holds several clips side by side; a second clip over a taken stretch is not seated. + +```bash +./formblocks cli run part.place part=87994 colour=7 'position=[0,-80,0]' +./formblocks cli run part.set_transform id=p1 'position=[0,-80,0]' +./formblocks cli run part.place part=4085c colour=4 on=p1 +./formblocks cli run part.place part=4085c colour=4 'position=[2,-45,21]' +``` + +A floating bar is put exactly with `part.set_transform`, because `part.place` rounds an unseated part to the grid (the first line answered position `[4, -76, 4]` and `seated` false). With `on`, the clip took the first free stretch of the bar, its centre at y = -70. With a position, a clip whose centre was at y = -41 seated at -50, the nearest place at the Stud step. The clip of `4085c` is at `[0, 4, -20]` in the part's own axes (`part.connectors part=4085c`), so its origin ends up 4 above the clip's centre and 20 behind the bar's line. Always read `seated`, `joined` and `marks` in the answer. + +## Seating hinge halves + +Snapping never turns a part. Turn the half first so its pivot line runs the way its partner's does, then place it near: it moves so the two lines meet. + +```bash +./formblocks cli run part.place part=44302a colour=4 'position=[0,-100,0]' +./formblocks cli run part.set_transform id=p1 'position=[0,-100,0]' +./formblocks cli run part.place part=44301a colour=1 'position=[63,-102,2]' 'rotation=[-1,0,0,0,1,0,0,0,-1]' +``` + +The last answered `seated` true at `[60, -100, 0]`, one joined pair and a mark at `[30, -98, 0]`. With `part.fit`, the same half unturned at `[2, -101, 1]` answered `seated` false, a three-finger plate hinge half held against another `4275b` answered false, and a `4276b` held against a `4275b` turned a half turn answered true at `[60, -100, 0]`; unturned it answered false. `3938` seated on `3937` at `[0, -100, 0]`. + +## Opening and closing a hinge + +`part.pivot` (read) on a seated half answers `kind` `hinge`, the hinge's point as `about` and its axis in `axes` (LDraw and scene axes); a clip seated on a bar answers the same, since it turns on the bar. Give that point and axis to `part.rotate`: + +```bash +./formblocks cli run part.pivot 'ids=["p2"]' +./formblocks cli run part.rotate 'ids=["p2"]' 'axis_vector=[0,0,-1]' 'about=[30,-98,0]' angle=90 +``` + +The half turned 90 degrees, from `[60, -100, 0]` to `[28, -128, 0]`. `part.rotate` turns only the placements in `ids`: when other parts are attached to the half, give their ids too. A hinge turns all the way round; with the person's overlap check on, a turn into a part that does not turn is refused (`sub-skills/turning-parts/SUB-SKILL.md`). In the window the person turns the same half with the one ring of the pivot dial, in angle steps. + +## What overlap.check says + +Two halves joined by a seated hinge answered `count` 0. A clip seated on a bar, anywhere along it, answered `count` 0 and `nested_count` 0: a pair joined by a seated connector is fitted, never an overlap and never nested. + +## Not found, not built + +A hinge or clip drawn without the library's own pieces is found only where the engine's list of corrections names it (the 1 x 2 hinge brick, the swivel plates, the 1 x 1 tile with a clip); other parts do not snap, so place them by position and say so. Pins, axles, ball joints, a bar into a hole, hinge turning limits, click positions and flexible parts are not built: do not promise them. diff --git a/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md index 0d46b5d..2b050bd 100644 --- a/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md +++ b/skills/formblocks-driving/sub-skills/files/SUB-SKILL.md @@ -27,7 +27,7 @@ A saved file holds references to parts (`3001.dat`), never a part's own lines. F | `model.insert` | change | `path`, `position`, `submodel` | Brings another `.ldr`, `.mpd` or `.fblk` in as new submodels and places one use of its main model (at `position`, or the origin). | | `model.recent` | read | none | The last ten files opened or saved, newest first, each with whether it still exists. | | `model.report` | read | none | What opening reported: lines that could not be read, with their numbers, and the text encoding. | -| `model.info` | read | none | The model's title, author, licence, file, library update, counts and size. | +| `model.info` | read | `table` | The model's name, title, author, licence, file, library update, counts, size and missing parts, with its parts list unless `table` is false (`sub-skills/model-information/SUB-SKILL.md`). | | `model.set_info` | change | `title`, `author`, `licence` | Changes the main model's header: the title (its file's first line), the author, and the licence, empty or one of the Creative Commons licences the parameter lists. | Two other commands write files of their own and wait for the person like a save: `parts.list_save` (a CSV, `sub-skills/parts-list/SUB-SKILL.md`) and `picture.save` with `picture.steps` (PNG pictures, `sub-skills/pictures/SUB-SKILL.md`). diff --git a/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md new file mode 100644 index 0000000..b9e46d0 --- /dev/null +++ b/skills/formblocks-driving/sub-skills/model-information/SUB-SKILL.md @@ -0,0 +1,40 @@ +--- +name: model-information +description: Reads and changes a FormBlocks model's own information, its name, description, author, licence, counts, size, file facts and missing parts, with model.info, model.set_info and submodel.rename, the facts the window shows in its Info tab. Use when asked what a model is, how big it is, how many parts, colours or steps it has, which parts the library lacks, who made it, what licence line it carries, or to set its title, author, licence or name. +--- + +# Model information + +The window's Info tab (the fourth tab of the right column) shows these facts and lets the person edit four of them. The engine counts every value; an agent reads and writes the same ones. + +## Reading: model.info + +`model.info` (`cmd_model_info`, read) answers: + +| Key | What it holds | +| --- | --- | +| `name`, `title`, `author`, `licence` | The main model's `Name:` line, its description (the title line an LDraw file starts with), its author, and the licence line, empty when none. | +| `path`, `kind`, `builtWith`, `library` | The file it came from or was saved to, its kind (`fblk`, `ldr`, `mpd`), the library update it was last saved with (`null` for an LDraw file that did not come from FormBlocks), and the update in use. | +| `counts` | `placements`, `parts` (through every use of a submodel), `differentParts`, `colours`, `pairs` (part and colour rows), `submodels`, `steps` of the main model, `missing` (parts the library lacks) and `overlaps` (as `overlap.check` counts them, nested pairs left out). | +| `size` | `ldu`, `studs`, `bricks`, `plates`, `mm` and the `box`; an LDU is 0.4 mm. | +| `missingParts` | Each part the library lacks: `part`, `file` and `count`. | +| `licences` | The licence lines `model.set_info` accepts. | +| `partsList`, `csv` | The parts list rows and its CSV text. Pass `table` false to leave them out; the answer is large on a big model. | + +On the library's sample car, `model.info` with `table` false answered 61 placements, 26 different parts, 7 colours, 32 rows, 8 steps, 0 overlaps and a size of 4.5 by 10.8 studs and 5.17 bricks high, which a hand count of the file matched. + +## Changing it + +| Command | Parameters | What it changes | +| --- | --- | --- | +| `model.set_info` | `title`, `author`, `licence` | The description, the author and the licence line. Any of them may be left out. `licence` is empty or one of the lines in `licences`; another is refused with the list. | +| `submodel.rename` | `name`, `new_name` | The main model's name when `name` is it, and every use of it. `.ldr` is added when `new_name` has no extension. | + +Each is a change command: one undo step labelled "Change model information" or "Rename ...", approved by the person when it comes from outside the window. A model that was never saved keeps its changes only in memory until `model.save_as`. + +## Habits + +- Read `counts` and `missingParts` before telling the person a build is complete; a part in `missingParts` is drawn as a marked box and counted in the parts list as "Not in this library". +- `overlaps` here is the same as `count` in `overlap.check`; for the pairs themselves call `overlap.check`. +- Set the licence line only when the person says which; it describes the model, never the parts, which keep their own licences. +- The window shows a changed value in place at once, because the tab is rewritten from the engine's answer. diff --git a/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md index d673fcd..43eb734 100644 --- a/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md +++ b/skills/formblocks-driving/sub-skills/placing-and-snapping/SUB-SKILL.md @@ -78,7 +78,7 @@ The full list is `references/error-codes.md`. ## The overlap check -The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's body box would overlap another part's; with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. +The overlap check is the person's switch, off at the first start. With it on, `part.place` refuses a place where the part's real shape would cut more than 1 LDU into another part's (a part resting in a hollow it fits is not refused, and a nested pair never is); with it off, parts may share space without a word. Either way `overlap.check` reports overlaps on demand (`sub-skills/checking-a-model/SUB-SKILL.md`). The switch, like snapping and the grid step, is the person's setting: ask before you change it, and prefer `overlap.check` after placing, which changes nothing. ## Habits that save undo steps diff --git a/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md b/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md new file mode 100644 index 0000000..a52a37b --- /dev/null +++ b/skills/formblocks-driving/sub-skills/turning-parts/SUB-SKILL.md @@ -0,0 +1,52 @@ +--- +name: turning-parts +description: Turns placed parts in FormBlocks by any angle with part.rotate (angle in degrees or quarter turns, about x, y or z or any axis_vector, about a point), reads what a turn would turn about with part.pivot, and explains the angle step, the pivot dial and J that the person uses in the window. Use when asked to turn, tilt, tip, roll, angle or swivel parts, to turn by 45 or 22.5 degrees, to turn about a stud, a corner or a hinge, when a turn lifts a part or is refused, or when the person talks about the pivot dial or the angle step. +--- + +# Turning parts + +A turn is one `part.rotate` and one undo step, whoever asks for it: the person's key, a drag on the pivot dial, or an agent. + +## What part.rotate takes + +| Parameter | Meaning | +| --- | --- | +| `ids` | Placement ids such as `["p1","p2"]`; the selection when left out, which may be the person's, so pass `ids`. | +| `axis` | `x`, `y` or `z`, LDraw's axes, `y` being up and down. Give this or `axis_vector`. | +| `axis_vector` | Any direction as `[x, y, z]` in LDraw axes, such as a hinge's axis, in place of `axis`. | +| `quarter_turns` | Whole quarter turns, right-handed about the positive axis; negative goes the other way. Give this or `angle`. | +| `angle` | Degrees, right-handed about the axis; negative goes the other way. | +| `about` | The point to turn about, in LDU. Left out, the centre of the box round the placements' real shapes. | + +Giving both `quarter_turns` and `angle`, or neither, or neither axis, is refused with a sentence that names the parameter. A quarter turn leaves a part where its studs can seat again; any other angle does not seat anything, and a turn never seats a part. Four quarter turns give back the same numbers exactly; other angles are settled to six places. + +```bash +./formblocks cli run part.rotate 'ids=["p1"]' axis=y angle=45 +./formblocks cli run part.rotate 'ids=["p1","p2"]' axis=y quarter_turns=1 'about=[0,0,0]' +``` + +The answer lists each turned placement with its new `position`, `rotation` and `matrix`, the `about` point, the `angle` and `axis` used, and `lifted`, how far the turned parts were raised. + +## Two rules the engine keeps + +- A turn never leaves a part below the ground. When the turned parts would end lower than the ground, the whole turned group is lifted straight up until it rests on it, and `lifted` says how far. A 2 x 4 brick standing on the ground, turned 45 degrees about y and then 90 about x, answered `lifted` 28.426 on the second turn. +- With the person's overlap check on, a turn that would push a turned part into a part that does not turn is refused and nothing turns: "ids: the turn would overlap p1 with p2 by 3.0 LDU with the overlap check on, so nothing was turned." With the check off the turn happens and `overlap.check` reports it afterwards. + +A turn of a whole number of full circles changes nothing and adds no undo step. + +## part.pivot + +`part.pivot` (read) says what the person's pivot dial turns about: for `ids` or the selection, `kind` `centre` with the centre of the box and the three axes in LDraw's axes (`about`, `axes`) and in the window's scene axes (`scene`), and `reach`, how far the box extends from the point. For one part joined by a hinge it answers the hinge's own point and axis alone. With a pointer ray (`origin`, `direction`, scene axes) it answers the point the ray meets on a part, or the connector within 8 LDU of it. Use it to find the axis for an `axis_vector` turn; it changes nothing. + +## The angle step, the person's setting + +`angle.step` (`step`: 90, 45, 22.5, 15, 5 or 1) sets the step the dial and Alt with R, T or Y turn by; it is the person's setting like the grid step, so ask before changing it. `part.rotate` does not use it: give the angle you want. + +## What the person sees + +Selected parts show a green pivot ring lying flat about the up axis; pressing on it and dragging turns them in angle steps, Shift for whole degrees, Esc to put them back. J shows three rings and a click on a part sets the pivot on its nearest connector. A key turn is Alt with R, T or Y; A goes to the next angle step. An agent's turn shows in the window at once. Typing an angle on the dial is not built; send `part.rotate` instead. + +## Traps + +- `part.rotate`'s `axis` is LDraw's, with -Y up. A pointer ray's axes are the scene's (`sub-skills/moving-parts/SUB-SKILL.md`). +- After a turn other than a quarter turn nothing is seated: check with `overlap.check`, and turn the part back or move it if the person wants it joined. diff --git a/skills/formblocks-harness/SKILL.md b/skills/formblocks-harness/SKILL.md index 00b4f7a..a0cc957 100644 --- a/skills/formblocks-harness/SKILL.md +++ b/skills/formblocks-harness/SKILL.md @@ -1,10 +1,10 @@ --- name: formblocks-harness -description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, meshes, connections, command catalogue), its window, its setup scripts, its agent dock wiring or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, boot and ports, doctor, selfcheck, contract and agents checks, looking at the window headless under throttling with layout shift recorded, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash or flicker, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, where code lives, what packages may import, and adding a command, a connector kind, a router, a pane, or an agent program to the dock. Also the picture round trip, the parts list's rows, the parts library's scratch copy, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." +description: "Use when asked to install, boot, verify, debug, extend or release the FormBlocks repository itself: its engine code (the LDraw reader, parts library, meshes, connections, command catalogue), its window, its setup scripts, its agent dock wiring or its skill packs. Works on the checkout as a developer agent: the ./formblocks launcher, boot and ports, doctor, selfcheck, contract and agents checks, the window looked at headless under throttling with layout shift recorded, the CLAUDE.md laws (hand-made single-region edits, zero DOM flash, tokens, no emoji, HASHOUT logs, one commit identity), the clean room with spec/ as the authority, where code lives, and adding a command, a connector kind, a router, a pane, or an agent program to the dock. Also the picture round trip, the parts list's rows, the library's scratch copy, freezing the engine and the release. Not for building models in a running FormBlocks through its MCP tools or command line; that is formblocks-driving." license: Apache-2.0 metadata: product: FormBlocks - pack-version: "0.4.0" + pack-version: "0.5.0" audience: developer agent --- diff --git a/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md b/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md index a2075b1..1559257 100644 --- a/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md +++ b/skills/formblocks-harness/sub-skills/add-connector-kind/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: add-connector-kind -description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding pins, axles, clips, bars, hinges or any joint beyond studs and anti-studs, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. +description: Adds a connector kind to FormBlocks' connection model as a module that registers itself in backend/app/connect/kinds/, with its data beside it as JSON. Use when adding a joint beyond studs, anti-studs, clips, bars and the hinge families, such as pins or axles, when correcting the primitive list of an existing kind, or when a part's connectors come out wrong. --- # Add a connector kind @@ -36,6 +36,11 @@ A subclass of `Kind` from `backend/app/connect/kinds/__init__.py`: | `from_mesh(mesh, connectors)` | Optional: connectors found from the whole flattened part. | | `mate(a, b)` | `None`, or a `Mate`: the correction that brings `a` onto `b`, the residual, and the `Freedom` left (`Freedom.spin`, `slide`, `hinge` or `fixed`). `axial_mate` covers round connectors on a shared axis. | | `blocks(connector, other)` | Optional: a blocked test of the kind's own, as the stud's blocked-stud test is. | +| `line` | True when the connector is a line, not a facing: its axis has no sign, the mate compares lines (clips, bars and hinge halves). | +| `takes_step` | True when the seat moves in grid steps: `mate(a, b, step)` is then also given the grid step's across value, and gets 0 when pairs are only being counted. | +| `spans` | True when a connector is a segment from `position` along `axis` for `length` (a bar): reach and mating distance are measured to the segment, the spatial hash keeps it by every cell it passes, and it is taken stretch by stretch. A `Mate` then says where along the partner it sits (`at`) and half the stretch it takes (`span`). | + +`kinds/clip.py` (clip and bar) and `kinds/hinge.py` (the five hinge families, three read from primitives and two from overrides only) are the worked examples; each has its numbers in `clip.json` or `hinge.json`. `mates_with` is declared once per kind and the registry makes it symmetric, so a half pairs only with the other half of its own family. Connectors already carry `ref` (for kinds whose turn about the axis matters) and `length` (for kinds that slide), so the connector shape does not change. @@ -48,5 +53,6 @@ Connectors already carry `ref` (for kinds whose turn about the axis matters) and 1. Selfcheck: `backend/venv/bin/python backend/formblocks_engine.py --selfcheck` imports the kinds. 2. With a library in reach, `./formblocks cli run part.connectors part=[number]` for each part you worked by hand: the counts, positions, axes and `source` must match your numbers. Run it with a throwaway data folder (`--settings-dir ''`) so no old cache answers. 3. Place two parts that should mate with `part.fit` and `part.place` and read `seated` and `joined`; run `overlap.check`. -4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. -5. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. +4. Check the stud kind still answers as before: `part.connectors` for `3001` gives 8 studs and 11 anti-studs, as `spec/CONNECTIONS.md` Example 1 works out. `part.connectors` takes `kind` to list one kind, and its counts always cover every kind. +5. A mate that is a line needs the half turned first: snapping never turns a part. Check a pair with `part.fit` once turned and once not, as `spec/CONNECTIONS.md`, "Worked snaps: a clip along a bar, and hinge halves", does, and read `seated`. +6. Log the kind, its sources and the parts you checked in `backend/app/connect/HASHOUT_LOG.md`, in the same commit as the module. diff --git a/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md b/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md index fd877a7..406f3d8 100644 --- a/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md +++ b/skills/formblocks-harness/sub-skills/add-dock-program/SUB-SKILL.md @@ -41,4 +41,5 @@ The Outside agents tab is the model: kind `agent`, read only, made by the engine ## Checking -Only Claude Code may be real on a check machine, and nothing may sign in or start a paid turn. Codex may be installed from the npm registry into a scratch prefix under `/tmp` to check its version call and that it takes the arguments. Every other program is checked with a stand-in: a script under `/tmp` named as the program, put on the path through `FORMBLOCKS_[PROGRAM]_BIN`, which records its arguments, folder, environment names and the MCP entry it finds, then calls the MCP address with the token it was given. Open its tab in the window headless (`sub-skills/verify/SUB-SKILL.md`), then check: `formblocks_status` with the tab's token answers 200, `/api/terminal` with it 403, the token absent from the arguments, 401 after the tab closes, the shell tab's environment without either variable, `./formblocks [program] --print-config`, `./formblocks agents status`, and layout shift 0 opening and closing the tab. Say which programs were real and which were stand-ins. +Nothing may sign in or start a paid turn. On 27 November 2026 all four programs were real on a check machine: Claude Code from the machine, Codex from the npm registry into a scratch prefix, and Cursor's agent and Antigravity from their own installers into a scratch home folder given to the engine as `HOME`, so the finder found them in their known folders. +When an installer cannot be reached, or for a program being added, use a stand-in: a script under `/tmp` named as the program, put on the path through `FORMBLOCKS_[PROGRAM]_BIN`, which records its arguments, folder, environment names and the MCP entry it finds, then calls the MCP address with the token it was given. Open its tab in the window headless (`sub-skills/verify/SUB-SKILL.md`), then check: `formblocks_status` with the tab's token answers 200, `/api/terminal` with it 403, the token absent from the arguments, 401 after the tab closes, the shell tab's environment without either variable, `./formblocks [program] --print-config`, `./formblocks agents status`, and layout shift 0 opening and closing the tab. Say which programs were real and which were stand-ins. diff --git a/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md b/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md index d53f42e..65942d2 100644 --- a/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md +++ b/skills/formblocks-harness/sub-skills/add-pane/SUB-SKILL.md @@ -24,5 +24,6 @@ Load `sub-skills/laws-and-logs/SUB-SKILL.md` first. The window renders what the 4. Style it in `frontend/src/styles/[name].css`, linked once in `frontend/index.html` beside the others. Every colour, space, size and layer is a `var(--...)` from `styles/tokens.css`; add a token there when none fits. No raw colour, no numeric `z-index`. Interface text goes in `ui/strings.ts`. 5. Icons: add a hand-written inline `currentColor` SVG to `ui/icons.ts` and use `icon('[name]')`. No icon library, no copied icon art, never a three-star sparkle. 6. A window command (a button, a menu item, a key) is added through `commands` in `ui/commands.ts`, so the palette, the menu and the keys all find it. A command that changes the document calls `runCommand` with an engine command; it never changes the view directly. -7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. The right column's tabs (Model, Steps, Parts) come from the one list in `ui/tabs.ts`; a pane there takes its host with `tabHost(name, fn)` and hears `onTabShown`. A list that can grow long uses `RowScroller` from `ui/parts-list-scroller.ts` and its rules (`sub-skills/parts-list-rows/SUB-SKILL.md`). A panel over the view, like Save Picture, is built once hidden and shown at its final size. +7. A new region of the shell is a change to `SHELL` and `ShellHosts` in `ui/shell.ts` and to the grid in `styles/shell.css`. Make it only when no existing host fits, and log why in `frontend/HASHOUT_LOG.md`. The right column's tabs (Model, Steps, Parts, Info) come from the one list in `ui/tabs.ts`; a pane there takes its host with `tabHost(name, fn)` and hears `onTabShown`. The column is three sections, the colour palette, the tabs and the details panel, laid out and folded by `ui/splits.ts` with their least, default and greatest heights and the header height from `styles/tokens.css`; the tab section takes the room the other two leave, the heights and folds are kept in the engine's `right_column` setting and read before the first paint, and Reset Right Column is a window command. + A new tab never changes those heights: give it a place in the one list and fill its host in place, as the Info tab does (`ui/model-info.ts`, every value's place present before it arrives). A list that can grow long uses `RowScroller` from `ui/parts-list-scroller.ts` and its rules (`sub-skills/parts-list-rows/SUB-SKILL.md`). A panel over the view, like Save Picture, is built once hidden and shown at its final size. 8. Verify: `npm run typecheck` and `npm run build` in `frontend/`, then look at the window headless (`sub-skills/verify/SUB-SKILL.md`, "Looking at the window"): a screenshot of the pane, and a hard reload under 4x CPU and network throttling with a layout shift score of 0. Say what you looked at, or that it was not run. Log the decision in `frontend/HASHOUT_LOG.md` in the same commit. diff --git a/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md b/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md index 6a13d0c..288fc67 100644 --- a/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md +++ b/skills/formblocks-harness/sub-skills/freeze-and-ship/SUB-SKILL.md @@ -19,7 +19,7 @@ Nothing in this repository pushes, signs (beyond the frozen engine on macOS) or | `./build_app` | a desktop build for a person, start to finish | Logs to `build_app.log`; `--no-install`, `--install`, `--open`, `--clean`, `--config FILE`. | | `./formblocks clean`, `clean --all` | removes build output; `--all` also the venv and `node_modules` | Ask before `--all`: other agents may be using them. | -Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing, as on the check machines here, no Tauri build runs: say so, never claim one passed. +Windows has a `.bat` twin of every script. A desktop build needs WebKitGTK (`libwebkit2gtk-4.1-dev`) on Linux; where it is missing no Tauri build runs: say so, never claim one passed. One Linux build (deb and AppImage, unsigned) has run; its report is in `src-tauri/HASHOUT_LOG.md`. Its self-check imports numpy and every module, and the freeze must carry the connector data files (clip and hinge kinds included). macOS, Windows, signing and rpm are not run. ## Data files the freeze must carry diff --git a/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md b/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md index bb6ae9b..0bb322c 100644 --- a/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md +++ b/skills/formblocks-harness/sub-skills/verify/SUB-SKILL.md @@ -44,7 +44,7 @@ This is the method the 0.4.0 lanes used, several at once in one tree. Then do each interaction you built and add up `window.__shifts` entries without `input`. A score above 0 on load or on any of them is a defect to fix. Vite's development server sends hundreds of modules, so under this network a load takes over a minute: give it the time rather than lifting the throttle. 6. The outside agent path: run `./formblocks mcp` as a child process speaking JSON-RPC on its standard input and output, call the tool in one thread, and answer the window's question from Playwright in the other. The question is a dialog; the dock's Chat holds a hidden button of the same name, so pick the visible one (`page.get_by_role("button", name="Allow once", exact=True).locator("visible=true")`). The answer from a test is yours as the person in a scratch data folder, never an agent's on a real one. -7. Agent programs: only Claude Code may be real here, never signed in; the others are stand-ins (`sub-skills/add-dock-program/SUB-SKILL.md`). Say which were which. +7. Agent programs: never sign in. Use the real programs where they install (all four did on 27 November 2026) and a stand-in where one cannot (`sub-skills/add-dock-program/SUB-SKILL.md`). Say which were which. 8. Scripts, screenshots and data stay under `/tmp`, never in the repository. Stop the engine, Vite and the browser when the check is done, each by the process id you started; never by name, since other lanes' engines carry the same name. ## What CI runs diff --git a/spec/CONNECTIONS.md b/spec/CONNECTIONS.md index 7302fc4..e77f181 100644 --- a/spec/CONNECTIONS.md +++ b/spec/CONNECTIONS.md @@ -2,11 +2,11 @@ FormBlocks' own model of where parts connect and how a dragged part seats on another. The LDraw library describes shapes only and records nothing about connections, so every rule here is our own design, derived from the geometry of official library files and from the LDraw specifications summarised in `spec/LDRAW.md`. No other program's connection data, format or documentation was read or used. Statements taken from LDraw documents or measured in a library file carry a source key in square brackets, listed under "Sources" at the foot; everything without a key is our own design. -Version 0.1.0. Written for Phase 5 of the development plan. The code lives in `backend/app/connect/`. +Version 0.1.0. Written for Phase 5 of the development plan. The code lives in `backend/app/connect/`. Clips, bars and hinges were added in 0.5.0 (see "Clips and bars", "Hinges" and "Snapping clips and hinges"). ## Scope of this pass -- Two connector kinds: `stud` and `anti_stud`. Pins, axles, clips, bars, hinges, ball joints and flexible parts are later kinds, added as modules without changing the service (see "Adding a kind"). +- Two connector kinds in 0.1.0: `stud` and `anti_stud`. 0.5.0 adds two modules: the clip module (`clip` and `bar`) and the hinge module (three pairs of hinge halves). Pins, axles, ball joints and flexible parts are later kinds, added as modules without changing the service (see "Adding a kind" and "Left for later"). - Snapping while a part is dragged, a grid when nothing snaps, an overrides file for parts the derivation gets wrong, and the overlap check (the coarse check `spec/NAMES.md` names), which can be switched off. - All coordinates are LDraw coordinates in LDU, with -Y up [LDRAW]. The conversion to the window's scene happens only in the engine's mesh output [LDRAW]; nothing in this document is in scene coordinates. @@ -35,9 +35,9 @@ A connector is one place on a part where another part can attach, in the part's | Field | Meaning | | --- | --- | -| `kind` | The registered kind's name, lower case with `_`. This pass registers `stud` and `anti_stud`. | -| `position` | A point on the mating plane, in LDU, part coordinates. | -| `axis` | A unit vector pointing out of the part, the way the connector faces: from a stud's base to its tip; from a receptacle out through its opening. | +| `kind` | The registered kind's name, lower case with `_`. 0.1.0 registered `stud` and `anti_stud`; 0.5.0 adds `clip`, `bar` and the six hinge halves. | +| `position` | A point on the mating plane, in LDU, part coordinates. For a clip, a bar or a hinge half, a point on the line it turns or slides about (see "Clips and bars" and "Hinges"). | +| `axis` | A unit vector pointing out of the part, the way the connector faces: from a stud's base to its tip; from a receptacle out through its opening. For a clip, a bar or a hinge half it is the direction of a line, and its sign carries no meaning. | | `ref` | A unit vector at right angles to `axis` for kinds whose turn about the axis matters (a cross axle, a clip). `null` for studs and anti-studs, which are round. | | `length` | The distance along `axis` over which a partner may sit, for kinds that slide (an axle, a bar). 0 for studs and anti-studs. | | `source` | Where it came from: the primitive file name, `grid`, `tube:` or `override`. Shown when a person inspects a part; never used by the snapping rule. | @@ -47,7 +47,7 @@ Rules: - Positions are rounded to 0.001 LDU and axes are normalised when a connector is made, so the same part always gives the same numbers. - A part's connectors are kept in one list sorted by `kind`, then `y`, then `z`, then `x`. Sorting makes the list stable, so two runs and two machines give the same order. - To get a placed connector in model coordinates: `position_model = P * position` (as a point), `axis_model = normalise(R * axis)` where `R` is the 3 by 3 part of `P`. -- Two connectors mate when their kinds are a registered pair, their model positions are within 0.5 LDU of each other, and their model axes point in opposite directions within 5 degrees (`dot <= -cos 5 degrees`). The tolerances are wide enough for the three-decimal rounding of official files and narrow enough that a neighbouring stud, 20 LDU away, can never qualify. +- Two connectors mate when their kinds are a registered pair, their model positions are within 0.5 LDU of each other, and their model axes point in opposite directions within 5 degrees (`dot <= -cos 5 degrees`). The tolerances are wide enough for the three-decimal rounding of official files and narrow enough that a neighbouring stud, 20 LDU away, can never qualify. Clips, bars and hinge halves keep the two tolerances but compare lines, not facings, and a clip meets a bar anywhere along it: see "Snapping clips and hinges". ## The first two kinds @@ -158,6 +158,152 @@ Bricks and plates are open boxes: walls round the footprint, a ceiling 4 LDU abo - Rule T places a receptacle in every tube, including tubes in places a stud cannot reach from outside; the "blocked stud" test of the snapping rule and the overrides file are the remedies. - Both rules assume the underside faces +y, as official parts with studs are modelled [LIB]. A part drawn on its side gets no rule G anti-studs. +## Clips and bars + +Added in 0.5.0. A clip is a pair of jaws that close round a rod; a bar is a rod with enough room round it for jaws to close on it. The clip module, `backend/app/connect/kinds/clip.py`, registers both kinds. + +### One size of bar + +The library's reference describes its clip primitives as made "to hold an 8LDu diameter pole or rod" [PRIM-M], and every clip primitive counted below has a gripping surface of radius 4 [PART-2]. So 0.5.0 knows one size class, 8 LDU across, and the kinds `clip` and `bar` are that class. A rod of another size would be another pair of kinds, never a test inside these two, because the snapping rule compares only kinds. + +### `clip` + +- `position`: the centre of the grip, on the line a held bar's axis lies on, midway across the jaws' width. +- `axis`: along that line. A clip grips the same either way along it, so the sign of the axis carries no meaning here, unlike a stud's; the module writes the primitive's own direction. +- `ref`: at right angles to `axis`, from the grip's centre out through the opening between the jaws, the way a bar enters. +- `length`: the jaws' width along the axis, 8 LDU for every clip counted. +- Mates with: `bar`. + +### `bar` + +- `position`: one end of the bar's free length, on its axis. +- `axis`: along the bar, from that end to the other. Again the direction is a line, not a facing. +- `ref`: `null`; a bar is round. +- `length`: the free length, the stretch of the bar where jaws fit round it, in LDU. +- Mates with: `clip`. + +### Deriving clips + +The walk claims clip primitives by exact file name, as it claims studs, and does not descend into them. The module's data file, `kinds/clip.json`, gives for each file the grip's centre `c`, its axis `a`, its opening `o` and its width `w` in the primitive's own axes, read by us from the radius 4 cylinder primitives each file references [PART-2]: the centre is the middle of the cylinder's run, the axis is the cylinder's own, and the opening is the middle of the arc the cylinders leave uncovered. + +For a claimed reference with accumulated transform `M'` (3 by 3 part `R'`): `position = M' c`, `axis = normalise(R' a)`, `ref = normalise(R' o)`, `length = w`. A clip is kept only when it is unscaled (each column of `R'` has length 1 within 0.01), since a scaled grip no longer holds an 8 LDU bar. Two clips closer than 0.5 LDU are one. + +Counted, each file read in the 2026-10 library; the description is the file's first line, and the reference entry is quoted where the reference has one [PRIM-M, PART-2]: + +| File | Description | Centre | Axis | Opening | Arc covered | +| --- | --- | --- | --- | --- | --- | +| `clip1.dat` | Vertical Clip for Flags; reference: "a vertical clip designed to hold an 8LDu diameter pole or rod" for flag parts | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 180 degrees | +| `clip2.dat` | Vertical Clip for Bricks; reference: the same, for brick parts | (0, 0, -10) | (0, 1, 0) | (0, 0, -1) | 180 | +| `clip3.dat` | Clip Horizontal with Parallel Sides; reference: "a horizontal clip designed to hold an 8LDu diameter pole or rod" | (0, 2, 0) | (1, 0, 0) | (0, 0, -1) | 225 | +| `clip5.dat` | Clip Symmetrical with Rounded Sides | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip6.dat` | Clip Horizontal with Rounded Sides | (0, 2, 0) | (1, 0, 0) | (0, 0, -1) | 225 | +| `clip7.dat` | Clip for Round Arm 4 LDU (the 4 is the radius) | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip8.dat` | Top Clip with Rounded Tips and Centre Notch | (0, -6, 0) | (0, 0, 1) | (0, -1, 0) | 180 | +| `clip9.dat` | Clip Vertical (Thin C-Clip) | (0, 0, -10) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip10.dat` | Clip Vertical (Thin U-Clip) | (0, 0, -10) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip11.dat` | Top Clip with Rounded Tips | (0, -5.994, 0) | (0, 0, 1) | (0, -1, 0) | 225 | +| `clip12.dat` | Clip without Attachment (Thick C-Clip); reference: a thick C clip "for use with organic shape parts with a clip" | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip13.dat` | Clip Minimal (Thick C-Clip) | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip14.dat` | Clip Vertical (Thick U-Clip) with Centre Notch | (0, 0, -10) | (0, 1, 0) | (0, 0, -1) | 180 | +| `clip15.dat` | Clip for Round Arm 4 LDU without Adapter | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 225 | +| `clip16.dat` | Vertical Thick Clip for Flags | (0, 0, 0) | (0, 1, 0) | (0, 0, -1) | 225 | + +Every one is 8 LDU wide along its axis. + +Not counted: + +| Files | Why not | +| --- | --- | +| `clip4.dat` | Its first line is "Clip for Roadsign and Click-Hinge". The reference still lists `clip4.dat` as a three-fingered clip for an 8 LDU rod [PRIM-M], but the file in the 2026-10 library has no radius 4 surface: its only cylinders are two of radius 1.5 at x = -5.069 and 5.069 [PART-2]. Left out until it is read against a part that uses it. | +| `handle.dat`, `handle2.dat` | Handles for shields, gripped by a hand, not by a clip. | +| `phandle1.dat`, `phandle2.dat` | "Bar Handle Attachment with Open Side" and "with 2 Open Sides": the join between a handle's bar and its plate, not the bar. | +| `clh*.dat` | Click hinge fingers; see "Hinges". | + +### Deriving bars + +No primitive marks a bar. Bars are drawn with the library's ordinary cylinders [PRIM-M, PART-2]: `87994.dat`, Bar 3L, is one `4-4cyli.dat` with radius 4 and length 60; the handle of `2540.dat`, Plate 1 x 2 with Handle, is a `4-4cylo.dat` and two `4-4cylc.dat` on one line. So a bar is found from its shape: + +1. Candidates. A reference to a whole-circle cylinder, `4-4cyli.dat`, `4-4cylo.dat` or `4-4cylc.dat` (also from `p/48` and `p/8`, which the walk reduces to the same names), whose first and third columns of `R'` have length 4 within 0.05 (radius 4) and whose second column has length at least 1. In its own axes the cylinder has radius 1 and runs from y = 0 to y = 1 [PRIM-M], so its ends are `M' (0, 0, 0)` and `M' (0, 1, 0)`. Part circles are not candidates: a bar is drawn whole round, and a part circle of radius 4 is far more often a fillet, a hole's half or a jaw. +2. Joining. Candidates on one line (axes parallel within 5 degrees, each one's ends within 0.05 LDU of the other's line) whose stretches overlap or meet within 0.5 LDU are one stretch. +3. Free samples. Each stretch is sampled every 1 LDU, starting 0.5 in from its first end. A sample is free when eight probes from it, at right angles to the axis and 45 degrees apart, each running from radius 4.25 to radius 7.75, cross no triangle of the part. 7.75 is just over the outer radius of the thickest jaws read, 7.537 in `clip12.dat` and `clip13.dat` [PART-2]: a free sample is a place where those jaws could close. A hole of radius 4 has material round it, the solid bar under a 1 x N plate stands 2 LDU from the cavity's walls, and a bar's ends run into what holds them; none of these samples is free. +4. Bars. Each run of consecutive free samples whose span is at least 6 LDU is one bar: `position` at the run's first end (its first sample less 0.5), `axis` along the stretch, `length` the run's span (its number of samples, in LDU). 6 is the jaws' width less 1 LDU at each side, so a handle whose free part is a clip's width, measured to the sampling step, still counts. + +A bar's triangles count in the body box; a clip's too. + +### Where it will be wrong + +- A bar drawn with part circles or raw triangles, a bar scaled unevenly, and a clip drawn without a clip primitive (some recent parts draw their jaws from cylinders): not found. The overrides file adds them. +- Every free radius 4 rod is a bar, including rods not made to be gripped, such as a lever's shaft. That errs on the side of snapping, as studs do. +- Jaws thinner than 7.75 fit a little nearer an end than the free length says; the free length is the stretch where every clip read fits. +- A bar crossing another part's geometry within the same part (a ring round a pole) splits into two bars, which is right, but a ring thinner than the 1 LDU sampling step may be missed. + +## Hinges + +Added in 0.5.0. A hinge joint is two halves on one pivot axis: the knuckles (fingers) of one half sit between the knuckles of the other, and the two turn about the axis. Each half is one connector. The two halves of a joint are two different kinds, so a half never seats on a half like itself (two three-finger halves would occupy the same places). The hinge module, `backend/app/connect/kinds/hinge.py`, registers them. + +### A hinge half + +- `position`: the middle of the half's knuckles, on the pivot axis. Halves made to meet are drawn so that this point is the same on both, so seated halves share it. +- `axis`: along the pivot axis; a line, its sign without meaning. +- `ref`: at right angles to `axis`, from the axis into the half's own part, toward where its knuckles join it. The angle between two seated halves' refs about the axis is how far the hinge is open: 180 degrees when the two parts lie flat on either side. +- `length`: 0. +- Mates with: the other half of its family. + +### Three families + +The library draws three hinge systems with their own primitives, and their sizes differ, so each is its own pair of kinds and none mates across [PRIM-M, PART-2]: + +| Family | Half with fewer knuckles | Half with more knuckles | Size, as read | +| --- | --- | --- | --- | +| Click hinge | `hinge_click_1`: a single finger, `clh1.dat` and the other single-finger files | `hinge_click_2`: a dual finger, drawn as two mirrored half files such as `clh4.dat` | pins of radius 2.25 at the pivot, fingers 12 to 15 LDU from base to tip | +| Plate hinge | `hinge_plate_2`: two fingers, `h1.dat` | `hinge_plate_3`: three fingers, `h2.dat` | round knuckles of radius 4 on a 20 LDU long axis; the reference: "the standard two-fingered hinge" and "three-fingered hinge with a depth of 8LDu - the thickness of a plate" | +| Arm hinge | `hinge_arm_2`: two fingers, `arm1.dat` | `hinge_arm_3`: three fingers, `arm2.dat`, `arm3.dat` | discs of radius 10; the reference: "hinge component of the cylindrical arm with a radius of 10LDu" | +| Brick hinge | `hinge_brick_top` | `hinge_brick_base` | no primitive: the 1 x 2 hinge brick's top and base, `3938.dat` and `3937.dat`, are drawn from cylinders and boxes; the halves come only from the overrides file | +| Swivel plate | `hinge_swivel_top` | `hinge_swivel_base` | no primitive: the 1 x 4 hinge plates that turn flat about a vertical axis, `2430.dat` and `2429.dat`; from the overrides file only | + +The last two families have no files in `kinds/hinge.json`, only their kind names, so that override entries can give those parts their halves; they pair and turn like the others. + +### Deriving hinge halves + +The walk claims hinge primitives by exact file name and does not descend into them. The module's data file, `kinds/hinge.json`, gives for each file its kind, the pivot point `p`, the axis `a` and the ref `r` in the primitive's own axes, read by us from each file [PART-2]: the axis is the one the click pins (`4-4cylc.dat` or `4-4disc.dat` scaled to radius 2.25), the dual finger's click positions (`clh-finger.dat` turned in steps of 22.5 degrees), the plate fingers' round knuckles or the arm's discs are turned about; the point is the middle of the knuckles along it; the ref points to the side where the file's geometry meets its part. + +For a claimed reference: `position = M' p`, `axis = normalise(R' a)`, `ref = normalise(R' r)`. A half is kept only when unscaled (each column of `R'` of length 1 within 0.01). The two mirrored files of a dual click finger each give the same point, so they merge into one connector, the first one's axis kept. + +| File | Description | Kind | Point | Axis | Ref | +| --- | --- | --- | --- | --- | --- | +| `clh1.dat` | Click Lock Hinge Single Finger for Bricks | `hinge_click_1` | (0, 0, -10) | (1, 0, 0) | (0, 0, 1) | +| `clh2.dat` | Click Lock Hinge Single Finger for Plate Top | `hinge_click_1` | (0, -7, 0) | (1, 0, 0) | (0, 1, 0) | +| `clh3.dat` | Click Lock Hinge Single Finger for Arms Narrow Slot | `hinge_click_1` | (0, 0, -10) | (1, 0, 0) | (0, 0, 1) | +| `clh6.dat` | Click Lock Hinge Single Finger for Plate Ends | `hinge_click_1` | (0, 0, -10) | (1, 0, 0) | (0, 0, 1) | +| `clh6d.dat` | Click Lock Hinge Single Finger for Plate Ends - Opening Downwards | `hinge_click_1` | (0, 0, -10) | (1, 0, 0) | (0, 0, 1) | +| `clh6u.dat` | Click Lock Hinge Single Finger for Plate Ends - Opening Upwards | `hinge_click_1` | (0, 0, -10) | (1, 0, 0) | (0, 0, 1) | +| `clh8.dat` | Click Lock Hinge Single Finger for Crevices and Ledges | `hinge_click_1` | (0, 0, -7) | (1, 0, 0) | (0, 0, 1) | +| `clh9.dat` | Click Lock Hinge Single Finger for Plate Top with Groove | `hinge_click_1` | (0, -7, 0) | (1, 0, 0) | (0, 1, 0) | +| `clh12.dat` | Click Lock Hinge Single Finger Tall | `hinge_click_1` | (0, -7, 0) | (1, 0, 0) | (0, 1, 0) | +| `clh13.dat` | Click Lock Hinge Single Finger for Plate Top with Wide Groove 2L | `hinge_click_1` | (0, -7, 0) | (1, 0, 0) | (0, 1, 0) | +| `clh15.dat` | Click Lock Hinge Single Finger for Arms Wide Slot | `hinge_click_1` | (0, 0, -10) | (1, 0, 0) | (0, 0, 1) | +| `clh4.dat` | Click Lock Hinge Half Dual Finger - 4.5LDU | `hinge_click_2` | (0, 0, 4) | (1, 0, 0) | (0, 0, -1) | +| `clh5.dat` | Click Lock Hinge Half Dual Finger for Arms | `hinge_click_2` | (0, 0, 10) | (1, 0, 0) | (0, 0, -1) | +| `clh7.dat` | Click Lock Hinge Half Dual Finger 3-Position Type 1 | `hinge_click_2` | (0, 0, 4) | (1, 0, 0) | (0, 0, -1) | +| `clh10.dat` | Click Lock Hinge Half Dual Finger 7-Position | `hinge_click_2` | (0, 0, 4) | (1, 0, 0) | (0, 0, -1) | +| `clh11.dat` | Click Lock Hinge Half Dual Finger - Missing Clicks 2 and 4 | `hinge_click_2` | (0, 0, 4) | (1, 0, 0) | (0, 0, -1) | +| `clh14.dat` | Click Lock Hinge Half Dual Finger 7-Position for Arms | `hinge_click_2` | (0, 0, 10) | (1, 0, 0) | (0, 0, -1) | +| `h1.dat` | Hinge Plate 2 Fingers | `hinge_plate_2` | (0, 10, 0) | (0, 0, 1) | (0, -1, 0) | +| `h2.dat` | Hinge Plate 3 Fingers | `hinge_plate_3` | (0, 10, 0) | (0, 0, 1) | (0, -1, 0) | +| `arm1.dat` | Hinge Arm 2 Finger | `hinge_arm_2` | (0, 0, -10) | (0, 1, 0) | (0, 0, 1) | +| `arm2.dat` | Hinge Arm 3 Finger without Ribs with Round Middle Finger | `hinge_arm_3` | (0, 0, -10) | (0, 1, 0) | (0, 0, 1) | +| `arm3.dat` | Hinge Arm 3 Finger without Ribs with Truncated Middle Finger | `hinge_arm_3` | (0, 0, -10) | (0, 1, 0) | (0, 0, 1) | + +The half files of a dual click finger carry the library's own note "Requires 2 halves rotated 180 degrees apart on Z-axis" [PRIM-M]: such a turn leaves the point (0, 0, 4) where it is, which is why both halves give one point. + +Not counted: `clh2c.dat`, `clh3q.dat`, `clh5s.dat`, `clh6c.dat`, `clh-base.dat` and `clh-finger.dat`, the pieces the counted files are built from (claiming a piece would count the files that use it twice, and `clh-finger.dat` is part of the dual finger, not a single finger); the hinge primitives of the larger scale, `dhinge*.dat`, `ddoorhinge*.dat` and `dtruncdoorhinge*.dat`, which belong to another system of sizes, left for later. + +### Where it will be wrong + +- Hinges drawn without these primitives (the 1 x 2 hinge brick base and top, `3937.dat` and `3938.dat`, are drawn from cylinders and boxes) are not found. The overrides file adds them, as an entry with a hinge kind. +- The pivot point is the middle of the knuckles, so two halves seat with their middles together. A part whose knuckles are offset along the axis from the partner's by design would need an override. +- Turning limits are not modelled: a hinge turns all the way round, and the overlap check, when on, is what refuses a turn that cuts into another part. + ## Worked examples Each example is worked from the official files fetched on 26 November 2026 [PART]. The numbers were also produced by a throwaway script, outside the repository, that walked the fetched files with the rules above; it agreed with the hand working below. @@ -284,6 +430,67 @@ Anti-studs by rule G (4). `yb = 24`; vertices with y >= 16 span x -20 to 20 and Checks against the dimensions [LDRAW]: a 40 by 40 outline one brick high; two studs on the 20-deep flat top only; four receptacles under the full footprint with the tube at its centre. Seated squarely on a Brick 2 x 2 (`3003.dat`, studs at (+-10, 0, +-10) [PART]) the slope's origin sits at (0, -24, 10) from the brick's, and its four rule G receptacles then lie at (+-10, 0, -10) and (+-10, 0, 10) in the brick's coordinates: all four of the brick's studs. +### Example 5: `4085c.dat`, Plate 1 x 1 with Clip Vertical (Thick U-Clip) + +Worked from the 2026-10 library [PART-2], and checked with `./formblocks cli run part.connectors part=4085c` on 27 November 2026. + +The tree: `4085c.dat` references `box5.dat`, `box3u2p.dat` and two `rect3.dat` for the plate and the clip's neck, `stud.dat` with a quarter turn about y at the origin, and `clip2.dat` at (0, 4, -10) with the identity. + +Clip (1). `clip2.dat`'s grip, from the table in "Deriving clips", has its centre at (0, 0, -10), axis (0, 1, 0), opening (0, 0, -1), width 8. With `M'` the translation (0, 4, -10): `position = (0, 4, -20)`, `axis = (0, 1, 0)`, `ref = (0, 0, -1)`, `length = 8`. The reference is unscaled, so it is kept. + +Stud (1) at (0, 0, 0), axis (0, -1, 0): the turned `stud.dat` is still unscaled and round. + +| kind | position | axis | ref | length | from | +| --- | --- | --- | --- | --- | --- | +| clip | (0, 4, -20) | (0, 1, 0) | (0, 0, -1) | 8 | `clip2.dat` | +| stud | (0, 0, 0) | (0, -1, 0) | | 0 | `stud.dat` | + +Checks: the grip stands 20 in front of the stud, its centre 4 below the plate's top, the middle of the plate's 8 LDU thickness, so a vertical bar held in it passes the plate's front face at 10 from its edge; the opening faces away from the plate. Rule G gives no anti-stud: the clip's neck lies in the lowest 8 LDU and widens the footprint to z = -24, which is not whole cells ("Where it will be wrong" under "Deriving anti-studs"). + +### Example 6: `87994.dat`, Bar 3L, and `2540.dat`, Plate 1 x 2 with Handle + +`87994.dat` is one `4-4cyli.dat` with matrix `4 0 0 / 0 60 0 / 0 0 4` at the origin, closed by two discs [PART-2]. Rule step 1: columns 1 and 3 have length 4, column 2 length 60, so it is one candidate from (0, 0, 0) to (0, 60, 0). Step 3: samples at y = 0.5, 1.5, ... 59.5; the only other triangles are the end discs, radius 4 in the planes y = 0 and y = 60, which no probe from radius 4.25 reaches. Step 4: one run of 60 samples. + +| kind | position | axis | length | +| --- | --- | --- | --- | +| bar | (0, 0, 0) | (0, 1, 0) | 60 | + +`2540.dat` draws its handle as three cylinders on the line y = 2, z = -20: a `4-4cylo.dat` from x = 6 to -6 (matrix `0 -12 0 / 4 0 0 / 0 0 4`), and a `4-4cylc.dat` from x = -20 to -12 and another from x = 20 to 12 [PART-2]. Two legs, `phandle2.dat` at x = -9 and 9, carry the bar down to the plate and draw its surface where they join it. Step 2 joins nothing: the pieces are 6 LDU apart, more than 0.5. Step 3 finds every sample of each piece free, since the legs lie between the pieces. So the handle gives three bars, its middle between the legs and an end beyond each leg. The plate's own underside bar, `stud3.dat` at (0, 4, 0), is a radius 4 cylinder too and is a candidate, but every one of its samples has a probe that meets the cavity's walls 6 from its axis, so it gives none. + +| kind | position | axis | length | +| --- | --- | --- | --- | +| bar | (-12, 2, -20) | (-1, 0, 0) | 8 | +| bar | (6, 2, -20) | (-1, 0, 0) | 12 | +| bar | (20, 2, -20) | (-1, 0, 0) | 8 | +| stud | (-10, 0, 0) and (10, 0, 0) | (0, -1, 0) | 0 | + +Checks: the handle stands 10 out from the plate's front face at z = -10 and 2 LDU below its top; a clip 8 wide fits the middle stretch with 4 LDU to spare, and each end exactly. + +### Example 7: `44301a.dat` and `44302a.dat`, the locking 1 x 2 hinge plates with one and two fingers + +From the 2026-10 library [PART-2]: + +- `44301a.dat` references `s\44301s01.dat` with the identity, which references `clh6.dat` at (20, 2, 0) with matrix `0 0 -1 / 0 1 0 / 1 0 0`. `clh6.dat`'s half, from "Deriving hinge halves", has its point at (0, 0, -10), axis (1, 0, 0) and ref (0, 0, 1). So `position = (20 + 10, 2, 0) = (30, 2, 0)`, `axis = (0, 0, 1)`, `ref = (-1, 0, 0)`: the finger's pivot is 10 beyond the plate's end at x = 20, 2 below its top, along z, and the plate lies toward -x. +- `44302a.dat` references `clh4.dat` twice at (26, 2, 0), with matrices `0 0 1 / 0 1 0 / 1 0 0` and `0 0 1 / 0 1 0 / -1 0 0`: the two mirrored halves of the dual finger. `clh4.dat`'s point (0, 0, 4) goes to (26 + 4, 2, 0) = (30, 2, 0) under both, so they merge into one connector; the first one's axis is (0, 0, 1) and its ref, from (0, 0, -1), is (-1, 0, 0). + +| part | kind | position | axis | ref | from | +| --- | --- | --- | --- | --- | --- | +| `44301a.dat` | hinge_click_1 | (30, 2, 0) | (0, 0, 1) | (-1, 0, 0) | `clh6.dat` | +| `44302a.dat` | hinge_click_2 | (30, 2, 0) | (0, 0, 1) | (-1, 0, 0) | `clh4.dat` | + +Both also have two studs, at (-10, 0, 0) and (10, 0, 0). The two parts are drawn so their pivots are the same point: a `44301a.dat` turned a half turn about y (matrix `-1 0 0 / 0 1 0 / 0 0 -1`) and moved by (60, 0, 0) has its half at (-30 + 60, 2, 0) = (30, 2, 0), axis (0, 0, -1), ref (1, 0, 0). The axes are opposed, which for a line is parallel; the refs are 180 degrees apart; so the pair seats with the two plates lying flat end to end, 20 LDU apart. + +### Example 8: `4275b.dat` and `4276b.dat`, the 1 x 2 hinge plates with three and two fingers + +Each references its finger primitive at (20, 4, 0) with matrix `0 1 0 / 1 0 0 / 0 0 1`: `h2.dat` in `4275b.dat`, `h1.dat` in `4276b.dat` [PART-2]. Both primitives' halves have their point at (0, 10, 0), axis (0, 0, 1) and ref (0, -1, 0); the matrix swaps x and y, so `position = (20 + 10, 4 + 0, 0) = (30, 4, 0)`, `axis = (0, 0, 1)`, `ref = (-1, 0, 0)`. + +| part | kind | position | axis | ref | from | +| --- | --- | --- | --- | --- | --- | +| `4275b.dat` | hinge_plate_3 | (30, 4, 0) | (0, 0, 1) | (-1, 0, 0) | `h2.dat` | +| `4276b.dat` | hinge_plate_2 | (30, 4, 0) | (0, 0, 1) | (-1, 0, 0) | `h1.dat` | + +The knuckles' axis is 10 beyond the plate's end and level with the middle of its 8 LDU thickness, as the reference's "depth of 8LDu" says; two plates, one turned a half turn and moved 60 along x, meet on it as in Example 7. + ## Snapping while a part is dragged The engine runs the snap; the window sends the pointer and shows the result. The same function runs again on the drop, with the same input, so the preview and the committed placement never differ. @@ -313,7 +520,7 @@ Decided in 0.4.0. The point under the pointer is not always where the part can b Where it will be wrong: -- The test is the overlap check's, so a hollow it counts as solid (an arch, the inside of a tyre, the cavity under a part) can lift a part that would really fit there onto the next level. +- The test is the overlap check's. Until 0.5.0 that check counted a hollow as solid (an arch, the inside of a tyre, the cavity under a part) and could lift a part that really fits there onto the next level; since 0.5.0 it measures real solids and counts a part that only sits in another's hollow as nested, not overlapping, so such a part stays where it fits. A hollow narrower than the solids' 1 LDU cells can still read as solid. - Only the tops of slabs are levels. A stud's base and its part's top are the same plane on every part read for this rule (7,548 files of the 2026-10 library whose names begin 30 to 47 were checked: no stud stands more than 1 LDU above its part's top slab), so studs add no level of their own. - Levels more than 960 LDU above the raw pose, and any after the sixth, are not tried; the part then keeps the place at the pointer. @@ -370,6 +577,76 @@ The lower brick at the origin, the upper brick's connectors from Example 1, uppe So every whole-stud offset and both rotations seat, and the half-stud offsets that the tubes alone would allow are refused because the lower brick's other studs would hit the upper brick's walls. A 2 x 4 brick moved by (10, -24, 0) onto a 1 x 2 plate (Example 2) is different: the plate's studs at x = -10 and 10 land in the brick's tubes at x = -10 and 10, nothing else lies under the brick, so 2 pairs mate with no blocked stud and it seats, as real parts do. On a 1 x 4 plate the same offset leaves the end stud at x = -30 under the brick's end wall, and it is refused. +## Snapping clips and hinges + +Added in 0.5.0. The rule above applies unchanged to clips, bars and hinge halves: candidate pairs within the reach of 15 LDU, one correction per pair, counting, the blocked tests, tie-breaking and hysteresis. What these kinds bring is their own mate, a reach measured to a line, what a bar can still take, and the anchor. + +### Snapping never turns a part + +The standing rule holds for every kind. A mate whose axes are not already lined up proposes nothing; the person turns the part first, a quarter turn or the fine angle at a time (`spec/SPEC.md` 5.2), and the snap then seats it by moving it only. + +### The mate of two hinge halves + +1. The kinds are the two halves of one family (`hinge_click_1` with `hinge_click_2`, `hinge_plate_2` with `hinge_plate_3`, `hinge_arm_2` with `hinge_arm_3`). +2. Their axes are parallel or opposed within 5 degrees: `|dot| >= cos 5 degrees`. A pivot is a line, so either way round is the same axis. +3. Their refs, each projected into the plane at right angles to the first half's axis, are at least 30 degrees apart. Two halves folded flat onto each other would put both parts in one place, and no hinge closes that far. +4. The correction is the translation `d = b - a` of the two points, so the axes then coincide and the knuckles' middles meet: the pair seats when the axes coincide. The residual is `|d|`, and the pair mates when it is at most 0.5 LDU, as for studs. +5. The freedom left is `hinge(axis, -180, 180)`: a turn about the shared axis. Turning limits are not modelled (see "Hinges"). + +### The mate of a clip on a bar + +1. The kinds are `clip` and `bar`; the axes are parallel or opposed within 5 degrees. +2. With the bar's end `p`, its unit axis `u`, its free length `L` and the clip's centre `c` and width `w`, the clip's place along the bar is `t = (c - p) . u`, then moved to the nearest allowed place. +3. Allowed places: the clip's jaws stay on the free length, so `t` lies from `w / 2` to `L - w / 2`; within that stretch the places are `L / 2 + k s` for whole numbers `k`, where `s` is the grid step's across value (20 at Stud, 10 at Plate, 1 at Fine; see "The grid fallback"). The middle of the bar is always a place. When no other place falls in the stretch, or the free length is shorter than the clip, the middle is the only one. So a clip slides along a bar in grid steps measured from the bar's middle, and at the Fine step anywhere along it. +4. The correction is the translation from `c` to `p + t u`, which puts the clip's centre on the bar's axis. The residual is its length; the pair mates within 0.5 LDU. +5. The freedom left is `hinge(u, -180, 180)`: a clip turns on its bar. It also slides, but sliding is what the snap does, a step at a time, while the part is dragged. + +### Reach to a line + +For a bar, the reach of 15 LDU, and the 0.5 LDU of mating, are measured from the clip's centre to the bar's free length (the segment from `p` to `p + L u`), not to the bar's `position`. So a clip held anywhere along a long bar finds it. Bars are kept in the spatial hash by every cell their free length passes through. + +### What a bar can still take + +A bar holds several clips side by side. A seated clip takes only its own stretch of the bar, `t - w / 2` to `t + w / 2`; a bar is never taken whole. Another clip may seat on the same bar where its stretch overlaps no taken stretch by more than 0.5 LDU; a candidate that would overlap is not proposed. Studs, anti-studs and hinge halves are taken whole, as before. + +### The anchor + +Step 2 of "The raw pose" gains one case. When the person took hold of the part by a connector of a kind that does not rest on a face, that is any kind that is neither the ground's (`stud`) nor a partner of it (`anti_stud`): a clip, a bar or a hinge half, that connector is the anchor whatever way the face met looks, and the raw pose puts it on the hit point. When the part was taken from the palette and the face met looks sideways, the anchor is its clip, bar or hinge half nearest the centre of its bottom face, when it has one. A face that looks up or down still picks an anti-stud or a stud first, as before. So a plate with a clip, held by the clip and pointed at the side of a bar, has the clip's centre put on the bar's surface, 4 LDU from its axis, well within the reach, and it seats on the bar. + +### Turning a seated half + +- The quarter turn about the anchor is offered only for a mate whose freedom is a spin. Held by a clip or a hinge half that is seated, the part has a hinge freedom: `turn_step` answers none, and the part is turned about the hinge axis instead. +- Held by a clip, a bar or a hinge half that is not seated, a quarter turn is about the vertical through the anchor, not about the anchor's own axis: turning a clip about its own axis would never line it up with a bar. +- The engine gives the hinge axes a placement is joined on, one per joined pair whose freedom is a hinge: the partner placement, the axis as a point and a direction (in the window's scene axes, and in LDraw axes), the opening angle (the turn about the direction from the partner's ref to the placement's own, so flat reads 180) and the allowed range. Turning about one moves the turned half, and whatever moves with it, as one rigid body about that line; the partner stays where it is. The motion is a turn about a line through the axis point, so the joined point stays joined. + +### Worked snaps: a clip along a bar, and hinge halves + +Run with `part.fit` through an engine on the 2026-10 library on 27 November 2026, each part fitted from a raw position near its partner, snapping on and the overlap check off. + +A Bar 3L (`87994.dat`, Example 6) stands at (0, -80, 0), so its free length runs from y = -80 to -20 and its middle is y = -50. A Plate 1 x 1 with Clip (`4085c.dat`, Example 5), unturned, is fitted with its clip's centre 2 LDU to the side of the bar and 1 LDU off it, at the heights in the first column. The clip's jaws keep it from y = -76 to -24. + +| Clip's raw height | Stud step | Plate step | Fine step | +| --- | --- | --- | --- | +| -76 | -70 | -70 | -76 | +| -63 | -70 | -60 | -63 | +| -55 | -50 | -50 | -55 | +| -47 | -50 | -50 | -47 | +| -38 | -30 | -40 | -38 | +| -27 | -30 | -30 | -27 | +| -21 | -30 | -30 | -24 | + +Every seat puts the clip's centre on the bar's axis, x = 0 and z = 0, joined to the bar. With one clip placed at -50 at the Stud step, a second clip held at the same height is refused (the stretch from -54 to -46 is taken), and one held at -37 seats at -30. Pointed at the bar's side with the pointer, the plate is anchored by its clip and seats the same way: rays at scene heights 50, 33 and 62 seat it at -50, -30 and -70. + +Hinge halves, the first part placed at (0, -100, 0), clear of the ground: + +| Placed | Fitted | Raw position and turn | Result | +| --- | --- | --- | --- | +| `44302a.dat` | `44301a.dat` | (63, -102, 2), half turn about y | seated at (60, -100, 0), one pair, mark at (30, -98, 0) | +| `44302a.dat` | `44301a.dat` | (2, -101, 1), unturned | not seated: the refs are 0 degrees apart | +| `44302a.dat` | `44301a.dat` | (38, -74, 1), quarter turn about z | seated at (28, -68, 0), folded at a right angle | +| `4275b.dat` | `4276b.dat` | (58, -103, 4), half turn about y | seated at (60, -100, 0) | +| `4275b.dat` | `4275b.dat` | (58, -103, 4), half turn about y | not seated: two three-finger halves do not pair | + ## The grid fallback When the snap finds no seat, when snapping is off, or when the part has no connectors, the raw pose is rounded to a grid. The person picks the step, named as in `spec/NAMES.md`; Stud is the default. The steps and their values are the same as in `spec/SPEC.md` section 7.2. @@ -460,7 +737,7 @@ Every entry carries its own header, so it can be reviewed, credited and moved on ### What an entry does - `patch`: start from the derived connectors of `file`, then apply `remove`, then `add`. - - `remove` is a list of matchers. A matcher has `kind` and `position` and may have `axis`; it removes every derived connector of that kind within 0.5 LDU of the position (and, if an axis is given, with an axis within 5 degrees of it). A matcher that removes nothing is reported as stale. + - `remove` is a list of matchers. A matcher has `kind` and `position` and may have `axis`; it removes every derived connector of that kind within 0.5 LDU of the position (and, if an axis is given, with an axis within 5 degrees of it, or of its opposite for a kind whose axis is a line: a clip, a bar or a hinge half). A bar is matched by its `position`, the first end of its free length. A matcher that removes nothing is reported as stale. - `add` is a list of connectors in the form of "What a connector is"; `source` is set to `override`. - `replace`: ignore the derivation for `file` and use `connectors`, a full list in the same form. An empty list means the file has no connectors. - Where it applies: during the walk, when the walk reaches `file`, the entry's result, in `file`'s own coordinates, takes the place of what the derivation would have collected inside `file`, and is carried up through the transforms above it. So an entry for a sub-part fixes every part that uses it, and an entry for a part fixes it wherever it is placed. Rule G runs on the whole part after the walk and is then subject to the part's own entry only. @@ -485,6 +762,7 @@ The coarse check named the overlap check in `spec/NAMES.md`; what the person see - The boxes are placed by their placement as oriented boxes. The dragged part's body box is tested first against the body boxes of placements found near it in the spatial hash with the separating axis test for two oriented boxes (the three face axes of each and the nine cross products); when two body boxes overlap, every slab of one is tested against every slab of the other, and the pair overlaps only when two slabs do. The depth reported is the deepest of those slab overlaps. - Before and after, on the 2026-10 library: the sample car `models/car.ldr` went from 21 overlapping pairs to 20 (the seat 4079, whose back leans out over the plate 3021 beside it, no longer counts, and the steering wheel in the windscreen 3823 went from 13.7 to 7.5 LDU, what is left being the cavity under the windscreen's base); the house of the driving pack's example stays at 0; a 1 x 1 plate held in the open space over the face of a 3039 is no longer flagged (it was 7 LDU), and one that cuts into the face still is. - With the check on, a pose (snapped or on the grid) whose box overlaps another is not taken: the ghost keeps the last pose it had that did not overlap and is marked as blocked while the pointer stays over the overlapping place, so a drop never makes an overlap (`spec/SPEC.md` section 4.2). With it off, nothing is tested. +- Since 0.5.0 the box and slabs are the quick first test and the outline for nested pairs; overlap is decided by real solids (SPEC.md 8.2), so resting no longer lifts a part out of a hollow. ### Why it can be wrong @@ -494,6 +772,42 @@ The coarse check named the overlap check in `spec/NAMES.md`; what the person see - Studs are not in the boxes, so a stud pushed into a solid face is not found here; the blocked-stud test of the snapping rule finds the common case on the bottom plane only. - It never reports parts that would not physically fit for reasons below 0.5 LDU. +## Compatibility between kinds + +Decided in 0.5.0. Which kinds pair is declared by each module (`mates_with`) and made symmetric by the registry; nothing else pairs. The ground is a `stud` lattice, so only kinds that pair with `stud` ever seat on it. + +| Kind | Mates with | Axes | Correction | Freedom left | Taken when seated | +| --- | --- | --- | --- | --- | --- | +| `stud` | `anti_stud` | opposed | point to point | spin, 90 degrees | whole | +| `anti_stud` | `stud` | opposed | point to point | spin, 90 degrees | whole | +| `clip` | `bar` | parallel either way | onto the bar's line, at a grid step along it | hinge about the bar | whole | +| `bar` | `clip` | parallel either way | as for `clip`, seen from the bar | hinge about the bar | by stretches | +| `hinge_click_1` | `hinge_click_2` | parallel either way | point to point | hinge | whole | +| `hinge_plate_2` | `hinge_plate_3` | parallel either way | point to point | hinge | whole | +| `hinge_arm_2` | `hinge_arm_3` | parallel either way | point to point | hinge | whole | +| `hinge_brick_top` | `hinge_brick_base` | parallel either way | point to point | hinge | whole | +| `hinge_swivel_top` | `hinge_swivel_base` | parallel either way | point to point | hinge | whole | + +Not paired, on purpose: + +- A clip does not take a stud: a stud is 12 LDU across and a clip holds 8. +- A bar does not go into an anti-stud. A bar of 8 LDU does fit some round receptacles, the inside of an open stud (`stud2.dat`, inner radius 4) and holes made for bars; that is a later pair, `bar` with a bar hole, once those holes are found from geometry. +- Halves of different hinge families never pair, even where a half of one would come near a half of another; their sizes differ (see "Three families"). +- A clip does not grip a hinge finger, a plate's edge or a rod of another size; the library's `clip4.dat`, made for a sign and a click hinge, is left out for that reason (see "Deriving clips"). + +A part may carry connectors of several kinds, and one drop may join pairs of several kinds at once: a plate with a clip seated both on a stud below and on a bar beside it counts every pair in `n(d)`. + +## Left for later + +What 0.5.0 does not model, each a later module registered with the service, written into this document first: + +- Pins and pin holes: the friction and plain pin primitives (`confric*.dat` and kin) and the round holes of beams (`beamhole.dat`, `peghole*.dat`). A pin in a hole leaves a spin of any angle and, for a long pin, a slide. +- Axles and axle holes: the cross-shaped `axle*.dat` and `axlehol*.dat` families. An axle leaves a slide and no spin; its `ref` gives the cross's turn. +- Ball joints: the ball and socket primitives such as `joint8ball.dat`. Their freedom is a turn about a point, which the `Freedom` record does not yet describe. +- A bar into a hole made for it or into an open stud (see "Compatibility between kinds"). +- Hinge turning limits, the click positions of click hinges (the 22.5 degree steps of the dual finger read in "Deriving hinge halves"), and hinges of the larger scale. +- Flexible parts: hoses, strings and chains. + ## Adding a kind A connector kind is a module that registers itself with the connection service. The service never names a kind; adding a pin, an axle, a clip or a hinge adds a module and, where needed, override entries, and changes nothing else. @@ -514,7 +828,9 @@ A connector kind is a module that registers itself with the connection service. | `settle(mesh, own)` | Optional. Corrects the connectors this kind's `from_reference` made, once the walk is over and the bottom plane is known, before any `from_mesh`; it may move or drop them. The last step of rule T (a tube's free end moved down to the bottom plane, or dropped when higher) is this hook for `anti_stud`, because the bottom plane is not known while the walk runs. Without it a kind's connectors stay as the walk made them. | | `from_mesh(mesh, connectors)` | Optional. Connectors found from the whole flattened part after the walk. Rule G is this hook for `anti_stud`. | | `version`, `body` | The kind's version, part of the cache key (see "Caching and inspection"); and whether the triangles of files it claims count in the overlap check's body box (false for studs, true for tubes). | -| `mate(a, b)` | Given `a` of this kind and `b` of a kind in `mates_with`, both in model coordinates: `None`, or a mate: the rigid correction (rotation and translation) that brings `a` onto `b`, the residual distance, and the freedom left. | +| `mate(a, b)` | Given `a` of this kind and `b` of a kind in `mates_with`, both in model coordinates: `None`, or a mate: the rigid correction (rotation and translation) that brings `a` onto `b`, the residual distance, and the freedom left. Added in 0.5.0: a mate may also say where along a sliding partner it sits (`at`, in LDU from the partner's `position`) and half the stretch it takes there (`span`), which is how a bar is shared between clips. | +| `takes_step` | Added in 0.5.0. When true, `mate(a, b, step)` is also given the grid step's across value, for kinds whose seat moves in grid steps (`clip` and `bar`). The snap passes it when proposing a seat and passes 0, no step, when counting pairs. | +| `spans` | Added in 0.5.0. When true, a connector of the kind is a segment from `position` along `axis` for `length` (`bar`), so the snap measures reach and mating distance to the segment, keeps it by its whole length, and takes it stretch by stretch. | ### Freedom @@ -551,6 +867,8 @@ All read on 26 November 2026. Everything not marked with a key is FormBlocks' ow - [LIB] LDraw.org Official Parts Library Specifications, revision 2.4, 3 February 2023: the origin and stud orientation rule for parts. https://www.ldraw.org/article/512.html - [PRIM] Primitives Reference, ldraw.org wiki: the names and descriptions of the stud, tube and underside primitives. https://wiki.ldraw.org/wiki/Primitives_Reference - [PART] Official library files fetched one by one from `https://library.ldraw.org/library/official/parts/` and `https://library.ldraw.org/library/official/p/`. Parts and sub-parts: `3001.dat`, `s/3001s01.dat`, `3003.dat`, `s/3003s01.dat`, `s/3003s02.dat`, `3023.dat`, `3023b.dat`, `s/3023bs01.dat`, `3039.dat`, `s/3039s01.dat`, `3068b.dat`, `s/3068bs01.dat`. Primitives: `stud.dat`, `studa.dat`, `stud2.dat`, `stud3.dat`, `stud4.dat`, `stud4a.dat`, `stud4o.dat`, `stud6.dat`, `stud9.dat`, `stud10.dat`, `stud12.dat`, `stud13.dat`, `stud15.dat`, `stud16.dat`, `stud17.dat`, `stud17a.dat`, `stud23.dat`, `stud26.dat`, `studel.dat`, `studh.dat`, `studp01.dat`, `studx.dat`, `stud2s.dat`, `stud-logo.dat`, `stud2-logo.dat`, `ridge.dat`, `stug-1x2.dat`, `stug-2x2.dat`, `stug2-1x2.dat`, `box3u2p.dat`, `box3u4a.dat`, `box4.dat`, `box4-4a.dat`, `box4t.dat`, `box5.dat`, `4-4cyli.dat`, `4-4ring3.dat`, and the circle, disc and edge primitives these reference. All carry `0 !LICENSE Licensed under CC BY 4.0 : see CAreadme.txt`. +- [PRIM-M] Primitives Reference, ldraw.org wiki, read again on 27 November 2026 for its "Miscellaneous primitives" section: the entries under Arm, Click-lock, Clip, Handle and Hinge, and the cylinder entries (`n-fcyli`, `n-fcylo`, `n-fcylc`). https://wiki.ldraw.org/wiki/Primitives_Reference +- [PART-2] Official library files of the 2026-10 release, read on 27 November 2026 from the complete library unpacked on a check machine (never committed). Primitives: `clip1.dat` to `clip16.dat`, `clh1.dat` to `clh15.dat`, `clh2c.dat`, `clh3q.dat`, `clh5s.dat`, `clh6c.dat`, `clh6d.dat`, `clh6u.dat`, `clh-base.dat`, `clh-finger.dat`, `h1.dat`, `h2.dat`, `arm1.dat`, `arm2.dat`, `arm3.dat`, `phandle1.dat`, `phandle2.dat`, `handle.dat`, `handle2.dat`, `4-4cyli.dat`, `4-4cylo.dat`, `4-4cylc.dat` and the part-circle cylinders, cones and discs these reference. Parts and sub-parts: the ones the clip, bar and hinge examples name. Every file carries `0 !LICENSE Licensed under CC BY 4.0 : see CAreadme.txt`. The numbers were taken by a throwaway script kept outside the repository, which walked the files with the walk of this document. - [ours] Hand arithmetic and a throwaway script, kept outside the repository and not part of FormBlocks, that walked the fetched files with the rules in this document; its output matched every number in the worked examples and the brick-on-brick snap table. No program other than that script, and no other program's data, documentation or connection format, was used. diff --git a/spec/LDRAW.md b/spec/LDRAW.md index f7c5c44..5052913 100644 --- a/spec/LDRAW.md +++ b/spec/LDRAW.md @@ -39,6 +39,12 @@ Rules for each: - Type 3 and 4. Official parts must not colour a triangle or quadrilateral with 24 [LIB]. A quadrilateral's points are in order around its edge, in one plane, not a bow-tie, and not concave [FF]; official concave quads are split into triangles, and quads are coplanar within 3 degrees [LIB]. The flattener therefore splits a quad `p1 p2 p3 p4` into the triangles `p1 p2 p3` and `p1 p3 p4` [ours]. - Type 5. Points 1 and 2 are the line; points 3 and 4 are control points that are never drawn. The line is drawn only when the two control points, projected to the screen, fall on the same side of the projected line [FF]. +### Numbers FormBlocks writes + +- The format sets no number of decimal places for a type 1 line [FF]. A number FormBlocks writes in one is the number it holds, in the shortest form that reads back as the same number, with no trailing zeros and `0` for zero [ours]. +- A turn made in FormBlocks holds its result at a fixed precision, so what is saved and read back is what was held: a turned position is rounded to three places, as FormBlocks' own lines are, and a matrix turned by anything but whole quarter turns about X, Y or Z is made a true rotation again and rounded to six places, since its entries lie between -1 and 1 and three places would bend a long part by a visible amount [ours]. +- A quarter turn about X, Y or Z only moves and negates a matrix's numbers, so it is never rounded: four of them give back the same line, byte for byte, unless the part had to be lifted off the ground on the way (`SPEC.md` 5.2) [ours]. + ## Units and axes - Lengths are in LDraw units. 1 LDU is given as 1/64 inch and as 0.4 mm, and the specification says these real-world figures are approximations [FF]. diff --git a/spec/NAMES.md b/spec/NAMES.md index dccfd42..dfe2e69 100644 --- a/spec/NAMES.md +++ b/spec/NAMES.md @@ -64,7 +64,8 @@ The names FormBlocks uses for its own features, tools and panels. None is taken - **grid step**: the size of a move when not seating: **Stud**, **Plate** or **Fine**. - **nudge**: a move of one grid step by a key. - **turn, tip, roll**: rotation about the up axis, about the screen's left to right axis, and about the axis into the screen. -- **fine angle**: the smaller rotation step used with Alt, 45 degrees unless changed. +- **angle step**: the step a turn on the pivot dial moves in and Alt with R, T or Y turns by: 90, 45, 22.5, 15, 5 or 1 degrees, shown in the status bar beside the grid step; it took the place of the fine angle in 0.5.0. +- **pivot**: the point and axis a turn goes about: the centre of the selection's box, or the axis of the hinge a part is joined by. - **move handles**: the three axis arrows shown on a selection for moving along one axis. - **overlap check**: the coarse check, with its switch, that keeps parts from being put inside each other. - **select tool**: the default tool for choosing parts. @@ -80,7 +81,7 @@ The names FormBlocks uses for its own features, tools and panels. None is taken - **rest**: what a ghost or a dragged part does when the place under the pointer would cut into another part: it stands on the lowest top under its whole footprint where it fits. - **body slabs**: the stack of boxes, 4 LDU thick, that stands in for a part's body in the overlap check, following its outline up its height. - **pivot tool**: the tool that turns parts about a chosen point with a dial or a typed angle. -- **pivot dial**: the ring the pivot tool shows for turning with the pointer. +- **pivot dial**: the ring about the up axis shown around a selection for turning it with the pointer; with the pivot tool, three rings, one for each axis; for a hinged part, one ring about the hinge. - **brush**: the tool that recolours each part it touches with the current colour. - **sampler**: the tool that makes a clicked part's colour the current colour. - **hide tool**: the tool that hides each part it touches. @@ -95,9 +96,13 @@ The names FormBlocks uses for its own features, tools and panels. None is taken ## Model information and files -- **Model information**: the panel with the About and Parts list tabs. -- **About**: the tab with the model's name, author, description, licence line, counts and size. +- **Model information**: the facts about the model as a whole: its name, description, author, licence line, file, counts and size, shown in the Info tab. +- **Info tab**: the fourth tab of the right column, after Parts, with the model information; named Info rather than About so it is not taken for the About FormBlocks dialog, which is about the app. +- **Parts tab**: the third tab of the right column, with the parts list. - **parts list**: the table of every part and colour the model needs, with counts. +- **section**: one of the right column's three parts, the colour palette, the tabs and the details panel, each with a header it can be folded to. +- **fold**: to close a section of the right column to its header; **open** it again with the header. +- **divider**: the line between two sections of the right column that is dragged to change their heights. - **project file**: a `.fblk` file: the model as an LDraw multi-part document plus FormBlocks' own view state. - **Export LDraw**: writing the model as a plain `.ldr` or `.mpd` file. - **Insert LDraw model**: bringing another LDraw file in as a new submodel. diff --git a/spec/PROVENANCE.md b/spec/PROVENANCE.md index 616b138..94a34ed 100644 --- a/spec/PROVENANCE.md +++ b/spec/PROVENANCE.md @@ -114,6 +114,8 @@ Each entry gives the source id used in `SPEC.md`, the title, the address, the ki | [F-LIB] | [S59] | below | | [F-ROT] | [S60] | below | | [PART] | [S61] | below | +| [PRIM-M] | [S62] | below | +| [PART-2] | [S63] | below | 48. **[S48]** Official Library Header Specification, revision of 21 February 2025. https://www.ldraw.org/article/398.html · LDraw.org standards document. Read 26 November 2026. Established: the order of a library file's header lines; the description prefixes for sub-parts, obsolete and moved files, aliases, third-party and physical colour parts; the `!LDRAW_ORG` types and qualifiers and the `YYYY-RR` release name; the four `!LICENSE` forms; that a moved file holds a header and one reference to its new number. 49. **[S49]** LDraw.org Official Parts Library Specifications, revision 2.4 (3 February 2023). https://www.ldraw.org/article/512.html · LDraw.org standards document. Read 26 November 2026. Established: lower-case official names of at most 25 characters; the origin of a part with studs centred on its top studs with studs pointing up; colour 24 only on lines; every official part certified for back-face culling. @@ -129,6 +131,8 @@ Each entry gives the source id used in `SPEC.md`, the title, the address, the ki 59. **[S59]** Forum thread "Updating the Library". https://forums.ldraw.org/printthread.php?tid=28804 · public forum thread on forums.ldraw.org. Read 26 November 2026. Established: that a folder holding `p` and `parts` is a library, with `parts/s`, `p/8` and `p/48` for the rest. 60. **[S60]** Forum thread "ROTSTEP questions". https://forums.ldraw.org/printthread.php?tid=21487 · public forum thread on forums.ldraw.org, seen in search results only and not opened. Read 26 November 2026. Established: only that a rotation step command is discussed as an extension that came from one program. 61. **[S61]** Official library files fetched one by one from https://library.ldraw.org/library/official/parts/ and https://library.ldraw.org/library/official/p/ · LDraw.org official library, CC BY 4.0. Read 26 November 2026. The files are listed at the foot of `LDRAW.md` and `CONNECTIONS.md`. Established: the geometry the dimensions and worked examples are measured from; that `3023.dat` is now a file moved to `3023b.dat`; that part descriptions carry runs of spaces, as in the description of 3001. +62. **[S62]** Primitives Reference, section "Miscellaneous primitives". https://wiki.ldraw.org/wiki/Primitives_Reference · LDraw.org wiki page, the same page as [S51], read again for this section. Read 27 November 2026. Established: the clip primitives are described as made to hold an 8 LDU diameter pole or rod; `clip4.dat` is still listed there as a three-fingered clip, while the library's file now says otherwise; the click-lock entries name single fingers and the halves of a two finger hinge that "Requires 2 halves rotated 180 degrees apart on Z-axis"; `h1.dat` and `h2.dat` are the standard two and three fingered plate hinge with a depth of 8 LDU; the arm primitives are hinge components of a cylindrical arm of radius 10 LDU; the cylinder primitives `n-fcyli`, `n-fcylo` and `n-fcylc` make whole or part cylinders. No entry says where a hinge's axis lies; that was measured in the files ([S63]). +63. **[S63]** Official library files of the 2026-10 release, from `complete.zip` unpacked on a check machine and never committed. https://library.ldraw.org/library/updates/complete.zip · LDraw.org official library, CC BY 4.0. Read 27 November 2026. The files are listed at the foot of `CONNECTIONS.md` under [PART-2]. Established: the grip centre, axis, opening and width of each clip primitive, the pivot point, axis and side of each hinge primitive, how bars are drawn with ordinary cylinders, and the parts of the clip, bar and hinge worked examples. ## The plan's recalled facts, checked diff --git a/spec/SPEC.md b/spec/SPEC.md index e266332..9f25822 100644 --- a/spec/SPEC.md +++ b/spec/SPEC.md @@ -44,13 +44,14 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de - There is no toolbar row, decided in 0.3.0: the top bar holds the menu, the file tools and the edit and window tools, and the tools to come (select, stamp, pivot, hide, brush, sampler) take their place in it; the snap switch, the grid step and the overlap check switch are buttons in the status bar; the step controls are the step strip under the viewport, with a chip per step and the New Step button. This keeps the viewport as tall as it can be. [S13, S15; our own design] - The viewport fills the centre: the 3D view of the model on a ground grid. [S13, S14] - The parts palette runs down the left side. [S13, S14; our own design] -- The right side is one column of three panels from top to bottom: the colour palette, a panel with two tabs (model tree and steps), and the details panel for the current selection. [S13, S14, S15; our own design] +- The right side is one column of three panels from top to bottom: the colour palette, a panel with tabs (the model tree, the steps, and since 0.4.0 and 0.5.0 the parts list and the model information), and the details panel for the current selection. [S13, S14, S15; our own design] - The status bar runs along the bottom: on the left what is selected and a hint for whatever is under the pointer, in the middle the current step and submodel, on the right the pointer's position on the grid in LDU, the snap and overlap states, and progress of long work. [S13, S14, S15] - Below the status bar the family dock can be opened for terminals and agents; it is closed by default. [our own design] ### 1.2 Rules - Panels are resized by dragging the separators between them; the viewport takes whatever room is left. [S15] +- Decided in 0.5.0, the right column's heights. Each of its three sections has a header and folds to it with a click on the header or Enter on it: the colour palette's header names the current colour, the details panel's names the selection, and the tab section's header is its tab bar, where a click on a tab opens the section again. The tab section is the one that grows: it takes every pixel the palette and the details panel leave, because the list a person is working in is the one that needs rows. The palette and the details panel keep the height the person dragged them to, held between a least and a greatest height set in the window's tokens: the palette between its search, hue row and two rows of swatches and a bound past which more height would only show more of a scrolled list, the details panel between its first three rows and all of them. The tab section keeps at least its bar and five rows. With the tab section folded the palette grows instead, and with both folded the details panel. Dragging a divider changes heights only; nothing in the sections is built again. Double-click on a divider, or Up and Down on it, work as before: back to the default height, or 16 pixels at a time. When the column is too short for every open section's least height (a short window, or the dock at the bottom), the palette and the details panel first shrink to their least heights, and then the one that still cannot fit is shown folded, the details panel before the palette, without changing what the person chose; the section the person opened last is the last to be folded this way. The heights, the folded sections and the tab shown are kept in the engine's settings (`right_column`) and restored before the window first paints, so nothing moves when it opens; the window keeps its own copy to restore from, and when the engine's differs (another browser, or the desktop app and a browser on one data folder) the engine's is used from the next start rather than moving the column under the person. [our own design] - Each side column can be collapsed to a narrow rail and opened again; one key hides both side columns at once for a clear view. [S15; our own design] - The layout (column widths, collapsed panels, which tab is open) is saved when the window closes and restored at the next start. [our own design] - The interface is dark by default, and its colours come from a theme that can be changed in preferences. [our own design] @@ -78,7 +79,7 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de | --- | --- | --- | | `view.panel` (name, open or closed) | View menu, rail buttons | settings [our own design] | | `view.clear` (all side panels hidden or back) | View menu, key | settings [our own design] | -| `view.layout_reset` | View menu | settings [our own design] | +| `view.layout_reset` | View menu, command palette: Reset Right Column, a window command since 0.5.0 that opens the right column's sections at their default heights; not yet an engine command | settings [our own design] | | `app.state` (what is open, library status, version) | none; status bar uses it | reads only [our own design] | - From the command line the panel commands change the layout the window will use at its next start or, when a window is running, the live layout. [our own design] @@ -274,6 +275,15 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de - The rotation keys work on a held ghost and during a drag as well as on a still selection. A held ghost or a dragged selection turns about the connector it is held by, not about its centre, so it stays under the pointer, and the snap then runs again; `CONNECTIONS.md`, "Rotation", defines the point and axis. [S22, S24; our own design] - The pivot tool turns about a chosen point instead: the person clicks a connector or a point on a part to set the pivot, then drags around a dial or types an angle; the drag moves in fine-angle steps and Shift frees it to whole degrees. [S25; our own design] - With the overlap check on, a turn with the mouse stops at the last free angle; a turn by key that would overlap is refused with a message. [S25; our own design] +- Decided in 0.5.0, turning with the pointer, which replaces the quarter turn limit of 0.3.0 above: [our own design] + - The pivot dial shows whenever parts are selected with the select tool, nothing is held and nothing is dragged: one ring lying flat about the up axis through the selection's pivot, a little wider than the selection. One ring and not three, because a turn about the up axis is the turn that leaves a part standing where it can seat, it is by far the most common, and three rings around a small selection cover the parts a press would take hold of to drag. J, the pivot tool, shows all three rings, about LDraw's X, Y and Z through the pivot, each in its own colour; J again, or Esc with no drag, goes back to the one ring. The rings are drawn in the viewport, so they appear and go without moving anything else in the window. + - The pivot is the centre of the box around the selected parts' shapes as they are placed. When the selection is one part joined by a hinge connector (`CONNECTIONS.md`), the pivot is the hinge's axis: the dial shows that one ring, about the hinge axis through the hinge, in place of the others. The engine answers the pivot (`part.pivot`); the window draws what it is told. + - Pressing on a ring and dragging along it turns the selection about the ring's axis, in steps of the angle step; Shift held frees the turn to whole degrees. The selected parts turn in place in the viewport while dragged, with the angle turned in the status bar. Letting go sends one `part.rotate` with the axis, the point and the angle, which is one undo step ("Rotate"); Esc during the drag, or losing the pointer, puts the parts back and adds no step. + - The angle step is one setting of 90, 45, 22.5, 15, 5 or 1 degrees, 90 at the first start, shown in the status bar beside the grid step; a click on it or A goes to the next value, and it is the person's setting, like the grid step. It takes the place of the fine angle: Alt with R, T or Y turns by the angle step. 90 comes first because a quarter turn leaves a part where its studs can seat again; finer steps are a choice. + - The engine decides every turn's result. A turn, by the pointer, by the keys or by `part.rotate`, never leaves what turned below the ground: when the turned parts' lowest point would be below the ground plane, the whole selection is lifted straight up until it rests on it, or, when it was already lower, until it is no lower than it was. A turn about a hinge is never lifted, which would pull the part off its hinge: the ground stops it as a part would, and the dial stays at the last free angle. With the overlap check on, a turn that would put a turned part into a part that does not turn is refused with a message naming the parts, as a move is; while dragging a ring, the engine is asked once for each step reached, not for each pointer move, and the parts stay at the last free angle in the warning colour until the pointer comes back to a free one. + - Snapping never turns a part (7.3), and a turn does not seat a part: a turned part keeps the place the turn gives it. Rotation matrices of quarter turns stay exact: four quarter turns give back the same file, byte for byte (`LDRAW.md`, "Numbers FormBlocks writes"). + - With the pivot tool on, a plain click on a part sets the pivot there: on the connector (a stud, say) within 8 LDU of the point clicked, else on the point itself, with the three rings; the point stays for turns of the same selection, and a new selection, leaving the tool or a click on no part goes back to the centre. Shift and Ctrl clicks still change the selection. `part.pivot` takes the click's pointer ray for this. + - Not built in 0.5.0: typing an angle on the dial; `part.rotate` with `angle`, `about` and `axis_vector` turns by any angle about any point and axis from the command line and MCP tools. ### 5.3 Nudging and exact values @@ -429,21 +439,28 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de - An overlap switch in the status bar (1.1), lit when the check is on; O toggles it. [S28, S35; our own design] - With the check on, parts that overlap another part are drawn as wireframe in the warning colour, so the clash can be seen through. [S35] -- The tooltip on the switch says plainly that the check is coarse and is a guide, not a proof that a model can be built. [S35] + Built in 0.5.0 as the nearest the instanced drawing allows: each part of a real overlap (8.2, never a nested or fitted pair) keeps its shape with its faces washed almost to the background and its edges in the warning colour, and is drawn so again whenever the model changes; turning the check off draws it as before. [our own design] +- The tooltip on the switch says plainly that the check is a guide, not a proof that a model can be built. [S35] +- Beside it, a "Nested" switch, also in Preferences as "Report nested pairs", chooses whether nested pairs (8.2) are reported too; off by default, the proposed default awaiting the owner's decision. Built in 0.5.0. [our own design] ### 8.2 Rules - The check is off at the first start; the last state chosen is remembered. [our own design] - With the check on, placing, dragging and duplicating never put a part where it would overlap; the part stays at the last free place (sections 4 and 5). [S22, S35] - With the check off, parts may share space freely. [S35] -- The check is coarse in 0.x: each part is stood in for by a box fitted to its body without its studs and, since 0.4.0, by a stack of slabs 4 LDU thick that follow the body's outline up its height, so a slope is solid under its face and not above it; all are shrunk a little on every face, so parts that only touch, and studs sitting in the parts above them, never count. The box, the slabs, the amount they are shrunk and the test are defined in `CONNECTIONS.md`, "The overlap check". [our own design] -- Two parts joined through seated connectors are never reported as overlapping each other. [our own design] +- Since 0.5.0 the check compares the parts' real shapes: each part's solid, studs included, is the inside of its triangles filled into cells of 1 LDU, and two parts overlap when their solids share a region thicker than 1 LDU across its thinnest direction. + Parts that only touch, a stud in the hollow of the part above, and intersections 1 LDU thick or less, which is how near LDraw's own parts come to their neighbours, never count. The box and the slabs of `CONNECTIONS.md`, "The overlap check", stay as the quick first test and as the outline below. [our own design] +- Two parts whose outlines (the box and slabs of `CONNECTIONS.md`) meet but whose solids do not overlap, and which no seated connector joins, are a nested pair: one sits in the other's hollow by design with nothing the connection model knows holding it there, as a rim in its tyre or a pin in a hole (pins and holes are not connector kinds yet). + A nested pair is never an overlap: it never blocks placing, dragging, duplicating or turning, and it is reported apart, as its own kind, so nothing is hidden. + One setting, "Report nested pairs" (`overlap_nested`), chooses between reporting only real overlaps and reporting nested pairs too; off, reporting only real overlaps, is the proposed default awaiting the owner's decision. [our own design] +- Two parts joined through seated connectors are a fitted pair: a stud in its anti-stud, a hinge half on its partner, and a clip on a bar anywhere along the bar's length (`CONNECTIONS.md`, a bar being a line and not a point), decided in 0.5.0. A fitted pair is never nested, whatever their outlines do, and is an overlap only when their solids still cut more than 1 LDU into each other, which a real joint never does: a clip plate seated on a plate's handle with its own plate inside the other is refused with the check on and reported by it. Where either part has no solid (a part the library lacks), a fitted pair is never reported. [our own design] - The check looks only at the parts being placed or moved against their neighbours, so its cost does not grow with the size of the model. [S35; our own design] - Turning the check on looks once over the whole model and marks any overlaps already there; it does not move anything. [our own design] ### 8.3 Edge cases -- A part's slabs are still larger than the part where it is hollow or round (an arch, a tyre's hole, the cavity under a part), so the coarse check can refuse a place that would really fit; turning the check off places it anyway (the drag override of section 7.3 turns off snapping, not this check). [S35; our own design] +- A solid is only as good as the part's triangles: a part whose surface is not closed, or one drawn with its inside parts overlapping (some electric and figure assemblies), can show an overlap that is there by design, and an overlap 1 LDU deep or less is never shown. + Where a part is missing from the library, the outline of `CONNECTIONS.md` answers alone and every hit counts as an overlap. Turning the check off places a part anyway (the drag override of section 7.3 turns off snapping, not this check). [S35; our own design] - Hidden parts take part in the check, because hiding is only a view. [our own design] - If the check cannot keep up while a large selection is dragged, the drag carries on and the check runs when the selection is put down, marking any overlap. [S35; our own design] @@ -452,9 +469,10 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de | Id | Window | Kind | | --- | --- | --- | | `overlap.set` (on or off) | overlap switch, O | settings [S35] | -| `overlap.check` (parts, or the whole model) | Model menu, "Check overlaps" | reads only; lists overlapping pairs [our own design] | +| `overlap.check` (parts, or the whole model; nested pairs listed or not) | Model menu, "Show Overlaps", which selects the parts of each pair listed and says the counts in the status bar (0.5.0) | reads only; lists overlapping pairs [our own design] | +| `overlap.nested` (on or off) | "Report nested pairs" in the status bar and in preferences | settings, built in 0.5.0 [our own design] | -- `overlap.check` gives agents a way to confirm a build: it answers each overlapping pair of placement ids and the depth of the overlap in LDU. [our own design] +- `overlap.check` gives agents a way to confirm a build: it answers each overlapping pair of placement ids with the depth of the overlap in LDU and the volume shared in cubic LDU, and how many nested pairs there are. It lists the nested pairs, marked as their own kind, when its `nested` argument is true or, without the argument, when the setting is on. [our own design] ## 9. Hiding and showing @@ -644,10 +662,12 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de ### 13.1 Model information - The parts list is a tab, Parts, in the right column beside Model and Steps; it is not a panel over the viewport. [S38; our own design] -- In 0.4.0 the window has no model information panel: the facts below are read with `model.info` and changed with `model.set_info`, and the About FormBlocks dialog is about the app, not the model. [our own design] -- Model information shows the model's name, author and description, which the person can edit; the file it was opened from; and the library update it was built with. [S12; our own design] -- It also gives counts: parts in all, different parts, different part and colour pairs, submodels, steps. [S21, S38] -- It gives the model's size across, deep and high in studs, studs and bricks, and in millimetres. [S1, S21] +- Decided in 0.5.0, model information is a fourth tab, Info, after Parts in the right column's tab section. The tab section is the part of the column that grows (1.2), so the panel has room for every value without taking rows from the palette or the details panel; a section of its own would take height from the lists all the time for facts read now and then, and a dialog would hide the view and have to be opened again to see a count change. The About FormBlocks dialog stays about the app, not the model. [our own design] +- Model information shows the model's name (its main model's `Name:`), its description (the title line an LDraw file starts with) and its author, which the person can edit in place where the file carries them, which is every kind of file FormBlocks writes; and, read only, the file it was opened from and its format, the library update it was last saved with and the one in use. Enter or leaving a field changes it as one undo step, Esc puts the field back: the name through `submodel.rename`, which keeps every use right, the description and author through `model.set_info`. [S12; our own design] +- It also gives counts: placements as written, parts in all through every use, different parts, colours, submodels, steps of the main model, parts missing from the library, and overlapping pairs as `overlap.check` counts them. [S21, S38; our own design] +- It names each part the library lacks by its number, with how many the model needs. [our own design] +- It gives the model's size across, deep and high in studs, studs and bricks, and in millimetres (an LDU is 0.4 mm). [S1, S21] +- Every value is counted by the engine (`model.info`); the window only shows them. Each value has its place from the first frame, and a change to the model rewrites the values that changed where they stand. [our own design] - The model's licence line can be left empty or set to a Creative Commons licence; it is written into the file's header. [S10, S12; our own design] ### 13.2 The parts list @@ -675,8 +695,8 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de | Id | Window | Kind | | --- | --- | --- | -| `model.info` | none yet | reads only [S21, S38] | -| `model.set_info` (name, author, description, licence) | none yet | changes the model [S12; our own design] | +| `model.info` (`table` false leaves out the parts list) | Info tab | reads only [S21, S38] | +| `model.set_info` (title, which is the description, author, licence; the name is `submodel.rename`) | Info tab | changes the model [S12; our own design] | | `parts.list` (scope: `model`, `submodel`, `step` for up to the step shown, or `this_step` for the step shown alone; group by; `submodels`: `expand` or `row`; `text`) | Parts tab | reads only [S38, S39] | | `parts.list_save` (path, comma or tab) | "Save parts list" | writes a file [S21, S40] | @@ -841,7 +861,7 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de | General | Another copy waits under the pointer after a drop | on | [S22] | | General | Snap, grid step and overlap check for new models | on, Stud, off | [S29, S34, S35; our own design] | | General | Safety copy interval | every 2 minutes; can be off | [S21; our own design] | -| Building | Fine rotation angle | 45 degrees; 22.5, 15, 5 or 1 | [S21, S24, S25] | +| Building | Angle step, which took the place of the fine rotation angle in 0.5.0 (5.2); also the status bar button beside the grid step | 90 degrees; 45, 22.5, 15, 5 or 1 | [S21, S24, S25; our own design] | | Building | Strict seating: refuse a seat that would leave a stud standing under a wall (`CONNECTIONS.md`, "Choosing the seat") | on | [our own design] | | Building | Fade earlier steps while walking | on | [S37; our own design] | | Appearance | Theme | dark; light, or follow the system | [S21; our own design] | @@ -912,7 +932,8 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de | I | sampler | [our own design] | | M | show or hide move handles | [our own design] | | Ctrl+A, Esc, Ctrl+I | select all, select none, invert | [S28, S31; our own design] | -| R, T, Y (Shift reverses, Alt fine angle) | turn, tip, roll | [S24; our own design] | +| R, T, Y (Shift reverses, Alt turns by the angle step, 5.2) | turn, tip, roll | [S24; our own design] | +| A | next angle step: 90, 45, 22.5, 15, 5, 1 degrees (decided in 0.5.0) | [our own design] | | Arrow keys; Shift+Up, Shift+Down (Alt for one LDU) | nudge across; nudge up and down | [S14, S26; our own design] | | Space | drop the held ghost | [S22] | | S | snap on or off | [S29; our own design] | @@ -938,6 +959,7 @@ This file says what a person can do with FormBlocks 0.x and what they see. It de | Left drag from empty space | box selection, direction decides wholly inside or touching | [S31; our own design] | | Left drag on a part | move the selection | [S24] | | Alt+left drag on a part | copy the selection, decided in 0.4.0 (5.1) | [our own design] | +| Left drag on a ring of the pivot dial; with Shift | turn the selection in angle steps; in whole degrees, decided in 0.5.0 (5.2) | [S25; our own design] | | Double click on a use of a submodel; on empty space | enter it; leave to the level above | [S32] | | Right drag; Alt+left drag from empty space | orbit | [S14, S42] | | Middle drag; Shift+right drag; Shift+Alt+left drag | pan | [S14, S42] | @@ -1032,12 +1054,13 @@ The ids the engine's catalogue holds in 0.2.0 are the authority. The command tab | Area | Commands in the catalogue (kind) | The sections' ids they answer | Section | | --- | --- | --- | --- | | `model` | `new` (file), `open` (file), `save` (file), `save_as` (file), `insert` (change), `recent` (read), `report` (read), `tree` (read), `info` (read), `set_info` (change) | `file.new`, `file.open`, `file.save`, `file.export_ldraw` (`save_as` with an `.ldr` or `.mpd` path), `file.insert_ldraw`, `file.recent`, the open report of 14.6, `model.tree`, `model.info`, `model.set_info` (title, author, licence; the name is `submodel.rename`) | 12, 13, 14 [our own design] | -| `part` | `place` (change), `place_at_ray` (change), `fit` (read), `pick` (read), `connectors` (read), `move`, `move_at_ray`, `set_transform`, `rotate`, `recolour`, `duplicate`, `duplicate_at_ray`, `delete`, `hide`, `hide_others`, `show` (change) | `part.place`, the drop of 4.3 from the pointer's ray in the window's scene axes, `part.fit`, picking the placement under the pointer, `selection.move`, putting a dragged selection down from the pointer's ray (5.1), `placement.set`, `selection.rotate`, `selection.recolour` and `placement.colour`, `selection.duplicate` (by an offset, or as a ghost dropped from the pointer's ray, 5.4), `selection.delete`, `hide.set`, `hide.others`, `hide.show_all` (`show` with no ids) | 3, 4, 5, 6, 9 [our own design] | +| `part` | `place` (change), `place_at_ray` (change), `fit` (read), `pick` (read), `connectors` (read), `pivot` (read, 0.5.0: what the pivot dial turns about), `move`, `move_at_ray`, `set_transform`, `rotate`, `recolour`, `duplicate`, `duplicate_at_ray`, `delete`, `hide`, `hide_others`, `show` (change) | `part.place`, the drop of 4.3 from the pointer's ray in the window's scene axes, `part.fit`, picking the placement under the pointer, `selection.move`, putting a dragged selection down from the pointer's ray (5.1), `placement.set`, `selection.rotate`, `selection.recolour` and `placement.colour`, `selection.duplicate` (by an offset, or as a ghost dropped from the pointer's ray, 5.4), `selection.delete`, `hide.set`, `hide.others`, `hide.show_all` (`show` with no ids) | 3, 4, 5, 6, 9 [our own design] | | `select` | `get` (read), `set`, `add`, `remove`, `all`, `clear`, `invert`, `by_colour`, `by_part` (view) | `selection.get`, `selection.set`, `selection.add`, `selection.remove`, `selection.all`, `selection.none`, `selection.invert`, `selection.by_colour`, `selection.by_part` | 6 [our own design] | | `step` | `list` (read), `goto` (view), `break_after`, `delete`, `move_parts`, `rename` (change) | `step.list`, `step.show`, `step.add`, `step.delete`, `step.move_parts`, `step.rename` | 11 [our own design] | | `submodel` | `list` (read), `enter`, `leave` (view), `create`, `dissolve`, `independent`, `rename`, `delete` (change) | `submodel.list`, `submodel.enter`, `submodel.leave`, `submodel.pack`, `submodel.unpack`, `submodel.independent`, `submodel.rename`, `submodel.delete` | 10 [our own design] | -| `overlap` | `check` (read), `set` (view) | `overlap.check`, `overlap.set` | 8 [our own design] | +| `overlap` | `check` (read), `set` (view), `nested` (view, 0.5.0) | `overlap.check`, `overlap.set`, `overlap.nested` | 8 [our own design] | | `snap`, `grid` | `snap.set`, `grid.step` (view) | `snap.set`, `grid.step`; the kind "settings" of 7.6 is registered as view: no undo step, no model change | 7 [our own design] | +| `angle` | `angle.step` (view), built in 0.5.0 | the angle step of 5.2 and 17.2, registered as view like `grid.step` | 5, 17 [our own design] | | `parts` | `search`, `show`, `list` (read), `list_save` (file) | `parts.search`, `parts.info`, `parts.list`, `parts.list_save` | 2, 13 [our own design] | | `colours` | `list`, `used` (read), `current` (view) | `colours.list`, `colours.used`, `colours.current`; the kind "settings" of 3.4 is registered as view, as for the switches | 3 [our own design] | | `library` | `status` (read) | `library.status` | 17 [our own design] | diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 32f8378..21da355 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1047,7 +1047,7 @@ dependencies = [ [[package]] name = "formblocks" -version = "0.4.0" +version = "0.5.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ef4a71a..c12a6c9 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formblocks" -version = "0.4.0" +version = "0.5.0" description = "FormBlocks desktop shell" authors = ["nodemode-ai"] license = "Apache-2.0" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index da5145d..af5e3c6 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -2,6 +2,26 @@ Living record of decisions and removed context for the desktop shell, newest first. Read before editing. +## The Tauri command line and API package match the crate · 0.5.0 (frontend/package.json, frontend/package-lock.json, NOTICE.md) + +The crate in `Cargo.lock` is tauri 2.12.5, the command line was 2.11.4 and `@tauri-apps/api` 2.12.4. The older command line still set `STATIC_VCRUNTIME` for tauri-build, which tauri-build 2.7.4 answers with a deprecation warning on every build. Both packages are now pinned exactly to 2.12.5, which the npm registry has (2.12.6 is newer, but the pin follows the crate, not the newest), and the lock file was written by `npm install`. The 2.12.5 command line's binary no longer holds the name `STATIC_VCRUNTIME` at all, so tauri-build reads the static C runtime choice from its own default on Windows (`build.windows.staticVCRuntime`, true unless set), which is what the old variable asked for. Checked: `npx tauri info` names the command line and the API package 2.12.5. Not run: a full desktop build (about 40 minutes here) or any Windows build, so the warning's absence is read from the binary, not seen in a build log. + +## The first desktop build, on Linux, 27 November 2026 · 0.5.0 (the whole shell) + +The first Tauri build of FormBlocks, on Linux x64 with Rust 1.97.0, WebKitGTK 2.52.6 (4.1), GTK 3.24.41, libsoup 3.4.4 and librsvg 2.58.0, two processors. The shell's own code needed no change: `cargo check --locked` finished with no warning from it in 5 min 32 s, cold. The build was run as formcompiler runs it, from a fresh clone of the branch: `./formblocks install --lite` (14 s), `./formblocks install-desktop` (2 s), `./formblocks desktop build --config ` with a config that leaves the updater's artefacts off and asks for `deb` and `appimage` only (rpm's default compression is slow on a large engine, as formcompiler's log notes); nothing was signed. The release compile took 26 min 15 s; the whole step 41 min, with a wait for the shared cargo folder. A rebuild after the fixes it found took 1 min 37 s to compile. Tauri fetched the AppImage tools (linuxdeploy, its GTK and GStreamer plugins, the AppImage plugin) from GitHub through this machine's proxy without trouble. + +What it made: `FormBlocks_0.4.0_amd64.deb`, 58.4 MB at first (installed 156.6 MB), 50.0 MB after the freeze stopped doubling numpy's libraries (installed 130.1 MB); `FormBlocks_0.4.0_amd64.AppImage`, 121.5 MB. The shell's binary is 11.9 MB and the frozen engine 116 MB. The package is named `form-blocks` (Tauri makes it from `productName`, and has no setting for it), depends on `libwebkit2gtk-4.1-0` and `libgtk-3-0`, and installs `/usr/bin/formblocks`, `/usr/lib/FormBlocks/engine/` and the desktop entry with the three PNG icons. No LDraw file is in either bundle. The build found five faults, each fixed in its own commit: the self-check did not import numpy, nor the connector kinds that read data files; the freeze carried a fixed list of data files, so the new clip and hinge kinds were missing; the Linux engine's links into its own folder were copied as second files; the package's short description and category were the template's. + +Running it: the `deb` unpacked with `dpkg -x` into a scratch folder (not installed), started under Xvfb on display 95 at 1440 by 900 with no window manager, with `FORMBLOCKS_DATA_DIR` and `FORMBLOCKS_LDRAW_DIR` set to scratch folders. The shell found `../lib/FormBlocks/engine/formblocks-engine` beside itself and started it (the engine chose its own port, as the shell asks with port 0), the splash closed and the main window showed at 1152 by 720, 80 percent of the screen. `/api/health` answered 200. The window drew the dark layout with the palette's 83 categories from the scratch library, the colour panel, and the viewport's grid and two axes: WebGL works in WebKitGTK here through Mesa's software renderer (it warns that DRI3 is missing and goes on). `model.open` of the library's `models/car.ldr` through the engine's route put the car in the window, 61 parts in 8 steps, drawn with studs, wheels and the transparent windscreen. `part.connectors` answered from the frozen engine. Closing the window with the window manager's close message ended the shell, the engine and the web view's processes, `/api/health` stopped answering and the engine removed its lock and port files. Killing the shell outright ended the engine within six seconds (it watches its parent), leaving its lock file, and the next start ran normally. The AppImage, unpacked with `--appimage-extract` because this machine has no FUSE, showed the same window and ended the same way; it logs that GStreamer's `appsink` is missing, which FormBlocks does not use. + +Two notes for later builds: the Tauri command line in `frontend/package.json` is 2.11.4 while the crates are tauri 2.12.5 and tauri-build 2.7.4, so every build prints that `STATIC_VCRUNTIME is deprecated`; aligning the command line with the crates would end it, and on Windows it is how the C runtime is linked. A cargo folder shared with another Tauri app loses one app's AppImage when the other bundles, since the bundler clears `bundle/appimage`. Not run: macOS and Windows, any signing, the updater, the `rpm`. + +## The package says what FormBlocks is · 0.5.0 (tauri.conf.json) + +`bundle.shortDescription` still held the template's "The smallest real Form app". The Linux package carries it as the first line of its description, which package managers show in a list, so the first `deb` would have called FormBlocks the starter. It is now "Brick building on the open LDraw parts library", the summary the registry entry and the README use, cut to a line. Checked in the first built package's control file (see the first desktop build's entry). + +`category` was the template's `Productivity`, which the first package's desktop entry wrote as `Categories=Office;`, so a Linux menu filed FormBlocks with word processors. It is now `GraphicsAndDesign`, as FormCAD and FormSculpt have it, which becomes `Graphics` on Linux and the graphics and design category on macOS. + ## The window may ask for the desktop's open and save dialogs · 0.3.0 (capabilities/default.json, ../NOTICE.md) The window's `io/dialog.ts` calls `plugin:dialog|open` and `plugin:dialog|save` through `@tauri-apps/api` for New, Open, Save as and the library folder, and the shell already registers the dialog plugin in `main.rs` exactly as FormAnything's template does today (`tauri_plugin_dialog::init()`, used also for the shell's own message box). The capability granted neither command, so in a desktop build both calls would be refused and the window would fall back to a typed path. `dialog:allow-open` and `dialog:allow-save` are now in the default capability, as FormCAD and FormVis grant them; nothing else of the plugin (message, ask, confirm) is opened to the page. Not checked in a desktop build: the desktop toolkit is missing here, so no Tauri build or `cargo check` against the capability schema was run. diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 799b008..0ce9362 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormBlocks", - "version": "0.4.0", + "version": "0.5.0", "identifier": "ai.nodemode.formblocks", "build": { "frontendDist": "../frontend/dist" @@ -30,8 +30,8 @@ "bundle": { "active": true, "targets": "all", - "category": "Productivity", - "shortDescription": "The smallest real Form app", + "category": "GraphicsAndDesign", + "shortDescription": "Brick building on the open LDraw parts library", "longDescription": "Brick building: pick parts from the open LDraw library, place and snap them in 3D, and save LDraw files.", "copyright": "Copyright 2026 NodeAgentc, Inc.", "resources": { "engine": "engine" },