328 Commits

Author SHA1 Message Date
superGeometry f9bfba7322 Settings > Mouse: the mouse as in each major CAD program, by name (asked for: "It should have controls presets from all major CAD apps").
The four styles named by what they do are seven presets named for the programs that work that way, those alike sharing a row: superGeometry / Onshape / Tinkercad (right drag turns, middle moves); Fusion / Inventor / Revit / AutoCAD (Shift + middle turns, middle moves, Ctrl + Shift + middle zooms); SolidWorks (middle turns, Ctrl + middle moves, Shift + middle zooms); Creo / Solid Edge / Blender / SketchUp (middle turns, Shift + middle moves, Ctrl + middle zooms); NX (middle turns, middle + right moves, middle + left zooms, Shift and Ctrl as well); CATIA / FreeCAD (middle moves, middle with left or right held turns, Ctrl + middle zooms); Rhino (right turns, Shift + right moves, Ctrl + right zooms). Under the list, what the chosen one does in words.

Two buttons held together (NX, CATIA, FreeCAD) are new: while the middle button drags the view, another button pressed with it changes what the drag does, and let go it changes back. The wheel's way round stays its own switch (the programs differ, and each lets it be turned over). A plain right drag still turns the view in every preset, and Alt + left drag.

The presets are a table in settings.ts (MOUSE_PRESETS), one function for a press and one for buttons held together; a setting not known is the app's own way. tests/mousepresets.test.ts, 13 checks: every press of every preset. In the app: middle, then right and left held with it, in four presets; the list in Settings, a preset chosen and kept.

Fusion, SolidWorks, Creo, Onshape, Tinkercad, NX and CATIA are as their makers' pages give them (looked up 2026-11-24); Rhino, Solid Edge, SketchUp, Blender, Inventor, Revit, AutoCAD and FreeCAD from what is widely known of them, not checked against a page.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 14:39:15 +02:00
superGeometry 6f131b2efc Mouse styles, a shape's sizes by the pointer while it is drawn, a box and Ctrl+A that pick a sketch's shapes (asked for by many after the app was posted; "Let's do everything perfectly first").
- Settings > Mouse (where there is a mouse): which drag turns and which moves the view, for hands used to another program - right drag turns (as it was); middle drag turns, Shift moves, Ctrl zooms; Shift + middle turns, middle moves, Ctrl zooms; middle drag turns, Ctrl moves, Shift zooms - and which way the wheel zooms. In every style the wheel zooms where the pointer is, a right drag turns, Alt + left turns. Asked for: "in Fusion I have to use shift+middle", "a setting menu with a list", "support customizable control schemes". One function says what a press does (settings.ts mouseDrag); the styles are named by what they do, not after programs. Tried in the app: each of the four styles with middle, Shift + middle, Ctrl + middle, right, Shift + right, Alt + left and a plain left drag (still the box), and the wheel both ways.

- A shape's sizes while it is drawn show in small tags by the pointer (a mouse, or a pen hovering): Width and Height, a circle's Diameter, an arc's Radius and angles, a polygon's Radius and Sides. The one a typed number goes to is lit, a typed one is held (yellow); Tab goes to the next and round again, also before anything is typed; Enter or a click places the shape. Asked for: "type out a distance and switch to the next input field with TAB ... having the dimensions show up near the sketch lines or the cursor ... than pulling the mouse down to a bar". Typing while drawing was there already, but what was typed with the mouse only moved (not dragged) showed in the top left corner of the page: the pointer's place was only kept during a drag. A line keeps its own length box along it; the tutorial shows no tags. Tried: a rectangle, click, 30, Tab, 20, then Enter, and again with a click: 30 x 20 both times.

- A box dragged round no body takes the closed shapes of the sketches in it, and Ctrl + A picks everything: the bodies shown; with none, every sketch's shapes; in a sketch, its curves (the drawing tool put down for Select). Reported with an imported drawing of hundreds of shapes: "I tried click drag release around them all and a ctrl+a". Tried: 12 circles, a box round 4 of them picked 4, Ctrl + A 12, Extrude made all 12; in the sketch, Ctrl + A picked its 12 curves.

- Help and the README said a left drag turns the view; it draws the selection box, and has for a long time. Both now say what the buttons do, and where the styles are.

- The tutorial's first four steps walked with real clicks after these changes (Draw, Circle, the centre, the size: a circle of radius 5).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 14:35:54 +02:00
superGeometry 8911bf2b4a Five bugs reported after the app was posted: a rounding lost when an extrude is turned the other way, a thickened freeform's rim refused a rounding, STL files greyed out on an iPad, the page pushed down under the finger on an iPhone, guide text that could not be put away (the reports read together, then "Yes, bugs first").
- A rounding of five edges left on four after the extrude was edited (reported: "I make filet on 5 sides ... edit extrude to 20mm ... now I see filet only on 4 sides"). It happens when the edit turns the extrude to go the other way (10 up made 20 down): its far end was named for the side of the sketch it is on ("cap:1" above, "cap:2" below), so an edge or a face of the far end was no longer found by name, was looked for by place, and landed on an edge already taken. The far end is now found under either name when only one of them exists (to both sides at once, each end keeps its own). tests/flipend.test.ts, 15 checks; a fuzz of boxes (any plane, either way, rect or polyline, edges or whole faces picked) had 12 of 150 differ before, and none of 300 after.

- A freeform sheet given a thickness refused every rounding of its rim with "That edit would turn the body inside out" (GitHub issue 1). The thickened solid came out of the kernel inside out and was only marked as reversed: it measured right, but its faces still looked inwards, and a rounding took every edge for a hollow one. A solid is now made anew from its skin, faces outwards. And an edge with no corner along it (the lines between a freeform's patches) is said to be smooth already, not "the radius is too big". tests/thickfillet.test.ts, 24 checks.

- iPad: STL and STEP files and the app's own projects were grey in the Files window (reported from an iPad Pro, files in iCloud Drive). A file picker told a list of endings greys out every kind iPadOS has no name for; on an iPad or iPhone it is now told nothing, and a file of a kind the app does not read is said so once picked. The same for File > Open and a text's font file.

- iPhone, the app installed on the home screen: with the numpad up, everything was drawn a row lower than where touches landed ("0 is 2"). Not seen here (no iPhone to try it on): the cause is taken to be the page pushed along when a number box takes the focus, as a phone does for a keyboard - ours brings up none. The page is now put back whenever it is found scrolled (ui/steady.ts), the numpad's own focus calls ask for no scrolling, and installed, the page is pinned to the screen. To be confirmed on an iPhone.

- Guide text: a small x on it puts it away for good, with a line saying More > Guide text brings it back (reported: "there is no way to remove them" - the switch in More was not found). Only the x takes a tap; the words still let taps through to the model. Tried at 375 x 812 with a press, a frame, a release: hidden, the switch in More off, nothing drawn in the open sketch; switched on again from More.

- README: a thread's own faces can be tapped for a joint.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 14:20:26 +02:00
superGeometry ff84a02082 The tutorial's nut can be turned: it is made 4 mm up the thread, not at the rod's end (found with Assemblies' Stop on contact; from the list of what is left to improve - "Ok do them").
The nut was a block on the floor round the rod's end, cut by the bolt where it stood. The bolt's thread begins a little above the rod's end, a partial turn first, so the nut's hole had, below where the thread begins, a plain bore the thread cannot pass: the nut turned a third of a turn towards the head (137 degrees) and stopped - on the screen with Stop on contact, and as printed. "Ready to print ... so it turns" was not so.

The nut's block is started 4 mm up (Extrude's Start, set for them with its thickness; the card says so): the thread runs through the whole nut, the rod's end shows below it as on a real bolt. The nut's chamfers, its tap spots and the cut follow where it is.

In the app, at 375 x 812 by touch: all 45 steps, a finger's taps, no pointer left down; ten steps in History; the bolt 0 to 26.4, the nut 4 to 12.4, both sound. The nut against the bolt, by the contact check: free at every angle tried from 2400 degrees down (off the rod's end) to 1440 up; towards the head it meets it at 1806 degrees, 7.52 mm up - the 7.6 between the nut's top and the head's underside, less their chamfers' play.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 18:43:43 +02:00
superGeometry 4477fb2033 Assemblies: Stop on contact - a dragged part goes only as far as it can before it runs into another (from the list of what is left to improve - "Ok do them").
A switch in Assemblies, off unless turned on. With it on, each move of a drag is gone in steps (a millimetre, or three degrees, of the dragged joint), and at the first step a part runs into another the place is found by halving: the part stops there, and the value beside the pointer says "contact".

Two parts are run into each other when a corner of one is more than a quarter of a millimetre inside the other (inside: a ray from the point crosses the other's mesh an odd number of times; more than a little: six points round it are inside too). So parts that touch, or sit in each other with a hair of play - a nut on its thread - are let be: their drawn facets cross here and there without the parts doing so. What is in each other as the drag begins is left alone for that drag. Walls and teeth thinner than half a millimetre are not felt. Each body's mesh is put in a tree of boxes once (src/assembly/contact.ts).

Found with it: the tutorial's nut, cut round the bolt where it stands, turns a third of a turn towards the head and no further - the bolt's thread begins a millimetre above the rod's end, inside the nut, and the nut's hole below that is a plain bore the thread cannot pass. (The tutorial is put right next.)

tests/contact.test.ts, 14 checks: a point in and out of a box; boxes apart, touching, a tenth in, two millimetres in, one inside the other, swung on a hinge; a pin in a hole with play; a move undone; two meshes of 19 200 triangles asked 20 times. In the app: the M10 nut turned by its side with the switch on - 3.5 ms a move, not stopped by its own thread; turned on towards the head - stopped at 137 degrees, where the bolt's thread start meets the nut's plain bore; the switch off - no stop.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 18:39:13 +02:00
superGeometry 41ff788485 Assemblies: a thread's own faces give a joint its line (from the list of what is left to improve - "Ok do them").
A joint took its line from a round face (its axis) or a flat one (its normal, through its middle). A thread's flanks are neither: tapped, they gave no line, and a bolt and its nut had to be joined by flat faces that happen to lie on the thread's line. Any face turned round a line - a thread's flank, a cone - gives that line now, found from the face's drawn points and the way it faces at each: along the line the normals all lean the same (the direction their leaning varies least in), and seen along it they all point at it. A flat face, a ball and a freeform face have no such line and give none, as before.

Such a line is good to a few hundredths of a millimetre (it is found from the drawn points), so two picks count as on one line a little more loosely when one of them is such, and the joint's line is the other pick's when that one is known exactly.

tests/joints.test.ts: a helicoid round a slanted line (its direction and place found), a cylinder's wall, a flat face, a ball. In the app, on the M10 bolt and nut: every thread flank of both bodies gives the Z axis to within 0.05 mm; the bolt's thread and the nut's thread tapped - a Screw of pitch 1.5 along Z.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 18:32:44 +02:00
superGeometry 266aa176db The tutorial: a long press on a lit spot is a tap, and a window put up meanwhile can be answered (from the list of what is left to improve - "Ok do them").
- A press held more than half a second on the model is press-and-hold: it takes hold of what is under it, or opens its menu, and is no tap. A beginner presses slowly and waits: the lit spot did nothing. While the tutorial runs a press however long is a tap when it lifts (press-and-hold is itself again when the tutorial is left or done).
- A window the app puts up while the tutorial runs - a question, a warning - lay under the tutorial's rule that only the lit spot takes a tap: its buttons could not be tapped (the first visit's question was one such, fixed by itself before). Taps on such a window go through.

In the app, at 375 x 812 by touch: the circle's centre and its rim each pressed for a second - placed, the step on; the rod's top pressed for a second - picked, "Tap Sketch"; no finger left down. A window put up over the tutorial: its button tapped and taken. After Exit tutorial press-and-hold is on again.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 18:30:30 +02:00
superGeometry c5afac571d The tutorial begun from the welcome window on a first visit: the "New here?" question no longer comes up over it (reported: "now i cant do the tutorial on PC. i cant click draw", then "i opened the page in incognito").
On a first visit (a private window is one, every time) the welcome window's own Tutorial button closed the window - which is what asks, a moment later, whether to start the tutorial - and started it. The question came up over the tutorial already running: the tutorial lets nothing be tapped but its lit spot, so neither of the question's buttons could be, and the question lay over Draw. Nothing could be done but to reload.

The question is not asked while the tutorial is running or on its way (its new project being opened); and starting the tutorial, from anywhere, takes the question down if it is up.

In the app, with a real mouse, the first visit's flag cleared: the live site first - the question over the tutorial, as reported. With the change: Tutorial in the welcome window - the tutorial, no question; Draw, Circle and the circle's centre clicked, each taken, no pointer left down. Then all 45 steps as a mouse does them (down, the tutorial's frame, up, the click), the app idle after each; ten steps in History, both bodies sound.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 17:49:26 +02:00
superGeometry 6b796c06cf A check of security and of speed, and the words brought up to date; 0.6.0 (asked for: "check for speed and performance, also security" and "also update everything: about, help, guide text etc.").
Security. Looked for: code run from text (none: no eval, no Function made from text), text written into the page as markup, pages and messages from elsewhere, links opened, what is fetched, the packages' known faults (npm audit: none).
- A project file can come from anyone, and three things in one reached the page as markup. A body's colour was written into a tool's button ("<span style=background:...>"): a file with markup for a colour had it on the page when that body's tools were listed. A colour is given to the swatch as a colour now; and a project read from a file keeps only colours that are colours ("#rgb", "#rrggbb", "#rrggbbaa") and see-through levels that are numbers - anything else is dropped. A drawing's ids and its text's size, weight and colour went into the sheet's SVG as they were: escaped now, as its texts were.
- The site sends security headers on every file: a Content-Security-Policy (only the site's own scripts run - none written into the page, none from another site, no plugins; pictures and the Browser window's pages may come from anywhere, they are what the user opens), nosniff, and a referrer that names only the site. 'unsafe-eval' is in it for the geometry engine, which builds part of itself as it starts: without it the engine did not start (tried). With the policy, on a build served with these headers: the app opened, the engine started, the tutorial's first 24 steps were built (sketches, extrudes, chamfers), the Technical Sheet and Drawings opened - no violation reported.
- Found sound: the Browser window opens http and https pages only, in a sandboxed frame; links open with noopener; the About page escapes its text.

Speed. Measured, on a ten-step part:
- A change that leaves the model's steps as they were - a body renamed, coloured or hidden, a material, a joint, an assembly's pose (saved at the end of every drag), a pin - went to the geometry engine and back all the same: about a fifth of a second each. What is shown is brought up to date from the model there is now, the engine not asked (only when the model on the screen is the project's own, and none is being made). A change to a step still makes the model again; undo and redo as before.
- Nothing to change: the tutorial's work each frame and an assembly's parts placed on each move of a drag are a few thousandths of a millisecond; nothing is drawn while nothing happens, with the tutorial open or not.

Words. Help: Insert (Image on plane, File, Project), Assemblies (the pose is kept; Joint from two picked faces; where the parts are shown while a tool is open), the tutorial (New project at its end). About (the README): the tutorial, BIM and Assemblies, Insert, what a .super file holds, the project's joints and pose for scripts.

In the app: a project loaded with markup for a body's colour, its see-through level and a material's colour - none of it kept, nothing run, the body's tools listed; a pose saved five times - no engine call, the pose there; a colour and a name changed - shown, no engine call; a step's size changed and undone - the model made again each time. tests: joints, linked, sketchfollow, holepattern pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 17:01:43 +02:00
superGeometry 27eb88e5c5 The tutorial: a tap that began on a lit spot is let finish - step 3 no longer leaves the app deaf (reported: "I cant go past step 3 on mobile. when i tap where it says (in the box), it doesnt do anything and i have to tap exit tutorial. and if i exit tutorial, it goes into a mode that doesnt let me do anything and i have to hit new project. Verify every step").
Since the lit spots took their taps by where the tap is (1e282f3), each event of a tap was judged on its own. A point of a sketch is placed as the finger comes down: the next spot (the circle's rim) was lit at once, the finger's lifting - still at the centre, no longer lit - was stopped, and the app was left with a finger it thought was still down. Every tap after that was a second finger to it: nothing could be tapped, in the tutorial or after leaving it, until a new project. A touch that began on a lit spot goes through to its end now, wherever what is lit has gone by then (the finger's moves and its lifting, a touch's own events, a mouse button's release, the click that follows).

My walks did not show it: their taps were a press and a lift in the same instant, with no frame of the tutorial between. The walk is as a finger does it now - down, the tutorial's frame, up where it went down, the click - and checks after every step that the app has no finger left down.

In the app, at 375 x 812 by touch with the number pad: before the fix, the finger down at step 3 placed the centre, step 4 was lit, the lift was stopped (one pointer left, the app "captured"). After it: all 45 steps, each one checked - no pointer left, the app idle - ten steps in History, both bodies sound. Exit tutorial at step 4 (the circle's centre placed): the app idle, the next tap on the model finished the circle, More opened. The first twelve steps with a mouse the same way.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 16:23:58 +02:00
superGeometry 7a9e3caadc An assembly's parts stay where they were left: after OK, and when Assemblies is opened again (asked for: "if i do an assembly and i position some parts in a way, when i click OK, it resets to the original stance (like it was before assembly) and if i click on assembly again from More>BIM, it doesnt show what i made before. it just resets to the original modeled position").
Leaving Assemblies put every part back where it was modelled, and what had been moved was forgotten. The pose is kept in the project now - each joint's value, and how far the parts are pulled apart - saved with it (and in its .super file), undone and redone like any change:

- Assemblies opened again starts from it.
- After OK the parts stay as they were left, on the screen, while nothing is being worked on: no tool open, nothing picked. With something picked or a tool open they are where they were modelled - a tool's arrows, sizes and what it makes are there - and back in their pose when that is over. Home, in Assemblies, is the way back to the modelled position for good.
- What is lit of a part shown moved (the pointer over a face) is moved with it; a part shown moved is picked by its faces only, its edges and corners being known where it was modelled.

Still as modelled: what is exported, measured and drawn.

In the app, on a copy of the bolt and nut: the nut screwed up two turns (3 mm), OK - still 3 mm up, the pose in the project; a face picked - the nut where it was modelled; let go - 3 mm up again; Assemblies opened again - the joint at 720, the nut 3 mm up; left again - the same.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 16:08:43 +02:00
superGeometry 7bac6e1855 Assemblies, a first version: joints between the bodies, dragged by them, followed, pulled apart (asked for: "Can we work now on assemblies? ... Can we develop a system that its in the same theme with the rest of the app and its intuitive and easy to assemble? people build the models with the parts already in place so maybe thats a good start", then, to joints and dragging, linked motion and the exploded view, a pose that goes back to where it was modelled, and no physics: "ok do what you recommend and well start from there").
More > BIM > Assemblies (it was greyed out, "soon"), marked as still being tried out.

- Nothing is put in place: the bodies are where they were modelled. A joint only says how two of them move. Add joint, a face tapped on each of two bodies, and the kind is read off the faces as they stand: on one line (two round faces on one axis, two flat faces one above the other) a Hinge - a Screw of the thread's pitch when one of the two bodies is threaded; two flat faces side by side, a Slide along the first's normal; anything else, Fixed. The Type can be changed. Two faces picked on two bodies have Joint among their tools, which opens Assemblies with the joint made.
- A body dragged moves the way its joint lets it: round the joint's line (by where the pointer is across it, turn after turn; seen from the side, by how far the grabbed point went round), along it, or both at once on a screw. Its Angle or Distance can be typed. Limits keep it between two values. Flip turns the line round. A body held fast to another moves with that one's joint.
- Follows: a joint goes with another by a Ratio (a gear: minus the ratio of the teeth); dragging either moves both.
- Explode: a slider that pushes each body off its neighbour along their joint's line (a fixed joint: from middle to middle).
- Stands still: which body doesn't move (else the first of each group of joined bodies).
- Moving is a pose, not a change to the model: what is drawn of each body is put through its move, nothing is made again. Home, or leaving Assemblies, has every body where it was modelled. Joints are kept in the project (and its .super file), undone and redone like any change; their line follows the faces they were picked by when the model changes.

Not in it: weight, forces, bodies stopping against each other; a ring of joints (its last joint is left out); the pose in exports and drawings; parts from another project put in place by their faces.

A flat face's middle, for a joint's line, is its outline's (the middle of the box round it): a nut's top is a ring whose hole the thread runs out of to one side, its centre of area a quarter of a millimetre off the nut's line - the first try made a Slide of the bolt and nut for that.

tests/joints.test.ts, 26 checks: each kind of joint, limits, which body stands, a chain of two hinges, a ring, a joint following another, exploded, what two picks make. In the app, on the tutorial's M10 bolt and nut: the head's top and the nut's top tapped - a Screw of pitch 1.5; the nut dragged by its side - turned 18.3 degrees and up 0.076 mm; 720 typed - up 3 mm, the same way round; limits 0 to 360 - held at 360; Home; Explode at 60% - the nut off the end of the bolt; Joint from two picked faces; left - the nut home, the joint kept; undone - the joint gone. Not tried: the phone's layout, a touch drag, Follows through the app (its sums are tested).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 16:00:03 +02:00
superGeometry 1e282f3b1c The tutorial's lit spot takes its tap on every browser (reported: "am trimis aplicatia unui prieten sa faca tutorialul pe mobil si a zis ca nu poate da tap pe DRAW la step 1. Pur si simplu nu functioneaza. Eu pot pe telefonul meu").
The dimmed screen took every tap itself, an opening cut in it (a clip-path with a path) over each lit spot for the tap to go through. A browser that doesn't cut such openings - an older one on a phone - had a whole dimmed screen over the app: nothing could be tapped, the first step's Draw included. Not seen on that phone; this is what the code allows that fits "it simply doesn't work" on one phone and works on another.

Where a tap may go is told by where it is now, not by what is under it: each tap is looked at before the app has it, and goes on when it is on a lit spot (3 px over its rim) or on the card, stops otherwise. The dimmed screen is only looked at (it takes no taps). A browser that can't cut the openings dims the screen less, so what is lit is plain to see under it. At the end the view is theirs again, as before.

In the app, at 375 x 812 by touch: with the dimmed screen's openings taken away (as such a browser has it), step 1's Draw tapped and taken, then all 45 steps to the end; taps off the lit spot - the model, More, Exit when it wasn't lit - did nothing; at the end the wheel zooms; ten steps in History, both bodies sound.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 15:25:12 +02:00
superGeometry bce9708035 More > Insert > Image is named Image on plane (asked for: "in more > insert > Image, rename Image to Image on plane").
The name alone: what it does is as before. It says what it is beside Reference Image (a picture in its own window).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 14:05:19 +02:00
superGeometry ee568a78cb More > BIM > Assemblies is greyed out with a "soon" tag and takes no tap (asked for: "when i go to More > BIM > Assemblies, i want assemblies button to be greyed out with a soon sign, so they cant click it yet").
It looked like the tools beside it, and a tap said "Assemblies are being built - after Drawings". A tool can be marked not made yet now: dimmed in its place, a small "soon" tag after its name on every screen, and a tap does nothing.

In the app: More, BIM - Assemblies dimmed with "soon", tapped: nothing opened, nothing said, the list still open; Materials, Technical Sheet and Drawings as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 14:03:03 +02:00
superGeometry 82ec28a307 The tutorial's last card: where to export, and a New project button beside Finish (asked for: "the last message in the tutorial says 'file has export STL and 3MF'. maybe you should change that to ... 'you can export files now' or whatever. and near the Finish button, it should be a New project button").
The card's last sentence was "File has Export STL and 3MF."; it is "You can export them now, from File." Beside Finish, at the end only, is New project: the tutorial is closed and a new, empty project is opened (the bolt and nut stay in the list of projects).

In the app, at 375 x 812 by touch: the tutorial walked to its end; the card with the new sentence, New project beside Finish and both inside the card; New project tapped - the tutorial gone, an empty project with its first sketch open.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 13:41:02 +02:00
superGeometry 4d4016b92b The tutorial's bolt head and nut are chamfered on both sides (asked for: "chamfer the other sides also").
Each was chamfered round its top only. With Chamfer open on the top's edges, the hexagon's edges on its other side - the head's underside, the nut's bottom, which can't be seen to tap - are chamfered with them, and the card says so. Added once: with them chamfered the body as it is shown has new edges at that height, the cuts' own, which are left alone. No more steps: 45.

In the app: all 45 steps at 375 x 812 by touch; each Chamfer with 12 edges; turned to look from below, the head's underside and the nut's bottom chamfered; both bodies sound (2734.2 and 1157.2 mm3), no tap blocked.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 13:25:19 +02:00
superGeometry 739a819efd The tutorial's shapes land exactly, and its bolt and nut are a real M10 (asked for: "when the small boxes appears and tells you to place the center of the circle or the polygon, you can click it but you can place it slightly off the project center or different distances for diameter or polygon. make it so its placed exactly where its suposed to be. also, make the thickness of the bolt head and nut a default because they can type a ridiculous value and it will break. the dimensions should be exactly like from a real bolt and nut").
- Exact. A tap anywhere in a lit spot gave a centre a little off the middle, or a circle or hexagon of another size. Once the circle or the hexagon is drawn it is put exactly where the two spots were: its middle on the middle, its rim or corner at its size, a hexagon's corner along X. What the taps tied it to is let go, it is where it is by its numbers.
- The head's and the nut's thickness are set for them: no Distance to tap, nothing to type (the card says what it is set to). The rod's length is still typed, and still put right when typed wrong. 45 steps, were 49.
- Real sizes, an M10 bolt and nut as the standard has them: the rod 10 across and 20 long, the hexagons 16 across their flats, the head 6.4 thick, the nut 8.4, the thread's pitch 1.5 (set, with one start and right-hand, whatever the thread made last on a rod this size was), the nut's thread 0.2 bigger all round.

In the app: all 45 steps at 375 x 812 by touch, the taps for the circle and both hexagons put 13 to 16 px off the middle of their spots - the circle at 0,0 radius 5, both hexagons at 0,0 corner radius 9.2376 angle 0; and at 1577 x 1265 with a mouse. Ten steps in History each time, the extrudes 20, 6.4 and 8.4, pitch 1.5, clearance 0.2, both bodies sound (2760.8 and 1183.7 mm3), no tap blocked.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 13:20:09 +02:00
superGeometry 64f7b67432 The tutorial builds a printable bolt and its nut, is offered on the first visit, and is easy to follow on a phone (asked for: "can we show a popup only for the first time someone opens the app, after they close the welcome window, that ask them if they want to start the tutorial? also, lets work a little bit more on the tutorial. on mobile its kinda hard to follow because its so cluttered and the over layer that prohibits to click something else is also over the numpad. also, why dont we guide them to build something real, while using tools from each category? something simple but impressive", "make them put clearance so its a perfectly printable screw and nut. also add chamfer on the edges to look more finished", "or maybe you put 0.2 mm by default and thats it. simpler" and "why dont you make the tutorial so they cant screw up by entering wrong values or clicking somewhere else in the workspace?").
- What is built. A bolt and the nut that fits it, in 49 lit taps, with tools from Sketch, Create, Modify and Combine: a circle pulled up into a rod, a hexagon on its top pulled into a head, the head's edges chamfered, a thread cut on the rod, a hexagon block round the rod for the nut, its edges chamfered, and the bolt subtracted from the nut with the bolt kept. Subtract's Clearance is set to 0.2 mm for them, so the printed pair turns.
- No way to go wrong. A size typed wrong is set to the right one ("That is set to 20 mm for you"). The view is put at the tutorial's own zoom, on the middle, until the first circle is drawn, so the rod is 5 mm on every screen. A finger on the lit top of the head or the nut that takes a corner or an edge of it instead is the top all the same.
- On a phone. The view cube, the columns at the two edges, undo and redo and the floating boxes are put away while it runs. The card is a slim band across the top (lower when what is lit is up there), not beside the spot. The number pad is over the dimmed screen and takes its taps. Where an option is under Options, Options is lit first. At the end the card is low, so what was built is in full view.
- The first visit. Once the welcome window is closed for the first time on a device: "New here?", with Not now and Start the tutorial. Asked once, whatever the answer; More > Tutorial has it from then on.

In the app: all 49 steps walked at 375 x 812 by touch with the number pad on (a wrong 7 typed for the rod's height, corrected to 20) and at 1577 x 1265 with a mouse; no tap blocked, no card over what it lit; ten steps in History each time, both bodies sound, Clearance 0.2, the bolt kept. The first visit's question shown once after the welcome window, not again. Help and the More list say what the tutorial builds now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 12:41:20 +02:00
superGeometry 3e95ff557c The world's axes are behind what is made; a sketch's narrow shape is picked without zooming in on it (asked for: "sometimes different line overlap. like the axis line with the sketch line ... i want the line of whatever was made to be on top of everything. the axis lines should be in the background of that sketch line. and i saw this problem with solid bodies also. the axis lines overlap the edges and it makes a weird graphical glitch" and "if i sketch on a face and offset chain the edges, and the offset is a small value, when i click on that resulting 'frame', because the surface is so small, it doesnt select that sketch surface and i have to rotate the camera and zoom in very much to select it").
- Axes. A sketch's line or a body's edge lying along the X, Y or Z axis was in the very same place as the axis, and the two fought for each pixel: an edge in dashes of red, a sketch line in the axis's colour and not its own (white, green when held, orange for construction). The axes are drawn a hair further from the eye than they are (a third of a percent of the way to what is looked at) and write no depth; a sketch's lines are drawn after them. Lines of what was made are whole and in their own colour; the axis shows where nothing is on it.
- A narrow shape. A shape of a sketch too narrow where it is tapped to tap without its own outline - the frame between a face's edge and a small offset of it, a letter's stroke - took no tap: its line (which opened the sketch), the body's edge or the face under it took every one, by mouse and by finger. The tap is the shape now: under the pointer, or within a tap's reach of it when the shape is no wider than that reach. A shape wide enough to tap is as before - on its line, the line. A double tap on a line still opens the sketch.
In the app: a plate with lines of a sketch along X and Y past it (white over the axes, the plate's edge on X clean); a plate's top face with its outline offset 1 mm in - the frame tapped at its middle, on its line, on the body's edge and from just inside the wide shape, at 8 px wide and zoomed out to 2 px, by mouse and by touch: the frame each time; the wide shape tapped in its middle and 3 mm from the line: the wide shape; the body's side: the face.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 12:00:18 +02:00
superGeometry 443799d7d4 What is made from a sketch's curves follows them: offsets, mirrored copies, and curves projected into a later sketch (asked for: "if a sketch is based on an offset and that original sketch is constrained, and i want to change for example the line distance that original sketch is based on, that second sketch should change acording to the changes made to the first sketch. somehow linked. if i modify something from the timeline, it should keep the changes after that sketch. with every sketch tool").
An offset of a face's edge followed the face already, and a pattern's copies their originals. These did not - each was a curve of its own from the moment it was made:
- An offset of a sketch's own curve (a line, arc, circle, rectangle, polygon, ellipse) is tied to it: the original given another size or place - a dimension typed, a variable, a step changed in History - the offset is its offset still. An offset outline's pieces each stay on their own side's offset, trimmed to their neighbours. So is an offset made from a body's edge off the sketch's face, by its guide.
- A mirrored copy stays its original's mirror image across the line it was flipped over.
- A curve projected from another sketch (the two planes parallel) is kept as that sketch's curve: that sketch changed, it is put where the curve is now, and what is tied to it in its own sketch follows - an offset of it, a dimension to it.
A copy trimmed, split or otherwise reshaped afterwards is its own curve from then on (held to being the copy, a trimmed offset would be pulled back to its whole length).
tests/sketchfollow.test.ts, 14 checks: a line, a circle, a rectangle and an arc resized with their offsets; a four-sided outline made 90 x 35 with its offset outline 3 outside it all round; mirrored copies; a trimmed offset let go; a second sketch following the first through a variable. In the app: a rectangle, a line and a circle offset with Offset Edge, then given sizes - 90 wide and its offset 96, 70 long and its offset 70, radius 12 and its offset 14.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:37:57 +02:00
superGeometry 0fd4394bc0 A sketch's construction lines are as easy to see as its other lines (asked for: "when drawing with construction line, the line is so hard to see especially if its drawn on a face or a plane. should be more visible, like the normal line").
They were thin grey dashes (1.4 wide, nearly a body's own colour): on a face or a plane they all but vanished. They are as wide as the sketch's other lines now (2.2 while it is edited, 1.6 otherwise), in an orange that stands out on a body's grey, a plane's blue and the dark floor, their dashes a little longer. Dashed and orange is what tells them from the white lines that make shapes.
Looked at in the app: a construction line and circle on a plate's top face beside a normal line, with the sketch open and closed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:22:21 +02:00
superGeometry 8483f6cec2 An offset of a face's edge can be offset again (asked for: "if i want to offset a line further that is already an offset of an edge, it doesnt let me, it says that the line is already offseted and if i want i can change the distance. i should be able to offset any line whenever i want").
Offset Edge tapped on a line that is itself an offset of the face's edge was refused ("That's an offset of the face's edge already"). It is offset now: another offset of that same edge, as much further from it as is set - on the far side of the line tapped to start, Flip for the near side - and kept as the first is, so it follows the face when the face changes size too. Edge or Chain as the first was.
In the app: a plate's top face, its outline offset 3 in; that line tapped and offset 4 more (lines at 7 in, all four sides); that one tapped and offset 2 more (9 in).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:16:00 +02:00
superGeometry 47afac977c The tutorial: a first part built with a beginner, one lit tap at a time (asked for: "regarding the tutorial, can you come up with something? like building something with a beginner but you must guide them through and they cant click anything else. with simple guide text").
More > Tutorial (it said "soon"), and a Tutorial button in the welcome window - the one that stands out while there are no projects yet. It starts a new project and builds a small block with a rounded edge in twelve taps: Draw, Rectangle, two corners, Exit, Extrude, Distance, 10, Done, an edge, Fillet, Done. The whole screen is dimmed and takes no tap but on the one spot to tap next, which is lit, a card beside it with one short sentence and "Step n of 12". Keys do nothing either, but while a size is typed. Exit tutorial is on the card at every step; at the end nothing is dimmed and the card says how to turn the part and where Export is.
Where the beginner is, is read off the app each frame - the tool open, what is picked, what has been made - not counted in taps taken: a tap that went a little wrong (a list closed again, something else picked) is not a dead end, the next spot is shown from there. If the app ends up somewhere the tutorial has no use for, the card says so after four seconds.
In the app: started from More and from the welcome window; taken through all twelve steps at 1577 x 1265 with a mouse and at 375 x 812 by touch - Sketch, Extrude and Fillet made each time, the body sound; a tap off the lit spot did nothing; the card over nothing it lit and never off the screen; Exit tutorial left the app as it was. Also tried by hand in the app, with what was built before: a hole's wall patterned (five holes, the volume exact), three linked plates with one's edge rounded (all three the same), a variable renamed from its window, two lines set 15 apart, a pattern round a point following its variable from 4 to 7, Thread's Starts on its line.
Tests: all 183 test files pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 10:49:23 +02:00
superGeometry 3e3cece7fe A pattern of a hole repeats the hole; threads with several starts (asked for, of the gaps a user finds in week two: "fix them all").
- A pattern started from a hole's round wall repeats the hole in its body: a plug the size of the wall - a hair longer at an end that is open, exactly as deep at a bottom - cut again at each place of the pattern, in a row or round an axis. (It copied the whole body: there was no way to repeat a hole.) New holes that fall off the body are counted in a note; all of them off it, a spacing of 0, or a face that is no hole's wall is refused in plain words. A body with linked copies: they get the holes too. Its first spacing is three radii. tests/holepattern.test.ts, 13 checks.
- Thread has Starts (1 to 8): that many grooves side by side, the crests still a pitch apart, one turn taking a lid that many pitches along - a jar's neck and lid. A threaded body subtracted with a clearance keeps its starts. tests/threadstarts.test.ts, 11 checks: 1, 2, 4 and 6 starts on a 40 mm neck, each sound and taking what one start takes; four starts turned a quarter is the very same neck, one or two are not; left-hand; a lid cut from a four-start neck with 0.3 clearance stands 0.2988 off it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 10:15:44 +02:00
superGeometry 55f654073c A variable renamed everywhere; a distance between two lines; a sketch pattern that follows a count; fill patterns follow variables (asked for, of the gaps a user finds in week two: "fix them all").
- Variables > Rename: each variable's name in a box. A new name typed, every formula that used the old one says the new - other variables, steps' sizes, sketch dimensions, points placed by it, a pattern's count - and nothing changes size. Two can swap names at once; a name taken, a unit or a function is refused in plain words. (A variable could only be deleted and made again, and what used it lost its link.) tests/renamevariable.test.ts, 14 checks: the flange built on variables, three of them renamed, is the same flange and still follows them.
- Sketch: two lines picked that run the same way have a distance - shown in its box, typed, kept as a Distance constraint that holds them parallel and that far apart. (It was point to point and point to line only.) tests/linedistance.test.ts, 8 checks.
- A sketch pattern whose Count is typed with a variable or a formula is kept with the sketch: its copies are made again when the count comes to another number - "n" holes round a circle, floor(len / 10 mm) slots in a row. A count below 1 is said in plain words and the sketch left as it was. (A sketch pattern was its copies and nothing more.) tests/sketchrepeat.test.ts, 15 checks.
- Fill patterns are made again when a variable or a dimension resizes their shape, not only when the sketch is changed in the sketch tool.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 10:08:17 +02:00
superGeometry 69ea518b83 A list opened from inside More keeps More lit, and says where it is (asked for: "on the bottom bar if i open a level 3 window (the pulsating effect stops showing from what button i started)").
A list under one of the line's own words (Construct > Plane) keeps that word lit. More's list is under no word of the line: opening BIM or Insert from it put More out, and nothing on the line showed where the list had come from. More stays lit for a list opened from inside it now, and that list is headed "More › BIM", as "Construct › Plane" is.
In the app: More (lit), More > BIM and More > Insert (still lit, headed so), closed (out); Construct, Construct > Plane (Construct lit throughout).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 09:56:08 +02:00
superGeometry 65d38e3fff More: Offline mode under Update, a grey line over and under it (asked for: "move offline mode under update but separated by grey horizontal lines").
The list is now: Fullscreen, Install app, Update | Offline mode | Guide text, Tutorial | Help, Feedback, About, Support | the version. Looked at in the app.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 09:52:20 +02:00
superGeometry 70871f6a7e The line at the bottom keeps its own width with a list open (asked for: "the bottom bar extends in width so much if i click more and i select anything there").
The line may be as wide as there is room for since the last change (it stopped at 980, and a sketch's picked line had to be slid). A list opened from it shares its box, and as it comes - before it is sized to its buttons - a list is as wide as all its buttons in one row: the box widened to that, and the line with it, right across the screen. A list opened from inside another (More > BIM) also kept the place the one before stood at, and reached past the line's end. The line's own width is measured with the list out of the way now, and a list is sized and placed by that.
In the app, 1750 wide: the line 922 with nothing open, and 922 with More, More > BIM, More > Insert, Construct, Construct > Plane, Transform, Transform > Pattern, Freeform and Create open - each list within the line's ends. 1024 wide: 760 throughout.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 09:51:34 +02:00
superGeometry a2cfe76a3f Linked copies and patterns; Fill Pattern in sketches; freeform solids get every body tool; the right column's buttons lit and its windows clear of everything; More reordered with switches; the grid's size live; Draw turns Line on; the line as wide as its buttons (asked for, nine points: "make sure even the buttons on the middle right (fit, shaders, settings) show when something is opened. like the ones on the middle left ... when a window opens from those, to not override anything else (should be dynamic) ... In More, move Help above Feedback, move Update under Install App, and make the two buttons (guide text and offline mode) have a toggle icon ... Rename About supergeometry.app to only About ... the lock grid size should change on the fly when i zoom ... when i click draw, line should be automatically selected (but the window with different line types should open normally) ... if i copy a body, i have the option to link it, but that doesnt do anything ... whatever change i do to any copy of that body or the original, it should also change the other ones exactly the same. we should also have this in patterns ... a new tool in sketch mode named fill pattern ... when i double click a freeform body, i want the edit freeform button there ... a freeform body that is finished should be treated like a regular body ... on desktop, in sketch mode ... the bar should be wider to fit all the buttons without having to scroll on it").
- Linked bodies. A copy (Move/Rotate, Mirror, Scale with Copy on) or a pattern made with Link on, and what it was made from, are a group: a step that changes one of them - an edge rounded, a hole cut, something joined on - changes every other the same way, each where it stands (turned, mirrored). Moving or turning one only moves that one, and it still follows; one deleted leaves the others; a linked copy of a linked copy is of the same group. Both patterns have a Link switch now. (Link only did anything for freeform copies before.) tests/linked.test.ts, 17 checks.
- Fill Pattern, a sketch tool under Draw: tap inside a closed shape and it is filled with Lines, Crossed lines, Zigzag or Waves from edge to edge (ending exactly on the shape's edge, stopping at holes), or with Dots, a Honeycomb, Squares or Diamonds kept wholly inside it; Spacing (or the Gap between shapes), Size and Angle set, shown as they change. The strips and cells are shapes of the sketch: extruded or cut, a texture. A filled shape tapped again: its pattern changed or removed. The pattern is kept with the sketch and made again when the sketch's curves change (a rectangle made taller: 9 cells became 43). Too fine a spacing (thousands of curves) is refused in plain words. tests/fillpattern.test.ts, 28 checks.
- A freeform solid that is finished is a body like any other: its faces, edges and corners have every tool a body's have (they were held to Move, Mirror, Pattern and Delete Body), its edges their dot, its corners their gimbal and Move Vertex. Only a freeform left as an open surface keeps its own few. Edit Freeform is beside a freeform body double tapped - also after other steps were done on it - and in History.
- The right column: Shaded and Settings are lit while their window is open, as the three at the left are while they are on. Their windows (Units & grid and the others too) are placed in the room there is - under the top bar, the view cube, Items and History, over the line, undo / redo and the guide text - on every screen, and scroll inside when longer; on a phone on its side, beside the view cube. (They came down over the line on a phone.)
- More: Update under Install app; Guide text and Offline mode each with a switch (they said On / Off in words); Help above Feedback; About.
- Units & grid open, not locked: the size said on Lock grid size, in the box and in the note follows the zoom as it changes.
- A sketch's Draw opened with no tool on: Line is on and the list stays open - a tap on the grid draws, a tap in the list takes another tool.
- The line at the bottom is as wide as what is on it, up to all the room between undo and the right edge (it stopped at 980): a sketch's picked line or shape has all its sizes and buttons in view on a wide screen.
In the app: the nine tried - the windows at 390 x 800, 844 x 390, 768 x 1024 and a desk screen (nothing over anything); a rectangle filled with lines, then a honeycomb, then made taller; a circle filled with waves; a freeform box double tapped, a corner, a face and an edge of it picked; a pattern's Link switch; a sketch's line and rectangle picked on a 1577 wide screen (the line 1050 and 1115 wide, nothing to slide).
Tests: all 178 test files pass (mouse.test.ts's 30 s limit on a shell was missed once with five running at a time: 39 of 39 run alone).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 19:00:29 +02:00
superGeometry d53ddeaa76 Version 0.5.0 (asked for: "change the app version to whatever you think it should be, and push it").
It was 0.3.0 since 5 November, 465 changes ago. Since then: the pick-first line at the bottom as the whole interface, undo and redo inside every tool, sketch constraints and variables gone through, 3D splines, thread clearance, every export checked, building twice as fast on curved bodies. Half way to 1.0, not there: it has hardly been used by anyone but its maker, and not tried on many phones.
Shown in More, and sent with feedback.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 01:32:51 +02:00
superGeometry f8cc57fe7f A section's cut face is the same for every body, whatever its colour (asked for: "when i pick a color for a body and i section that body, i want the cut fill to be like in the default color (pink with black diagonal lines). it shouldnt matter what color the body is, the section should always be represented like this").
The cut face of a coloured body was its own colour, a little darker, with the lines. It is the pink with its dark diagonal lines for every body now, coloured, see-through or plain.
In the app: a box made blue, cut by a section 8 mm in: blue faces, the cut face pink with its lines.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 00:12:50 +02:00
superGeometry 47583abb3a A line of a sketch drawn on a body's face is picked, not the face (asked for: "When I want to select a line sketched on a bodies face, it selects the whole face, not the line. Verify this on all sketching tools").
A sketch's curve seen through a body must not win over the body in front, so a curve under the pointer is compared with the face there: which is nearer the eye. The curve's place was taken as the start of the piece under the pointer, not where the pointer is on it. A circle or a spline is many short pieces, so that was near enough; a straight line is one piece, and its far end stood for it - "further away than the face", and the face was picked. The place is now where the pointer's line of sight comes nearest the piece (right in perspective too).
In the app: a sketch on a box's top face with a line, circle, arc, ellipse, rectangle, polygon, open polyline and spline, each tapped - from the top and at an angle, orthographic and perspective, and low along the face in perspective: the curve each time (the line gave the face before). From below, through the body: the face in front, as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 20:02:21 +02:00
superGeometry fc404cc92b In perspective, a view picked on the view cube is shown orthographic until the view is turned (asked for: "When in perspective view, if I hit the buttons of the cube, when it goest to that view, I want that view to be ortographic. When I start rotating the camera, I want the view to change to perspective").
- A side, edge or corner of the cube tapped, or Top / Front / ... picked in Views, with Orthographic off in Settings: the view goes there without perspective. Panning and zooming keep it so; turning the view (by hand, or dragging the cube) puts perspective back. A double tap on the cube (back to where the view was, fitted) and Default view put it back too.
- With Orthographic on in Settings nothing changes: orthographic throughout.
- A sketch opened from such a view stays flat while it is turned, as a sketch does, and leaves to perspective.
In the app, Orthographic off: the cube tapped (orthographic), panned and zoomed (still), turned (perspective); another setting changed meanwhile (still orthographic, then perspective when turned); Orthographic on: tapped and turned, orthographic throughout.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 19:54:43 +02:00
superGeometry e4c5095be3 Faster building: joins, cuts, threads and every step on a body with curved faces (asked for: "can you look at speed at performance? i feel like it takes very long to generate certain shapes and changes on said shapes").
Timed every sample project step by step and profiled the slow steps. Most of the time was not the shape being made but the checks round it, each asking the kernel for something exact where about-right was enough:
- A body's exact box took 0.4 to 1 s on a body with curved faces (a mug with its handle, a freeform), and was worked out again every time: after each step (a guard against a size typed with too many noughts), for how fine to draw the body, for how big to make a helper, to tell whether two bodies can touch. The kernel's quick box (never smaller than the body, a few percent bigger on curves, under a millisecond) is used for all of those; the exact one is kept per shape where it is still asked for.
- A volume to a millionth took 1.7 s on the mug and 10.6 s on a jet engine's cowl; to a thousandth, 0.2 s and 0.06 s. The checks that only tell inside out from right way out, dust from a body, or whether a join or a cut came to about what it should (its limits are 60 % of the smaller body) measure to a thousandth; the exact measure only for a result near a limit. A thread's stages measure each body once.
- Each face's exact area was measured again for the whole body after every step: faces a step left as they were keep what was measured.
Whole projects, first build (the engine alone, on this computer): mug 10.0 to 3.4 s, shoe 16.7 to 5.7 s, watering can 7.8 to 3.5 s, jet 64.8 to 30.8 s, fan 39.3 to 21.9 s, guitar 46.7 to 33.5 s, valve 20.5 to 17.6 s, arc reactor 3.5 to 2.3 s. A late edit: shoe 4.8 to 1.7 s, fan 10.0 to 4.5 s, jet 2.1 to 0.9 s, arc reactor 1.7 to 0.6 s.
Not faster: a thread (about 2 s on a bottle's neck) and a shell of a lofted body (about 2 s) - what is left there is the kernel's own cut and offset.
Tests: all 176 test files pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 18:24:15 +02:00
superGeometry 2433833eef A thread's clearance on a bolt with a head; a lifted spline split keeps its heights; printing a drawing from a phone; STEP files of several solids, tested (asked for: "ok do all you can" - of the list of what to test next: undo inside each tool, 3D splines beyond Sweep, picking with every tool, thread clearance on awkward bolts, STEP files of several bodies, Print / PDF of drawings).
- Thread clearance. A bolt with a head, cut from a block with a clearance: the hole's thread ran into the bolt's (0.027 off it, not the 0.2 asked). The thread put back on the grown body was measured from that body's own round face, whose centre and direction are the kernel's choice and differ from the bolt's: the turns started somewhere else. It is measured from the first thread's own point and axis now, over its own stretch. The grooves are filled back in by taking the threaded stretch out and putting a clean ring in (filling them one by one left edges the kernel could not grow). tests/threadclearance.test.ts, 13 checks: the plain bolt at 0.1, 0.2, 0.4; a headed bolt; its head chamfered after the thread; a rod cut by a threaded nut; clearance taken from the bolt, and from both - each the gap asked (0.1998 to 0.2000).
- A spline with points off the plane, split or trimmed: its pieces keep their heights (they fell flat on the plane). A loft along a lifted spline as its guide: tested. tests/spline3d.test.ts, 22 checks.
- Print / PDF of a drawing, of all drawings, and of the Technical Sheet: the page was put back the moment print() returned. On a phone it returns at once, before the preview has drawn anything - a blank page, or the app. It is put back when printing is over.
- tests/stepimport.test.ts, 12 checks: a STEP of four solids (two touching, one sunk in another) comes in as four bodies, each its size, sound; the same file in metres and in inches; Windows line ends; one then moved, one cut by another, one deleted; two files in one project; forty solids; a file cut short, not STEP, empty - said in plain words. Nothing to fix.
In the app: undo and redo inside Offset Face, Extrude, Fillet, Chamfer, Shell, Move/Rotate Face, Edge and Body, Scale, both patterns, Thread, Subtract, Revolve - each step back in turn, nothing to fix; every tool started from every kind of pick (216 starts): none failed to open, no errors; Print / PDF pressed with the print window held: the sheet (420 x 297) in the page until printing is over, then gone, twice in a row the same.
Tests: threadclearance 13, thread, clearance 32, spline3d 22, sketchtools, exports 25, projectlean 29, stepimport 12, drawing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 17:29:38 +02:00
superGeometry 4f93cfbf83 Undo inside a tool; a thread cut with clearance; the phone's sketch line in two rows; undo / redo the bar's height; a sketch's steps in History pick what they made (asked for, six points: "when I want to subtract a thread and I put clearance, it always fails ... on mobile, when I hit sketch ... I have to scroll right in a box that is only a button wide. Maybe you can make that option window 2 buttons tall? ... in sketch, if I close a shape, it should automatically exit the line type ... the undo and redo buttons should be the same as the ones on the bottom bar. Same bar height ... in history, if I make changes in a sketch, I want those changes to be selectable from that history action so I can edit them ... when I ... select a vertex and I move it around, and I hit undo, that undo should change the last modification, not go back to the extruding action ... I want full history control").
- Undo. With a tool open (Move Vertex, Move Edge or Face, Extrude, Fillet, Move/Rotate, any of them), Undo closed the tool - all of what was done in it gone - and then took back the step before it as well. Each change made in an open tool is a step of its own now (a drag of its handle, a value typed, an option, something more picked): Undo takes the last one back, Redo puts it back, and the handles go with them. With nothing left to take back in the tool, Undo closes it; the next is the project's.
- Thread and clearance. The kernel cannot grow a thread's helical faces, so Subtract with a clearance round a threaded body failed every time. Such a body is grown another way: its grooves filled back in (what it was before its thread), that grown, and the same thread cut on it again - over the same stretch, from the same start, its V that much less deep so its sides stand the clearance off the first thread's sides (out by the clearance alone they stood half of it). tests/threadclearance.test.ts, 9 checks: an M10 bolt through a block, clearances 0.1, 0.2 and 0.4 - cut, sound, the bolt untouched, and the hole exactly that far from the bolt at its nearest (0.0999, 0.1998, 0.3996).
- A phone held upright, in a sketch with a tool's own parts on the line (Line on, a point placed): two rows of buttons, a picture over its name each, all in view. It was one row to slide, a button and a half wide.
- Undo and redo are the bar's height on every screen (49 to 61; they were 52, 48 on a phone), and sit on its line.
- History: each step listed under a sketch remembers the curves it made or changed. Tapped, the sketch opens with them picked, their sizes on the line to change.
- Closing a shape: looked at, and already so - the drawing tool is put down and the sketch stays open (line, rectangle, circle, polygon, ellipse, by touch).
In the app: a corner dragged three times with its gimbal, then Undo, Undo, Redo, Undo, Undo (each step back in turn, the gimbal with it), Undo again (the tool closes), Done after another drag and Undo (that step only); a rectangle and two circles drawn, their steps tapped in History (two circles picked; the rectangle picked and its width typed); the sketch line at 390 wide in two rows; undo against the line at four sizes.
Tests: threadclearance 9, clearance 32, thread 15, sketchtools, constraints, projectlean, exports as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 16:14:55 +02:00
superGeometry a305c3c859 Beside a picked corner: Move Vertex and Delete only (asked for: "remove the move/rotate body icon when I select a vertex. It doesn't make sense to be there"). Move/Rotate Body is still under Transform on the line. Tried on a box's corner: the two buttons beside it, the tool still on the line.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 12:47:51 +02:00
superGeometry 8ea2cb758c Beside a picked corner, two different pictures; beside a picked edge, Move/Rotate Edge (asked for: "if I select a vertex, two move icons show. If I select an edge I want the move and rotate edge icon there").
- A corner: Move Vertex has a picture of its own (a point with its four ways), Move/Rotate Body keeps the arrows - they were the same picture twice.
- An edge: Fillet, Chamfer, Move/Rotate Edge, then Delete and More. Move/Rotate Edge is for one straight edge: a round one has Thread there, several have the two.
Tried on a filleted box: a straight edge (the three, and Move/Rotate Edge pressed opens Move Edge), a round one, two edges, a corner (no picture twice).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 12:44:54 +02:00
superGeometry 29836a709f Every export made and read back; the working mark can't stay up over nothing; the handle is on the element picked last (asked for: "verify that each export works as intended", "sometimes the working icon still is showing even if there's nothing to work on ... if I hit undo", "if I select multiple elements, I want the arrow / fillet or chamfer circle ... to appear on the last element I selected").
Exports. tests/exports.test.ts makes each file from one project (the flange built by hand, a block beside it) and reads it back, 25 checks:
- STL: a binary file of the right length, both bodies, closed all over (every side of every triangle met by its neighbour's), the model's volume (within the 0.01 mm the facets keep to), in millimetres where the model is; one chosen body alone.
- STEP: a STEP file in millimetres with both bodies named; read back in, the same solids exactly. One chosen body alone.
- 3MF: a ZIP with its parts; millimetres; each object closed, its volume the body's; the colour; the exact model attached, which is what opens when the file is put back in.
- GLB: glTF 2, as long as it says; two meshes under a root that makes Z up into Y up and millimetres into metres; each closed, its box as the file says; a normal at every corner; the see-through body marked so.
- The project file: saved, opened, built again - the same.
(A sketch as DXF and SVG, and a drawing's sheet as SVG and DXF: dxf, svgexport, drawing tests - 118 checks, passing.)
Found: a STEP of several bodies came back in as ONE body of several pieces - the two bodies of a project saved as STEP and opened again were one that nothing could take apart. A STEP put in from now on brings each solid in as a body of its own (the file's name, and which). Files already in a project stay one body, as what was built on them expects.
The working mark. I could not make it stay up (edits and undos in quick runs: gone each time). Two ways it could, closed: the engine dying without an answer (out of memory) left what waited on it waiting for ever - it is noticed now, what waits ends, a fresh engine starts and the project is built again, with a line saying so; and the mark is looked at again every 0.4 s against what the engine really has to do, so it cannot stay up over nothing. The "Saving…" ring by the project's name: a save that fails is tried again (it was left, and the ring stayed).
The handle. With several shapes or edges picked, the arrow or the dot is on the one picked last, and Extrude, Fillet and Chamfer started from them work from there (it was on the first). Tried: three edges picked one after another - the dot on the third each time; Fillet from the button: its dot at the third, the three rounded, the body sound.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 12:41:34 +02:00
superGeometry 342fbd6390 The columns at the left and right edges move over for Items and History only when those are long enough to reach them (asked for: "the isolate, measure, sections and fit, shaded, settings windows should go to the left or right if the items and history windows aren't that long. They should be there only if they are that long").
- Items and History are as tall as what is in them now, so a short one ends well above the middle of its edge. The column there stays at the edge then, where it stands with the window closed; it moves over (Items: 274, History: 266) only once the window comes down as far as the column. Undo / redo the same, for Items.
- Decided from where the column stands with nothing beside it (the middle of the edge): with History open some screens move the right column up beside History, and going by that place it never came back for a short History.
- A narrow screen: the three at the left edge are hidden only under a card that reaches them (a short card leaves them showing).
- The view cube is at the top, where History always is: it moves over as before.
Measured with Items and History open, short (1 and 7 steps) and long (31 to 51), at desktop, 1024 x 768, 768 x 1024, 844 x 390 and 390 x 800: short - both columns at the edges; long - both moved over; neither window over a column, undo / redo, the line or the view cube in any of them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 12:07:28 +02:00
superGeometry f4d3113272 Items and History are as tall as what is in them, and stop above the line at the bottom (asked for: "check how the items and history windows overlap over other existing windows. We should make those change size depending on how many items/actions are there. For example not go all the way down on mobile and tablet because then it would overlap the bottom bar").
- Both were the screen's whole height whatever was in them (two rows in a window 1,250 px tall). They are as tall as their rows now, and scroll once there are more than fit.
- How far down they may come: a desk screen, to the bottom edge (the line and undo / redo stand beside them there); a tablet, never as far as the line and the tag over it; a phone on its side, the same (they came down over the line and the tag: 314 against a line at 275).
- A tablet: Items now stops above undo / redo, so those stay in their corner, and the line no longer gives way to History unless History really comes down beside it - it has the whole width.
- A narrow screen, Items or History open (a card across the top, past the middle): the three at the left edge step aside. A phone on its side with Items open: the guide text stands beside the card, not under it.
Measured with both open, with 1 step and with 31, with and without a pick, against the line, its tag, undo / redo, the two columns, the guide text and the view cube, at 390 x 800, 844 x 390, 768 x 1024, 1024 x 768, 1366 x 1024 and desktop: over none of them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 12:01:58 +02:00
superGeometry b01f0b8f2c Lists from the line stay on the screen; nothing usable on the line is greyed (asked for: "on mobile and tablet, portrait and landscape, when I open cascading windows from the bottom bar, some of those open as a single wide window and exit the workspace with the buttons. Test everything" and "verify why some tool modes/options in the bottom bar are greyed out. I don't want that. If something is available to use, make it clear").
Lists:
- A list opened from inside another (Construct > Axis, Construct > Plane) kept the place of the one before it whatever its own width: wider, it ran off the edge of the screen with its last buttons (65..443 on a screen 390 wide; 568..1117 on one 1024 wide). It keeps that place as far as its width allows.
- A list all but as wide as the line was left to stretch, and what it stretched to was the box the line sits in. It is given the line's width, never more.
- One button alone in a last row keeps its own width at the row's start (stretched across the list it was a bar).
- A phone: the three at the left edge step aside while a list is up (upright, Section stood on undo / redo as they rose).
Every list - each group, each list inside a group, More - opened and measured (inside the screen, each button inside its list, no word clipped, no row ending in a gap, no button as wide as its list) with nothing picked, a face, a body, Fillet open, and in a sketch (idle, Line on, two lines picked), on the phone and the tablet layouts at 320 x 640, 390 x 800, 844 x 390, 768 x 1024, 1024 x 768, 1366 x 1024: about 300 lists, none wrong. (Before: 6 off the screen.)
Greyed:
- The second part of a list ("Other modify tools") was drawn darker than the first: as clear as it now.
- The tag over the line that names the pick and the tool was at a third of its strength (drawn as a disabled button); the small names over a tool's options (Type, Blend, Size) and the arrow that says a word opens a list were faint. All clear.
- Still dim, because it can't be used: undo with nothing to undo; a group with nothing for this pick (it says why when tapped).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:59:22 +02:00
superGeometry d0d416c736 Every tap adds to what is picked; Fillet beside a picked edge (asked for: "I don't like that now I have to click the + icon after I select to add another one ... I should just be able to select another to add to the selection. If I want to deselect an element from the selection, I can just click on that element again" and "when I select an edge, I also want the fillet tool icon ... before chamfer").
- A tap on the model adds that thing to the pick, whatever it is; a tap on a picked one lets it go; a tap on nothing lets them all go. The + on the line is gone (Shift and Ctrl are no longer needed either).
- Beside a picked edge: Fillet, then Chamfer, then Delete and More (it was Chamfer and Thread; Thread is under More).
- Help and the guide text say so.
Tried in the app on a box: three faces tapped one after another (1, 2, 3 picked), the first tapped again (2 left), an edge added (3 items), a tap on nothing (none); an edge alone: Fillet, Chamfer, Delete Edge, More.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:48:08 +02:00
superGeometry aece06984b A sweep along a spline through space, looked at in a project built by hand: what was wrong with it, mended (asked for: "check ... and see how the sweep tool built the shape that was based on the new spline system").
The project: a spline of five points on an upright plane, each 22 to 31 mm up or down off it; a plane put on the curve at its end; a circle of radius 10 on that plane; the circle swept along the spline. The tube followed the curve through space and was sound, but lumpy, and 1.4 % short of its section times the curve's length. Two things:
- Plane on Curve went by the spline's shadow on its sketch's plane: it stood 25 mm off the curve and 22 degrees askew to it (the circle had been moved 25 across by hand to meet the curve). It goes by the curve where it is in space now: on it, square to it there. So does what is fitted to the view or isolated with a sketch in it.
- The curve bends tighter than the tube is thick: a radius of about 3 mm at its second point and 8 at its third, against a tube 10 from its middle. A body swept round such a bend folds over itself on the inside of it. That is the shape, not a fault of the build - and it is said now: a note on the sweep with both sizes ("The path bends tighter (a radius of about 3 mm) than the profile reaches from its middle (10 mm) ..."), for any path, flat or not.
Also: a point dragged a round number with the gimbal lands on it (163, not 162.99999957): the pull that keeps a drag near where it began is next to nothing now.
tests/spline3d.test.ts, 16 checks now: that path as drawn says its bend; with gentler rises and a rod of radius 3 on a plane square to the curve's end, the rod is as thick all the way (4,823 against 4,825, its section times its length) with nothing said. In the app: On Curve at Point on a lifted spline's end is at that end in space, its normal along the curve there. Sweep tests as before: doorhandle 13, drill 208 steps, bodyparity.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:41:05 +02:00
superGeometry 08803ba552 The left column on a phone on its side: the right column's tighter frame there too (54 wide, as it is).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:32:00 +02:00
superGeometry 6b1b01fc91 The column at the left edge is the size of the one at the right (asked for: "make the isolate, measure, section box the same wide size as the fit, shaded, units box"). Its buttons are the right column's own now (they were 8 px wider and a little taller), at every size of screen. Measured at desktop, 390 x 800, 800 x 390 and 768 x 1024: the same width, the same buttons, no name clipped.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:31:38 +02:00
superGeometry 1e97d848bf Isolate, Measure and Section are always on screen, at the middle of the left edge (asked for: "I want isolate, measure and section buttons to always be on screen because they are frequently used and I find myself clicking More way too much ... put them on middle left (like the middle right fit, shaded and settings)").
- A column of three at the left edge, the twin of the one at the right: each its picture over its name, lit while it is on, a tap switching it off again. Isolate with nothing picked says what to pick. It moves over with undo / redo when Items is open; on a phone on its side it stands beside the Items card, and steps aside while a list from the line is up.
- More no longer has them (Variables and Print / Share are left there).
- Help says where they are.
Tried in the app: Isolate with nothing picked (told what to pick), with a body picked (on, lit, off again); Measure on and off; Section on. Its place checked against undo / redo, Items, the line, the guide text, the top bar and the right column at 320 x 640, 390 x 800, 800 x 390, 932 x 430, 768 x 1024, 1024 x 768 and desktop: over none of them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:25:15 +02:00
superGeometry d666e27dc8 A spline's points can leave the sketch's plane (asked for: "if I select a point of a spline line, and the move gimbal appears, I want to be able to move that point in 3 dimensions, not just 2").
- Each point of a spline has a height off the plane (z, one for each point; none: flat as before). The curve runs through those heights by the same rule as through their places, so it is as smooth up and down as it is across.
- Tap a spline, then one of its points: the pick is that point (it was the curve with the point), and the gimbal has its third arrow, off the plane. Dragged, the point goes up or down with it, in grid steps (Shift: free); the label says how far off the plane. Several points of a spline picked go together. The two in-plane arrows slide it as before, the gimbal staying up where the point is. Its card has Height, typed; several points: Flat on the plane. Seen straight on the arrow points at the eye, so the guide says to turn the view.
- Drawn, picked and its points tapped where it is in space, in the sketch and out of it.
- A sweep's path, a loft's guide or rail made of it follows it through space.
- In the plane it is its shadow: the shapes it closes, constraints, snapping, DXF and SVG. Moved, turned or mirrored in the sketch it keeps its heights; scaled, they scale; run the other way, they turn with it. A curve that follows a body's edge has no third arrow.
- Not done: a spline split or trimmed comes out flat.
- While at it: a point dragged a round number by the gimbal ended a hundred-thousandth short (39.99999 for 40): the pull that keeps a drag near where it began is a tenth of what it was.
tests/spline3d.test.ts, 13 checks: heights in step with the drawn curve and through its points; kept when moved, scaled by a scale, left by the solver; a round rod swept along a flat spline is a straight rod, along one lifted 30 it rises 30, is sound, and is as long as the curve through space. In the app: the third arrow dragged up 20 and down 15, undone and redone; Height typed; the lifted point tapped where it is drawn; the in-plane arrow with the gimbal staying up; two points together; no third arrow for a line's end or a mixed pick.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:22:13 +02:00
superGeometry d0b39abbc0 The grid is what a sketch snaps to; Lock grid size takes the size shown; grey lines in Settings, File and More; Export SVG (sketch); a list on the line is the size of its buttons (asked for: "when I want to draw vertical lines, it doesn't snap to grid. Take a look at this whole system ... I want the lock grid size toggle to adjust to whatever the zoom level is ... a grey horizontal line between Settings and Units & grid ... also in File and More. In File, add the option to export SVG (sketch) ... the cascading window ... autoadjustable based on how many buttons are in that window. Right now it opens and it has empty space").
- Grid and snap. The grid's squares were powers of ten only, 10 to 100 px wide, and a sketch snapped to a finer lattice nothing showed (1 mm, with lines drawn every 10): a line's end "did not snap to the grid" - it had, to one that was not drawn. The squares are 1, 5 or 10 (times a power of ten) now, the smallest at least 10 px wide, with a stronger line every ten, and the snap goes to exactly those squares. Tried: a line upright from a point, level from it, and free, at two zooms - each end on a crossing of the lines shown.
- Lock grid size, switched on, keeps the squares as they are at this zoom (it kept a size typed earlier). Its row says the size it would take ("now 5 mm"), in the project's unit.
- A grey line under a list's own name at the right edge (Settings, apart from Units & grid, Snapping, Number pad, Appearance; Display the same), as there is over each part's heading. File: a line between the project, the 3D exports and the sketch exports. More: between the view, help and about. All the same grey.
- File > Export SVG (sketch), beside Export DXF: millimetres, the page just round the drawing; lines, circles and arcs exact, ellipses and splines fine polylines; construction curves in a group of their own, dashed. Its share button where the browser shares SVG. tests/svgexport.test.ts: written and read back in, as wide, as tall and as long a line (6 checks).
- A list opened from the line: its buttons in even rows, each as wide as the widest, a short last row's buttons wider, the list just as wide as its rows. (It was 420 wide for any number of buttons: 30 to 200 px empty at the end of each row.) Measured with every list open at 320 x 640, 390 x 800, 430 x 932, 800 x 390, 768 x 1024, 1366 x 1024 and desktop, in the model and in a sketch: no row ends in a gap, no word clipped, none off the screen or over undo / redo.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 11:12:38 +02:00
superGeometry 6e30ce44e0 Variables, gone through while building a pipe flange that every size of is a variable: what did not work, mended (asked for: "go into variables and do the same thing while building something complex that makes sense to have variables").
The flange, built by hand in the app: ten variables (outer size, bore, thickness, hub wall, the hub's size worked out from bore and wall, hub height, how many bolt holes, their size, the bolt circle worked out from the others, the chamfer); a disc, a hub on its top face, a bore through both, a bolt hole placed by a variable, patterned by a variable and cut, a chamfer. Its volume is the formula's to the hundredth of a cubic millimetre, and stays so through every change of every variable.
What that found:
- A variable's name typed into a size on the line was made the number it came to, and the link never kept. And a size that followed a variable, opened and closed again, was cut loose from it. (The line is the only way to type a size since it became the only UI.) Now the formula is kept; a size that follows one says so ("od / 2 = 60 mm"), its box opens on the formula, closed unchanged it does nothing, and it is not dragged sideways (a finger sliding off it would cut it loose). The box has ƒx: one of the project's variables, or a new one from what is typed. What can't be read is said, with the name no variable has.
- The project's unit changed, every plain number in a formula was read in the new one: a flange 160 mm across was 160 inches. Nothing changes size now: each formula that would is given the unit its plain lengths were typed in ("160 mm", "od / 2 + 5 mm"); a count, a factor and an angle are left as they are. And the unit is the project's own before its formulas are read (it was set after, so the model was a step behind).
- A chain of variables stopped at eight deep: the ninth "couldn't be evaluated". Any depth now; one that uses itself, round any number of others, is refused. Each is worked out once (a variable used twice by each of thirty built on one another was a thousand million readings).
- More to write formulas with: floor, ceil, round (how many fit: floor(length / pitch)), min and max of several, asin, acos, atan.
- New Variable: a value refused closed the window with what was typed gone - it stays to put right. A name that differs from another only in its capitals is refused. A name no variable has is named. An angle (30 deg) is taken, as it was in the list. One made again by the same name says it changed. Deleting: capitals count (W gone is not w gone); another variable that still uses it is named; a point placed by it keeps its place.
- A variable with no place of its own had no tag in the view: a point placed by one, the count of a ring of holes cut into the body, one that only other variables are made from. All ten of the flange's have one.
Not done, found on the way: a pattern started from a hole's face copies the whole body (holes by the count of a variable are a pin, patterned, then cut - as here); a sketch pattern's count is a plain number.
In the app: the ten variables made in the window one after another; names refused (sin, max, m, 2x), a value that uses itself, an unknown name, a formula cut short, a number too big; the flange built step by step with each size typed as its variable; nine changes of variables in the list of them all, each volume the formula's; 0, 1 and 2.6 holes, a bore bigger than the flange, a thickness below zero, each put back; undo and redo; inches, centimetres and back; a size changed from its tag in the view; a pattern's count edited to n + 2; the typing box at phone width.
Tests: variablesflange 22 (the hand-built project: its variables changed alone, together, to formulas, to awkward values and back, and through three units); unitchange 22; units 55 (27 new); vartags 20; the rest as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 10:52:17 +02:00
superGeometry e7cade47ce Sketch constraints, gone through one by one: what did not hold, mended (asked for: "go deep into the sketch constraints. Verify everything works perfect and the system is properly built").
A new test puts every constraint on every kind of curve it is offered for (line, arc, circle, ellipse, part of an ellipse, rectangle, polygon, spline, polyline; 15,178 cases) and measures from the curves themselves whether it is then true. 2,678 were not, or were refused though nothing stood in their way. All hold now.
The solver:
- Its steps were damped by each parameter's own share. A sketch with room to spare - most are - then stepped furthest in the direction that helped least: a line given a length drew its ends together sideways until it stood upright, and stopped, the length not met. Damped the same in every direction: the step is the shortest one that does it.
- A point put on a rectangle's side, a polygon's, a polyline's, a spline's or an ellipse was taken and did nothing (its measure was always 0). Each is measured now: an ellipse by its own equation, the others from the nearest place on them.
- Tangent was offered for a circle with anything - a rectangle, a spline, an ellipse - and taken, and did nothing. Offered for what it can do: a circle or an arc with a line or another of them, and (new) a line with an ellipse. Two circles: measured with its sign, so the last of the way is not crept.
- A shape with a size of its own (rectangle, ellipse, polygon, arc) keeps it sooner than its place: a rectangle whose corner was put on a point 60 away came out 0.00001 tall. (Not while dragged: a corner pulled is still the shape pulled about.)
- A line asked to lie a way it is far from (Vertical on one nearly level, an angle 130 degrees off, Perpendicular to one it is nearly parallel to) is turned there about its middle first, its length kept. Left to the steps it got there by shrinking; one given a far angle ended a speck.
- A dragged point lags the pointer a third as much on a long jump.
The buttons:
- Horizontal / Vertical for two points (a centre and a corner, two ends): the solver had it, no button gave it.
- Unlock on a circle takes off the size Lock put on it (it was left behind, and the circle kept its size).
- Refused with no lock anywhere, it no longer says locked points stop it.
- A constraint picked is named with a capital ("Distance dimension").
In the app, each by its own button on the line: Horizontal, Vertical (a line; two points), Parallel, Perpendicular, Equal (lines; circles), Tangent (line and circle, two circles, line and ellipse; not offered for circle with rectangle or ellipse), Concentric, Coincident (two points; a point on a circle, a rectangle, an ellipse), Midpoint, Symmetry, Lock and Unlock (a point, a circle, a rectangle) - each true once on, lit, its mark shown, and off again. Sizes typed: a line's length and angle (120 and -45 from 7.6, length kept), a circle's diameter, a rectangle's width and height, the angle between two lines, the distance between two points and from a point to a line. An L-shaped outline drawn with Line (its joins and H/V made as drawn), four lengths typed, the fifth refused when it contradicts and taken when it agrees; a corner locked: all six lines defined, and a drag moves nothing; two lengths off: a corner dragged changes only those, the outline square and closed. A dimension picked by its mark and deleted, undone, redone.
Tests: constraintmatrix 15,178 of 15,178; constraints 15; constraintbreak 218 steps, 0 broke (drag frames that could not follow 11 -> 3); dragspeed, cornerdrag, hvconflict, sketchtools, sketchdefined, sketchpattern, links, alignmove, ellipsearc, phonestand, projectfuzz, projectlean as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 10:29:43 +02:00
superGeometry 2d89322a97 A sketch's shape clicked in the model shows its tools at the first click (asked for: "it only shows the yellow arrow for extrude ... I want them to appear from the first click").
- A shape tapped went straight into Extrude at 0: the arrow alone, its tools only after tapping again. It is picked now, like anything else: the arrow to drag, and Extrude, Revolve, Delete and More (every other tool) beside it. Extrude is the first of them (it was Sketch).
- Extrude still starts by dragging the arrow or the shape itself, or by typing a size.
Tried in the app: a rectangle drawn and left; nothing picked, the shape clicked once (picked, arrow, the four buttons); the shape dragged (Extrude, 10.5).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 10:04:56 +02:00
superGeometry 6318ec47b5 Sketch: a closed shape tapped offers what to make of it; switches that are off are not greyed (asked for: "after I closed a shape in sketch mode and I click on that blue surface, I want the options to appear (like extrude, revolve etc.)" and "in sketch mode, the option buttons on the bottom bar are greyed out. I don't want that").
- A shape tapped in an open sketch had only its arrow. Beside it now: Extrude, Revolve, Sweep, Loft. Each leaves the sketch and starts on the shapes picked (several tapped: all of them). The arrow is still dragged as before; the guide says both.
- A switch on the line that is off (Lock, Construction, and every tool's own) was dimmed and struck through, and read as a button that could not be used. Off, it is a plain button; on, it is lit.
Tried in the app: a rectangle closed, its shape tapped, each of the four buttons pressed (ExtrudeOp, RevolveOp, SweepOp, LoftOp started, the shape picked, the buttons gone); at 390 wide the four sit under the shape, clear of the line and the guide.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 09:59:19 +02:00
superGeometry 96650a1652 Drawings: item numbers are moved, a note's letters are sized (asked for: "I should be able to move the number tag in the isometric view. And adjust the note text size. Make sure everything works. Every button / tool").
- An item number (the circle on the isometric view) is dragged where it reads well; its line still runs to its part. Picked, the bar says so, the arrows nudge it, and Put back - or Delete - returns it to where the sheet puts it. Kept by the part it numbers (balloonAt), so it stays through changes to the parts list.
- A note picked has A- and A+: its letters a step smaller or bigger (2.5, 3.5, 5, 7, 10, 14 mm on the paper), with the size said between them. A note that points at an edge keeps its leader at the text's height. Kept on the note (size), and through its view being taken off.
- Help has an entry for Drawings.
Every tool and button of the workspace gone through on a plate with a hole and a rounded corner, each by its own button and real presses on the sheet, with no error: the ten dimension tools and the four centreline tools (each put one on); Note on the paper and on an edge; an item number dragged, nudged and put back; a note sized up twice, down once, and dragged; Front, Top, Side and Isometric off and on; Hidden lines; Section, Detail, Projected and Base views; a view moved by its handle and Put views back; Overall sizes off and on; Arrange (13 dimensions); a dimension's Distance typed, Text and tolerance, Delete, undo and redo; zoom in, out and all of the sheet; all fourteen lists in Properties changed and set back; Balloons off and on; the drawing number typed (it is on the sheet); Portrait and Landscape; a drawing copied, a new one made, each deleted. Not pressed: Image (the device's file chooser), Print / PDF, SVG and DXF (they save files).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 02:12:35 +02:00
superGeometry 95bd548aaa Drawings: easier to work in (asked for: "I find it hard to use and not intuitive at all ... make the annotations move if I click on them after placement"). Nothing taken out.
- A dimension, a note or a picture already on the sheet moves when it is dragged with a tool still on (the tool stays on; a plain tap there is still the tool's). A dimension put on, the next thing a hand does is drag it where it reads well: that put on another, or did nothing, until the tool was put down.
- Its number or its words are what it is grabbed by: a see-through pad round each text, a finger wide on the screen (a dimension's number is a few pixels tall with the whole sheet in view).
- It stays on the paper: dragged past the edge it stops there (one pulled off the sheet was out of the print).
- With no tool on, what can be dragged lights up under the pointer.
- The arrows nudge what is picked: half a millimetre on the paper, Shift five. A note or a picture any way; a dimension nearer to or further from what it measures.
- Nothing picked and no tool on, the bar at the top says what can be done (drag a dimension or a note, tap a view for its handle, double-tap text to edit, the tools are on the left). It was empty, and the sheet read as a picture.
- A phone: a group of tools open (Views, Dimensions, Centrelines), the strip comes out over the sheet with every tool's name beside its picture - ten dimension tools were ten pictures, two pairs of them alike. A tool picked, it folds away and the sheet is clear to tap.
Tried on a box's drawing: its overall sizes dragged with no tool and with Line Length on (no new dimension made), one dragged at the top edge (it stops on the paper), a note put on and dragged with Note still on, a dimension nudged with the arrows; at 390 wide the named list and its folding.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 01:58:19 +02:00
superGeometry 3fa975596d Settings and Display: a grey line between their parts (asked for: "separate categories with grey lines. For example Units from Grid and Degree. Or Snap to from Show. Or in Shaded"). Over each heading but the first in the lists at the right edge, and under the way back to Settings.
The line, the buttons at the edges, the tag, the guide text and the buttons beside a pick checked for overlap, for parts off the screen and for words under 30 px, in nine states (nothing, a face, an edge and a body picked, Extrude, Fillet, a sketch with no tool, with Circle, with Pattern) at 320 x 640, 390 x 800, 430 x 932, 800 x 390, 932 x 430, 768 x 1024, 1024 x 768, 1024 x 1366, 1366 x 1024 and desktop width: none.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 01:51:14 +02:00
superGeometry 4cbd0d044e Freeform: what was missing.
- Sharp edges. Edges picked are made sharp (Sharp edge; one edge: Sharp loop, the whole loop it is part of): the surface keeps a crease along them instead of rounding over - followed as an open border is, a corner where three or more meet, fading out where one ends in the middle. Smooth edge takes it off. Shown orange on the cage. Kept in the cage (cage.creases), so in the step, its edits, copies and moves; the editor's quick weights and the solid are made by the same rules (a box with every edge sharp is that box: 24,000 for 40 x 30 x 20). Tools that change the cage carry them: a loop cut across one leaves its two halves sharp, taken out again it is one; Add detail halves each; faces deleted keep what is still an edge.
- Remove edge loop: the loop an edge is part of taken out, the faces either side of it made one (it could only ever be added).
- A picked face is pushed or pulled by dragging the face itself, along its normal (several: their average) - as everything else on the model is dragged.
- Place at, beside Move / Turn / Scale: the picked points put where their middle is at the X, Y, Z typed (there were only distances to move by).
- Soft: a distance round the picked points within which the others follow a move, less the further off (1 beside, 0 at that distance) - a bump, not a spike. By the gimbal, by typed values, by a face dragged and by Place at; with Symmetry, mirrored too.
tests/creases.test.ts: 18 checks. In the app: a face dragged (1.9 out), points placed at Z 60 and X 5, one point raised 10 with Soft 25 (13 others followed, up to 5.1), a loop added and removed (56 points, 68, 56), an edge and a loop made sharp, undone and redone, saved and opened again still sharp; each finished as a closed solid. The other freeform tests as before: freeform 15, freeformedit 29, freeformtools 40, faceff 26, faceffmulti 7, hoseconnector 14, connect 107.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 01:39:04 +02:00
superGeometry 953d939180 Freeform, gone through function by function with real taps: what did not work, mended.
- Symmetry across X / Y / Z went through the middle of the shape's points, not of its size: with more detail on one side (a face inset, a face pulled out) the mirror sat off-centre (1.3 and 2.7 off on a 40 box with one inset) and no point had a partner. Through the middle of its size: a point moved +4 has its mirror moved -4.
- Fill hole and Bridge holes took every edge of the rim picked, which nothing said; one edge of a hole tapped offered only Add edge loop. One edge is enough: the hole is the whole rim it is on. (Not a sheet's own outline - that is most of its points, and filling it would lay a face over the whole sheet; with every edge picked it is taken as before.) Connect edges is still offered beside them.
- Inset is typed in percent, as it is shown: typed as 40 it was taken as a fraction and jumped to 90 %, the most there is.
- A slider's value on the line goes in its own steps, typed or dragged: Steps and Faces are whole numbers (3.4 was kept as 3.4).
- Extrude face's Length and Bridge's Arch are lengths like any other, typed in the unit in use (they were typed in millimetres whatever the unit, and stopped at ten times the face's size).
- Pick in a box (touch screens): its switch on the line shows how it is set; it was read once and stayed as it was.
- A shape finished open with no thickness says so as it is made - a surface, and the ways to make it solid.
- A phone held upright: Freeform's line is not folded into Options - its tools (Extrude face, Inset, Delete) and all of X, Y, Z stay on it.
Checked in the app, each by its own word on the line: the five starting shapes with their sizes and rows; faces, edges and points tapped; move, turn and scale by typed values and by the gimbal; undo and redo; Extrude face (Length, Bend, Taper, Steps); Inset; Delete face; Fill hole; Bridge faces (a handle, Arch and Segments); Bridge holes (a tunnel); Add edge loop; Add detail; Select all; a box drawn round points; Symmetry; a surface on a plane with Extend surface, Connect edges and Thickness up, down and both; Done (closed and solid each time); Edit Freeform and Cancel; Fill hole from the model; Freeform Face with its four grids. Tests: freeform 15, freeformedit 29, freeformtools 40, connect 107, faceff 26, faceffmulti 7, hoseconnector 14, freeformscale 634 - none failing; freeformmix 437 passed before its time ran out.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 01:23:17 +02:00
superGeometry ac570d06c7 Beside a pick: one more tool is a button of the row, not a More that opens a single button (asked for: "if I select a vertex and I press More, there is only one button, Move. No need for More"). A corner: Move Vertex, Move/Rotate Body, Delete Vertex; a plane: Sketch, Plane - Offset, Split Body. A pick with two or more others keeps More.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:56:58 +02:00
superGeometry 3ed4fb89e9 Shell is under More beside a pick, and Help, About and the guide text say what the app does now.
- Beside a pick: a flat face Sketch and Move, a round one Thread and Fillet, a body Fillet and Mirror - then Delete and More. Shell is in More (asked for).
- Help: the line's groups as lists (the pick's tools, then the others), More holding only what is not on the line, Options on a phone, lists that stay up while the view moves, the looks ahead in dashed yellow, the right edge (Fit, Display, Settings) and what is in Settings, Print / Share and Picture, a tap picking one thing and + adding, Whole body, the pick dragged by itself, the gimbal's middle dot as the pivot, patterns dragged and shown along what is pointed at, Shell's arrow, Offset Edge on a body's edge with Edge / Chain and its double arrow, Project's arcs, a sketch starting on Line and the ways of a tool on the line, picking in a sketch (a box takes what it touches, a double tap faces the sketch). "Tool cards" is "A tool's settings": they are the words on the line.
- The README, which About shows: the first part starts from the sketch a new project opens in and ends in Print / Share; the screen piece by piece has the lists, More, Options, the looks ahead, the buttons beside a pick, the right edge and a tool's settings as they are; "the card" for a tool's values is "the line".
- Guide text: Text in a sketch says to type on the line (it said the card).
Looked at in the app: the rows beside a flat face and a body, Shell in their More; Help opens with 55 entries, none without its picture; About shows the new text.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:54:12 +02:00
superGeometry 39865e7a19 The buttons beside a pick: Delete, and every other tool it has (asked for: "when I select an element on a body and the icons with the relevant tools appear, I also want to have other tools there that could be used on that element. And also delete").
- The row is the pick's likeliest tools as before (a flat face: Sketch, Shell, Move), then Delete (red-edged), then More.
- More opens the rest of what the pick offers in rows of four under the row - a face twenty more, an edge ten, a body ten, a corner one - and shuts them again. Nothing is added to the row itself, so it stays as short as it was.
- In a sketch the buttons beside picked curves are unchanged.
Seen on a block with a hole: a flat face, a round face, an edge, a corner and the body, and the list opened on the flat face.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:49:47 +02:00
superGeometry fbcf3d977f More is a list like the others on the line: a card over its button, as big as what is in it (asked for: "the More window doesn't have to be this big for only a few buttons. Make it like the other windows from that bottom bar"). It was the whole line's width, laid out in columns, for six buttons.
Seen at desktop width (220 wide, over the grid button at the line's end) and at 390 wide (the line's width as every list is there, two rows).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:46:06 +02:00
superGeometry 768c6964fc The tool wheel is taken out, and More holds only what is not on the line.
- The wheel (src/ui/wheel.ts, 2,047 lines; toolInfo.ts, 155, which only it read) was never shown since the line at the bottom took over, and still shipped. Gone, with every call into it: the select tool's wheel taps, hold and Q, the sketch's, freeform's and section's covers, the two wheel handles on the app and in the debug handle, the right column's lists as wheel cells and as windows of their own, the "wheel" setting, the wheel wording in the guide text nothing reached. The three tables the line used from it (which group a pick's tool goes in, the order within a group, the names a pick's tool goes under) are in ui/toolGroups.ts.
- Styles only it used: 87 rules and two animations (13 KB of the stylesheet's 167).
- Seven exports nothing used, tests included: canConnect, EntityKind, previewMesh, editImage, startOf, planeFromNormal, buttonEnabled.
- More (the grid at the line's end): only what is not a word on the line already - with nothing picked Insert, BIM, Section View, Measure, Variables, Print / Share; with a pick its own (Delete, Color...) and the view's; in a sketch Construction and Normal to Sketch (asked for: "in More there should only be tools that are not already in the bar. Same in other tools that have More"). It repeated every group. The list of what "needs another pick" is gone from it: each group now holds those tools itself.
The build: script 1,976 to 1,921 kB, styles 110 to 102 kB. Checked: sg.sweep - 182 tools started from every kind of pick, every option tried, none dead, no errors; five test files.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:44:12 +02:00
superGeometry 2efe1a83ef A phone's lists: scrolled from anywhere, and their pictures a size down (from use on a phone: "you made the icons too big ... also I can scroll down in the windows only if I tap and hold on the space between buttons").
- A list scrolls under a finger wherever it is put down, on its buttons too. A word on the line keeps its touches from moving up and down (it slides the line sideways); in a list that left only the gaps between the buttons to scroll by.
- A list's buttons: picture 22 (from 28), name 13.5 (from 14.5), cell 64 tall (from 74).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:15:05 +02:00
superGeometry 8259fc913f From building a part by hand on a phone (a block, a hole cut in its top, an edge rounded, a face pulled, a pattern started), every tap a real touch: what got in the way, mended.
- A sketch on a face, left after closing a shape: the face around the shape was picked, not the shape (the sketch's curves hold the face's outline too, and the last shape of them all is the face less what was drawn). The shape drawn is picked.
- Extrude open (a tap on a shape opens it on a phone): dragging the shape or face itself pulls it, as it does before the tool is open. It turned the view.
- The line at the bottom says the number as it is dragged. It read it once, as the tool opened: pulled to -22, it still said -5.
- A value box stays above what is along the bottom - the line, and on a phone undo and the guide text. Pulled down into a cut, it sat on the guide text.
- A phone held upright: a tool says its size and what it still needs tapped; everything else is one word, Options (Extrude's line was seven things over two rows, Fillet put three choices before its radius). A tool with one option beside its size keeps it on the line.
- One face, edge or corner picked: "Whole body" beside its name picks the body (a double tap on the model does too - nothing said so).
- A phone's passing notes come up under the top bar: along the bottom they lay on the guide text.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 23:05:16 +02:00
superGeometry 58ce95a443 Ten points from use (the numbers are the list's).
1. The "Next" suggestions after a step are gone: in the way, and at odds with the guide text.
2. A new sketch starts with Line on (it did, except a new project's, which started on Rectangle).
3. Drag arrows are slimmer and shorter (64 on screen, from 84; a 3 px shaft with a dark edge under it so it reads over a lit face and the grid; a head the same size whatever the arrow's length). A double arrow - Offset in a sketch, Offset Edge on the model - is two short ones back to back: 68 across, from 168.
4. Move: the dot in the middle of the gimbal is dragged to move the point everything turns about - onto a corner, an edge or a face (it snaps, and says which), or anywhere. The body stays where it is. (It moved the body across the screen; the body itself is dragged for that now.)
5. In a sketch seen at a slant, a double tap on something drawn turns the view to face the sketch.
6. A box drawn in a sketch picks every curve it touches, not only those wholly inside it.
7. A pattern with no direction yet: pointing at an axis, an edge or a face shows the row of copies along it in dashed yellow; a circular one, the ring round the axis pointed at.
8. No line from the pick to its name: the name, with its +, says what is picked.
9. Looks ahead: the pointer over a tool draws what it would do to the pick, in dashed yellow on the model, before anything starts - a face's outline lifted (Extrude, Offset Face) or sunk (Shell), a sketch's shape lifted, the lines a Fillet or Chamfer runs between on a straight edge, a row or a ring of boxes for a pattern. Drawn from what the view already has (tools/ghost.ts), so it is there at once. Tools with no telling picture show none; a finger has no hover.
10. With something picked, a group's list holds the pick's own tools and, under them in a quieter part, the group's other tools (each asks for its own pick as it starts) - every tool is there, and a group is dimmed only when it has none at all.
Tried in the app: each of the ten (new project on Line; a box crossing a rectangle's side and a circle picks both; the view from three-quarter to straight on; the centre dot onto a corner with the body unmoved; dashed copies along X then Y; hover on Pattern - Linear in the open list; Modify with a face picked: six of its own, four others).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 22:43:57 +02:00
superGeometry c61e3f0734 A phone's lists: bigger buttons, centred (from use on a phone: "those icons are so small and so is the text. Also it's not centred on its button").
- A list's tools on a phone are a big picture (28, from 18) over its name (14.5, from 13.5), both in the middle of the cell, three to a row; a long name runs to a second line. They were a small picture and small text at the cell's left edge. The mark for "more under this" sits in the cell's corner.
- A list that is a card over its word (a phone on its side, a tablet, a computer) sits with its middle on the word's middle, as far as the line's ends allow - reckoned from its own width as drawn. The stylesheet guessed its width, which left a wide list off to one side.
Checked at 390 x 800 and 320 x 640 (31 lists each: nothing over undo or the right-edge buttons, no name cut off), 800 x 390 (30), and the centring of each group's list at 800, 768 and desktop width (0 off its word where there is room, at the line's end where there is not).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 21:50:10 +02:00
superGeometry d3c5146220 The line's layout is decided only from the room it is given and the words it holds (reported: "the bottom bar UI is glitching out on my iPad M2 13 inch"; not seen here - see below).
How the line is drawn - closed up or not, its names big or small, how far it stays from the buttons at the right edge - was partly read back from the line as drawn: its own width, its own height. Each of those choices changes that size, so one browser's rounding can make a choice undo itself on the next layout, again and again (it did on a phone 390 wide, in a sketch, before). Now:
- Closed up for a room and a set of words, it stays closed up until one of the two changes.
- Big or small names go by the room, not by the line's width as drawn.
- Whether the right-edge buttons reach down to the line goes by the line's tallest height, not its height now.
Not reproduced: at 1024 x 1366 and 1366 x 1024 (the 13 inch iPad both ways), with Items and History open and shut, in nine states each, and with the text made narrower and wider in 45 steps to stand in for another font, the line did not change once after settling - before this change or after. What is drawn at each size is the same as before (compared state by state at 390, 1024, 1366 and desktop width).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 20:47:43 +02:00
superGeometry c6b35b30e8 On a phone an open list covers nothing, and looks like a part of the line (from use on a phone: "the cascading level 2 on the bottom bar goes over the undo, redo buttons and it's not clean like the tool's window ... the buttons and windows should not overlap and be always at reach").
- A phone held upright: the list is as wide as the line and sits right on it, its tools in two even columns of cells (they were ragged chips in a card narrower than the line, off to one side), in the line's own colours.
- Undo and redo move up over the list for as long as it is up (they were under it), and back as it shuts. The tag and the guide text step aside while a list is up: it is what is being read.
- The list is never taller than leaves the buttons at the right edge clear above it; it scrolls instead. On a screen too short for both (a small phone with a tool's two lines) those buttons step aside while it is up.
- Either way up, the guide text is no longer under a list (More, with something picked, in landscape).
Checked by a script that opens every list of the line - with nothing, a face, an edge and a body picked, in Extrude, in a sketch with and without a tool, one level down where there is one, and More - and measures each against undo, the tag, the guide text and the right-edge buttons, and for cut-off names: 39 lists at 390 x 800 and 320 x 640, 38 at 800 x 390, 768 x 1024 and desktop width, nothing overlapping.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 20:32:55 +02:00
superGeometry 58b8bbe8c3 Direct touch is the only way: its switch in More is gone (asked for: "make direct touch the only UI and remove that button from More"). On for everyone, also where it was saved as off. Help and the README no longer mention switching it off.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 20:20:46 +02:00
superGeometry 839c6538f5 Patterns are dragged where the copies are.
- Pattern - Linear: once it has a direction, an arrow sits on the first copy, the spacing in a box beside it. Dragged, it sets how far apart the copies are (through the body to the other side: a negative spacing); a value typed while it is held, or in the box, sets it; Enter finishes.
- Pattern - Circular: once it has an axis, a dot sits on the last copy, the angle in a box beside it. Dragged round the axis it sets the angle the copies are spread over, by 5 degrees (Shift: freely); nearly all the way round is a full turn, shared out evenly as before.
- Their guide text says what to tap first, then what to drag. Count stays a number on the line.
Tried on a box: Linear along an edge, the arrow dragged from 32 to 35.6, done (3 bodies); Circular about Z, the dot dragged from 360 to 120, done (6 bodies over 120 degrees).
(Thread is left as it is: its one size is the pitch, picked from the standard for its diameter - nothing on the model to pull.)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 20:16:40 +02:00
superGeometry eb4cff5eeb A list opened from the line stays up while the view is moved, and its button on the line shows it is open (asked for: "transform > pattern > linear, I want to be able to navigate in the workspace without exiting that if I rotate the camera ... make it stay in place until I select something. Also if a level 1 button on the bottom bar is selected, indicate that").
- Any press on the view put the list away, a drag that turns the view too. Now a drag, a pan, a pinch or the wheel on the view leaves it up; it goes when something in it is chosen, when the model is tapped (a pick, or letting go), on a press elsewhere, or Esc. (A number being typed still ends at any press.)
- The word on the line the list came from - Transform, with Pattern's list open under it too - is lit, with a bar under it and its arrow turned, for as long as the list is up.
- A list under another says where it is: "Transform › Pattern".
Tried with nothing picked: Transform (lit), Pattern ("Transform › Pattern": Linear, Circular), the view turned with a finger and with the right button (the list still up, Transform still lit), Linear ("Pattern - Linear: tap the model", which stays through turning as before); a tap on the model puts a list away.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 20:07:46 +02:00
superGeometry bb622f4866 The right-hand column holds what is used while modelling; the rest is one Settings button.
It had nine buttons of three kinds mixed together. Now: Fit, Display (shaded / wireframe / X-ray), Settings - and Constraints in a sketch.
- Settings (the gear, which shows the unit in use): a row each for Units & grid, Snapping, the number pad and Appearance, each saying how it is set now ("mm", "4 of 5 on", "Orthographic"). A tap opens its list, with a way back; the number pad is switched right there.
- Screenshot is Picture in Print / Share (which opens with no body too: a sketch can be pictured). History keeps its button in the top bar; Views stay on the view cube.
- The lists are still kept by id for the parts of the app that open them. Help says where each is.
Tried at desktop width and 390 wide, in the model and in a sketch: the three buttons (four in a sketch), Settings > Units > Centimeter (the gear says cm, the row says cm) and back, Snapping's list, the four files in Print / Share.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:52:40 +02:00
superGeometry 4bfee451e2 The first minute makes something.
- A new project opens in a sketch on the floor with Rectangle on: two taps are a shape. (Other plane and Exit are on the line for anything else; a project opened from the library or a file is as it was.)
- Leaving a sketch right after closing a shape, seen straight on as it was drawn: the view swings round to three-quarter (a floor sketch; any other plane: from a little to its side and above), so the pull that comes next can be seen rising. The shape is picked, and with direct touch it is dragged by itself.
Walked through with a finger's events on a clean start: New project (sketch, Rectangle, Diagonal lit), two taps ("Shape closed. Tap Exit"), Exit (the shape picked, the view at three-quarter), the shape dragged up (Extrude, 11.5), Done: one body, and Next offers Round its edges, Hollow it, Print / Share. Five touches from nothing to a solid.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:46:06 +02:00
superGeometry c8de25789d Direct touch: the pointer is a grabbing hand over what is picked and can be dragged by itself (one pick per hover, as before; a second only where a sketch lies over the pick).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:43:58 +02:00
superGeometry 1a82d65802 Direct touch: what is picked is dragged by itself, not only by its small arrow or dot.
- A picked face, pressed anywhere on it and dragged, is pushed or pulled; a sketch's shape is pulled up into a solid; an edge is rounded (pulled in past the edge: a chamfer); a body slides over the floor (seen from the side: across the screen). The same tools as their arrow, dot and gimbal start, with the value at the pointer and typed while held.
- A finger or pen pressed and held still on a face, a shape or an edge picks it, with a buzz, and the same touch goes on to pull it; lifted without moving, it stays picked. (The hold was the menu there; it still is on everything else.)
- A drag that starts anywhere else turns the view (a finger) or draws a box (a mouse), as before. A face with a sketch lying on it is still the face under the press.
- More > Direct touch switches it off (On by default). The guide text, Help and the README say how.
Tried on a box 40 x 30 x 20 with real pointer events: a picked face dragged with the mouse (Extrude, 4), an edge (Fillet, 2.2), the body (Move, 5 / 0.5 / 0); not picked: nothing; switched off in More: nothing; a finger held on the top, pulled and Done (one step).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:35:21 +02:00
superGeometry a81d22f143 Sketch: the ways a tool can be used are on the line the moment it is on (asked for: "when I click on circle it selects the centre circle but I have to go back to Draw > Circle to select 2 points or 3 points. I should be able to select that from the first interaction").
- A drawing tool that has more than one way (Circle: Center, 2 Points, 3 Points; Arc, Rectangle, Spline, Trim, Fillet / Chamfer, Pattern) puts them on the line right after Stop, the one in use lit: a tap switches, with the tool still on.
- Where the line is too narrow to give each a finger's width (a phone held upright), or there are more than three (Polygon's shapes): one lit word, named for the tool and the way in use ("Circle: Center"), that opens them.
- In the model the same already holds: a tool's ways are in its own words on the line once it is on, and Plane, the one tool with kinds to choose before it starts, opens them at the first tap.
Tried in a sketch at desktop width (each of the nine tools, 2 Points tapped: lit, "Tap two points on opposite sides of the circle") and at 390 wide (six words of 46, the word tapped, 2 Points taken from its list).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:25:04 +02:00
superGeometry 0b9287cbeb Shell and Offset Edge are dragged, like Extrude and Fillet.
- Shell: an arrow at the inner side of the wall on the open face tapped last, pointing into the body. Dragged in, the wall gets thicker (never less than a step); a value typed while it is held sets it, Enter finishes. The box that was there shows the same value.
- Offset Edge (on the model): a double arrow on the middle of the new line, the distance in a box beside it. Dragged, it sets how far from the edge the line runs, through the edge to its other side too; dragged off the face it stays where it was, to drag back. The box takes a typed distance, Enter finishes.
- Their guide text says so.
Tried on a box 40 x 30 x 20: Shell on the top, arrow dragged from 1 to 3.5; Offset Edge of a top edge on the top face, dragged from 4 to 18, done (one sketch step). sg.sweep on a face: 29 tools started, every option tried, nothing dead, no errors; Shell now reports handle and box.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:17:14 +02:00
superGeometry 093046340f Sketch: part of an ellipse is a curve of its own, and that is what a round edge seen at a slant projects to.
A projected curved edge was a spline through 24 points with only its ends shown; now, where the edge is part of a circle or of an ellipse, the curve in the sketch is that part of an ellipse exactly - a centre, two ends, nothing between.
- The ellipse can have a start and a sweep (a0, sweep); without them it is whole, as before. Its two ends are points like an arc's: picked, snapped to, dimensioned, chained.
- Project and the curves that follow an edge make one when every point of the edge is on it (to a millionth of its size); else the spline as before. A curve an older project holds as a spline stays a spline (sizes may be tied to its points), and a face's own outline is untouched.
- It keeps the end it ran from when the body changes; moved, turned, mirrored and offset it is the same part; trimmed or split it becomes an open spline through 13 of its points.
- A shape closed with one extrudes to the right volume (a quarter of 20 x 10, 5 high: 785.40).
tests/ellipsearc.test.ts: 10 checks (the pieces, the extrude, a half disc followed from a tipped plane and made bigger). tests/projectlean.test.ts: 29. In the app: Project on the top rim of a half disc from a plane tipped 60 degrees gives half an ellipse 20 by 10 that follows the edge.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:11:57 +02:00
superGeometry 35c2a350b0 sg.sweep(): every tool tried through the line, kept as a tool (it was scripts written for the day and thrown away). From every kind of pick there is in the model it starts each tool the line offers, tries every option in it (each choice, switch, number, blank), and lists what did nothing or threw; each tool is cancelled and each step undone. It also says of each tool that takes a length or an angle whether it has a handle on the model, a value box and lit picks while it is open - the list of tools still to bring up to what Extrude and Fillet have. sg.sweep(['face']) for some picks only; sg.sweep(undefined, false) only starts the tools (quick).
On a box, a cylinder, a second box and a loose sketch: 243 tools started, none dead, no errors, no option that did not take. With a handle, a box and lit picks: Fillet, Chamfer. Without a handle or a box: Shell, Thread, Revolve, Rotate Around Axis, the patterns, Offset Edge on a body, Wrap & Emboss, Plane - Through Edge, the axes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 19:04:33 +02:00
superGeometry 57b6ca97e0 The first five minutes, and the way out with what was made.
- A tap picks that thing and lets the last pick go (a second tap on it lets it go). Every tap added before: a face, then an edge tapped to pick it instead, made "2 items" with fewer tools. To pick several: Shift or Ctrl, or the + beside the pick's name in the tag (on: each tap adds; off again once nothing is picked).
- Drawing goes straight on to 3D: a sketch left right after a shape was closed in it has that shape picked, its arrow up - drag it, no tap on the shape first. The guide text says so.
- "Next" after a step: with nothing picked, the tag over the line offers what is likely next for the step just made - Round its edges, Hollow it (its body picked and that tool started), Print / Share - until something is picked or started, or its x is tapped.
- Print / Share (also under More, with the view's tools): is the model fit to print - each body closed and solid, or what is wrong with it in plain words and where to mend it - its size, and the files to take it away as (3MF, STL, STEP), each with a line on what it is for. Export was only in File, under names a first-timer does not know.
Walked through on a clean project: sketch, rectangle, Exit (the shape picked, "Drag the arrow to extrude"), extrude 10, Next > Round its edges (fillet on the body's twelve edges), Next > Print / Share ("Ready to print", 40 x 30 x 10 mm), a face then an edge tapped (one pick), + on and a second face (two), off (one), x (none).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 18:50:44 +02:00
superGeometry b0a0d7124a Offset Edge in a sketch: what is being offset is shown, and the distance is dragged (asked for: "make the edges highlighted when I hover over them, or somehow represent them that they are selected", and "a double arrow ... click, hold and drag and the value box appears like with extrude or fillet").
- A body's edge lights up under the pointer while Offset Edge is on, as a curve of the sketch does.
- Tapped, the edges the offset is made from stay lit until it is applied or dropped - the one edge, or with Chain the whole outline of its face (a finger has no pointer to hover with: this is how it shows what was taken). They stay lit through the sketch's own redraws, and follow Edge / Chain when that is switched.
- A double arrow sits on the new curve, across from where the edge was tapped, with the distance in a box beside it. Dragged, it sets how far the offset goes - through the edge to its other side too; the box takes a typed distance, and Enter applies the offset. The line at the bottom shows the same distance. For an offset of a sketch's own curve and of the face's outline as well.
- A dashed guide left by an earlier offset, tapped, is its edge again (it was taken as a curve of the sketch, and its offset came out dashed).
Tried on a box from a sketch on the floor: hover on an edge, on a curve, on nothing; Edge, Chain and back; the arrow dragged out to 10 and in to 7; 5 typed and Enter; Esc.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 18:40:36 +02:00
superGeometry 720cbe9c28 Offset Edge in a sketch takes an edge of a body, with Edge or Chain (asked for: "just click the edge I want to offset on that face, and choose chain or single"). Before, only a curve of the sketch could be tapped - an edge had to be projected first - and on a sketch drawn on a face a tap on the face's own edge always offset its whole outline.
- Any body edge, in any sketch: tapped with Offset Edge on, its curve comes into the sketch as a dashed guide (it follows the edge when the body changes, where the edge is there before the sketch) and the offset is made from it, a curve like any other. Chain: every edge of the flat face the edge is on that faces the sketch comes in, and the whole outline is offset together, joined. Edge: that one edge. Switching between them after the tap works; an edge already in the sketch is not brought in twice.
- The face's own outline (a sketch on that face): Edge is now just the edge tapped (kept as a link to it, like the whole-outline one: OutlineOffset.single); Chain the whole loop, as before.
- Both start inside the face (a lip, a pocket's edge): the whole outline as before, one edge on the side the middle of the face is on. Flip for the other side.
Tried on a box: a sketch on the floor with an edge of the top tapped (Edge, Chain, Flip, switching, Apply: four guides, four joined lines), and a sketch on the top face (each of its four edges alone, the chain, saved and rebuilt).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 18:32:11 +02:00
superGeometry 179383d383 Sketch splines: a row of dots no more. The offset of a curve projected from an edge "made multiple points again": Offset wrote four points for every span of the curve it came from, so the projected curve's 24 (out of sight) came out as 97 dots.
- Any spline in the sketch being edited shows its two ends (a closed one none); the points between, the ones it is shaped by, come up when the curve is picked and go again when it is let go. Picked, they are tapped and dragged as before. So an offset, a text's outline, a freehand stroke, a free copy of an edge all look like the curve they are, and are still shaped point by point.
- Offset of a spline keeps only the points the new curve needs (within a five-thousandth of its size): 29 where it was 97 for half an ellipse.
(A curve that follows an edge still never shows more than its ends: those points are the edge's, not the user's.)
tests/projectlean.test.ts: 24 checks.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 18:24:10 +02:00
superGeometry 110eb695e5 Project in a sketch: a curved edge came in "full of points" - a spline through 24 dots, where the edge it copies has two ends.
- A curve that follows its edge (linked: it is made again from the edge whenever the body changes) shows only its two ends, as the edge has: those are the points to pick, snap to, dimension and drag. The points between are the edge's shape and stay as exact as they were (24 of them, out of sight). Sketches made before look right at once.
- A free copy (the edge is not there yet when the sketch is made, or a sketch's curves projected to another plane) is the user's to shape: a whole circle seen at a slant, or an ellipse, is a true ellipse; anything else a spline with the fewest points that hold it within a two-thousandth of its size (control points where those do it with fewer).
- Unlink turns the 24 into the few the curve needs.
- A face's own outline is untouched.
(The sketch's two kinds of spline both run straight at their ends, so part of an ellipse cannot be "two ends and a handle" at this accuracy: 15 points. Hence the ends-only showing for the ones that follow an edge, which is every one in the sketch this was seen in.)
tests/projectlean.test.ts: 22 checks.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 18:04:41 +02:00
superGeometry 5246af40b9 Sentence bar, from use on a phone:
- The line shook from side to side, fast. On a phone 390 wide, in a sketch with a tool on, bigger names made the end buttons wider, which narrowed the row, which made the names small again - it flipped on every layout. The size is now reckoned from the line's own width and the end buttons at their bigger size, never from the row as it is. Stable in every state at 320, 360, 375, 390, 412 and 430 wide.
- Groups were dimmed though their tools can be used (Create, Combine and Transform with nothing picked; Modify and Transform in a sketch with nothing picked). A group is dimmed only when nothing in it can be used now: with nothing picked every tool is there, and one that needs a pick asks for it as it starts. While it waits, the tag over the line says so ("Extrude: tap the model", with an x to let it go). In a sketch every tool is there whatever is picked; with a curve picked the ones that act where the view is tapped still start on it, where it was picked.
- The guide text, Help and the README say the same.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 17:43:20 +02:00
superGeometry 3a0efa62f0 The words catch up with the sentence bar: Help, the README (About's quick start) and the guide texts and toasts that still sent people to "the wheel" (Freeform's values and Symmetry, an image's width, a pick's other tools) now say where things are - the line at the bottom, More at its end, the buttons at the right edge. Found while checking every tool and option through the bar (ten kinds of pick, 204 tool starts with each option tried, a sketch's 20 drawing tools and 14 tools for a picked line: all worked, no errors).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 17:25:07 +02:00
superGeometry 26aeced38b The sentence bar is the only way to the tools: always on, its switch gone from More (asked for). The setting is forced on at start, as the wheel's was; the tool wheel stays in the code, never shown. sg.sentence() only describes it now.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 17:07:20 +02:00
superGeometry 7b225c93ae Sentence bar: made to be worked by hand on every screen, walked through as a beginner would (an empty project, a sketch, a first extrude typed in, an edge rounded) on a phone upright and on its side, a tablet both ways, a desktop with a mouse, and with a headset's bigger targets on.
- The groups never slide out of sight: when they do not all fit they close up - a small picture over a small name each, sharing the line evenly (a phone held upright: seven groups and More, each about 41 x 45; with room to spare, bigger names) - and open out again when there is room.
- What the sentence is about (the pick, the tool at work, "Sketch > Line") is a tag over the line, so the line keeps its whole width for what is offered. On a phone held upright the tag is at the line's far end, on the row undo has.
- A phone on its side: a tool's sentence is one line to slide along (three lines took a third of the screen), and the line keeps clear of the right buttons where they come down that far.
- Items and History both open on a small screen left a line 100 wide: it then runs over History's last rows rather than shrink to buttons too small for a finger.
- In a sketch: no second More on the line; the tag says which drawing tool is on.
- The guide text for the sentence bar: "Tap part of the model. The line at the bottom then shows what you can do with it.", "Your shape is ready: tap it, then drag its arrow up.", and in a sketch where Exit and Line are.
- A headset: words 52 high and more, the end buttons with them. Fingers: the words in a sheet 42 high, the tag's 36.
- undo and the guide text follow the line's height at once (they waited for the next frame, and a frame later overlapped it).

Not checked: a real phone, tablet or headset (all emulated in the browser), inside VR itself (its own hand menus are not this line).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 16:59:20 +02:00
superGeometry 98865ff7ce Sentence bar: no More among the groups on the line - the button at its end, with everything at once, is More (two of them were one too many). What More held (the pick's own, Insert, BIM, the view's tools) is in that sheet, first.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 16:47:51 +02:00
superGeometry a07315e65d Sentence bar: the groups run from More to Create (the wheel's order the other way round, as asked for), and with nothing picked the line starts with them - no "Make" before.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 16:45:52 +02:00
superGeometry 537ec20e5d Sentence bar: the line holds the tool wheel's eight groups, each in its place - Create, Combine, Modify, Construct, Transform, Freeform, Sketch, More - not a long row of loose tools (asked for: the row made no sense, the groups are known from the wheel). A tap on a group opens its tools for what is picked, over it; a tool's kinds open the same way; Sketch with nothing picked is the tool itself. A group with nothing for the pick stays in its place, dimmed, and a tap says why. More holds the pick's own (Delete, Color), Insert, BIM and the view's tools. In a sketch the same: Draw, Modify, Transform, More (Modify and Transform for curves that are picked), Delete a tap once curves are picked; none while the plane is still being chosen. The button with everything at once stays at the end.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 16:29:17 +02:00
superGeometry fe553f0c16 Sentence bar, with a mouse: the words past the end of the line could not be reached (a finger slides the line, a mouse had nothing to slide it with). The wheel slides it now, and a small arrow shows at either end whenever there is more that way (mouse and trackpad only; both keep their room while the line runs over, so one coming or going never changes how much fits). And its place on a wide screen: in the middle of the room between undo (which steps aside for Items) and History when that is open, never over either - it was centred on the screen and ran under History and over undo with both panels open.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 15:52:41 +02:00
superGeometry 248fc7deb7 The sentence bar: the app worked by finishing a sentence (More: Sentence bar, off unless switched on; while on, it stands in for the tool wheel). One line at the bottom says where things stand and is written by touching the model: the pick is its subject ("1 face", a thread running from the word to the thing on the model), the words after it are what can be done with that pick and nothing else, the tool chosen is the verb, and the tool's options are the rest of the sentence - a blank filled by tapping the model, a word swapped for another, a number typed or dragged sideways. The tick ends the sentence, the cross takes it back, the x on the subject lets the pick go.
- Pick first, always: with nothing picked the line starts with "Make" and offers only what makes something new (Sketch, the freeform shapes, Insert, planes and axes built from several picks, BIM) and the view's tools. A tool that asked for its pick after the tap is not there; it is offered once the thing is picked. What a pick has no use for is never a button: the sheet with everything for the pick says, under it, what those need instead.
- In a sketch the same: nothing picked, what draws; curves picked, what can be done with them. Trim, Split, Extend, Offset and Fillet, which act where the view is tapped, start on the piece picked at the place it was picked.
- Every word is one of the ToolItems or window parts the wheel shows (ui.shown(), ui.panelContent()): a tool added to the app is in the sentence by itself.
- Phones: the line has the bottom edge (a tool's sentence runs on to a second line), undo and the guide text sit over it; sideways it is beside undo. Words come in one after another, the finished sentence lifts away, a phone ticks under the finger; none of it with reduced motion on.
- Off, nothing changes: the wheel's `on` is the one line that asks; sg.sentence(true/false) switches and describes it.

Checked at phone size upright and on its side, tablet and desktop: every word offered tapped for nothing picked, a body, two bodies, a flat face, a round face, a straight edge, a round edge, a corner, a sketch shape and a plane (each did something); a sketch (draw, pick, trim, split, extend, offset); a freeform shape (new, edited, faces picked); typing with the numpad, dragging a number, colours, Done and Cancel; the switch both ways.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 15:10:36 +02:00
superGeometry 51c577d2ea Wheel: everything in the place it belongs, and offered only when it can be used. Every model ring checked at phone size with nothing picked, a body, two bodies, a flat face, a round face, a straight edge, a round edge, a corner, a sketch shape, a plane, a sketch line and the origin; each tool's options; the sketch's rings with nothing and a line picked.
- Align (Transform) was a "Coming soon" that could never be used, greyed in its place on every ring: gone (the sketch's Align, which works, stays).
- Replace Face was "Coming soon" on the main ring though it works on a picked face: it is now a tool there, asking for the face.
- Reveal in Items had the arrow, but it opens the Items panel: no arrow.
- Pattern's kinds were "Circular" and "Linear" with nothing picked, "Pattern - Circular" with a body: "Pattern - Circular" in both, on or greyed.
- Operation (Add, Cut, Intersect) is offered only when there is a body besides the one being made; Extrude's "Through all" too, and its hint no longer speaks of a cut with nothing to cut.
- Sweep shows only Path until there is one; Corners only for a path that turns a corner.
- Fillet's Corner setback only once three edges are picked (it joins three rounds at a corner); Loft's Closed loop only with three shapes or more.
- Split with bodies only when there is another body to cut along.
- In a sketch, the switch for new lines was named by its state ("Regular"): it is Construction, lit while on, and with curves picked it is with them only, not twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:32:35 +02:00
superGeometry 1b20de78d8 Wheel checked on every ring at phone size: the sketch tools, the freeform shapes (box, sphere, cylinder, torus, a surface, Freeform Face, Connect), every model tool's options ring with each choice in it and Back, and the Settings lists with each switch. Fixed on the way:
- Pattern in a sketch: its kinds showed "Pattern" once more, and its piece was named "Options" (now Pattern).
- A long name in a narrow piece ("Transform ›") had its arrow cut off: the box widens for its widest word.
- A name that won't fit two lines even at the least size ("Plane - Through Edge ›") takes three, never cut off.
- An edge picked: Construct showed a greyed Plane ("not for 1 edge") beside the two plane kinds that work. The kind takes Plane's place.
- Shell's Clear was "Clear ›", opening a ring with only Clear in it: now one tap.
- A freeform surface's Solid › Up, Down, Symmetric did nothing while Thickness was 0: picking a side now makes it 2 thick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:49:53 +02:00
superGeometry fb1a7a5314 Wheel: a tool that opens its options as the next ring has the arrow at the end of its name too (Extrude ›, Fillet ›, Sketch ›, Variables ›, Materials ›), on every model ring and the outer band. One that opens a window of its own (Technical Sheet, Drawings, Assemblies, Create Drawing, Insert's files), is done at once (Delete, Isolate, Union, Repair), or works on the model with nothing to choose (Measure, Section View) has none; nor does a greyed tool (it opens nothing) or a sketch's or freeform's own tool (its options are a piece of the ring). Checked at phone size on every ring: nothing picked, a body, a face, a round face, an edge, the Settings wheel, Extrude's options, the sketch wheel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:20:21 +02:00
superGeometry 5ffd6faf65 Wheels: every button that opens more choices has the arrow at the end of its name, on every ring - the first ring's groups (Create ›, Modify ›, More ›), a tool's kinds (Plane ›, Rectangle ›), a choice on a tool's options ring, the outer band's tools with kinds, and the Settings wheel's lists (Snap to ›, Units ›, Appearance ›, Shaders ›). Joined to the name by a no-break space, so it never sits on a line by itself.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:58:15 +02:00
superGeometry 54986f617d One wheel: the Options wheel is gone, a tool's options are the tools wheel's next ring. Pick Plane > Offset and the same wheel shows From, XY · XZ · YZ, Offset, Cancel, Done where the plane kinds were; the middle is Back, which leaves the tool and comes back to the ring it was picked on. Another tool's column (Variables, Section View's buttons) is that ring too, Back being its Exit. In a sketch the drawing tool's or the picked curves' window is one more piece of the sketch's ring, lit and named by the window (Line: Length, Cancel, Done), so Mirror and Pattern stay a tap away. A freeform's values are under Values on its own ring. The wheel keeps the model's place and fold for a tool's options; Section's tap on a cut unfolds it. Hints that named the Options wheel now say the wheel.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:54:09 +02:00
superGeometry e2711937c3 Stress tests aimed elsewhere, and what they found. A fuzz of the rebuild: random steps added the way the app adds them (taps from the last rebuild), then an early size changed and back, each step switched off and deleted - built warm (results kept) and from nothing, the two the same, every time (30 seeds, 850 checks: the cache held). Its refused steps found the bugs. Edit Freeform steps had no test: now edits stacked, switched off, rolled back to, with a subtract and a linked copy between, each the same as the cage made that way straight away.
Fixed:
- A face pushed out after an earlier step tilted it, then that tilt changed: the push became a slide - a sheared move, or "Sliding or turning a face within its plane..." on a body with a round face. A move that was a push when made stays a push, square to the face as it is now; a tilt about a line in the face stays that.
- The earlier tilt turned to 0 or switched off: the push lost its face ("The face it was built on is gone"). When the step that made a face makes none now, the face that is plainly the same one (facing the same way, its middle where it was, much the same size) is taken.
- Move Face on a shape projected onto a face (Project as Edge) did nothing and said nothing: the faces round it lie in its plane. Pushed out it now raises it (a boss), in sinks it (a pocket), following the sketch when it moves or grows; tilting it says why it can't.
- Project as Edge from a sketch on a block's top split the bottom too, out of sight behind the block: a line running wholly inside the body was taken as seen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:39:07 +02:00
superGeometry b8e7a3a58e Stress tests and what they found. Four new parts built by code and held to their volumes, then changed at the start: a sprocket (teeth, hub, keyway, patterned holes, fillet, chamfer), an oval soap dish (swept sides, shell, slots, split and joined, scaled), a pipe elbow (a ring swept round a bend, flange, bolt holes), a clamp jaw made by editing faces (also built by hand at phone size: the same to a millionth, and at 80 long). Fixed on the way: a face tapped while filleting brought in the preview's own round borders as edges to round; the value box after a drag could sit off the screen's edge (a face pushed out at a phone's right edge); a narrow round tapped in its middle gave one of its edges, never the face; a Delete Face that can't be done also said "1 step failed to rebuild - see History" with nothing there; typing a minus distance in Extrude's window cut, while Operation still said "Auto: Add". The delete-a-fillet test that kept failing had its hole touching the top along a line (the part without the fillet is pinched there too): moved 0.2 clear. Also: opening another project stops the last one's rebuild instead of waiting for it (a guitar's 90 s)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:16:27 +02:00
superGeometry bf0a7a3dd9 Speed: the slowest rebuilds in the test projects, measured and cut down. The jet's two unions 70 s each -> 13 s: volumes are integrated both ways piece by piece, each piece halved only where it still changes (halving every piece again and again, its sixteen blade faces took 4 s each and still hadn't agreed), a face an offset closed to nothing taken as it is, the tolerance floored and each face's work capped (a split box's shell 31 s -> 5 s). The guitar's shell 63 s -> 16 s, a mug's Connect 19.5 s -> 8.3 s: a shell's checks tell inside from outside by one section of short segments against the solid (not each point's distance to the whole of it), run the quick checks first, and only measure a wrong way's volume when nothing better came; a sweep's sign and emptiness by the rough measure. New test: a hose connector (Auto extrudes, revolve, inside thread, chamfer)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:16:26 +02:00
superGeometry 434954fb8a Freeform Connect: works after Edit Freeform. A surface edited after another was made has an Edit Freeform step of its own; Connect took that step (and the surface itself, compared as an edited copy) for something using it - "is used by ... it can't be merged". The edit steps' changes are in the joined cage already: they now go into the step that keeps it (one surface too, where a later edit put its old cage back over the join)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:19:25 +02:00
superGeometry 4d91f1d14a Freeform wheel: a group holding just one thing is that thing in the group's place - Add detail a tap, Cells across its 3/5/7/9 straight away, a lone switch (Symmetry) a tap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:12:40 +02:00
superGeometry 179c475191 Plane and axis icons: what makes each kind drawn big, the plane (or a dashed axis) small in the corner - Offset, Midplane, 3 Points, On Curve, Perpendicular, At Angle, Parallel; axes get their own: Square to Face, Along Edge, Cylinder / Cone, Point to Point, 2 Planes. An axis keeps what it was made from, so Items shows its icon (one from before: the plain one)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:09:37 +02:00
superGeometry 458b004e56 Measure: no Options wheel (it held only Exit Measure; the old column stays hidden too - Esc, a tap on empty space or its button in View close it). A round face (a shaft, a hole) shows its diameter and radius, each pinnable: the diameter pin a line straight across it through the axis
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:06:51 +02:00
superGeometry df383a1291 Materials: technical data filled in for the whole library - compressive and bending strength, yield, stiffness where they were missing (wood species, stone, boards, insulation), and three new rows on the data and technical sheet: elongation at break, melting point, max service temperature
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:59:59 +02:00
superGeometry fcafc90e8f Materials: 99 in the library (was 29) - more metal grades (C45, 42CrMo4, D2 tool steel, 303 and 17-4 PH stainless, ductile iron, 5052/7075/2024/cast aluminium, phosphor bronze, titanium Grade 2, magnesium, Zamak, nickel 718, lead, tungsten, gold, silver), plastics (ASA, TPU, SLA resin, PA12, PA66, HDPE, LDPE, PP, PET, PVC, PTFE, PEEK, HIPS, epoxy, silicone, natural rubber), composites (carbon and glass fibre), C40/50 and aerated concrete, glulam and wood species, MDF, chipboard, OSB, toughened and borosilicate glass, marble, limestone, sandstone, slate, ceramics, cardboard, leather, and more insulation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:55:56 +02:00
superGeometry efae4f257f Materials window: the search box shows whole on every screen (it was squeezed to a sliver), the body rows lie in a line again (the window's inside had the rows' own class), long names and values wrap inside the window on a phone, and the hint no longer covers the window there
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:52:01 +02:00
superGeometry e2178263ed Variables: Turn Off is now a Variables switch on the wheel in More's place - a tap turns the tags off, another back on, the card staying. On the Options wheel, one lone thing under More takes More's place
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:29:52 +02:00
superGeometry 3e15e3a628 Section View: with a cut on, a tap on the cut face itself brings its arrow to move the cut and its buttons, the Options wheel unfolded (Add Plane - was Place Plane - Flip, Section only, 2D section). Freeform: the wheel holds all the card offered (Shape: Delete face, Extrude face, Inset, Add detail, the hole tools; More: Cells across...), and the card stays out of sight
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:14:09 +02:00
superGeometry f38204bddd VR only in a headset's own browser: a computer no longer shows Enter VR (even with a headset connected). Phones and tablets keep Enter AR under More; the help says so
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:04:30 +02:00
superGeometry c652990d49 Browser window: a tap on a video hands it over like a page does - its own buttons (volume, seek, settings, full screen) all work; a hold or a drag moves the window again once the pointer has been back on the app (the bar always moves it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:32:45 +02:00
superGeometry af13a38f9b Browser window: pressed and dragged (or held) anywhere on the page or video, the window moves with it. On a video a tap plays or pauses it and a double tap fills the screen with it (the strip along its bottom stays the player's own controls); on a page a tap lets the page be used until the pointer is back on anything else
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:30:30 +02:00
superGeometry 183230be7c Freeform: a face just deleted no longer breaks the marks drawn for what is picked or pointed at (it threw on every move)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:24:15 +02:00
superGeometry 42008ee4f9 Browser, under More > Insert: a web page or a video in a window over the model - moved by its bar, resized from its corner, minimized, closed, kept where it was. An address box along the top; a YouTube or Vimeo link plays right there (its own full screen button fills the screen). Sites that refuse to be shown inside another page (YouTube's own pages, Google, most shops and social sites) say so and open in a new tab instead
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:24:15 +02:00
superGeometry 21ec16229d The kept wheel stays on the ring it is on: a pick there (a colour, a transparency, a tool), a tap on the model to select, a scroll - none take it back a step; put away while a tool is open, it comes back on the same ring after (as far as it is still there). The middle is still Back
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:07:46 +02:00
superGeometry c8044fe17d Custom transparency takes whole percents from 0 to 95: the numpad greys its point and minus keys, a keyboard's are left out, a drag stops at 0 and 95, and a value past either end is set to it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:04:27 +02:00
superGeometry 1e711dca72 Custom transparency is typed in whole percents (a drag on its box steps by 1), and Transparency's kinds go round the wheel in their order: Solid, 25%, 50%, 75%, Custom
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:01:31 +02:00
superGeometry c874eca73d Transparency has Custom as its fifth: on the wheel a value box comes up to type how see-through (40 = 40%, up to 95), elsewhere a small window asks; a body set so shows its amount
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:54:50 +02:00
superGeometry e08b81d3a4 Transparency offers Solid, 25%, 50%, 75% in that order, each named by how see-through it is (25% lets a little through)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:51:27 +02:00
superGeometry 5f3b455b33 Measure, Section View and Variables keep the wheel: the old column and bottom bar step aside and the Options wheel holds the tool's Exit (or its window's Done). Color offers seven soft colors and Custom as the eighth, no Grey (bodies are grey to start; tap the lit color to make one grey again). Reveal in Items: the row pulses until the next tap or key
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:49:34 +02:00
superGeometry 1ba9249c24 Freeform Face on faces touching a surface a Freeform Face step already made on that body grows that step: one cage over the surface as shaped and the new faces, one smooth surface, no edge where they meet. Kept as an Edit Freeform step (delete it and the faces are apart again)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:42:22 +02:00
superGeometry eb417e7f11 Freeform Face over several faces at once: pick flat faces of one body that touch (a top and the side it meets) and one cage is laid over them all, put down onto them, a border point on each corner where their outline turns - one smooth surface in their place, no edge where they met (even as laid). Refused, saying why, for faces that don't touch
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:36:19 +02:00
superGeometry c5858e55db Edit Freeform is a step in History: Done on a freeform (or a Freeform Face) made earlier adds "Edit Freeform" with the new cage, instead of changing the first step unseen. Delete it or roll back before it and the shape is as it was; open it from History to reshape that edit. Opening the Freeform step itself from History still edits that step
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:27:06 +02:00
superGeometry 60a2c0e671 Edit Freeform's gimbal follows Move, Turn and Scale: Move has the arrows and planes, Turn the rings, Scale the cube-ended handles (drag one to stretch that way, the middle to scale evenly; type a factor while dragging) - picked from the wheel or the window
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:20:25 +02:00
superGeometry 7019512295 The wheel shows the tool in use: in a sketch or Edit Freeform, its group's piece takes that tool's icon and is lit (Trim on: Modify shows the scissors; Rectangle: Draw shows a rectangle; Freeform's Move shows Move, Turn or Scale)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:15:16 +02:00
superGeometry 90ec917363 Edit Freeform's wheel: Delete Face in place of Holes, a tap (greyed with no faces picked; filling and bridging holes are the window's), and its groups with options to choose (Move, Symmetry, Solid) have the chevron tab outside the ring, as the tools wheel's do
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:12:12 +02:00
superGeometry d729a26fa8 Every tap adds to what's picked, whatever it is - a face, then an edge, then a plane - and a picked one tapped again leaves. Picks of different kinds get the tools of the kind picked last. Shapes tapped in a sketch join each other (one arrow pulls them all), and a body, plane or image tapped in Items joins the pick on every device. A double tap still takes the whole body; an empty spot still lets everything go
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:10:50 +02:00
superGeometry a8e7ed306a Free 3D CAD modeling on any device everywhere the page names itself: the link's preview when shared, its picture's text and the heading search engines read
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:04:43 +02:00
superGeometry bb23043b5b The page's tab says: Free 3D CAD modeling on any device
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:03:39 +02:00
superGeometry 4951ad37c2 A freeform face (a freeform body's, or one shaped by Freeform Face) has Edit Freeform first among the buttons beside it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:03:30 +02:00
superGeometry 2f1a7a9496 Freeform on the wheel: no Shape or More - their tools are the window's, not said twice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 16:01:45 +02:00
superGeometry 0c4c282297 The first model as a journey, the guide and a pulse saying the same next step: an empty project, Sketch pulses; an empty sketch with no tool on, Draw (and Line in it); a shape closed, Exit; back in the model with the shape and nothing solid yet, Create and Extrude in it. The wheel folded to its button: the button pulses (a ring swells out of it and fades) whenever the next step is on it, or the guide says to pick a tool there - and the guide says to tap the pulsing button. The blue dot for a pulsing tool is gone: its piece of the wheel glows instead
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:56:16 +02:00
superGeometry e3926d2405 Sketch wheel: Draw with no drawing tool on starts Line as its ring opens (lit there), so a tap on Draw and you draw point to point; another kind on the ring takes over, and one already in use stays
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:45:19 +02:00
superGeometry d826580029 Wheel: a tool with kinds (Rectangle, Trim, Plane...) has a small tab outside its piece, a chevron pointing out (a tap on it opens them too), in place of the blue dot and the "›"; no dot on what opens. Every icon the same size and in the same place on its piece, the name below on one line (a size smaller where it must be); the wheel a little bigger for it. A double tap on a sketch's line opens its sketch even where the line lies on a body
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:43:39 +02:00
superGeometry c82df43257 Freeform tools each have an icon of their own: Box, Cylinder, Sphere, Torus and Surface smooth in their dashed cage, Freeform Face a face with a bump pulled up, Connect two surfaces bridged, Edit Freeform a shape and a pencil
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:28:31 +02:00
superGeometry a2b7ff7c58 Freeform: a Torus to start from (its diameter, thickness and rows round the tube in the card), smooth all over; Surface (plane) is just Surface
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:26:42 +02:00
superGeometry 068eeaf38d Construct > Axis on the wheel: Face (square to it), Edge, Cylinder / Cone (its middle line, a cone's too), Point to Point and 2 Planes (where they cross), in place of Along X / Y / Z (the origin's own axes are there in the view). A picked flat face has Move/Rotate beside Sketch and Shell
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:25:18 +02:00
superGeometry 319a170c35 Project name on a small screen: its box keeps its size whatever is typed (a long name pushed File, Items, History and More off over the view cube); while it is renamed it opens over those buttons to the bar's end, and goes back to its size once done
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:20:51 +02:00
superGeometry 4c17d5d9f3 Plane kinds on the wheel go by short names that fit their buttons (Offset, Midplane, 3 Points, On Curve, Perpendicular, At Angle, Parallel); the full name stays in menus and the tip says what each does
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:12:35 +02:00
superGeometry 5c54a2a2cb Reference Image: zoom the picture in its window - the mouse wheel zooms about the pointer, two fingers pinch; zoomed in, a drag moves the picture about (the bar still moves the window); a double click or double tap shows it whole again
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:08:03 +02:00
superGeometry cb8082f363 Construct on the wheel is just Plane and Axis. Plane opens its kinds with Offset lit and waiting: tap a face or a plane and an Offset Plane starts from it; pick another kind on the ring and that tool starts instead (the waiting pick is dropped when another tool starts). Project as Edge is offered where it belongs, with a sketch shape or edges picked
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 15:06:18 +02:00
superGeometry 264fc1c244 Reference Image windows sit over the model but under every button, wheel and panel (a layer of their own), so moving one about never hides them; Help and the wheel say so
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:57:40 +02:00
superGeometry 3c0ddeb9df Construct on the wheel: Plane lists only the plane tools without a place of their own on the ring (On Curve at Point, Perpendicular to Edge at Point) - no tool twice
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:55:26 +02:00
superGeometry 67d29470a3 Reference Image: the picture itself drags its window; minimized, its tabs drag it (a tap still opens it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:50:28 +02:00
superGeometry 0509747792 Move Vertex on a body in separate pieces (a block added that does not touch the rest): only the piece with the corner is rebuilt, the others kept - made as one, the pieces came out as a group, not a solid, and every move of that corner failed with "would fold the faces"
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:48:17 +02:00
superGeometry 621009ba46 Sketch wheel: a tool with kinds (Rectangle, Circle, Arc, Spline, Polygon, Fillet, Trim, Pattern) opens them on the first tap, the one used last lit - no tapping it again once it is in use
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:44:11 +02:00
superGeometry 5e0f7f7ce6 A tool window holding nothing but Cancel and Done (Move Vertex) is not shown with the wheel on: a tap on empty space is Done, Undo takes it back, Esc and Enter still work
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:42:02 +02:00
superGeometry 28c8b69e12 Extrude from a face: round buttons beside it for what that direction can do - pulled out, Add and New body; pushed in, Cut, Intersect and New body; the one it does now lit, a tap switches the Operation (quick-action buttons stay clear of the value box on the model)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:36:06 +02:00
superGeometry e3c81bc114 Wheels: what a button does, in the middle of the screen - its name and a line on what it does for every tool and group (a mouse at once, a finger once held a moment); Transform: Circular and Linear side by side (Move, Circular, Mirror, Linear first); More: Section View, Insert, Measure in that order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:33:32 +02:00
superGeometry 844647fb22 Reference Image: minimized, a window is only as wide as its tabs and its three buttons
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:21:26 +02:00
superGeometry 4ea8c70857 Reference Image (More › Insert): pictures to look at while modelling, each in a window over everything - dragged by its bar, resized from the corner, minimized to its bar; more pictures are tabs along the top, a tab dragged out is a window of its own and dropped on another window's tabs joins it; kept on this device (not in the project) until closed; Help says so, sg.refImages() / sg.refAdd() to check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:17:15 +02:00
superGeometry 8258fcc05d Wheels' first places along the right edge: Settings folded under the view cube, the tool wheel (its middle now a wrench) halfway down, Options at the bottom; all three step left of History while it is open (a place set by hand is kept, moved only out from under History), on a phone Settings sits below History's strip and Options on the undo row; Help says so
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:08:45 +02:00
superGeometry 5478bc71c9 The app's name is written superGeometry.app wherever it is shown: the top bar, the page title and share tags, the install name, About, Help, the welcome, toasts, the screenshot mark, exported files' generator, the share image, README and LICENSE (web addresses, storage keys and the subreddit stay as they were)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:55:01 +02:00
superGeometry 409b01bab8 Logo: the G sits lower on the cape, where the cloth is wider, and is bigger
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:51:29 +02:00
superGeometry 21116bdcb3 Logo: back to the full-strength red, yellow and blue; the cape fills more of the tile and the G on it is bigger (the maskable icon keeps the cape inside the safe circle, the watermark crop follows)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:49:46 +02:00
superGeometry 9a54b500d2 New logo: a red cape in the wind, a faceted cloth surface shaded by its triangles, with a yellow clasp and a yellow hexagon bearing a blue G printed on the cloth (it folds and shades with the facets); muted red, gold and blue
scripts/logo.py draws it and writes public/icon.svg; scripts/icons.mjs now reads the paths from icon.svg for the home-screen icons (192, 512, maskable with safe-zone padding, Apple touch). The share image shows the cape, and the screenshot watermark takes the mark from icon.svg without its tile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:47:41 +02:00
superGeometry 28393ed9cc Help and About rewritten around the wheels: no left or right column any more, the quick buttons folded into what a pick offers, Extrude's Auto, the line ending on a closed shape and thread lead-ins each in a few words; the first-part walkthrough follows the wheel
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:20:45 +02:00
superGeometry bafa89d599 Guide text, one short line each: a pick says its handle, then "or tap a button beside it"; Extrude says what Auto does by the way it goes; the line tool says closing a shape ends it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:18:16 +02:00
superGeometry c2f9f33b9d Guide text: Extrude says which way does what under Auto, the line tool says it lets go on a closed shape, a pick points to its quick buttons, the Options wheel no longer "at the bottom"
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:17:02 +02:00
superGeometry 43466f5b31 Help and About: the wheels kept in a column beside History, quick buttons on every pick, Operation and Auto by direction, the line tool letting go on a closed shape, thread lead-in chamfers
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:15:24 +02:00
superGeometry 4b00ff0eca Quick actions on every pick: bodies, sketch shapes, planes, axes, images, several faces or edges, freeform picks, and a sketch's own curves and points
- Model: a body (Shell, Fillet; clear of its gimbal), a sketch's shape (Sketch, Revolve), a plane (Sketch, Offset plane), an axis (Delete), an image (Scale, Delete); several faces or edges get their kind's buttons beside the last one picked; freeform faces and edges too.
- In a sketch: picked curves get Construction/Regular and Delete beside their gimbal; points get Delete.
- A longer name (Construction) makes the button a pill instead of being cut short.
- A sketch is never stored without a plane, and one saved that way is skipped when drawing (it made every project switch after it throw).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:02:41 +02:00
superGeometry 857f632c95 iPad findings: wheels kept on screen in a column beside History, clean thread ends, line tool ends on any closed shape, Auto by direction, quick actions on a picked face/edge/point
- Wheels: the tool wheel is always kept on screen; a tap on its middle folds it (never gone). First places on tablets and computers: one column left of History, below the view cube (tools, Options, Settings), far enough apart not to overlap when open. New places key, so old dragged spots don't hide it.
- Browser dark-mode add-ons washed the wheels out (they lighten dark fills): darkreader-lock tells them the page is already dark.
- Threads: the groove's stopped ends left a thin ring of the face and a flat stub at the end, and a flat triangle where groove pieces met. Free ends now get a 45 degree chamfer to the root; the pieces are fused into one groove.
- Line tool: a line that ends on an existing point and closes a shape (drawn in pieces, after an arc, carried on after a stop) puts the line tool down, as closing on its own first point did.
- Auto, by the way it goes (new extrudes, byDirection): on its own, + is a new body, - cuts what it runs into; on a face, out adds, in cuts. Older extrudes keep the old rule. The choice is "Operation"; the Options wheel names it by what it does (Cut, Add, New body).
- Quick actions: the two most likely next tools as round buttons beside a picked face, edge or point (clear of its arrow and of the wheels).
- Welcome text: a free MakerWorld Boost or a follow.
- valve test: threaded pairs' overlap confirmed by point sampling (the kernel's intersect said 34 and 83 mm3 where no point is in both).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:35:21 +02:00
superGeometry 6541d92040 Stress test: a coil spring (a wire revolved five turns with Travel; its volume exactly the wire area times its middle's path)
Built by hand on a phone-sized screen the same: a circle typed on the front plane, Revolve about Z, Angle 1800 (a plain message until Travel is set), Travel 30. Nothing to fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:43:43 +02:00
superGeometry 1d458cee3e Stress test: a step stool (an L extruded both ways, the step offset up, shelled open at the bottom, a hand hole through the seat)
Built by hand on a phone-sized screen the same: the side as typed lines, Offset Face on the step, Shell from below (the inside rounds the step's inside corner, as an offset does), a rectangle on the seat cut through. Nothing to fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:41:22 +02:00
superGeometry 664ef5a900 Stress tests: a cookie cutter (a hexagon offset twice, the flange and wall extruded, the wall taken on up, its top rounded) and a waste bin (drafted out, shelled open, handle slots through both walls)
Found building them by hand on a phone-sized screen:
- Extruding the wall's ring on, on Auto, cut it out of the flange and added nothing past it, without a word (the sketch is on the floor, not on a face, so Auto saw a body in the way). Auto now adds to the body made from the same region of the same sketch.
- Rounds bigger than half a wall (a 1.2 wall rounded 1 inside and out, as the fillet starts) ran into each other and came out "Repaired automatically" with a flat patch over the gap. A fillet or chamfer that tears the body open now says the size is too big.
- Draft angle 5 leaned the bin's sides in, and nothing said which way a sign leans: the hint says so while a draft is set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 09:35:23 +02:00
superGeometry 5c2bdfbb8c Stress test: a birdhouse (a house shape both ways, shelled open at the bottom, the ridge rounded, an entrance and a perch)
Built by code and by hand on a phone-sized screen; the two match (273340.6 mm3, 17 faces).
The shell is held to the house shape moved in 4 on every side but the floor,
the ridge round to its spandrel at the roofs' angle.
What the hand build found, now fixed:
- Extrude, Symmetric: the distance box is called "Each side" then, so a 60
  meant for Distance went nowhere, and Done at 0 closed the tool without a
  word. It says "Nothing made: the distance each side was 0" now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:25:30 +02:00
superGeometry 895366f2c2 Stress test: a picture frame (a section swept round a rectangle, mitred; rounded outside, chamfered inside, a hanging hole)
Built by code and by hand on a phone-sized screen; the two match (65675.9 mm3, 25 faces).
What it found, now fixed:
- A mitred sweep left each flat side that runs round the path (the frame's
  front, back and rebate floor) in one piece per leg, meeting along the
  mitres. A 1 mm chamfer round the inside edge failed as "too big", and a
  round on the outside took 2.7 mm3 more than it should at the corners. The
  pieces are merged into one face each now (24 faces to 15).
- Edge picking: two edges on the same pixels (the front and the back edge,
  seen from straight above) went to whichever came first, so a tap just off
  the face took the hidden one. The one nearer the eye wins now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:15:28 +02:00
superGeometry ef29247234 Stress test: a die (a cube intersected with a ball, pips on three faces)
Built by code and by hand on a phone-sized screen; the two match (3442.7 mm3, 19 faces).
The intersect is held to the ball less six caps, the pips to their cylinders.
The hand build went through without a fault: sketches on three faces with
typed circles, a revolve as a new body, Combine Intersect picked from a corner
sticking out of the ball.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:10:21 +02:00
superGeometry 1bd75f8ed4 Stress test: a cable reel (a revolved section, hub corners rounded, a circular pattern of windows, chamfered rims)
Built by code and by hand on a phone-sized screen; the two match (37963.2 mm3, 26 faces).
What the hand build found, now fixed:
- A line typed as Across / Up on a phone: "Up 34" drew 34 down. The box showed
  where the finger last was (-2.7) and the numpad keeps a minus already in a box
  when digits are typed over it. That rule stays for set values (a cut's -5
  retyped as 8 is still a cut); a box that only follows the finger is now typed
  over whole, sign and all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:08:07 +02:00
superGeometry 1ba46073ee Stress test: a domino (rounded all round, a groove, pips by revolve, pattern, mirror, subtract)
Built by code and by hand on a phone-sized screen; the two match (9038.1 mm3, 37 faces).
What the hand build found, now fixed:
- Fillet: a face tapped again took its edges out only half the time - it added the
  rounded preview's borders instead. Those borders are skipped, and a face whose
  edges are all in (or rounded into the preview) is taken out again.
- Fillet: a tap on a thin side face next to a picked edge dropped that edge; a
  face's tap now reaches less far for edges.
- Revolve: a tap on the axis line mostly lands on its end points; an axis takes
  the sketch line through a tapped point.
- Mirror / Pattern: after the first body, a tap on the next one said "tap a flat
  face" (only Items could add it). A body the plane or direction can't use now
  joins what is mirrored or patterned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:08:07 +02:00
superGeometry 433ffce1f4 Stress test: a shelf bracket (an L, a gusset, a split inside round, holes in both legs)
Fillet / Chamfer: a face tapped again, as its preview shows it (its
edges rounded in), takes its picked edges back out. It added the rounded
preview's new edges on top instead: a gusset's side tapped by mistake
could not be undone with a second tap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 07:27:11 +02:00
superGeometry bfcf43bed6 Stress test: a reducing pipe tee (join, a shell open at three ends, chamfered rims)
- A round face's seam (the line where it starts and ends, drawn on the
  body) is marked as one, and Fillet and Chamfer turn a tap on it away
  with a word why. Taken, it broke the step with "an edge it was built
  on is gone", a tap again didn't drop it, and as Chamfer's first pick
  it used up the wait, so the next edge tapped was only selected.
- The test is a reducing tee (branch 16 across): OpenCascade can't bring
  an equal tee in by a wall (the two cylinders' meeting curves cross at a
  point), so its shell came out only now and then.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 07:19:20 +02:00
superGeometry 7d935ebf3b Pipe tee stress test (by code); Auto's cut explained; numpad decimals
- Auto extrude drawn inside a body and reaching out of it cuts, and now
  says so with Add named (a pipe's branch drawn on the floor through the
  pipe came out a notch, no word why). A tool's notes show as it previews.
- A value box no longer rewrites its text from the value while the numpad
  types into it: "1." became 1, so 1.5 came out 15 (the numpad works
  without focus, and the box only held back while focused).
- tests/pipetee.test.ts: run, branch, shell open at three ends, chamfered
  rims; the by-hand part is still to come.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:28:25 +02:00
superGeometry 7a3e190f53 Stress test: a square-to-round duct adapter (loft, a shell open at both ends)
The plane's From presets show as "XY · XZ · YZ" on the options wheel, not
"Kind". The shell's thickness box goes on the open face tapped last, so it
is not hidden on a face turned away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:17:00 +02:00
superGeometry bb34a0a807 Stress test: a cable clip (offset, trim, a tab with screw holes)
Built by code with checks (the outline's area from circles' segments and
strips) and by hand on a phone-sized screen with Offset Edge and six Trim
taps; the two match exactly. Nothing new to fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:09:27 +02:00
superGeometry 17e25f76ad Stress test: a cabinet knob (revolve, an inside round, 12 patterned notches)
Built by code with checks (the round by Pappus, the notches by the lens
each circle shares with the cap) and by hand on a phone-sized screen; the
two match exactly. The hand build used More → Other plane in the sketch
tools (fixed with the wall hook) and a circular sketch pattern; it found
nothing new to fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 23:04:11 +02:00
superGeometry fcc78e60f8 Stress test: a soap dish (rounds, a shell, a 4 x 2 pattern of drain holes)
Built by code with checks (the rounds by Pappus, the hollow as the outside
less the same shape 2 in) and by hand on a phone-sized screen; the two
match exactly.

- Sketch on: from the usual view most of the floor plane sits behind the
  front plane, and a tap for the floor took the front plane. With the
  wheels on, the hint now names XY, XZ and YZ on the options wheel.
- Fillet: a picked edge tapped again was added, not dropped, when the
  preview's round put its border edge a hair nearer the finger. A border
  of a picked edge's own round (parallel, the radius off it) now drops it.
- Numpad: − first, then digits, flipped the old value's sign and put the
  digits on its end (−24 in a box showing -24.6224 gave 24.622424). It
  types that number, negative, now; − then ↵ still flips the sign.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:56:46 +02:00
superGeometry a5f53b5555 Stress test: a wall hook (rounded plate, countersunk holes, a swept J arm)
Built by code with checks (the arm held to Pappus) and by hand on a
phone-sized screen; the two match exactly.

- Sketch tools: More opened on an empty ring (its ring was made from its
  own empty list and opened before its cells), so Other plane and
  Constraints were out of reach. It shows them now.
- Sweep: a path with a gap said the kernel's "Failed to build the wire,
  disconnected wire". It says the curves don't join end to end, and how
  to fix it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:53:59 +02:00
superGeometry a036d550c4 Stress test: an M10 nut (polygon, chamfers, a hole, an inside thread)
tests/hexnut.test.ts builds it by code, each step held to its size: a
hexagon 17 across its flats extruded 8, the twelve edges round its top and
bottom chamfered 1 (each end's band to the hexagon shrunk in as it goes,
exact), a hole at M10's tap drill through it, threaded M10 x 1.5 inside.
Then the same nut built by hand on a phone-sized screen
(tests/fixtures/hexnut-hand.json): the same volume and faces.

What the hand build found:

- Chamfer (and Fillet) wanted every edge tapped: twelve round a nut's
  ends, three of them out of sight from any one side. A face tapped did
  nothing. Now a face tapped takes every edge round it (tapped again, it
  drops them), when starting the tool or while it runs: the nut's twelve
  in two taps, its top and then its bottom.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:30:00 +02:00
superGeometry 5a7fd027f1 Stress test: a funnel (loft, a spout, a round, a shell open at both ends)
tests/funnel.test.ts builds it by code, each step held to its size: a loft
from a 12 circle on the floor to a 60 one on a plane 40 up (a frustum,
exact), a spout drawn on its small end and extruded 30, the join rounded
4, shelled 1.5 thick open at the top and the spout's end. Then the same
funnel built by hand on a phone-sized screen
(tests/fixtures/funnel-hand.json): the same volume and faces.

What the hand build found:

- The bottom face pulled 30 down for the spout: nothing happened, not a
  word. A flat face pulled carries its sides on along their own surfaces,
  and a cone's sides meet in a point 10 down: pulled 11 or 20 it made an
  hourglass through that point that every check passed as sound, 25 or
  more gave the body back unchanged. The outline's area as it goes is a
  quadratic in how far: when it comes to nothing on the way, the step is
  refused, saying so and what to do instead (draw the shape on the face
  and extrude that). Pulled 5 it still carries the cone on.
- Shell, the top tapped, then the spout's end from below: the tap went
  into the thickness box, which sits on the top face's middle - right
  behind the spout's end, seen from below. A value box on a face now
  steps aside when that face is turned away (the value is in the tool's
  card then, and the numpad lets go of it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:22:11 +02:00
superGeometry fccdae44d6 Stress test: a box with a lid (rounds, a sealed shell, a plane, Split)
tests/splitbox.test.ts builds it by code, each step held to its size: a
60 x 40 x 30 block, its upright corners rounded 8, its top and bottom
edges rounded 2 (held to Steiner's formula: the inside grown 2 all
round), hollowed 2 thick with no face open, then cut in two along a
plane 22 up: the base and the lid, each to its volume. Then the same box
built by hand on a phone-sized screen (tests/fixtures/splitbox-hand.json):
the same two parts.

What the hand build found:

- Shell, sealed, with walls as thick as the edges are round (2 and 2):
  after a minute and a half it said two faces were closer together than
  two walls, which nothing was. The rounds shrink to nothing inside; the
  offset came out with hair-thin faces there, Shell took it, and the
  check every edit gets turned it down after a long repair. Shell now
  holds its tries to having no hair-thin faces too, and tries a hair
  thicker (a thousandth) for sealed shells as well as open ones: the
  sharp inside it should have, in about ten seconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:06:15 +02:00
superGeometry 6a53df0019 Stress test: a bottle (revolve, fillets, shell, a thread on the neck)
tests/bottle.test.ts builds it by code, each step held to its size: the
half section revolved round Z (Pappus), the bottom's edge rounded 5 (the
ring of its corner), the shoulder's two edges rounded 3, shelled 2 thick
open at the neck, a thread of pitch 2 cut round the neck. Then the same
bottle built by hand on a phone-sized screen
(tests/fixtures/bottle-hand.json): the same volume and faces. The hand
build went through without a new finding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:34:48 +02:00
superGeometry 2cb65c2146 Stress test: a key tag (rounded plate, a hole, raised text, a rounded edge)
tests/keytag.test.ts builds it by code, each step held to its size: a
50 x 24 x 3 plate with its corners rounded 6, a 6 round hole for the
ring cut through, "SG" raised 1 in the app's own sans, the top outer
edge rounded 1 all round. Then the same tag built by hand on a
phone-sized screen (tests/fixtures/keytag-hand.json): the same volume
and faces.

What the hand build found:

- Sketch fillet: typing a Radius on the card after tapping a corner
  didn't change that corner; it only set the size for the next one.
  The card's Radius now resizes the corner being sized, as its box does.
- One edge of a smooth outline filleted rounds the whole outline (the
  kernel follows tangent edges), so the round all round is one tap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:27:22 +02:00
superGeometry b8de2dc60f Stress test: a V-belt pulley (revolve, keyway, a circular pattern)
tests/pulley.test.ts builds it by code, each step held to its size: the
half section (hub, web, rim with a V groove) revolved round Z and held to
Pappus, a keyway cut along the bore, a peg through the web patterned six
round the axis and subtracted, the rim's outer edges chamfered 1. Then the
same pulley built by hand on a phone-sized screen
(tests/fixtures/pulley-hand.json): the same volume and faces.

What the hand build found:

- Extrude waiting for a shape or a face: a tap in the keyway's small box,
  drawn across the bore, gave the corner on the bore's seam. Extrude
  can't take a corner, so nothing happened. A tool that wants a shape, a
  face or an edge now looks past corners.
- Subtract waiting for bodies, the pegs inside the web: they can only be
  picked in Items, and a tap there put Subtract away and selected the
  body. A tool waiting for a body takes the one tapped in Items now (as
  a pattern already did).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:17:09 +02:00
superGeometry 221187e60c Stress test: an L bracket (gussets mirrored, slots, a hole, round corners)
tests/bracket.test.ts builds it by code, each step held to its size:
the L drawn on the side plane and pulled out 20 each side, the inside
corner rounded 5, a gusset on an offset plane mirrored (Copy) to the
other side and joined, two slots (a box and two circles each) cut
through the foot, a round hole through the upright, the four outer
corners rounded 6. Then the same bracket built by hand on a phone-sized
screen (tests/fixtures/bracket-hand.json): the same volume and faces.

What the hand build found:

- Sketch, on a phone: the first point typed (X, Y), then a length and
  an angle, and Enter: the shape was dropped. Typing the first point
  lets go of the finger's spot, and Enter only placed the point with a
  spot to go by. It is placed as Done places it now.
- Sketch Mirror: the shapes tapped one by one, a rectangle's width label
  sat under its edge, where the circle's bottom was. The label took the
  tap and every shape picked so far was let go. The size and constraint
  labels are only tapped in Select now; in the other tools a tap goes to
  the drawing under them.
- Sketch Mirror: the axis tapped beside a slot 5 from it, zoomed out:
  the slot was within a finger's reach, and was let go instead of
  mirrored. A shape near an axis only wins when the tap is right on it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:16:58 +02:00
superGeometry 8de2367a0c Stress tests: a phone stand, an ice cube tray, a headphone hook, a spanner, a planter, a door handle
== A phone stand (plane at angle, offset edge, through-all cut) ==

A phone stand built by code and by hand on a phone, the two matching:
a base, a back leaning at 75 degrees on a plane through its top edge, a
lip raised from an Offset Edge line, a cable hole cut through all, the
lip chamfered and the back's top rounded. What it turned up:

- A join that only touches along an edge (the back stood on the base's
  edge) made two solids meeting at an edge and was called sound. Health
  now counts pinched edges (more than two faces round them) and such a
  body is not healthy; the join says "only touches the body along an
  edge" and to let them overlap.
- A rectangle's height typed 93 came out 92.999999999999 (the solver's
  float noise, shown, saved and built). Values a hair off a clean one
  are put on it when the constraints stay as well met.
- Cut with Through all on a sketch on a face went out into the air and
  cut nothing: with no way picked yet, a through-all cut now goes into
  the body (Flip direction still turns it).
- Once a chamfer's preview showed, its edge was gone from the view, so
  tapping it again could not un-pick it: a tap near a picked edge's own
  line now drops it.

== An ice cube tray (draft, two-way pattern, shell, lettering) ==

An ice cube tray built by code and by hand on a phone, the two the same:
one pocket pulled down with a 6 degree draft as a body of its own,
patterned four along and two across, all eight subtracted from the
block, the block shelled from below (walls 2 thick round every pocket),
the rim rounded, ICE typed on the front and raised. What it turned up:

- Subtract's clearance box sat between the first two bodies: over the
  middle of the tray, on the pockets still to be tapped, and a tap meant
  for one opened its number pad over half the tray. It moves down the
  screen, clear of the bodies.
- With many bodies taken away, the signs (to swap the bodies round)
  were pushed aside onto bodies still to be tapped, and a tap meant for
  a pocket swapped the tray out. Past two, only the first keeps a sign.
- A pattern running, its first body picked, the view's taps go to its
  direction: four pockets to pattern across could only be had by
  starting again from Items. Now a body tapped in Items joins the
  running pattern (or leaves it).

== A headphone hook (symmetric, up to a plane, thread) ==

A headphone hook built by code and by hand on a phone, the two the
same to the face: a C clamp pulled Symmetric, an arm pulled Up to a
plane 50 out, a lip raised and rounded, a screw hole cut up through the
jaw and threaded M7. What it turned up:

- With Symmetric on, the box still read Distance, and 30 typed for a
  clamp 30 wide made it 30 each way, 60 in all. The box reads "Each
  side" and the hint says to type half the whole width.
- Up to a plane with the distance box left at 0: Done did nothing.
  The distance only has to be set when the ends are a distance.
- Fillet: tapping a picked edge to drop it took the picked edge even
  when the tap was on another edge nearer; now the nearer real edge
  wins.
- The radius dot catches taps for some 40 px round it, so an edge
  near it could not be picked or dropped. A tap on it that doesn't
  move, away from the dot itself, now goes to the model.

== A spanner (pieces pulled up at once, polygon, corner rounds) ==

A spanner built by code and by hand on a phone, the two the same to the
face: two circles and a bar pulled up 6 as one, an open jaw cut through
all, a hexagon 10 across flats cut through the ring end, the inside
corners rounded and the hexagon chamfered. What it turned up:

- New project kept the last project's view: left looking up from below,
  a tap meant for the top picked the bottom face. A new project starts
  from the default view.
- Through all with Auto, on a sketch on a body's face, went up off the
  face: a tower 354 high was added instead of the jaw cut. Auto on a
  body's face now goes into it, as a cut does.
- The Polygon's Values only took a radius to a corner: a hex 10 across
  its flats meant typing 5.7735. It takes Across flats too, kept as the
  radius dimension that makes it.

== A planter (loft square to round, shell, circular sketch pattern) ==

A planter built by code and by hand on a phone, the two the same to the
face: lofted from a square foot to a round mouth on an Offset Plane,
shelled open at the mouth, four drain holes (one circle, patterned round
in the sketch) cut through the floor, the rim rounded. What it turned up:

- The loft leaves the mouth's circle in five pieces, where the square's
  corners run up to it. A tap on the rim picked one quarter, and its
  fillet could not be made ("would damage the body"). A tap on a piece
  of a circle now takes the whole circle, and a tap drops it whole.

== A door handle (sweep along line, arc, line; sketch mirror; countersinks) ==

A lever door handle built by code and by hand on a phone, the two the
same to the face: a plate with rounded corners, two screw holes (one
circle mirrored in the sketch) cut through and countersunk, a round bar
swept up from the plate along a line, a centre arc and a line, its end
rounded. What it turned up:

- Mirror (Copy) applied on the first tap on the axis, but kept the shape
  picked and its card still read "Apply (1)", so a second tap made the
  same copy again, on top of the first. A mirrored copy now lets go of
  the shape, and a copy exactly on a curve already there is not made
  ("Those copies are there already").

Health: a body where more than two faces meet on one edge (pieces
touching only along a line) is no longer called clean. The drill's
housing halves have one such seam each, where the grip runs into the
wall and the inside and outside meet; the drill test allows that one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:54:00 +02:00
superGeometry bb97faba29 Stress test: a mouse of Fill surfaces (fill, fill to plane, freeform face)
A computer mouse built by code and by hand on a phone-sized screen, the
two the same to the mm3 (tests/fillmouse.test.ts,
tests/fixtures/fillmouse-hand.json), with the two tools no build had used:
its top a surface stretched over the outline and two arches (Fill), filled
down to the desk (Fill to Plane), a thumb rest pressed into the side
(Freeform Face, points moved by typed values), a slot cut for the wheel,
the wheel in it, the slot's curved rim rounded.

What it found, fixed:
- A plane of the project's own couldn't be tapped to sketch on: the
  origin planes, drawn over everything, always won (a plane 18 up, tapped
  from the top, gave the floor). Now it wins where it's tapped; a sketch's
  shape on it still comes first, to carry on with it. The toast names it.
- A line typed 80 long at 90 degrees ended at x -29.999999999999996, and
  the arc drawn from its end was off as much: square angles are exact now.
- A tool's own preview could be tapped: Fill's last boundary curve, once
  the loop closed, took the new surface's edge instead.
- Waiting for an edge (Fillet, Chamfer), a corner within a finger's reach
  won over the edge under the finger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 19:27:22 +02:00
superGeometry a5b544dd16 Stress test: a mug (revolve, shell, move face, project, connect, wrap)
A mug built by code and by hand on a phone-sized screen, the two the same
to the mm3 (tests/mug.test.ts, tests/fixtures/mug-hand.json): a profile
revolved and shelled open at the top, the floor raised, two pads projected
onto the side, a handle bridged between them along a drawn curve, and a
word wrapped round the far side and raised.

What it found, fixed:
- Move Face next to a tapered face (the mug's foot) failed: the cone's
  region was left open. Cones are now worked out from the face itself.
- Connect between two patches on a round face: the ends were paired from
  different corners (a twisted bridge) and their outlines weren't flat (an
  open tube was accepted). The far end's outline is now lined up with the
  near one as carried along the curve, flat sections are tried, and open
  results are refused. Own outlines are still tried first, so a square to
  an L joins as before.
- A pad projected across the seam of the round face comes in two halves:
  a tap on one half now bridges from the whole pad, its outline sampled
  evenly so the handle doesn't bulge.
- Wrap & Emboss started the word where its first letter was, not centred
  where the plane touches the face, and a sketch on a plane facing in came
  out mirrored. Both fixed.
- Project as Edge and Wrap & Emboss from the menu took one shape only:
  they have a Shapes slot now, with All (letters with their holes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 18:45:56 +02:00
superGeometry e946d020cf Freeform on a phone: Pick in a box; a sneaker built of freeforms
A sneaker made of freeforms, by code and then by hand on a phone-sized
screen (tests/shoe.test.ts; the hand build is tests/fixtures/shoe-hand.json):
a foam sole with a toe spring and a higher heel, a hollow upper open at
the collar standing in it, a tongue, three lace bars (one and a pattern of
it), the upper cut back where it sits in the sole (Subtract, the sole
kept), tread grooves cut into the bottom. Every part comes out the same as
by code, the cages point for point.

- Touch: a freeform's slice of points (25 on the end of a box) could only
  be picked a tap at a time, and the points behind the shape not at all; a
  mouse draws a box round them, a finger only turned the view. The card
  has Pick in a box on touch screens: a finger then draws the box, the
  points behind picked too (a whole slice from a side view), added to what
  is picked like a tap. Two fingers still pan and zoom; it stays on for
  the next shape until switched off
- New step names: a box after two surfaces was "Freeform 04" ("Freeform
  surface 01" counted as one of the "Freeform"s); now "Freeform 02"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:52:14 +02:00
superGeometry d55b4193f4 Subtract / Intersect: tap a + or - sign to swap the bodies round
Picked in the wrong order, one tap fixes it: a "-" body becomes the one
changed and the one that was takes its place; the "+" swaps with the
first of the others. Signs that would sit on each other (a peg through
a plate) go side by side, and clear of the clearance box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:29:31 +02:00
superGeometry 9c6818592c Subtract: a clearance, cut from the body, the others or both
Subtract gets a Clearance (typed in a value box on the model, with a
drop-down for which bodies give way) for parts that must fit or move:
- from the body: a hole the clearance bigger all round than its peg;
- from the others: each is cut by the body grown by the clearance;
- from both/all: half each, in turn - a peg through a plate becomes a
  hole r + gap/2 and a pin r - gap/2, every pair the gap apart.
Bodies are grown a piece at a time (the kernel's offset of a body in two
pieces fails), and only bodies as they were are grown or brought in.
tests/clearance.test.ts: exact volumes and gaps, 32 checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:00:08 +02:00
superGeometry 9be1e8b074 Stress test: a print-in-place planetary gearbox
A housing with a 48-tooth internal ring gear, a 12-tooth sun on a shaft with
a flat, three 18-tooth planets on the carrier's pins, a carrier with an output
shaft and hex socket, a lid on M3 threads. Checked: each gear holds what its
involute should, every pair of moving parts is clear by the 0.25 print gap and
every mesh by its backlash (0.02 to 0.15), assembled and turned as it runs.
Then every gear made again herringbone (twisted sweeps, the ring cut the same
way) and checked again, and a ball bearing pressed 0.05 into the lid, its ten
balls 0.2 clear in their grooves. 260 checks, all passed: no engine fault found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:52:28 +02:00
superGeometry 9ca93f03e5 Measure: right volumes and areas on extruded and revolved splines and their shells
The engine's measure integrated a face swept from a spline in one piece, blind
to the spline's own pieces: an extruded closed spline read 316 000 mm3 for
284 800 (11 % over), its side 1.7 % over, a revolved spline 1.2 %, the shelled
mouse 21 489 for 22 249. Bodies and faces with swept faces (extrusion,
revolution, offset) are now integrated in ocFree piece by piece (Green's
theorem round each face's outline, cut at the surface's joints and where the
outline crosses them), giving volume, area and centres to a millionth. A shell
measures in about 1 s (the kernel's own exact measure took 11 s), and each
shape is measured once.

Mouse test: the block equals its end x 45 and its side the outline x 45, the
shell agrees with a mesh, the button lines' change read straight off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:56:42 +02:00
superGeometry 60b0c5e287 Shell: cuts across a curved shell's inner walls work (loose offset edges made again)
A slot right across a shelled mouse's top failed at every tolerance
("the faces don't meet up"). Two causes:

- The kernel's offset gave the edge where two smooth offset faces meet
  (the inner top and the inner rim round) a 3D curve 0.2 mm off, its
  tolerance 0.14 mm, while its curves on both faces were exact. Any cut
  across it broke the faces. tightenEdges (used by offsetSolid, so by
  Shell) makes each such edge again from its exact curve on each face,
  rebuilds those faces and sews them back; kept only if it is one sound
  solid of the same volume.
- unify (merging faces on one surface after a boolean) joined the two
  pieces of a closed round either side of its seam into a broken face.
  A merge that breaks a sound shape now keeps the pieces.

That second change showed a thread check letting a broken groove through:
on a whole round face, a thread must take all its grooves hold (the
"what the groove overlaps" fallback is for faces that aren't whole).

The mouse test now cuts the line across; the cut's change is checked by
mesh (the engine's volume measure is off on offset faces).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:04:14 +02:00
superGeometry a41684a5ed Stress test (a computer mouse): faster shell checks, quick no on broken cuts, a missed cut says so
- tests/mouse.test.ts: a spline outline cut by a spline side profile,
  rim and foot rounded, shelled from below, button slots, a scroll wheel
  with 24 patterned knurls joined, thumb holes, a base plate.
- Shell: the wall checks test points inside the body and the shell,
  instead of booleans with little cubes (the mouse's shell: 51 s -> 17 s).
- Repair: a "fix" measuring below nothing or more than its box is
  turned down at once, without meshing it (a failing cut across the
  shelled mouse: 186 s -> 10 s before it said no).
- A Cut that takes nothing away (drawn on the wrong side) leaves a
  note on its step; before, nothing happened and nothing was said.

Known limit, kept in the test: a cut that splits the shell's inner
(offset) faces in two leaves them invalid at every tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:07:20 +02:00
superGeometry 6af3b1727d More: Support holds only MakerWorld
Buy Me a Coffee and Stripe are gone from the menu, the list behind it and
their logos; the button is just "Support".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:56:17 +02:00
superGeometry d5e2d0655e Wheel: every tool keeps one place, whatever is picked
A group's ring used to place only the tools that fit the pick, most used
first, so the same tool sat somewhere else with an edge picked than with
nothing picked. Now each group has its places (SLOTS, most used first): a
tool that doesn't fit the pick stays in its place, greyed, and a tap says
why. A picked thing's tool under another name (Pattern - Linear, Move/Rotate
Body, Delete Body) takes the place of the one it is.

Construct shows Offset Plane, Midplane, Through 3 Points, Parallel and
Through Edge at Angle straight away (Plane still opens all of them);
Transform shows Pattern's Linear and Circular as places of their own. In
the top place Measure, Section View and Variables are where they are with
or without a pick. The sketch wheel's tools keep their places the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 14:29:08 +02:00
superGeometry 7ac0242515 Wheel: every name stays inside its piece
A name gets the width its piece really has where it sits (measured across
the slice at the name's height, clear of the hairlines), breaks at spaces
onto two lines (three for a three-word name), and only then goes a size
smaller. The ring's own pieces wrap too; the mouse wheel is a little wider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:50:13 +02:00
superGeometry 2e2a92c02b Wheels: a group turns the ring into its tools, in place; most used first
A tap on a group (or a press slid out across it) no longer fans its tools
out beside the ring: the same ring, in the same place, becomes the group's
tools and the middle becomes Back (Esc too). The most used tool takes the
group's own place, under the finger, the next ones either side, on round.
Past eight, the rest sit in a band round the outside. Every wheel works
this way: tools, sketch, Settings, Options.

The model's ring has eight fixed places: Create up, Combine, Modify right,
Construct, Transform down, Freeform, Sketch left, More. More holds what
the view offers, Insert and BIM; the recent tools are gone from it.
Move/Rotate, Translate and Rotate Around Axis are Transform's own tools.
The sketch's ring: Draw up, Modify right, Transform left, Exit down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:03:04 +02:00
superGeometry 655ba0e09d Wheels: values open their box, real icons, fans symmetric about their group
- A value on the Options wheel is one tap: its box comes up to type it in,
  with the numpad where that's on - no more +1 / +10 / -1 / -10 steps. One
  value: the Values sector is it.
- Switches and choices show what they are (grid, axes, units as text,
  through all, up to, symmetric, link, select all...), not a pointer, a
  tick or a cross: on or off shows by the highlight.
- A group's tools fan out symmetric about it: an odd number of rays has the
  first straight out, an even number the first two either side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:41:28 +02:00
superGeometry 5f756942dc Top bar: Items lights while its panel is open, like History
Both follow the panels' own open state, so opening one panel (which closes
the other on a phone) leaves the right one lit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:39:21 +02:00
superGeometry 6a6ef8753e Top bar History, cube double tap fits, Snapshot on the wheel; no autofill bar in any typing box
- History is in the top bar (lit while open). On a phone or tablet Enter AR
  goes under More. A headset keeps Enter VR in the top bar.
- No Fit button: a double tap (or double-click) on the view cube fits
  everything, keeping the view the cube had before the first tap.
- Snapshot is on the Settings wheel. With the wheel there is no right column.
- Every keyboard typing box is editable text now (ui/textField.ts): dialogs,
  the Text tool, colour code, grid size, command search, feedback, the BIM
  boxes. A phone shows no autofill bar over them, and a finger never gets the
  whole text selected (that brought up the Cut / Copy bar). The Text tool
  shows the last text as its placeholder on touch: Enter keeps it, typing
  starts afresh.
- Number boxes with the numpad: on touch the value to type over is lit, not
  selected; the first key still replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:34:52 +02:00
superGeometry 150dfa2550 Project name: no autofill bar or Cut / Copy bar on a phone
The name was an input: a phone's browser hung its autofill bar (passwords,
cards, addresses) over the screen, and selecting the whole name on focus
brought up the Cut / Copy / Select all bar. It is editable text now (no
autofill), and only a mouse selects the whole name; a finger gets the caret
where it tapped. Enter / leaving renames, Esc puts it back, a paste comes in
as one line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:36:25 +02:00
superGeometry 7c0279a5af Sketch: a pen gets the line's length box once the line is placed
A pen (an iPad's pencil) hovers, and the box of the line just placed went
the moment it moved on. It now stays to type in while the pen hovers (the
next line's moving length hides), and shows for a pen with the numpad off
too. The next tap keeps the typed length as a dimension, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:45:41 +02:00
superGeometry 959e28f2be Wheel: fixes from a phone hand test
- Options wheel: buttons (the sketch planes too) are sectors of their own, and
  with nothing else on the ring each value gets its own sector, not one lone
  Values group.
- Text tool: its input shows while the Options wheel is up (it was hidden
  with the card).
- Hints say "on the Options wheel" instead of "in the card".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:30:33 +02:00
superGeometry fcd4c95bbb Wheel: a freeform shape's own wheel; constraints on the Options wheel
Shaping a freeform shape brings up its own wheel, as a sketch does:
what its card offers, by what it does, each group in the same place
every time and greyed (saying why) while nothing picked fits it -
Done at the top; Shape (extrude, inset, extend, edge loop, bridge,
add detail), Holes (fill, bridge, connect, delete faces), Move (move,
turn, scale), Symmetry, Solid (thickness side, fill to a plane); Select
all and Cancel a tap each. The Options wheel beside it keeps only the
values to type.

The sketch's wheel has no Constrain group again: a selection's
constraints are on the Options wheel, the switches under More ›
Constraints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 22:04:40 +02:00
superGeometry 39c0d3fc7a Wheel: tools grouped by what they do, families in one cell
The 19 tools under Tools are split by what they're for, each group about
one or two short rays, every group in the same place each time:
- Create: Extrude, Revolve, Sweep, Loft.
- Modify: Fillet, Chamfer, Shell, Offset Face, Offset Edge, Thread,
  Wrap & Emboss, and Fix › Fill, Fill to Plane, Repair Body.
- Combine: Union, Subtract, Intersect, Split Body.
- Transform: Move › Move/Rotate, Translate, Rotate Around Axis; Scale,
  Mirror, Pattern.
- Construct: Plane, Axis, and Project as Edge.
- Freeform as it was; Insert and BIM under More.
View also shows the last three tools run from the wheel. The sketch's
wheel gets a Constrain group: the constraints that fit what's selected,
one tap each, then Auto constrain, Show constraints and Stays put.
A picked thing's tools go in the new groups the same way. Help says
where everything is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:20:26 +02:00
superGeometry 676a2bd1d2 More: no Tool wheel switch, the wheel is always on
The wheel is the only way to the tools now, so More no longer offers to
turn it off. Anyone who had turned it off has it back on. Help says how
the tools, the Settings wheel and the Options wheel are reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 20:41:42 +02:00
superGeometry 4a68114543 Wheel: the other groups grey out while a group's tools are out
With a group's tools out, the rest of the ring greys out, and the pointer
crossing one of those groups on its way to a tool neither lights it nor
swaps the fan for it (before, resting on it for a moment did). A tap on
a greyed group still opens it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 20:39:20 +02:00
superGeometry 62589ebd85 Wheel: no tap flash, what's on or open stands out
- No blue square over the whole wheel on each tap: a phone's browser lit
  up the wheel's drawing as a tapped thing; the wheel turns that off.
- What is on (the tool in use, a setting that's on) gets a blue fill and
  an accent outline, its icon brighter; what is open (the group tapped,
  the tool whose row is out) a lighter blue, a pale outline, its name
  white and bold. Both are drawn over their neighbours, outlines whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 20:34:33 +02:00
superGeometry 1b4ee841f9 Phones with the wheel: undo/redo and the guide text lower
The tool strip along the bottom is gone with the wheel, so on a phone:
- upright: undo/redo go down to the bottom edge, the guide text just
  above them, and the Options and Settings icons on that same row at
  the right, side by side;
- sideways: the guide text moves from the top of the view down to the
  bottom row, between undo/redo and the icons (between undo/redo and
  History when that is open); the icons come down level with undo/redo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 20:19:58 +02:00
superGeometry 9e1c181905 Wheel: fans as rays, values typed on the Options wheel
- A group's tools open as rays from the wheel, the first one next to the
  group tapped (up to four out along each ray, rays to either side);
  where they would not fit, the arc as before. Cascade rows stay arcs.
- Options wheel: a value's steps end in "Type…", a small box on the
  wheel for the exact value (expressions too). Enter or tapping away
  sets it, Esc leaves it as it was; the fan stays open. No window.
- A value set from the wheel is kept in the tool's window too, so the
  next step starts from it.
- A screen resize puts an open fan away (it reopens where it fits),
  except while a value is typed (a phone's keyboard is a resize).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 19:39:37 +02:00
superGeometry 4001b05c0e Options wheel: values set on the wheel, no window
Each number or slider of the tool's window is a cell under Values, its
value as its second line; it fans out steps (-10, -1, +1, +10 in the
unit shown; a slider by a little or more) set right there. Values no
longer brings the window back. Not yet tried in the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:59:42 +02:00
superGeometry 3a8f5bdb56 Options wheel: a tool's window as a wheel, behind an icon of its own
- While a tool has a window with something to set, a third wheel is on
  the screen, folded to an icon of its own (three sliders) above the
  Settings cog. A tap unfolds it; it is dragged and folded like the others.
- Its ring is what the window holds: each choice fans out its options, a
  switch or a slot is one tap, chips fan out, a primary button is a place
  of its own, the window's other buttons and actions are under More, then
  Values, Cancel and Done. What is set from it is set right there and the
  wheel shows it set.
- With it up, the tool's window stays out of sight; Values brings it back
  for typing numbers or dragging sliders, and puts it away again. The
  value box on the model works as before.
- The two icons keep their places by their folded size; unfolded, a wheel
  comes in from the screen's edges as far as it must.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:47:20 +02:00
superGeometry 252de0e420 Settings wheel: its own wheel, always on the screen, set from the wheel itself
- Settings leave the tool wheel (View and the sketch's More) for a second
  wheel that is always on the screen while the wheel is on: folded to its
  cog at the bottom right, a tap unfolds it, it is dragged by its middle
  like the other and keeps its own place.
- Its ring is Snap to, Units, Appearance, Shaders and NumPad. Each list
  fans out its switches and choices (made from the right column's own
  lists), lit while on: a tap sets one and the fan stays, showing it set.
  What only a slider or a typed value sets is under More…, in the list's
  window.
- The tool wheel no longer shows a handle while another tool is open.
- Both wheels keep their places in the one store without overwriting each
  other's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:41:58 +02:00
superGeometry 9f814af551 Tool wheel: dragged by a finger on a phone, it keeps following
On a phone the browser took a finger dragging the wheel's middle over as a
page pan after a few millimetres and cancelled it, so the wheel stopped.
The wheel and its drawings now say touches on them are never a pan, and a
finger pressed on the wheel has its touch moves kept from the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:24:50 +02:00
superGeometry 136bef9419 Tool wheel: on by default, kinds open in a cascade, Settings as windows
- The wheel is how the app is worked now: on for everyone (settings v5);
  More - Tool wheel still turns it off.
- A tool with kinds of its own (Settings, Plane, Colour) opens them in a
  further row outside its fan, centred on it, instead of swapping the fan
  away. Resting on another tool of that row closes it; a tap on the opened
  tool again does too. Where the screen is too small (a phone upright) the
  row turns round the wheel to where it fits.
- Snap to, Units, Appearance and Shaders from the wheel open as a window
  with a title bar to drag it by and a close button. It stays open while
  the model is worked on (Esc closes it too) and opens where it was last
  dragged.
- The welcome window lists only the ways to support that have a link
  (Buy Me a Coffee and Stripe are out for now).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 18:23:01 +02:00
superGeometry d48ca428bc Build the site again (the last build failed on the host's side)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:35:43 +02:00
superGeometry 63352c1916 Tool wheel: Settings in reach while a tool is open
With the wheel on, the right column keeps only Fit, Screenshot and
History, and Settings (Snap to, Units, Appearance, Shaders, NumPad) are
on the wheel - which wasn't up while a tool with a window of its own was
open (Extrude, Fillet, Shell, Measure…): the numpad or X-Ray couldn't be
switched until the tool was done.

While such a tool is open the wheel is now there as its handle alone,
folded, a cog on it. A tap unfolds it: the five Settings as a ring, a
tap each (a list opens beside it, NumPad is switched), and it folds away
again. It stands in for nothing there: the tool's own column, bar and
window stay. It sits where the model's wheel is kept if that is kept
somewhere, else at the left beside Items - and beside the tool's own
column where that has one (Extrude's other tools, Exit Measure); it can
be dragged and remembers its place. The tool closed, the wheel is as it
was. The same while a new sketch asks for its plane.

A press on the model that closes a Settings list is spent on that. It
went on to the model before: with a tool open, a tap on empty space is
the tool's Done, so closing the list finished the tool.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 17:11:18 +02:00
superGeometry 5204f9d6b8 Tool wheel: Settings on it, less beside it, and fans that fit a phone
With the wheel on, what it holds is no longer shown twice:

- The bar at the bottom left (Section View, Measure, Variables, Isolate;
  in a sketch the line type and Normal to Sketch) steps aside with the
  column: its tools are in View, or under More in a sketch.
- View has Section View, Measure, Variables and Settings. Zoom to Fit
  and Select Through are out of it (Fit is in the right column, Select
  Through on Ctrl+Shift+S and in the right-click menu).
- Settings opens Snap to, Units, Appearance, Shaders and NumPad: the
  right column's own lists, opened by the wheel where they were asked
  for (they close at a press elsewhere, or Esc); NumPad is a switch. In
  a sketch, More has Settings too, and Constraints on or off.
- The right column keeps Fit, Screenshot and History.

With the wheel off the bar and the right column are as they were.

A right-click is the menu again, not the wheel: the wheel comes up at a
click on the model or on an empty spot, and at Q. A finger or pen held
still (they have no right button) still brings it up under it.

On a phone:

- A finger's wheel comes up at the tap, the ring kept whole on the
  screen, and slides when a fan needs the room. (A mouse's opens where
  every fan fits, so it never moves under the pointer.)
- A fan is sized to the screen: each row is as much of the ring as fits
  at its distance, the outer rows narrower, with more rows where a half
  ring is too tall. On a phone on its side the nineteen main tools ran
  off the top and bottom of the screen; they are three rows now, all of
  them on it.

Switching the wheel on or off inside a sketch put the model's bottom bar
(Section View, Measure, Variables) in place of the sketch's: only the
selection tool is told to show its tools again now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 16:58:29 +02:00
superGeometry 409f0dfd9e Tool wheel: moved by its middle and kept there; a wheel for the sketch
The middle of the wheel is a handle now (a move mark in place of the
cross). Dragged, the wheel goes along and is kept where it is let go: it
then stays up there instead of coming up at the pointer, showing what is
picked (or the main tools with nothing picked), and a press on the model
no longer puts it away. A tap on the middle folds it to just the handle,
another unfolds it; two taps let it go, and it comes up at the pointer
again. Q folds and unfolds it, a right-click unfolds it. While a tool is
open it steps aside and is back after. Its place is remembered per kind
of screen, as the tool card's is. Not dragged, the wheel is as it was: up
at the pointer, a tap on the middle closes it.

In a sketch the wheel is the sketch's, always kept: Exit at the top;
Draw (Line, Arc, Spline, Rectangle, Circle, Ellipse, Polygon, Text),
Modify (Fillet, Trim, Extend, Split, Align, Offset Edge, Project) and
Transform (Move/Rotate, Rotate About, Scale, Mirror, Pattern) down the
right, each fanning out; More (Other plane, the line type, Normal to
Sketch); Delete and Select on the left, a tap each. The tool in use is
lit, and its group marked. As in the column, a tool with kinds starts
with the kind used last, and shows its kinds when tapped while in use.
The sketch's column steps aside for it; while the sketch asks for its
plane the column (Exit Sketch) shows and the wheel does not. It starts
where the column is, beside Items, and has a place of its own once
dragged; on a phone it starts folded.

A kept wheel's fan goes away a moment after the pointer leaves it, on Esc
and on a press elsewhere; a finger's press on the model is spent on
that, so closing a fan never draws a point. The ring is drawn again only
when what it shows has changed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 16:34:50 +02:00
superGeometry be7a232a3b Tool wheel: the tools in a ring round the pointer, beside the column
An experiment, off unless switched on (More - Tool wheel; a setting kept
on the device): with it on, a tap on the model brings the tools up in a
ring round the pointer in place of the column on the left. The column,
the right-click menu and a tapped shape's Extrude are untouched while it
is off. The UI as it was is tagged ui-before-wheel.

The ring has eight places that never move: what is picked at the top
(Deselect, Delete, Colour, Reveal in Items, and the view's Section View,
Measure, Variables, Isolate, Zoom to Fit, Select Through), then Sketch,
Freeform, Insert, Construct, Transform, Tools and BIM clockwise, as the
column lists them. Pointing at a group fans its tools out as a half ring
on that side, in a second row when one is full; a tap on a tool runs it.
A tool with kinds of its own (Plane, Axis, Colour, Scale) opens them in
place of the fan, and the group brings its own list back.

It holds what the column and the bottom bar hold, by the same rule: the
same ToolItems, only those that can be used now. With something picked
each of its tools goes to the group the main tool of that name is in; a
group with nothing for the pick is dimmed and says why. The keys, the
search box and sg.actions() go on reading the same lists.

How it is brought up and put away:
- A tap on a face, edge, body, corner, shape, plane or image picks it as
  ever and the wheel comes up for the pick; on an empty spot with nothing
  picked, the main tools. A shape tapped stays picked (its arrow ready,
  a number typed still extrudes); tapped twice, its sketch opens.
- Shift or Ctrl add to the pick without it. Right-click, or Q, brings it
  up for what is picked; a finger held still does too, and can slide to
  a group, on to a tool, and lift there.
- The middle, Esc, or a press anywhere else closes it; what is picked
  stays picked (a press on the model goes on to the model: a tap picks,
  a drag turns the view). The second tap of a double tap passes through
  it, so the whole body is still two taps.
- It opens whole on the screen with any of its fans out, so it does not
  move under the pointer; on a phone, too narrow for that, it slides to
  bring a fan on, and a tap acts on what it came down on.

Nothing is measured or changed on the page while the pointer stays on
the same piece: what it is over is worked out from its distance and
direction from the middle.

sg.wheel() says where the groups and the fanned-out tools are on the
page; sg.wheelTools() lists every tool the wheel offers now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 15:53:07 +02:00
superGeometry a448d87ea5 Shell: cut-outs between one wall and two apart
A pocket 1.7 mm from a hole could be shelled with 0.5 mm walls and with
2.5 mm walls, but not with 1 or 1.5: OpenCascade's offset of the whole body
gives up where the offsets of two cut-outs run into each other, and the
step said the walls don't fit. One more way is tried last: the hollow is
put together from what is cut out of the body - the box round it brought
in by the wall, less each lump the box holds besides the body (the hole's
room, the pocket's) grown by the wall on its own. The same shape as the
body offset inward; the lumps just overlap. It is held to the wall asked
for: nowhere nearer the body's skin than that.

Tests: the hole and the pocket at 1 and 1.5 (volumes worked out by hand,
the tube and the pocket's walls one lump), two pockets 1.5 apart, a row of
hole, hole, pocket.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:34:02 +02:00
superGeometry 5088a5c9fd A moved body's faces are still the faces of the steps that made them
A body moved, turned, mirrored or copied in a pattern had its faces put
down to the Move (or, by chance of where it landed, to a mix of the Move
and the step that made them, with no word of which of that step's faces
each was). A pick on it then knew only where its face had been: make the
block wider and a fillet on the moved block's corner rounded another
corner, with no word; put a Move in before a fillet and the fillet's edges
were "gone".

Each face of a moved body now keeps its step, and where its body has been
moved to since: asked which of its step's faces it is, it is taken back to
where the step made it. So a pick follows the body through earlier
changes, a Move put in before a step leaves it its picks, and a face a
Freeform Face step made can be reshaped after its body was moved. Later
steps on the moved body carry this on. Picks saved before name the Move:
that answer is kept beside (the page is told too, for "pick it again" and
for an edge a sketch follows).

Tests: gridmoved (22).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:22:37 +02:00
superGeometry 777720540b Flat faces with a great many holes are meshed by the engine itself
OpenCascade's mesher takes time and memory by the square of the holes in
one face: a plate with 400 holes took 5 s and 700 MB to show, and half a
minute and 2.9 GB to send out as STL. A flat face with 30 outlines or more
is now cut into triangles here (earcut), between the very points its
neighbours' meshes have along its edges, so the mesh stays closed. The
same plate: shown in half a second less of meshing with no memory to speak
of, an edit on it twice as fast, out as STL in 4 s and 163 MB. 900 holes:
1.4 s (13 s and 1.3 GB before).

Earcut leaves out points that lie in line with their neighbours (rows of
square holes lost corners): no three points are in line for it, and the
triangles without area that makes are taken out again. The body's edge
lines come from the same points. A point wanted on such a face (a push, a
shell's checks) is found the same way.

Tests: plates with 144 round, 144 square and 400 round holes - shown,
closed, of the part's volume, out as STL closed, a face pushed, a side pulled.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:10:58 +02:00
superGeometry 3e00e60b37 A shown body no longer keeps its mesh in the kernel
The view's triangles were left on a body once it was shown, and stayed for
as long as the kernel held the body - which, for a body one of its tools
made, is for good. They are taken off once the view has them: every edit
works on a copy of the body, which has none, so nothing read them again.
Dragging a fillet on a 44-face plate 400 times: 811 MB, now 496 MB; a shell
on it 100 times: 595 MB, now 496 MB. No slower.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 13:06:36 +02:00
superGeometry 337c802689 Engine review: memory given back, meshes come in as solids, sweeps that say why
Memory. The kernel build frees nothing when most of its things are deleted
(one do-nothing function stands in for their destructors): a deleted handle
still counted as a user of its shape, so no body the engine made was ever
freed, and each tool kept what it had worked out. Now each is told to let go
before it is deleted (release.ts): shape handles emptied, explorers pointed
at nothing, booleans cleared and given a last tiny job so they drop their
bodies. The validity check, which left over half a megabyte behind per check
of a 35-face part, is pointed at nothing before it goes. A body's copy is
written out and read back (the kernel's copier keeps both bodies for good).
Rebuilding a hole 1500 times took the engine from 100 MB to 595 MB, now to
199 MB; a face pushed on a 44-face plate 400 times, 1871 MB, now 811 MB; a
shell on it 200 times broke the engine, now it doesn't.

Meshing. A body is meshed a few hundred faces at a time (meshing.ts): the
kernel's mesher kept working notes on every face and edge at once - a body
of 4 500 faces took 1.3 GB, one of 40 000 the 4 GB a browser allows. Same
triangles, same order. STL is written from that mesh, of a copy of the body
(the print mesh no longer stays on the model). A face's own triangles are
made for that face alone, not by meshing its whole body.

STL and 3MF meshes in. A closed mesh comes in as one solid, its flat
triangles merged (the reader hands back loose triangles; every file came in
as loose faces until Repaired, a 12-triangle block too). A binary file is
told from a text one by its length (a blank heading and round sizes made the
reader take it for text: a 10 mm cube out of a 3MF couldn't be read). Up to
250 000 triangles; more is refused at once with the count (it used to run
the engine out of memory). A broken-down engine is no longer taken for an
unreadable file.

Sweep. Facing the same way along a path that runs in the profile's own
plane never returned; a profile that changes size or turns left a sweep in
pieces at a sharp corner: both refused in words. Joins and cuts made by a
step go through one checked boolean. An unknown mode is a damaged step, not
a step that does nothing.

Tests: gridloft (340), gridio (51: up to a face or plane, STEP and STL out
and back, meshes in, split by a body, copies, memory over 400 rebuilds).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 12:59:39 +02:00
superGeometry 835816fef1 Engine review: faces with holes, Shell, a join's stray edge; grid tests
Each operation tried over a grid of shapes, places and sizes, every
result held to a volume worked out by hand. What that found:

- A face with a hole in it pulled out: the hole was closed with a lid
  (the slab added took the face's outer outline only). Pushed in with a
  boss standing on it: refused, "would break the body into pieces".
  The slab now stops at each hole's own walls, and such a face goes the
  exact way first (a round hole stays one true cylinder).
- Shell, where two faces are closer together than two walls (a pocket
  1.7 mm from a hole, a hole 2 mm from a side): the pocket's walls were
  left out without a word (the pocket a window into the hollow), the
  tube round a hole in the opened face ended a wall and a half short of
  the opening, and a broken shell came out "repaired" a sixth too
  light. Shell now takes a result only if it is sound, has a wall
  behind every face it kept and nothing left deep inside, trying each
  way in turn; the opening is cut from the hollow's own floor. What
  still can't be built says why (walls would run into each other; a
  pocket in the opened face would be left loose).
- A join where an edge of one body lay in a face of the other left that
  edge lying across the face, bounding nothing: taken for a gap,
  "would tear the body open". Such edges are taken out of every
  boolean's result.

Tests: grid.ts and gridbooleans (65), gridextrude (152), gridfaces
(122), gridfillet (126), gridshapes (98), gridshell (48), gridsizes (90).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 00:20:23 +02:00
superGeometry f692ac9e92 Connect: a bridge never folds through itself
Where the faces are wide for how close they are (or far to the side of
each other), no curve of the plain kind turns gently enough, and the
bridge was swept along one anyway: its inner side ran backwards, a solid
through itself that no join or cut could use (a triangle to anything:
"the shapes only just overlap", or a body left torn).

- Two arcs of circles, the gentlest way from one face to the other, where
  the plain curve would fold.
- Where that folds too and the faces face each other: the outline slides
  along the curve instead of turning with it (two wide plates close
  together, one a little to the side).
- The fold check carries the outline along the curve (an arch's top went
  unchecked) and takes it as far between the two ends' as it has got.
- A sweep that went wrong without saying so (a bridge of 128 mm3 for one
  of 30 000) is no longer taken for the bridge.
- Tests: 50 pairs of outlines, joined, cut and as a body of its own -
  all sound (14 were, before this week).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 23:31:32 +02:00
superGeometry 3bc4c143ba Review fixes: Connect never leaves a damaged body, Add Another, Other plane
- Connect's result is checked like any other edit's: a join that tore the
  body open, or a cut that broke it, went through without a word.
- The bridge from the faces' very edges that can't be joined or cut: made
  the other way (a little inside the edges), on the bodies as they were.
- Create Variable from a field, then Add Another: the field gets its own
  variable, not the last one made; a bad name or value comes back as typed.
- Other plane: only while the sketch is empty, and a shape just started is
  dropped with the old plane.
- Tests: 50 pairs of outlines connected (join and cut); moved, mirrored and
  patterned bodies' edge lines.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 22:54:30 +02:00
superGeometry 23e7932c7d Faster rebuilds: no measuring or meshing the same shape twice
- A step's working copy of a body keeps the body's known volume: a big
  housing was measured again on every step (a quarter of a small cut).
- A cut that gives back one solid in a group: its volume, known already,
  isn't measured again.
- Each face of a shown body: middle and area from one measuring, not two.
- A body moved, turned, mirrored or patterned: its mesh is the original's,
  moved (a fan's rotated casing: 3 s of meshing to 12 ms; a pattern no
  longer meshes every copy).

A small cut on the drill's housing: 2.5 s to 1.5 s; the drill built from
nothing: 40 s to 32 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:03:12 +02:00
superGeometry 0646991d21 Connect: the bridge starts on the faces' edges
Joined or cut, each end was set back into its body and the outline began
changing into the other face's from there: where it left the face it was
already part way to it (a 20 x 30 top into a small round end left the top
as 19.5 x 28.9, inside its edges). Now it is swept face to face from the
faces' own outlines, and a straight plug of each outline goes back into
its body; where that can't be made one clean solid (a curved face, a
triangle into a square), the bridge is made as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:46:18 +02:00
superGeometry 52bbe0acb1 Window build test: Other plane, drawing ways kept, Add Another variable
- A new, empty sketch has Other plane in its tools: seen square-on it took
  the face in front, and the side plane was a trip to the Views menu away.
- The way each sketch tool draws (Rectangle: Center...) survives a reload.
- Create Variable has Add Another: makes it and opens a fresh one.
- Window test compares the hand build at W 900, H 1800 as typed on the
  model's tags in the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:33:47 +02:00
superGeometry 3f2f8811c3 Window build test: sketches follow their planes, points typed with variables
A parametric triple-glazed window for passive buildings, built by code
(tests/window.test.ts: 22 variables, every part's volume, no clashes,
glass cover, seal contact, ten variable sets) and by hand on a phone-sized
screen (tests/fixtures/window-hand.json). The hand build matches the code
build part for part, in volume and in place, after the variables change.

What the hand build found:
- A sketch drawn on a construction plane stayed where it was drawn when the
  plane's offset (or its variable) changed. It now follows the plane.
- A sketch used by a feature and shown again in Items couldn't be tapped
  through the bodies. It now draws on top, like a fresh one.
- A centre's X / Y typed with a variable ("Ws/2 - S/2") was worked out once
  and forgotten. The centre is now held there and follows the variable.
- A point's card had no X / Y. Typed, the point is locked there, with a
  variable kept.
- Editing a plane: From offered the plane itself and later planes, and
  named its base just "Plane". It now leaves those out and says "XZ plane",
  "Plane 02" or "Face of Body 1".
- After a shape's first tap the hint still said "Tap the centre". It now
  says what's next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:55:23 +02:00
superGeometry 5090030843 Loft: guide curves along the sides, connection points; Fill: continuity per edge
- Loft > Guide curves: any number of curves that each run through every
  profile; the sides follow them.
- Loft > Connections: a point on each profile in turn, and the loft joins
  them (a square's corner to a point on a circle, or a twist).
- Both work by resampling the profiles on one shared parametrisation, with
  sections added between profiles that the guides pull into place. Sharp
  corners stay sharp; smooth profiles stay smooth (C2).
- The old guide is now called Centre line.
- Fill: each body edge of the boundary can have its own continuity (G0,
  G1, G2); the setting for all stays as the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 11:32:01 +02:00
superGeometry 495e1cef79 Split Body: several planes and other bodies at once
- More planes: a body cut into slices in one step.
- Split with bodies: cut along other bodies' surfaces; those bodies stay as
  they are. A plane isn't needed when bodies are picked.
- Every piece becomes a body; the biggest keeps the original's place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:58:07 +02:00
superGeometry 7368d01b62 Files: GLB export, 3MF import, each body in a file of its own
- Export GLB: the bodies' meshes with smooth normals and their colours
  (see-through ones blended), named, Y up and in metres as glTF wants.
- Insert > File takes 3MF: the exact model packed in one of ours, else the
  file's meshes (components placed, its units turned into mm).
- Export each body separately: STL, STEP, 3MF or GLB, one file per body
  named after it, together in a ZIP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:45:49 +02:00
superGeometry 2c9fc953fd Items: Reveal in Items from the model
Right-click a body, face, edge, plane or sketch curve: Reveal in Items opens
the panel, unfolds the folder or heading it's under, scrolls to its row and
flashes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:42:59 +02:00
superGeometry 66acab2163 Drawings: intersection marks, dimensions snap to an even spacing
- Intersection Mark (under Centrelines): tap two straight edges and both
  are drawn on, thin, to where they'd meet - a rounded corner's sharp corner.
- A straight dimension dragged near a parallel one of the same view snaps
  in line with it, or one standard step out or in from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:41:51 +02:00
superGeometry f2fdb5acc7 Drawings: Horizontal, Vertical and Block title blocks, a revision table
- Horizontal: a strip along the bottom of the frame (two rows on a narrow
  sheet). Vertical: a column down the right, the revision table at its top.
  Block: the corner block with a revision table above it.
- The views keep off whichever side the title block takes.
- Revisions are added and removed in the Title block section; the newest
  becomes the title block's revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:39:31 +02:00
superGeometry 2d36f9f20d Sketch: fully defined curves in green, which pick stays put, linked Project and Pattern
- Curves the constraints hold completely draw green in the sketch being
  edited (from the rank of the constraints' Jacobian), with a note when the
  whole sketch is fully defined.
- A toggle on the constraint bar: the first or the last picked curve stays put.
- Project as Sketch makes linked curves that follow the body's edges.
- Linear and circular sketch patterns keep their copies tied to the
  originals: change one and the copies follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:35:40 +02:00
superGeometry f6eb68c07e Selection: box directions and kinds, a list for overlapping faces, Select Through
- Box selection: left to right takes what's wholly inside; right to left
  (drawn dashed) whatever it touches - faces under the box and edges
  crossing it count.
- While dragging the box: Tab cycles everything / bodies / faces / edges;
  B, F, E and A pick one. The hint says which.
- A tap on faces of several bodies in the same place: a list by the
  pointer to choose which.
- Select Through (Ctrl+Shift+S, or in the right-click menu): corners,
  edges and sketches behind the faces in front can be picked; the bodies
  show see-through while it's on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:29:06 +02:00
superGeometry 3d9cb2533b Fill: a surface over a network of curves
- Tools > Fill: tap the curves and edges round the surface (any sketches,
  any bodies' edges) and, if wanted, guide curves across it that the
  surface passes through. It's an open body of its own.
- Along body edges it can just touch (G0), be tangent to the face there
  (G1), or match its curvature (G2) - G2 says so when it can't be held.
- Starts with the curves and edges picked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:25:45 +02:00
superGeometry e0a8f6a982 Sweep: profile position, orientation and corners; Loft: start and end continuity
Sweep
- Profile position: where it is, or on the path's start (moved to the
  nearer end and turned square to the path).
- Orientation: normal to path (it turns with the path), or parallel to
  profile (it keeps facing the same way).
- Corners: round or mitre.

Loft
- Start and End: free, tangent (G1) or smooth (G2), each with a magnitude
  - the body leaves the first shape (meets the last) straight out of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:21:32 +02:00
superGeometry c675482277 Section View: Section only, a 2D section, and Normal to Section
- Section only: just the cut faces (and their outline), the rest of the
  model gone.
- 2D section: seen straight on and without perspective, flat like a
  drawing - the cut filled, the edges beyond it drawn in light lines.
- Normal to Section: look straight at the cut from the side cut away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:17:58 +02:00
superGeometry 93e355ced8 Display modes: zebra stripes and a curvature map
- Analysis in Display modes: Off, Zebra stripes, Curvature map.
- Zebra: stripes reflected in the bodies (a kink shows a crease between
  faces, a jump a gap); upright or horizontal, 4 to 48 of them.
- Curvature map: red where a face is domed, green where it's flat, blue
  where it's hollow; a slider sets the radius shown in full colour
  (0.5 mm to 5 m). Worked out from the mesh's normals, per vertex.
- Both keep the section's cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 10:16:16 +02:00
superGeometry 272aee1888 History: a breakpoint (roll back without deleting) and Merge
- A step's menu: Insert Breakpoint After - the later steps are off and
  greyed under a bar, the model as it was there. New steps go in at the
  breakpoint (before the ones it switched off). Remove on the bar (or in
  the menu) switches them all on again.
- Merge History…: every step becomes the bodies as they are now (each kept
  exactly, with its id, so names, colours, materials and folders stay).
  Keep the sketches and keep the variables are ticked by default. Undo
  takes it back.
- The dialog can show tick boxes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:58:01 +02:00
superGeometry 8468f8409d Keyboard: shortcuts for the tools and views, a command search, and a cheat sheet
- X or Ctrl+F: search every command by part of its name; what the picked
  thing offers comes first, the ones used last when nothing is typed.
  Up/Down pick, Enter runs, Right completes the name, Esc closes.
- Letters: L A C R G I O T start a sketch with that drawing tool; E Extrude,
  F Fillet, H Shell, M Move/Rotate, N Translate, P Project as Sketch,
  S Scale, V Revolve, W Sweep - each as a tap on its button would.
  Ctrl+U / B / I: Union, Subtract, Intersect.
- Ctrl (or Alt) + 1 the default view, 2-7 front, back, top, bottom, right, left.
- Space over a face zooms to it.
- ?: the list of keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:38:18 +02:00
superGeometry 9160a0669d Extrude: Through all, Up to a face or plane, a start offset, a draft angle, and Intersect
- Ends: Distance, Through all (Flip direction turns it), or Up to - a face
  (flat: its whole plane; round: split there, the part at the shape kept)
  or a plane, picked like any slot.
- Start: it begins that far from the shape along its normal.
- Draft angle: the sides lean in (negative: out) from the shape's plane.
- Result gains Intersect (only what's in both stays), for Revolve, Sweep,
  Loft and Pattern too; Connect keeps its four.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 09:31:01 +02:00
superGeometry c0a1fe72cf Drawings: the sheets in their own pane, apart from the drawing's tools
- The left column: the tools at the top (Exit Drawing, Views, Dimensions,
  Centrelines, Note, Image, Delete); under them a Sheets pane of its own,
  shaded, with its count.
- The pane: a row of small buttons (new, copy, delete, Print / PDF all,
  DXF all; names as tips), the find box, then the list, which scrolls by
  itself, so with hundreds of drawings the tools stay where they are.
- The list keeps where it was scrolled to; opened, the open drawing is in
  sight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:56:01 +02:00
superGeometry 7d14d5f525 Drawings: the frame's fields measured out from the centring marks (ISO 5457)
The numbered and lettered fields were the frame split evenly from the
filing margin, so the centring mark in the middle of the sheet fell inside
a field (between 4 and 5 on A3). Now the fields are 50 mm, measured out
both ways from the centring marks, the end fields taking what's left: the
centring marks are always on a field line, on every sheet size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:51:32 +02:00
superGeometry 7620d398f6 Drawings: a picked body gets its own drawing; Print / PDF all, DXF, DXF all; find among many
- Bodies picked as Drawings is tapped: the drawing of just them opens, or a
  new one is made for them (titled with their names, set out like the last
  drawing; the very first asks its preferences). Before, the bodies chosen
  for a drawing were drawn with all the others since a project could hold
  several drawings: fixed.
- Print / PDF all: every drawing, each on its own page of its own size, in
  one print (save as one PDF).
- DXF (this drawing) in the bar; DXF all: every drawing as a DXF in one
  .zip. AutoCAD R12, mm, y up: exact lines, arcs and circles, text, solid
  arrowheads, sections' hatching as lines, details cut to their circle;
  layers VISIBLE, THIN, HIDDEN (dashed), CENTER, TEXT.
- More than 8 drawings: a box over the list to find one by its title.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:43:09 +02:00
superGeometry 21e4e28850 Drawings: the project's drawings listed under the tools on the left
- Under Exit Drawing, Views, Dimensions and the rest: each drawing (tap to
  open it, the open one lit), then New drawing, Copy drawing, Delete drawing.
- The menu in the top bar is gone; on a phone the list shows as icons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 23:03:20 +02:00
superGeometry 90822d82c9 Drawings: as many drawings as wanted in one project
- Drawings ▾ in the drawing's bar lists the project's drawings: tap one to
  open it; New drawing (its preferences first, its own title), Copy this
  one, Delete this one (Undo brings it back).
- Drawings in the BIM menu opens the one open last, else the first.
- Each drawing keeps its own sheet, views, dimensions and notes.
- Projects saved with one drawing open it as their first; nothing is lost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:55:27 +02:00
superGeometry bdcb66b4a6 Drawings: Arrange lays every dimension out the way a technical drawing has it
Dimensions > Arrange (ISO 129-1):
- Outside the view, on the side nearest what each measures.
- Rows 10 mm out, then 7 mm apart; shorter nearer the view, longer
  further out, so no extension line crosses a dimension line. Dimensions
  that meet end to end share a row (a chain).
- The value in the middle, or just past the end when it doesn't fit
  between the arrows; no two values on top of each other.
- A radius's or diameter's leader points away from the middle of its view,
  out past it, no two the same way.
- Slanted ones stand 10 mm off; angles stay. The overall sizes too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:51:06 +02:00
superGeometry 997156bb88 Drawings: the overall sizes are dimensions like the others: picked, moved, given text, taken off
- The width, height and depth the drawing puts on by itself can be picked
  and dragged (out or in, value along), given a distance, text and a
  tolerance, like a dimension put on by hand. They still follow the model.
- Delete takes one off; Overall sizes, off and on again, brings them back
  where they were moved to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:45:40 +02:00
superGeometry 3363a7f140 Drawings: drag a dimension straight away to move it out or in and slide its value along
- A dimension or note moves as soon as it's dragged, no tap to pick first
  (views still move only by their handle).
- Dragging a length or distance across its line sets how far out it sits;
  along it, slides its value. Past an end, the dimension line runs out under
  the value; near the middle it snaps back to the middle.
- A picked dimension shows its distance from what it measures, to type
  exactly, and Centre text once its value has been slid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:19:16 +02:00
superGeometry 4bbf53e7a8 Drawings: what a dimension tool would take lights up under the pointer
- With a dimension tool on, the edge, arc or circle, point (corner, middle,
  centre) or view a tap would take is drawn in blue under the mouse, and
  the pointer becomes a hand.
- Only what that tool can take: Radius lights up circles and arcs, not
  straight lines; Line Length lights up lines only.
- Same thickness at any zoom; it goes away when the pointer leaves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:09:49 +02:00
superGeometry a58fa408e7 Drawings: a tap picks, only what's picked moves; a picked view has a move handle and its scale
- A tap on a view, dimension or note picks it; a drag from something not
  picked moves the sheet, so nothing moves by accident while looking round.
- A picked view shows a round handle in its middle: dragging it moves the
  view. Held anywhere else, the sheet moves.
- Its scale sits on a chip under the handle (tap for the list), instead of
  in the bar.
- A picked dimension or note moves by dragging it.
- The handle is the same size at any zoom and follows the view and the
  camera.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:04:07 +02:00
superGeometry 2b7b29ab41 Drawings: zoom and move round the sheet
- The mouse wheel zooms where the cursor is (the paper under it stays put),
  about 8 % a notch; two fingers pinch to zoom and move together; a touchpad
  pinch zooms and a sideways swipe moves.
- Dragging the empty paper moves it (a tap still picks nothing); the middle
  or right button moves it whatever is under it.
- A double tap on the empty paper goes closer there, or back to all of it.
- Zoom buttons at the bottom right: out, how close (tap: all of the sheet),
  in; keys + and - and F.
- Zooming only changes what of the sheet is shown: lines stay sharp at any
  zoom and the sheet isn't drawn again. It can't be lost off screen, and it
  stays fitted when the window or the sheet size changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:52:38 +02:00
superGeometry 60c66fd731 Tools for checking the app: sg in the console, a project checker, pictures without a browser, a shared test kit, version.json
- sg (the browser's console): the project, tool, hint, open window,
  selection, errors and bodies in one look; pick things by name; list and
  run what's offered; read and set the open window's rows (slots, numbers,
  choices, toggles); give a waiting slot a face or edge; Done / Cancel;
  wait for the engine; each body's health; open a project. sg.help() lists it.
- npm run check <project>: rebuilds it step by step and says what each step
  made, changed or took away, its error, and how sound each body is.
- npm run render <project> <out.png>: a shaded picture with edges from any
  side, drawn without a browser.
- tests/kit.ts: the engine started once, check / done, and quick sketches,
  shapes and steps (wrap.test.ts uses it).
- version.json on the site: the commit it was built from; npm run live says
  whether main is live (--wait until it is).
- The engine measures each body's health on request (valid, closed, solids,
  faces, volume, box).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 21:23:25 +02:00
superGeometry c9562582d9 Project as Sketch for a sketch's shapes: onto a plane or flat face, square to it
- Pick a sketch's shapes, then Project as Sketch, then a plane, a flat
  face or XY / XZ / YZ: a new sketch there with the shapes drawn onto it
  square to it (on a face, it stays on that face).
- Lines stay lines and circles stay circles where the planes are parallel;
  tilted, a circle comes out as a spline. A side two shapes share is drawn
  once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:40:44 +02:00
superGeometry 31ed4ad14b Drawings: base and projected views, view scales, arc angles, min-max distances, pictures; Project as Edge, Wrap & Emboss, edge tools
Drawings
- Base View: the model from any side (front, back, top, bottom, left,
  right) or any isometric corner, put where it is tapped, at its own scale.
- Projected View: tap a view, then beside it for the view square on (lined
  up with it, first or third angle), or past a corner for an isometric one.
  Projected from sections and added views too; deleting a view takes what
  was made from it along.
- Scales per view: the isometric view and added views have their own; the
  front, top and side views share the sheet's (they line up).
- Arc Angle: the angle an arc goes round, past 180 degrees too.
- Min-Max Distance: between any two of a point, an edge, a circle or an
  arc; the nearest, or the farthest with Max.
- Images: a picture from the device on the sheet, moved by dragging, made
  bigger or smaller in the bar.

Modelling
- Project as Edge (beta): a sketch drawn onto the faces of a body seen
  from it, or edges onto a face; the faces are split along them.
- Wrap & Emboss (beta): a sketch wrapped round a round face with its
  lengths kept, raised from it or sunk into it.
- Edges: Plane - Through Edge, Project as Sketch, Project as Edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:26:37 +02:00
superGeometry a728e74d91 Drawings: section and detail views, angles, tolerances, centrelines, notes that point; toolbars that fit what is picked
Drawings, after a study of how a professional CAD app does them:
- Section View: draw the cut line on a view (corners, middles and centres
  snap), tap the side it goes on. The model is cut there and the view is
  lined up with its parent: cut faces hatched at 45 degrees, "A-A" under it,
  a chain line with thick ends, arrows and letters on the parent. Flip turns
  it round; dragging slides it along its line.
- Detail View: a circle on a view, drawn bigger where it is tapped, with its
  letter and scale ("B (2:1)"); its scale can be changed when it is picked.
  Dimensions can be put on details and sections.
- Dimensions: Point-to-Line, Line-to-Line, Line-to-Line Angle, 3-Point Angle
  beside Line Length, Point-to-Point, Radius, Diameter. Points snap to the
  middles of edges too.
- Text and tolerance on any dimension (double tap, or the bar when picked):
  text before and after, symmetrical, deviation (stacked), limits, basic.
- Centrelines: centre mark, 2-point and 2-line centrelines.
- A note tapped on an edge points at it with a leader.
- The first drawing asks its title, sheet, scale and views first.
- Angle precision, centreline and hatching line widths, ANSI E.
- Fixed: a second note started while one was open lost the first (and threw);
  taps off the paper made notes outside the sheet; the note box ran off a
  phone's screen.

Picking in 3D:
- A round face shows only what works on it: Axis - Cylinder (on its axis),
  Fillet and Chamfer of its rims, Pattern, Translate, Rotate, Mirror of its
  body. Sketch, Extrude, Plane and the other flat-face tools are left out.
- A body has Fillet and Chamfer of all its edges, and Create Drawing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 18:14:41 +02:00
superGeometry 0bd3f44977 Each piece is a body: picking some copies of a pattern uses just those
A Subtract given a bolt and its first copy cut all six bolts of the pattern
(the original and copies from the first on counted as "the whole pattern"),
while its card said 2 bodies and the other copies vanished from the preview.
Now a pattern counts as whole only when the original and every copy were
picked. The step keeps that with it (whole), worked out the first time it
runs, so a pattern picked whole still stays whole when its count changes.
Changing a step's picks works it out again.

A Subtract (or any tool) opened again with everything picked now takes taps
straight into its list of bodies; before, taps did nothing until its slot was
tapped.

The crankshaft hand build was redone this way: Subtract 01 reopened, the four
other bolts tapped (6 bodies), and it still matches the code build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 17:03:36 +02:00
superGeometry a791ffad5e Build stress tests: a crankshaft, helical gears and a propeller, by code and by hand
Three hard parts built step by step in tests, and the crankshaft built again by
hand on a phone-sized screen. The hand build matches the code build's volume
to within 3 mm3 of 2.2 million.

Engine fixes found on the way:
- Volume and area measured to a millionth (ocFree.ts). replicad's measure was
  1.2% over on the propeller's spline faces and put its centre of mass off the
  axis.
- A face's point and normal read straight off its surface: the old way leaked
  engine memory on spline faces, and a twisted gear outline ran it out.
- Lofts through single closed curves whose starts already line up are made as
  one smooth side (loftAlign.ts). A propeller blade came out in six strips and
  its root fillet failed.
- Picked edges are found again more reliably after a rebuild; a near match is
  only used when nothing better is found.
- Sweeps along straight runs, round-about paths, slivers skipped.

Fixes in the app:
- Subtract can pick a body that sits flush inside another one (the face under
  the finger on the other body counts), and never picks its own preview.
- Thread: tapping the middle of a revolved shank picks its seam line; it now
  takes the round face under the finger.
- Sketch: typed end points join the shape they land on; Values can clear a
  box; arcs follow the side tapped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:37:12 +02:00
superGeometry 76d597bdab Phones and tablets: Enter AR - the model in your room through the camera
- On a phone or tablet the top bar says Enter AR (shown where the browser
  can do AR: Chrome on Android). A headset still says Enter VR.
- Point it at the floor or a table: a ring shows where the model goes; tap
  to put it there (tap again to move it). Two fingers: pinch to size it,
  twist to turn it; it stops at real size on the way.
- Over the camera: Exit AR at the top, a short hint at the bottom, the
  scale (1:1 as the zero) at the left.
- Help text updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:08:42 +02:00
superGeometry 70f17540f8 VR: a scale over the left hand, 1:1 in the middle; sizing stops at real size
- A tape over the left hand shows the model's scale: 1:1 (real size) is the
  zero, 2:1 and 4:1 above, 1:2 and 1:4 below; it slides under a pointer and
  the number on top is the scale now (2.6:1, 1:37).
- Right stick up / down sizes it and stops at real size on the way (a buzz;
  let go and push again to go on), as both grips already did.
- Size changes no longer pop up a message (the scale shows it).
- Help text updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 00:37:50 +02:00
superGeometry 7d580425d3 VR is a viewer: your model in your room, at real size, through passthrough
- Enter VR opens passthrough where the headset has it (else a dark room).
  Only the bodies show: no grid, axes, sketches, planes or highlights.
- The model starts at real size in front of you (a big one on the floor).
- Right trigger: put it down where the ray meets a table or the floor (the
  headset's room scan, else the floor), standing up and facing you, with a
  soft shadow under it.
- Grip: pick it up, move and turn it. Both grips: size it; it stops at
  real size on the way.
- A: real size / hand size. B: bring it back in front of you. Y: X-Ray.
  Right stick: turn it or size it. Left stick: raise or lower it.
- Hold X: the wheel (Real size, Hand size, Bring here, X-Ray, Edges, Exit).
- The in-VR editing (picking, tool wheel, tool numbers) is gone.
- Help text updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 00:18:42 +02:00
superGeometry a8b031ea7f VR: a tool wheel on each hand, picking corners, edges and faces, B/Y reused
- The ray lights up the corner, edge or face it points at (same priority as
  on the screen); the trigger picks it, with a buzz and a short note.
- Hold A: the right wheel, the tools for what's picked (Done and Cancel while
  one runs). Hold X: the left wheel - Undo, Redo, Recenter, X-Ray, Edges,
  Deselect All, Exit VR. Tilt the stick to a button and let go, or point the
  other hand at it and pull the trigger.
- B no longer leaves VR: it cancels the running tool, or undoes. Y redoes.
  A quick tap on A is Done; on X it recenters the model.
- While a tool runs, a card over the right hand shows its number: right
  stick up / down sets it, a flick left / right goes to the next one. Its
  problem shows in red.
- Glass round buttons with the app's icons; drawn only when something changes.
- Help text updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 00:00:53 +02:00
superGeometry ae49d30f8f VR: Enter VR in the top bar; left stick moves the model up and down
- The VR button moves from the bottom of the right column (on a headset the
  column's bigger buttons push it out of sight) to the top bar: a blue
  Enter VR beside Items. It shows on a headset always, elsewhere when a
  headset can be used; if the browser can't open VR, it says why.
- Left stick up / down moves the model up / down (half a metre a second at
  full tilt); the right stick still sizes it. The sticks go by time, not by
  frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 23:14:18 +02:00
superGeometry 4465a430fe Fillet overflow: a round too big for a face beside it cuts on through
When the kernel gives up on a round because it's bigger than a face beside
it (a 3 mm round on a 2 mm plate's edge), the round is built from its own
cross-section and cut away with booleans instead: still exactly round, it
cuts on through that face's far edge (overflow, keep surface). A note says
so. Straight edges between flat faces and round edges of cylinders, like
the G2 blend, which now shares this code.

Two rounds side by side that would run into each other along their length
(both edges of a block narrower than the two) still don't fit: refused,
not cut into a ridge.

Also: a comment in tests/bodyparity.test.ts that wasn't valid UTF-8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 23:00:49 +02:00
superGeometry c74770930a Fillet chord width, G2 and setback; sweep twist; closed and guided loft; VR
- Fillet, Size: Radius or Chord width (straight across the round, face to
  face). The radius is worked out along each edge, so faces meeting at a
  changing angle still get the width asked for.
- Fillet, Blend: Round or Smooth (G2) - the bend eases in from flat at both
  faces (no line in reflections). Straight edges between flat faces (cut
  away, or added in an inside corner) and round edges of cylinders.
- Fillet, Corner setback: where three or more rounded edges meet, they stop
  short and one smooth patch joins them. Too small a setback is refused with
  the size it needs; a patch that wouldn't close is refused, not kept.
- Sweep, Twist: the profile turns round the path from start to end (it
  follows the path's own non-spinning frame), with End size or without.
- Loft: Closed loop (from the last profile back to the first) and Add guide
  (a curve the body follows through the profiles).
- VR: with a headset, View in VR in the right column. The model floats in
  front of you; trigger picks a face, grip grabs it to move and turn it, both
  grips or the stick size it, B / Y comes back.
- Help text updated; tests/bodyparity.test.ts covers each new kernel option.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 22:30:39 +02:00
superGeometry 2036d7b8eb Sketch fillet on a corner, polygon presets, variable fillet, sweep end size
- Sketch Fillet / Chamfer: tap the corner itself (of a line chain, rectangle or
  polygon) to round it; two lines that meet still work.
- Polygon: its button names the shape (Triangle, Square, Pentagon, Hexagon,
  Octagon); a second tap on the running tool opens those choices. Tools with
  variants run on the first tap and show the variants on the next.
- Clearer hints for sketch Fillet, Move, Scale and Pattern.
- Fillet: Type Constant or Variable - a start and an end radius along each
  edge, with Flip ends.
- Sweep: End size - the profile grows or shrinks evenly along the path.
- Help text updated; tests/bodyparity.test.ts covers the variable fillet and
  the sweep end size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:52:27 +02:00
superGeometry 03b340a733 Picking a thing arms its tool; right-click and hold menus; two-distance chamfer, symmetric extrude
- An edge picked: Fillet is ready (its dot, and a number typed is the radius).
  Move/Rotate Edge stays in the list (M).
- A face picked: a number typed starts Offset Face with it (Total: the wall left).
- The hint says what the armed tool does and how (drag, or type).
- Right-click on the model opens a menu by the pointer: a running tool's Done
  and Cancel, or the selection's tools and Deselect All, then Zoom to Fit and
  the view switches (grid, axes, edges, hidden edges). A stray right-click no
  longer throws a tool's work away.
- Fingers, pens and headset controllers: press and hold still for the same menu.
- History: right-click a step for Edit, Show/Hide, Suppress, Delete.
- A tool's problem shows as a red line in its card, with a warning mark by
  the title (not only in the hint).
- Chamfer: Equal distance or Two distances, with Flip sides.
- Extrude: Sides - One side or Symmetric (the distance each way).
- Help text updated; tests/bodyparity.test.ts covers the new kernel options.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 21:38:42 +02:00
superGeometry 1d40bd0daf The view's drawing buffer isn't kept; a list that isn't one is a damaged step
- The 3D view no longer keeps its drawing buffer between frames (the browser
  shows each frame the quick way, which matters on phones). The library's
  picture and the screenshot draw the view right before they read it, as
  they already did.
- A step whose tools, bodies, edges or faces aren't a list (a damaged file)
  is refused as damaged before it runs, instead of tripping the code and
  being put into words afterwards (with the raw error in the console).
- The perf test checks memory only when it can collect garbage first (run
  with --expose-gc, as its first line says); without it, it failed on
  garbage not yet collected.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 19:54:58 +02:00
superGeometry 9963abe841 Speed: big sketches, drags and previews across all tools
From a review of the code for speed, each measured on the saved projects.

- A sketch's regions: pieces, their ends and holes were compared each with
  every other. A plate with 900 holes took 1.1 s, now 70 ms; 200 lines
  crossing in a grid took 23 s, now 70 ms.
- Dragging a value in any tool (extrude, fillet, move, scale, offset...)
  asked for a rebuild on every pointer move, also when the snapped value was
  the same: 150 moves were 150 rebuilds, now one per value (19).
- Each preview shown rebuilt the whole History list and refreshed the
  selection tool twice: 11 ms a preview on a 208 step project, now 3. The
  list is rebuilt when what its rows show changes.
- A reference image's picture is no longer sent to the engine (it never
  reads it), and a step's big values (an imported model) are fingerprinted
  once instead of hashed on every rebuild: 17 ms to under 5 for 5 MB.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 19:40:49 +02:00
superGeometry 80e348744a BIM drawings: faster to open, lighter to drag
Profiled on every saved project (the model built, then the views drawn):
guitar 14.0 s to 9.9 s, fan 14.0 to 11.6, jet 21.2 to 19.1, arc reactor
2.1 to 1.2, drill 4.0 to 3.6 (in the app: open in 3.5 s, was 4.6).

- Each body's exact box is worked out once, not again for every view (the
  side and top views took 0.85 s each on a fan, now 0.25).
- The model drawn without its threads is meshed with only what a drawing
  reads, not everything the 3D view needs (seconds on a guitar).
- Dragging a note or dimension reuses the views' placed outlines (24 ms a
  frame on the drill's sheet, now 10), and the sheet is redrawn once a
  frame at most however often the pointer moves.
- The copy of the sheet for printing and SVG files is made when asked for,
  not on every redraw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 18:48:48 +02:00
superGeometry 6106f7f4c3 BIM drawings: mesh views match the exact ones, views cut at the frame
More stress tests: every sheet option on several projects (1776 sheets),
and the mesh drawing compared line by line with the exact one.

- The mesh views' depth buffer took big flat triangles as up to 20 pixels
  larger than they are: a panel hid its own edges beside them (a closet's
  doors drawn dashed). Seen lines now match the exact drawing on every
  project that can be drawn both ways.
- A tangent line lying on a seen edge or outline gives way to it (a face
  split in two, seen edge on, came out as a thin line).
- Many balloons on a small sheet: those with no room round the view go to
  the nearest free place on the sheet, not off the paper.
- A scale too big for the sheet: the views, their dimensions and balloons
  are cut at the frame instead of drawn over it and the title block, and
  the properties say so.
- Drawings opened while a project is still loading wait for its model
  (it said there were no bodies to draw).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:46:24 +02:00
superGeometry 300b507c4d BIM drawings: fast on big models, threads drawn as drawings show them
Stress tested on every saved project, every sheet size, both projection
methods and every title block.

- Freeform or very big models are drawn from their meshes (a depth buffer,
  the mesh's own edge lines, outlines from the normals, round outlines put
  right on the surface, the view's box from the solids): the drill draws in
  4 s instead of a minute, a fan in seconds instead of minutes.
- Threads are drawn plain with a thin line at the thread's depth (ISO 6410);
  the valve's six threads took the exact hidden lines minutes. The plain
  model is kept apart, reusing the steps before the first thread.
- Only the views the sheet shows are drawn, one at a time with progress;
  the other side view is drawn when the projection changes.
- Parts hidden inside a housing get a balloon on their hidden lines.
- Balloons stay off the overall dimensions, other views, other balloons and
  the title block (a ring further out when there's no room).
- The automatic scale takes an in-between one (1:3) where the next standard
  one would leave most of the sheet empty.
- Dimensioning an edge twice picks the one it has; a long parts list stops
  at half the sheet and points to the technical sheet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:02:41 +02:00
superGeometry 41984d3092 BIM: a drawing workspace - dimension by tapping, notes, sheet properties
The BIM card gets a grip to drag it anywhere (it opens there again) and an
X that leaves BIM.

Drawings is now a workspace: tools at the left, the sheet, its properties
at the right.
- Dimensions by tapping: Line Length (a straight edge), Point-to-Point (two
  corners), Radius and Diameter (a circle or arc seen face on). Each lands
  off its edge at once; drag it to move it. The kernel now hands over each
  seen edge as a line or a circle for this.
- Notes: tap where, type, Enter; double tap one to write it again.
- Drag a view to move it: the projected views stay lined up with the front
  one. Delete takes off what is picked; everything undoes.
- Views: front, top, side, isometric each on or off; hidden lines; put the
  views back.
- Properties: title, portrait or landscape, ISO A4 to A0 and ANSI A to D,
  a longer list of scales, projection, title block (empty, border, simple,
  with parts list), date format, balloons, units, precision, decimal comma,
  line widths.
- The frame has grid zones (numbers along, letters down); the title block
  shows the units; the projection symbol is cone first, then its end view.
- Bodies picked before opening Drawings are the ones drawn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:38:31 +02:00
superGeometry 79a69ca9a5 BIM: drawings - views with hidden lines, dimensions, balloons, title block
Drawings opens from BIM (the left column, and inside BIM): the bodies on a
sheet of paper at a true standard scale.

- The kernel projects each body with exact hidden line removal: front, top,
  the side view and an isometric one, each body's edges kept apart so a
  balloon can point at it. Hidden edges lying under seen ones are left out.
- First-angle projection (ISO) by default, third angle as an option, with
  the projection symbol in the title block.
- Paper A4 to A1 inside an ISO 5457 frame; the largest standard scale the
  views fit at, or one chosen.
- Overall dimensions: width and height on the front view, depth on the side.
- Balloons carry the technical sheet's item numbers; the parts list above
  the title block (item, qty, name, material, mass) is the same list.
- ISO 7200 title block: title, owner, author, date, scale, size, drawing
  number, revision, sheet; its fields are the technical sheet's too.
- Print / PDF at the paper's size, SVG download, tap the sheet to zoom.
  The options are saved with the project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:06:17 +02:00
superGeometry da321a17f4 BIM: real materials for bodies, and the technical sheet
BIM sits under Tools in the left column: Materials, Technical Sheet,
Drawings and Assemblies (the last two say they are coming next).

Materials: a library of 29 real materials in six classes (metals,
plastics, concrete and masonry, wood, glass and stone, insulation and
boards), each with identity (class, the standard of its grade), how it
shows (a colour, see-through for glass) and its technical data:
physical (density, stiffness, Poisson's ratio, strengths) and thermal
(conductivity, specific heat, expansion). Tap a body, then a material;
the card lists every body with its material and mass. Also from the
body's own column: Material.

Technical Sheet: a title block (project, number, revision, author,
company, date, units), the parts list (item, material, volume, area,
mass, centre of mass, size, totals) and every material used with its
data. Prints or saves as a PDF; the parts list downloads as CSV. Item
numbers are the ones the drawings will use.

The engine measures each body's volume, area, centre of mass and box on
the solid. The worker now takes one message at a time (a request that
arrived during a rebuild ran the same steps at once).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 11:21:39 +02:00
superGeometry bd64c83a82 A full round leaves one clean face; a body's faces are its own step's
From a project that stopped half way.

Two roundings that use up the face between them (4 mm on both corners
of an 8 mm end): the sliver left was closed, but its ends stayed on the
top and bottom faces as edges millionths of a mm long - picked with the
rest of an outline, and what later fillets, cuts and edge moves there
failed on. The flat faces are made again without them, and the two
roundings become the one half cylinder they are. Old picks of such an
edge are passed over.

A new body's face on the same plane as a face of another body (both on
the ground, both as tall) was put down to that body's step: change it
and steps on this one lost their faces. It is the new step's now; the
old answer is kept beside it so projects saved with it still open.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 10:50:14 +02:00
superGeometry d1e6813928 Projected edges follow the body they came from
Project on a body's edge makes a sketch curve that stays on that edge:
on every rebuild the engine puts it where the edge is now and solves the
sketch again with it held, so what is dimensioned to it moves with it
(a hole 8 mm from another part's wall stays 8 mm from it). What is tied
to a moved curve is carried along first, so a distance keeps its side.

The page takes the moved curves as the sketch's own (no undo step, no
second rebuild: a sketch that comes out the same to the last digit is
the same sketch to the steps made from it). In the sketch a followed
curve is held by the solver, drawn in its own colour, and has Unlink
and Delete; moved, cut or copied there it becomes a plain curve.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 10:09:07 +02:00
superGeometry 225bd7e021 Only the steps that read what changed are rebuilt
- A change to a step used to rebuild every step after it. Each step now
  notes what it reads of the model as it runs (which bodies, sketches,
  planes); when an earlier step changes, a step that read nothing of what
  changed is put back as it was. On the valve (96 steps), one step changed
  at a time: 337 of the 555 steps after them not rebuilt, 74 s of rebuilds
  against 176 s.
- What a step builds no longer depends on which steps were rebuilt before
  it (helper solids took their sizes from a counter that ran on from step
  to step: the same project could come out a hair different).
- Test: deps - real projects, one size of one step nudged, every rebuild
  the same (bodies, volumes, faces, edges, errors) as building from nothing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 03:07:09 +02:00
superGeometry 7d7d0960df Previews rest after rebuilds that cost the engine a lot of memory
Some steps cost OpenCascade tens of MB on every rebuild (a fillet on a
cone's rim ~45 MB, a thread ~75 MB), never given back. Dragging one of
their sizes rebuilt it some 20 times a second: gigabytes in a few seconds.
The page now watches what rebuilds cost and, when it is a lot, lets the
next preview wait up to 0.4 s (the drag's last value is always shown): a
3 s drag of such a fillet is 9 rebuilds, not 60. Steps that cost nothing
are as quick as before. A spare engine is also got ready, and swapped in,
in the middle of a drag - not only once it ends.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 02:04:27 +02:00
superGeometry 9217cc937e Freeform Face is the cage's own smooth surface, its border on the face's edges
- The shaped face is built from the cage itself (a patch per cell, as a
  freeform body is), not one surface fitted through a cloud of points: the
  same every time, with no fit to fail. The cage's border points are put on
  the face's edge and the surface's border made to run through them, turning
  a corner where the face does; by an inward corner (an L, a T) the surface
  is kept from swelling past the edge.
- A new cage's border goes through the face's corners, inward ones too.
- The lines between the patches aren't drawn or picked: it looks one face.
- Where the cage can't follow the face (too coarse for its corners, a cage
  laid before this), the fitted way is used as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 02:02:57 +02:00
superGeometry b63833b611 Steps stay on the face they were made on; Connect shows without a guide
- A step built on a face or an edge of an extrusion or a revolve now knows
  which sketch curve that face came from, and finds it by that. Before, it
  took the face of the same step nearest to where the pick used to be: a
  comb's teeth moved apart put the boss on the wrong tooth, two holes moved
  past each other swapped which one a later step changed - with no word.
  Picks saved before this are found as they were.
- Connect: two faces are enough. The bridge shows at once, bowed by Bend; a
  sketch curve can still be tapped for it to follow, and let go again.
- Connect between outlines that don't pair up (a square to an L, to a
  triangle): each end as one smooth curve, a little inside the face's edge.
  A bridge that can't be made without a guide says so in its own words.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 00:58:39 +02:00
superGeometry 52d03e4dde Engine hardening: a mutation sweep of real projects, and the fixes it found
- A step with a size typed far too big (an axis a billion mm away) ran the
  engine out of memory showing it, and every step after failed with engine
  words. Now refused at once: nothing may reach past 10 km from the origin,
  or be scaled away to a speck; a huge shape's mesh is no finer than
  1/50 000 of its size.
- A step whose saved values are broken (a direction that is an empty list,
  a number missing from a point) could hang a rebuild for minutes. Refused
  as damaged, at once; code-level errors read as words, not "x is not
  iterable".
- The engine breaking down (out of memory, a fault inside OpenCascade): a
  fresh one is loaded and the rebuild done again; a step that breaks a fresh
  engine too is refused from then on, the rest of the project still built.
  Past 1200 MB the engine is replaced before the next rebuild.
- Freeform Face: on outlines with inward corners (L, T, U) one point pulled
  out by the corner folded the face over: points of the cage's surface past
  the face's edge are left out, and a fill that fails is tried through
  fewer points. A triangular face takes a cage.
- Tests: mutate (real projects replayed with one value of one step changed
  to 0, negative, tiny, huge, nothing, a missing reference: refused in
  words or left sound, never a crash or minutes), leak (the engine's memory
  cost of a rebuild, step by step), harden, and the L / T / U / triangle
  faces.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 00:17:32 +02:00
superGeometry 725e07b0fd Connect and Freeform Face carry a BETA tag wherever they show
In the tool menus, on the face's actions, by their card's title and on
their History steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 21:19:44 +02:00
superGeometry 7442b13910 Connect follows an edited guide even where it turns too tightly
A guide with a corner tighter than the bridge is wide is rounded off a little
at a time (its ends kept square to the faces) until the bridge fits, instead
of the step failing and the bridge vanishing. The guide is followed smoothly
through its points (Catmull-Rom), and the bridge eases onto it with a smooth
curve that meets it going its way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 21:09:05 +02:00
superGeometry a9919395b3 Connect sweeps the faces' outlines; Freeform Face is a cage edited in Freeform
Connect: the bridge is face A's outline swept along the guide (or a curve
straight out of each face) into face B's outline, so it starts and ends
exactly on the faces: no patch grid, no step. It never turns tighter than it
is wide, eases onto a guide square to the face, and a Cut between two faces
of one body makes a tunnel. Size defaults to 100%.

Freeform Face: a quad cage laid over the face (its border round the face's
edge, locked) and shaped in the Freeform tool - pick points, edges or faces
and move them with the gimbal on the face's axes. Cells across 3/5/7/9, Add
edge loop and Add detail; Edit Freeform reopens it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 21:03:08 +02:00
superGeometry b20d93a32f Connect follows a guide curve; Freeform Face edits again, with a gimbal
- Connect asks for a guide: a sketch curve (a spline drawn from one face to
  the other); the bridge runs along it, its ends pulled onto the faces'
  middles, whichever way round it was drawn.
- A face made by Freeform Face shows Edit Freeform when selected: the step
  opens again with its points, and the 3 / 5 / 7 / 9 grid presets.
- Picked points move with the move/rotate gimbal, lined up with the face:
  along it, out of it, within a plane, or turned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:14:36 +02:00
superGeometry 623dfb7a8e Freeform with sketch bodies: Connect, Freeform Face, faint back of the cage, no engine leaks
- Freeform edit: cage points and lines behind the shape are drawn faint.
- Connect: a smooth freeform bridge between two picked faces, Auto / Add /
  New body / Cut, Bend and Size; it narrows in tight bends and lengthens its
  straight ends instead of folding through itself.
- Freeform Face: a flat face becomes a smooth surface through a grid of
  points you pull out or push in; its edges stay put. Faces with holes and
  shapes that would cross the body are refused.
- Thicken "both" builds one solid (two halves fused leaked ~50 MB a rebuild).
- The engine is restarted in the background (a warmed spare swapped in when
  idle) once its memory passes 500 MB: OpenCascade leaks on booleans with
  freeform bodies.
- Stress test of freeform bodies against sketch bodies: every boolean both
  ways, extrudes, fillets, shells, transforms, patterns (541 checks).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 19:47:49 +02:00
superGeometry 63a8236bde Lid built by hand on a phone: the fixes it found
- A short edge tapped in its middle (a 3 mm slab's upright corner) is the
  edge, not the corner point 11 px away.
- Sketch from a straight view (Top, Front...) finds a thin face square to
  the view that the 9x9 sample grid missed (it went on the origin plane
  behind a 3 mm slab's front).
- A new sketch on a face knows the face's outline before anything is drawn:
  Offset on the face's edge works as the first step (it did nothing), and
  makes the sketch with the linked offset in it.
- A second offset of the face's edge right by the first: the tap goes to
  the edge when it's nearer the edge than the offset.
- A fillet's edges matched by step must still be much the same edge, and
  never a seam: a lid made round said "radius too big" (its corners went to
  the cylinder's seam); now "the edges are gone, pick them again".
- The hand-built lid is a fixture: rebuilt 100 x 60 with corners 10 it
  matches the formula exactly; made round, the lip follows the circle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:25:32 +02:00
superGeometry 86835f6588 References that never grab the wrong face, sketches that follow the model, UI fixes
- Every face remembers the step that made it (edges: the steps either side).
  A fillet, shell, sketch or thread picks only from its own step's faces and
  edges; when they are gone it says so ("tap this step and pick again")
  instead of quietly using a different one. Re-opening the step drops the
  gone picks with a toast so a new tap is all it takes.
- Offset of a face's edge in a sketch on that face is linked: it is rebuilt
  from the face's outline every time, so a lip or groove follows the face
  when it changes size or its corners change. Card: distance, flip, delete.
- Angle box keeps expressions; Variables turns off when there are none;
  toasts stay clear of the keypad, panels and lists; auto-plane toast names
  the plane; thread remembers the last pitch per size; gallery thumbnails
  fill in after the first build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 18:05:01 +02:00
superGeometry e13a0d6a5e Enclosure stress build: exact-fit fillets, long threads, patterns that change count
A box built the usual way (rounded, shelled, screw bosses with threaded
holes, vents patterned and subtracted) and then resized, re-counted and
switched off step by step:

- Fillets and chamfers that use a face up exactly (4 mm on both edges of an
  8 mm block, a full round) failed where 3.999 worked: retried a hair
  smaller, the same shape to a millionth of a mm.
- Shell with walls exactly as thick as the corners are round (2 and 2)
  failed: retried a hair thicker (sharp inside corners).
- Threads: a long groove (40 turns, an M3 boss hole 20 mm deep) cut
  nothing and failed after 40 s. The groove is now made in pieces of
  8 whole turns: 1.5 s, and M10 x 30 went from 2.7 s to 0.8 s.
- A thread whose hole is gone (its boss switched off) latched onto the
  nearest face - the box's rounded corner - and threaded it for 75 s. It
  now keeps to round faces of the kind and size picked, and says the hole
  is gone.
- A whole pattern picked for Subtract/Delete stays whole when its count
  changes (made 9: all 9 cut; made 3: still works), copies of copies
  included. Copies picked one by one that are gone are left out with a note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 17:34:22 +02:00
superGeometry 03ed32c740 Abuse sweep: typos, nonsense values, damaged files, messy sketches
- Pattern: up to 1000 copies (a typo like 30000 used to build them all, and
  again each time the project opened); spacing or angle 0 is refused instead
  of stacking every copy in one place.
- Revolve: a shape across the axis says so (was "could not compute this").
- Thread: a pitch under 0.2 mm says it is too fine; a failed fine pitch says
  "try a coarser pitch", not "slightly different".
- Value boxes: 5,5 (decimal comma), 5. and +5 are read; 1,000 is not guessed;
  "30 deg" works in angle boxes and as an angle variable; sizes over 1000 km
  are refused. Variables can't be named sin, pi, deg and the like.
- Deleting a variable that steps use: they keep their sizes as plain numbers
  (every rebuild said "can't be evaluated").
- Imports: an empty, damaged or wrong STL/STEP is refused with the reason,
  not added as a failed step holding the broken file; a damaged or newer
  project file says so in words; reference images are kept at 2048 px (a
  12 MB photo went into the project) and an unreadable one (HEIC) says why.
- Sketch: a spline crossing itself (a hand-drawn loop past its start, a
  figure 8) is split where it crosses: it had no region to extrude.
- Tests: limits, resize (a part's first sizes changed: every later step
  follows), self-crossing splines, the new value-box cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:28:44 +02:00
superGeometry 9cd59bfc28 Targeted sweep after the phone valve build: the same kinds of bugs found elsewhere
- A step opened from History brings what it works on into view (only when
  some of it is off screen, never zooming in).
- On a phone, History and Items close when any tool opens (they covered the
  step's arrow and value box; before, only a sketch closed History).
- Cancel after changing an early step's value is instant: the engine keeps the
  saved project's results while a step is previewed (10.7 s rebuild before).
- Freeform's "tap a plane" step has XY / XZ / YZ and the project's planes as
  buttons, like Sketch.
- A tool waiting for a body (Repair Body, Split...) takes a tapped corner too:
  on an STL a tap lands on a triangle corner almost everywhere.
- Text: after placing it, the hint says to type in the card.
- Typed variables kept in the remaining value boxes (feature numbers, Rotate,
  Tilt); hints for the control-point spline and Join.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 15:58:32 +02:00
superGeometry c30abdf92f Valve by hand on a phone, first third: the fixes it found
- A sketch not made into anything yet shows through bodies and can be tapped there (a pocket sketched through the middle of a body was invisible and out of reach)
- Shape sizes typed with a variable while drawing (bore, bore/4) stay linked to it
- Size boxes take ^, sqrt, sin, cos, tan, abs and pi (36/sqrt(3) for a hex); an unreadable size says so
- A sketch on a face, or one opened again, comes into the free part of the screen
- Phone: opening a sketch from History closes History
- Rectangle hint follows its variant (Center, 3 Points)
- Fillet flyout keeps the picked edges; a full-circle revolve hides its sketch; History's eye hides sketches/planes/axes instead of switching them off, and a switched-off sketch says so
- Valve code build: the left port is threaded now (both threads went into the right one), and the check counts each port

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 15:19:54 +02:00
superGeometry 14dd3898f6 Shell with every face of a body picked (a ball tapped, then Shell) hollows it sealed, with a note, instead of failing with "try a smaller thickness"
Found building the valve's ball by hand on a phone: a ball has one round face, so tapping it picks every face there is, and nothing is left to be the wall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:53:10 +02:00
superGeometry 24e516c812 Ball valve stress test: a 1" brass ball valve built in code with all 23 kinds of step (96 steps, 10 bodies), and the geometry fixes it found.
- Split: a plane crossing a round face's seam twice (the top off a ball turned round the pipe's axis) gave an empty, broken half with no error. The halves are now checked (sound, and adding up to the body), with the tolerant split as the fallback.
- Sweep: flat and round faces of a swept body come out as true planes and cylinders, not curved patches that only look flat. Move Face, Replace Face and fillets treat them as such now.
- Scale Face leaves a side alone that keeps its place (scaled 1 that way): a lever's side runs from the hub to the tip and can't tilt.
- Replace Face on a face that ends on a round boss from one side (a lever's arm on its hub) no longer runs out past the boss: the region stays on the face's side of the boss's axis.
- Thread on a round face that isn't a whole ring (a stem with flats cut along it) is checked against what the groove really overlaps, so it no longer fails with "try a slightly different pitch".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 13:50:35 +02:00
superGeometry 0d57e2a642 Plain guide text for every tool, Offline mode, and phone buttons that say their names
- Every tool's guide text rewritten for beginners: what to tap, in order, in
  everyday words. An empty project says to start with Sketch, which pulses.
- More -> Offline mode: the app's files are kept on the device (a service
  worker and a file list the build writes), so it opens with no connection.
  While online, a new version is downloaded in the background.
- Phones sideways: the guide text shows with History open, the sketch tools
  show their names until one is picked (tap it again to see them), and the
  right column's buttons are wider.
- Touch screens: press and hold any icon button to see its name.
- Phones: the Snap and Units cards are no taller than History.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 00:13:24 +02:00
superGeometry bb4a1faaa0 Phone sideways: the right column's buttons slimmer, so all of them fit without a scroll bar
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 23:55:34 +02:00
superGeometry db270bb2f4 Phone: the Constraints column opens beside its button
It was pinned to a fixed place (low on the screen, then up under the view cube), away from the button that opens it. Phones now place it as bigger screens do: beside the right column, its bottom level with the Constraints button. Sideways phones too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 23:50:38 +02:00
superGeometry a8102dfc14 Phone: a folded card shows a Values chip that opens it again, and the drawing tool's Values chip has no grip
- Double-tapping a card's grip folds it to its title, but a phone doesn't show titles: the folded card was an empty bar with just the grip, and nothing said what it was. Folded, it now shows a Values chip; a tap opens the card again.
- The Values chip while drawing (a card of one button) carried a grip of its own, with nothing to fold: it's just the chip now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 23:49:58 +02:00
superGeometry 4e976b4cd2 Phone: the sketch's Constraints column shows its switches' names, and a tool's window with nothing to set isn't shown
- The Constraints column (Auto constrain, Show constraints) showed only the two switches on a phone: the rule hiding their names was left from when it was a column of icon buttons. The names are back. Its how-to note is left out on phones, and the column sits up under the view cube, clear of the card of what's selected along the bottom (it sat over it).
- On a phone, a tool's window with no values, choices or actions in it - only Done (Cancel being the ✕ by undo) - isn't shown: a tap on empty space finishes, and Enter and Esc still work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 23:34:47 +02:00
superGeometry e8292106c0 Drill build test reshaped after the reference photo (208 steps, 45 bodies), and a plain message for a kernel failure.
The drill now has the photo's shape and parts. The motor housing and the foot are each built from a side outline and a front outline (Intersect), with their sharp edges rounded. The grip is lofted through four rounded-square sections. It also has:
- a black rear cap, a framed vent grille, a label plate, the two-speed slider on top and an LED in the foot;
- black rubber over the grip's back and front, with a stripe down its side;
- a notched silver collar, the clutch ring with its numbers, and a chuck with two ribbed sleeves, a silver nose and three jaws closing to a point;
- a black slide-on battery with a sloped front, the red release button and a "48V Lithium-ion" panel.
The housing and battery are hollowed by taking away copies drawn a wall smaller; the housing then gets a round opening for the gearbox.

- When both the tolerant boolean and the plain one fail with no shape, the step now says that the geometry engine couldn't work it out there, instead of "This shape has not type, it is null". The plain-cut fallback for an invalid tolerant cut is guarded the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 23:16:50 +02:00
superGeometry ae88149180 Drill build test: a cordless drill-driver at 1:1, built in code (132 steps, 33 bodies), and five geometry fixes it found.
Its parts: a housing in two halves (barrel, grip, foot, shelled, with vents and slots for the trigger and the direction switch) under a rubber overmold; the motor with its fan; a planetary gearbox (ring gear, sun, three planets, carrier and spindle); the collar, numbered clutch ring, a keyless chuck with three jaws and a 6 mm bit; trigger, direction switch and switch module; the wires down the grip; a battery in two halves with four 18650 cells, terminals, a release button and an "18V LI-ION" label.

- Shell with no face picked (a sealed hollow) gave back only the inner core: the battery case came out solid. It now keeps the wall round a closed void.
- In the app, a Shell that fell back to an offset copy always failed: a closed shell from the offset was spotted by its class name, which the app's build renames. It is now asked of the shape itself.
- A subtract whose tolerant cut leaves faces that don't meet up uses the plain cut when that one is clean (the direction switch's slot through the housing).
- A cut's volume check counts from meshes when the measured volume of a sound result is off (shelled loft faces: two 120 mm³ terminal slots "took" 920 and were refused).
- A repair of a broken body must keep its volume counted from a mesh: "fixed faces" had added 764 mm³ to the housing, and splitting it later left pieces inside out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:39:49 +02:00
superGeometry 1e5453fd0f Arc reactor build test: a round chest reactor 80 across, built in code for 3D printing (38 steps). Its parts:
- Housing: the case with a bevelled foot and rounded rim, ten slotted screw heads, the inner ring, ribs between the coils, sockets for the coils, a pocket for a 10 mm LED under the lens and a hole for its wires.
- Ten copper coils with their windings grooved in.
- A clear domed lens.

The checks: each part is a clean solid that stands on a flat base, with no overhang past 45°, and fits with 0.2 mm play. The variables "coils" and "play" drive the build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 22:01:03 +02:00
superGeometry f9867107fb Guitar stress test: a steel-string acoustic built in code with 21 kinds of step (143 steps, 38 bodies), and four geometry fixes it found.
- A closed spline is now one smooth periodic curve, its seam halfway along a span. Its start point was a seam that no fillet could pass, so rounding the bottom edge of a body pulled up from a guitar outline failed at any radius.
- Replace Face carries a curved side on along its tangent when the side meets the face along a straight edge (a spline side pulled straight). Moving a heel's foot down ran the foot off along the heel instead.
- Delete Face removes the picked faces together first. A slot's two walls and floor could not be removed one at a time.
- A sweep path's curves are chained end to end. They were used in list order, so a path with a sketch fillet (its arc added last) stopped at the fillet. A string swept over a rounded saddle came out 11 mm long instead of 658, with no error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 21:45:39 +02:00
superGeometry 07dad071d3 Speed: a rebuild sends and draws only the bodies it changed. Every rebuild (each move of a cut or extrude drag too) sent every body's triangles from the geometry worker to the page, and the view rebuilt them all for the graphics card - 3.8 MB a move on the jet engine for one body changed (0.9 MB now). Meshes have a key: an unchanged one goes across as its key only, and the view keeps what it drew for it. Join / cut checks work out a body's volume, gaps and hair-thin faces once per shape (the target's volume was measured twice and the result's three times, and the body before the step was checked again on each drag move - slow on a freeform's curved faces)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 20:47:24 +02:00
superGeometry 6fc54e4871 Phone sketch cards: smaller and narrower, and none over the drawing while a shape is drawn
- Phones only: tool cards are at most 300 px wide (they ran across the whole screen), with shorter value boxes (48 x 28, was 58 x 34), smaller names, buttons, chips and icons. Tablets and desktops unchanged
- Phones, while drawing a line, arc, rectangle, circle, polygon, ellipse or spline: no values card, just a small Values chip (a spline keeps its Done beside it). Tap Values for the full card as before: X / Y of the first point, Length, Angle, Across / Up, Radius..., with Done placing it. It stays open for the rest of that shape or line chain. The finished curve's card shows when it's tapped in Select

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:59:07 +02:00
superGeometry de38479e43 Reload and More → Update: no flash of black text on a white page first - the page itself now carries the app's grey and keeps the text for search engines hidden (a few rules in index.html), so the moment before the app's stylesheet is in looks like the app
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:34:15 +02:00
superGeometry a2dc0cc860 Feedback: the project file option taken out - a Reddit post takes text up to 40,000 characters and no files, so a real project rarely fit and pasting it was a chore. The window is back to a kind, a title, a description and the version / browser line; nothing from the project goes along
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:21:52 +02:00
superGeometry 1043a38051 Feedback: the project file is always copied as it is, for pasting into a Code Block of Reddit's own editor - the post marks the spot. It was filled into the post as Markdown (```json) when small and copied with those marks when big, which ended up inside Reddit's code block. The 40,000-character count stays
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:08:33 +02:00
superGeometry f905c20008 Feedback: a project file up to Reddit's whole 40,000 characters can go in a bug report - the window counted 4,500 for a description that might be written, so a 36k-39k project was turned away with a short one. Now the real post is counted: past 40,000 Open Reddit waits and the window says how many characters to cut from the description (or untick the file)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:05:19 +02:00
superGeometry ef9fa8ddf5 Project links taken out entirely: Feedback adds the project only as its file in a code block (filled into the post when it fits Reddit's address, else copied for pasting; one too big for a post can't be added), and the app no longer opens supergeometry.app/#p=… links. Removed io/projectLink, io/linkHash, their test and the fflate dependency. Feedback still loads on first tap
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:59:44 +02:00
superGeometry 98254380a6 File → Share by link taken out: chat apps (WhatsApp) show only the start of a long message, so a big project's link arrived cut short, and a short link would need the project stored on a server (the app promises work stays on the device). Sharing is the .super file (Save and its share mark). Links still open (bug reports on Reddit carry one); a cut-short link now says so and asks for the .super file instead
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:55:52 +02:00
superGeometry bb816bf60c File → Share by link (under Save project): copies a link with the whole project in it - paste it anywhere, and whoever opens it gets the project in supergeometry.app (a new project, theirs kept). Copied inside the tap (Safari needs that); where copying isn't allowed the link is shown to copy by hand; a very long link says some apps may cut it. Feedback and the link packing (with its compressor) now load on first use instead of with the app: only reading the address for a link (io/linkHash) is there at start
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:39:06 +02:00
superGeometry 4a6bee6a37 Project links about a third shorter (half for a small project): the long made-up ids become short ones in the link (and long unique ones again when it's opened, so two linked projects never mix), and it's compressed with a dictionary of the words every project file has. The first letter is the packing's version, so links made now keep opening later. Rounding off float noise was tried and left out: it changed what the fan rebuilt into. fflate (already installed with three's types) is now a dependency of its own. Test: tests/projectlink.test.ts builds every fixture project from its file and from its link (each in a fresh process) - same bodies, volumes and errors
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 18:23:28 +02:00
superGeometry 95e4fdfd69 Project links: supergeometry.app/#p=... opens the project packed in it (compressed, after the # so it never reaches a server) as a new project of its own - the one open is kept as it was, the welcome window is skipped, and the address is cleared so a reload doesn't open it again. Works on a fresh visit and when pasted into an open tab. Feedback: a bug report puts such a link in the post ("Open it in 3D in supergeometry.app") along with the file as code; what doesn't fit in Reddit's address is copied for pasting (only the code first, then the link too), and only a project too big even as a link can't be added
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:40:21 +02:00
superGeometry 522bef980b Feedback: a bug report can carry the project's file as a code block (a .super file is JSON), ticked by default and said in the window. A small file is filled into the post; a longer one is copied and the post marks where to paste it (the button says Copy file and open Reddit); one too big for a Reddit post can't be ticked and the window says to save and share it with a link
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:28:08 +02:00
superGeometry cfaafde27d More → Feedback: report a bug, suggest something or start a discussion on r/supergeometry. Pick the kind, write a title and a description, and Reddit's new-post page opens in a new tab with it filled in (sign in there and press Post). A bug report adds the app version and browser (shown in the window, can be unticked); nothing from the project goes along
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:22:27 +02:00
304 changed files with 55383 additions and 1741 deletions
+2 -2
View File
@@ -1,5 +1,5 @@
supergeometry.app - free browser-based solid modeler
Copyright (C) 2026 supergeometry.app contributors
superGeometry.app - free browser-based solid modeler
Copyright (C) 2026 superGeometry.app contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
+154 -79
View File
@@ -1,10 +1,10 @@
# supergeometry.app
# superGeometry.app
**A free 3D design (CAD) app that runs in your web browser** - on a computer,
an iPad or Android tablet, a phone, or a VR headset like the Meta Quest 3.
No account, no download, no subscription. Your work stays on your device.
👉 **Open it:** [supergeometry.app](https://supergeometry.app)
👉 **Open it:** [superGeometry.app](https://supergeometry.app)
Use it to design things for 3D printing, woodworking, laser cutting or just to
think in 3D: brackets, boxes, vases, knobs, threads, enclosures, furniture parts…
@@ -30,7 +30,10 @@ think in 3D: brackets, boxes, vases, knobs, threads, enclosures, furniture parts
15. [For developers](#for-developers)
16. [License](#license)
Inside the app, **More → Help** shows what every button does.
Inside the app, **More → Help** shows what every button does, and **More →
Tutorial** builds a first part with you: an M10 bolt and the nut that fits it,
one lit tap at a time (the first time the app is opened, it is offered once
the welcome window is closed).
---
@@ -42,8 +45,9 @@ Almost everything follows the same rhythm:
2. **Turn it into a solid** - pull it up (*Extrude*), spin it around an axis
(*Revolve*), or move it along a path (*Sweep*).
3. **Select something and change it** - tap a face, an edge or a whole body:
only the tools that make sense for it appear on the left. Drag the arrow or
type a number.
it can be dragged by itself (or by its arrow or dot), or typed; the buttons
beside it hold the next likely tools, Delete and More, and the line at the
bottom has every tool by group.
4. **Every step is remembered** in *History*, so you can go back and change a
size later - everything after it updates.
@@ -53,21 +57,28 @@ There's no wrong order. Undo (bottom left) is always one tap away.
## Your first part: a box with a hole
1. Tap **Sketch** (left column), then tap the blue **XY** square near the
middle of the screen. The view turns to look straight down at that plane.
2. Tap **Rectangle**, tap one corner, tap the opposite corner. While you draw,
type a number for an exact size (e.g. `40`, Tab, `30`).
3. Tap **Circle**, tap a centre inside the rectangle, tap again for the size
1. A new project opens straight in a sketch on the floor, looking down at
it, with **Line** on. (Any other time: tap **Sketch** on the line at the
bottom, then a plane or a flat face.)
2. Tap **Draw**, then **Rectangle**; tap one corner, tap the opposite corner. While you draw,
type a number for an exact size (e.g. `40`, Tab, `30`, then Enter or a
click): with a mouse the sizes show in small tags by the pointer, the one
a typed number goes to lit. The ways a tool can
be used (Rectangle: Center, Diagonal, 3 Points) are on the line while it is on.
3. Tap **Draw**, then **Circle**; tap a centre inside the rectangle, tap again for the size
(or type `8`).
4. Tap **Exit Sketch** (top left of the tools) - or just tap an empty spot
while looking at it from the side.
4. Tap **Exit** at the end of the line. The view swings round to a
three-quarter view.
5. Tap inside the rectangle (but outside the circle): that region turns blue
and an **arrow** appears. Drag the arrow up, or type `20`. You now have a
box with a round hole.
6. Tap the top face of the box. Drag its arrow to make it taller - the hole
follows. Tap an edge and drag the dot **outward** for a rounded edge
(*fillet*) or **inward** for a bevel (*chamfer*).
7. **File → Export STL** to 3D-print it.
and an **arrow** appears. Drag the shape itself, or its arrow, up - or type
`20`: drawn on a plane, up makes a new body (down would cut). Tap the tick.
You now have a box with a round hole.
6. Tap the top face of the box and drag it to make it taller - the hole
follows. Tap an edge and drag it **outward** for a rounded edge
(*fillet*) or **inward** for a bevel (*chamfer*). Tap the hole's wall:
**Thread** is on a button beside it.
7. **More → Print / Share** says whether it is fit to print and saves it as
3MF, STL or STEP.
## Second part: a vase
@@ -86,28 +97,37 @@ There's no wrong order. Undo (bottom left) is always one tap away.
| | Mouse | Touch / pen | Headset controller |
|---|---|---|---|
| Turn the view | left-drag empty space | one-finger drag | drag with the trigger |
| Move the view | right or middle-drag | two-finger drag | - (use the view cube) |
| Turn the view | right-drag (or Alt + left-drag) | one-finger drag | drag with the trigger |
| Move the view | middle-drag (or Shift + right-drag) | two-finger drag | - (use the view cube) |
| Zoom | mouse wheel | pinch | thumbstick / pinch |
| Select | click | tap | point and trigger |
| Select several | left-drag a box on empty space, or Ctrl + A for everything | tap one after another | point and trigger |
| Select a whole body | double-click | double-tap | double-trigger |
| Deselect | Esc or click empty space | tap empty space | tap empty space |
| Step back | right-click or Esc | - | - |
- **Used to another program's mouse?** Settings → Mouse makes the buttons
turn, move and zoom the view as they do there: Onshape and Tinkercad (the
way the app comes), Fusion / Inventor / Revit / AutoCAD, SolidWorks,
Creo / Solid Edge / Blender / SketchUp, NX, CATIA / FreeCAD, or Rhino -
and sets which way the wheel zooms.
- **Right-click steps back**: first what's half done or picked, then the
drawing tool, then out of the sketch; in other tools it backs out. With
something selected, right-click shows its tools by the pointer.
- On touch screens **every tap adds to the selection**; tap again to drop it.
- **A tap picks that thing** and lets the last pick go; tap it again to drop
it. Shift, Ctrl or the **+** beside the pick's name adds to the pick. With
a face or an edge picked, **Whole body** beside its name picks the body (a
double tap on the model does too).
- **A list opened from the line stays up** while you turn, move or zoom the
view; it goes when you choose something in it or tap the model.
- **Fit** (right column) zooms so everything is on screen.
- **Fit**: double-tap the view cube to get everything on screen.
- **View cube** (top right): tap a face for a straight-on view (Top, Front…);
⟲ ⟳ at its top corners turn the view by 90°.
- **Orbit centre** (the cube's bottom-left button): tap it, then tap a point -
the view now turns around that point. Fit resets it.
- **Views** (the cube's bottom-right button): standard and saved views, and
how the view looks; tap again to close.
- On touch screens, **press and hold a tool** to see its name in the middle
of the screen; let go on it to use it, slide off to cancel.
- **Views** (the cube's bottom-right button): standard and saved views; tap
again to close.
---
@@ -116,28 +136,44 @@ There's no wrong order. Undo (bottom left) is always one tap away.
**Top bar** (top centre) - the project name (tap to rename), **File** (new / open / save /
export), **Items** (a list of everything, with eyes to hide or show and
folders to group; each kind - Bodies, Sketches, Planes & axes, Images - folds
away under its heading, and a plane's icon shows how it was made), **More**
(fullscreen, Help, About, support). On tablets and computers Items runs the
full height of the screen, like History.
away under its heading), **History**, **More** (fullscreen, Help, About,
support).
**Left column** - the tools. With nothing selected you get the ones that
*make* things (Sketch, Freeform, Extrude, Revolve, Transform, Construct,
Insert…). With something selected you only see what can be done with it,
in groups (picking, moving and patterns, making, combining, construction,
colour, delete) apart with a dim line.
**The line at the bottom** is how every tool is reached. Tap part of the
model: a tag over the line names what is picked, and the line shows the
groups - Sketch, Freeform, Transform, Construct, Modify, Combine, Create -
each a list: what can be done with that pick first, then the group's other
tools in a quieter part (each asks for its own pick as it starts). The group
whose list is open stays lit. **More**, at the end of the line, holds only
what is not on the line already: Insert, BIM, Section View, Measure,
Variables, Print / Share, and the pick's own (Delete, Colour, Isolate). Tap a
tool and the line becomes its settings: tap a number to type it or drag it
sideways, tap a word to change it, tap the model to fill a blank; the tick
finishes, the cross takes it back. On a phone held upright a tool shows its
size and what it still needs tapped, and the rest is one word, **Options**.
In a sketch the line holds Draw, Modify and Transform.
**Right column** (middle of the right edge) - Fit, Snapping, Units & grid,
Display mode, Screenshot, Numpad (on / off), History, and in a sketch,
Constraints.
**Looks ahead** - with a mouse, the pointer over a tool draws what it would
do in dashed yellow on the model before anything starts: a face's outline
lifted (Extrude, Offset Face) or sunk (Shell), the lines a Fillet or Chamfer
runs between, a row or a ring of copies for a pattern.
**Bottom left** - Undo / Redo, Section View (cut the view open), Measure and
Isolate (show only the selected bodies).
**Quick buttons** - round buttons beside a pick with its next two likeliest
tools (a flat face Sketch and Move, a round face Thread and Fillet, an edge
Chamfer and Move, a body Fillet and Mirror), then **Delete**, then **More**,
which opens every other tool that pick has. In a sketch: Construction and
Delete.
**The tool card** - the values for whatever you're doing (sizes, counts,
options), its own actions, and Cancel / Done, each apart with a dim line. It
keeps clear of what you're drawing; drag it by its grip where you want it
(remembered per screen type), double-tap the grip to fold it down to its
name (and again to open it).
**Right edge** - **Fit**, **Display** (shaded, wireframe, X-ray) and
**Settings**: one sheet with Units & grid, Snapping, the number pad and
Appearance, each row saying how it is set now.
**Bottom left** - Undo / Redo.
**A tool's settings** - the values for whatever you're doing (sizes, counts,
options) are the words on the line while the tool is open, with Cancel and
Done at its end. The size that is dragged is also in a box on the model:
tap it to type.
---
@@ -145,12 +181,12 @@ name (and again to open it).
Tap **Sketch** and pick where to draw: an origin plane (tap it, or the
**XY** floor / **XZ** front / **YZ** side buttons), a flat face of a part, or
one of your construction planes (listed by name in the card). In a
one of your construction planes (listed by name on the line). In a
straight-on view (Front, Top…) Sketch goes on the face you're looking at.
Sketches on a face measure X / Y from the model's origin.
**Drawing tools:** Line (keeps going from the last point; tap the first point
to close), Arc (two ends, then the bend - or by centre), Spline (smooth curve through points;
to close, which ends the line), Arc (two ends, then the bend - or by centre), Spline (smooth curve through points;
*Fit* or *Control* points, or *Draw*: press and drag freehand like a pencil - the stroke
is cleaned up into a few lines, arcs and smooth curves, corners kept, so an extrusion
gets a handful of faces, not hundreds; end where you began to close it), Rectangle (diagonal / centre / 3 points), Circle
@@ -160,7 +196,7 @@ a few lines, arcs and smooth curves, so extruded text has a face per side, not h
(copies body edges or other sketches' curves here).
**Exact points on touch screens:** right after the first tap of a line,
rectangle, circle, polygon or ellipse the card has **X / Y** for that point
rectangle, circle, polygon or ellipse the line has **X / Y** for that point
(a fingertip can't hit a 1 mm grid). A line then takes **Length and Angle**,
or **Across and Up** for a slope ("in 10, up 12"); an arc by centre takes the
centre, Radius and the Start and End angles. Grid snapping follows the zoom
@@ -171,6 +207,10 @@ is placed with Enter or Done.
perpendicular, where two cross) are kept as constraints. Dragging a point onto
another joins them.
**Fill Pattern:** a closed shape filled with lines from edge to edge (straight, crossed, zigzag, waves) or with
small shapes (dots, honeycomb, squares, diamonds), its spacing, size and angle set; the strips and cells are
shapes to extrude or cut, for textures.
**Edit tools:** Offset Edge (parallel copy; whole outlines too), Fillet and
Chamfer (round or bevel a corner where lines or arcs meet; tap the next corner
to go on), Mirror (the selected shapes, across a line or an axis), Trim (cut
@@ -180,8 +220,6 @@ on along their circle), Split, Move/Rotate (gimbal, or Rotate About a tapped
centre), Scale, Pattern (linear with an arrow you drag, or circular around a
centre), Delete. Tools with options start with the option you used last.
Tapping empty space finishes Offset, Move, Scale, Pattern, Rotate and Mirror.
On phones the tool column shrinks to icons once you place a point; tap the
tool in use to see the names again.
**Select** (in a sketch): tap curves to select them, double-tap for a whole
shape. Drag points or curves, or use the gimbal. Tap an arc or circle to type
@@ -198,13 +236,13 @@ picked stays put, the others adapt to it). Constraints are strict: one that
contradicts those already there isn't added - remove the old one first, or
switch **Auto constrain** off; a typed value that can't be met is refused
rather than bending the sketch. Their marks are small and faint, a colour per
kind, and never catch a tap meant for the drawing. Toggle the column with the
**Constraints** button on the right.
kind, and never catch a tap meant for the drawing. Show or hide their column
with the **Constraints** button at the right edge while sketching.
Any closed shape becomes a **region** (blue when selected) you can extrude,
revolve, sweep or loft. Overlapping shapes split into separate regions.
Tapping a region shows Extrude's arrow - drag it, or type a height - and
Revolve, Sweep and Loft beside it in the column for the same shape. While the
Tapping a region shows Extrude's arrow - drag it or the shape itself, or
type a height - with Sketch and Revolve on the buttons beside it. While the
arrow is still at 0, tapping more regions of the same sketch adds them;
**All shapes** takes every shape at once. Double-tap a shape to open its
sketch. A sketch stays in view until every region of it is used.
@@ -213,9 +251,9 @@ sketch. A sketch stays in view until every region of it is used.
## Making and changing solids
- **Extrude** - pull a region or a face. Negative distances cut. In *Auto*
mode an extrusion that runs into another body cuts through it; choose *New*
for a separate body. **Taper end %** sizes the far end (100 none, 0 a
- **Extrude** - pull a region or a face. **Operation** (Auto, New body, Add,
Cut, Intersect): Auto goes by direction - on a plane + is a new body and -
a cut, on a face out adds and in cuts. **Taper end %** sizes the far end (100 none, 0 a
point: a spire, a pyramid or a cone in one step) - type it or drag the box
left / right. Extrude starts at the last distance.
- **Revolve** - spin a region around an axis (a separate line, a side of a
@@ -229,6 +267,10 @@ sketch. A sketch stays in view until every region of it is used.
- **Fillet / Chamfer** - tap edges, drag the dot (outward rounds, inward
bevels) or type a size in the box on the model; variables work too. A
fillet that can't be made leaves the edge sharp with a note in History.
- **Direct touch** - what is picked is dragged by itself: a face pushed or
pulled, a sketch's shape pulled up into a solid, an edge rounded, a body
slid over the floor. On a touch screen press and hold a face, shape or edge
and pull, in one touch.
- **Faces** - drag the arrow to push/pull a face: its neighbours follow,
curved ones included; fillets next to it are kept. **Move/Rotate Face**
(a gimbal on the face) moves it every way and turns it about its normal. A
@@ -256,17 +298,19 @@ sketch. A sketch stays in view until every region of it is used.
- **Split Body** - by a plane (yours, by name) or a face.
- **Thread** - tap a round face or a hole's rim: a shank at the nominal size
gets an outside thread, a hole at the tap-drill size an inside one. The
pitch starts at the ISO coarse pitch (the card says what it makes, e.g.
M10 × 1.5); left-hand as an option.
pitch starts at the ISO coarse pitch (the line says what it makes, e.g.
M10 × 1.5); left-hand as an option; free ends get a 45° lead-in.
- **Repair Body** - fixes an imported or broken body (gaps, bad faces,
slivers, inside-out) without changing its shape or size.
- **Fill to Plane** - an open freeform surface becomes a solid by filling
the gap down (or up, or across) to a plane.
- **Freeform** - organic shapes: start from a box, sphere, cylinder or plane
(its size and rows in the card) and pull its cage points, edges and faces.
(its size and rows on the line) and pull its cage points, edges and faces.
Tap picks the closest point, edge or face (tap a face again for the one
behind it); press on empty space and drag a box to pick the points inside.
Move / Turn / Scale take exact X, Y, Z values in the card. Cage tools:
behind it); press on empty space and drag a box to pick the points inside
(on a touch screen: switch on **Pick in a box** on the line, and a finger
draws the box - the points behind are picked too, a whole slice from a side view).
Move / Turn / Scale take exact X, Y, Z values on the line. Cage tools:
**Extrude faces** (Length, Bend, Taper and Steps sliders - a spout in one
go), **Bridge faces** (two faces become a tube; two looking the same way
arch into a handle, with Arch and Segments), **Inset**, **Add edge loop**,
@@ -294,9 +338,26 @@ sketch. A sketch stays in view until every region of it is used.
- **Colour** - ten soft colours or **Custom…** for any colour; and how
see-through a body is.
- **Section View** - cut the view (not the part) to look inside; the cut
shows as a solid face with a thick outline. **Place Plane** in its card
shows as a solid face with a thick outline. **Place Plane** on the line
puts a construction plane where the cut is (to sketch on or split with).
- **Measure** - distances and angles; pin a measurement to keep it.
- **BIM** (under More) - **Materials**: a real material for each body, which
gives it its mass. **Technical Sheet**: the parts list with masses and the
materials' data. **Drawings**: sheets with views, dimensions, item numbers
and a title block.
- **Assemblies** (More → BIM, still being tried out) - how the parts move.
The parts stay where you modelled them; a **joint** only says how two of
them move against each other. **Add joint**, tap a face on each part, and
the kind is read off the faces: two round faces on one axis, or two flat
faces one above the other, make a **Hinge** (a **Screw** of the thread's
pitch when one part is threaded - a thread's own faces can be tapped too);
two flat faces side by side, a **Slide**;
anything else, **Fixed**. Drag a part to move it by its joint, or type its
angle or distance; **Limits** keep it between two values; **Follows** makes
one joint go with another by a ratio (gears); **Explode** pulls the parts
apart. The pose is kept with the project and shown after OK; **Home** puts
every part back where it was modelled. **Stop on contact** keeps a dragged
part from running into another. No weight or forces.
---
@@ -312,11 +373,17 @@ sketch. A sketch stays in view until every region of it is used.
↔ a length, ∠ an angle, # a number - and follows it as the model moves.
Tap a tag to type its value or a formula, or drag the value: the model
follows as you go, and lines show what it's made from and what uses it.
The card has New Variable and the whole list; tap Variables again to switch off.
The line has New Variable and the whole list; tap Variables again to switch off.
Type them into any field (`wall * 2`) or pick them from the **ƒx** menu
next to a value. Change the variable later and everything using it updates.
- The **on-screen numpad** (the keypad button in the right column - tap it
on or off) replaces the system keyboard for value boxes. It's on by default
A size that follows a variable says so on the line (`od / 2 = 60 mm`).
Formulas take `+ - * / ^`, brackets, units (`2 in + 5 mm`) and `sqrt`,
`abs`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `floor`, `ceil`,
`round`, `min`, `max` - `floor(length / pitch)` is how many fit. Changing
the project's unit changes no size: plain numbers in formulas are given
the unit they were typed in.
- The **on-screen numpad** (Settings at the right edge, Number pad on
screen) replaces the system keyboard for value boxes. It's on by default
on phones, tablets and headsets. Tapping a box selects its value, so typing
replaces it; nothing is applied until you press ↵. After the second tap of
a line, its length box opens right away. Drag the numpad by its grip where
@@ -362,8 +429,12 @@ can't be rebuilt after a change, it's marked and the reason is shown.
File → Export DXF. Construction lines go on their own layer.
- **File → New project** starts an empty one; the open project stays in the
gallery.
- **Insert** brings in STEP, STL, SVG and DXF files, and images to trace over
(on the floor, front or side, its middle at the X / Y you type).
- **More → Insert** brings in files (STEP, STL, OBJ, 3MF, DXF, SVG), another
project's parts (**Project**), and pictures to trace over (**Image on
plane**: on the floor, front or side, its middle at the X / Y you type).
- A **.super** file is the whole project: every step and sketch, variables,
saved views, names, colours, and the BIM side - materials, drawings, joints
and the assembly's pose.
---
@@ -373,15 +444,12 @@ can't be rebuilt after a change, it's marked and the reason is shown.
first turns the bin red, the second deletes. It goes back by itself after 3
seconds, or at a tap anywhere else. Delete in the tools and in a tool's
window takes one tap (Undo brings it back).
- Tools show as icons: press and hold one to see its name.
- With a pen, fingers are ignored while the pen touches the screen.
- iPad / Android: **More → Fullscreen** gives the whole screen. On phones and
tablets the app offers to be **installed on the home screen** (or More →
Install app); on iPhone/iPad it's *Share → Add to Home Screen*.
- The window the app opens with has a **Full screen** button. The tool card fits the widest
clear gap along the bottom (beside undo/redo on a phone on its side), and a
tool's options open beside a column of tools instead of over it.
- Fit frames the model in the part of the screen the columns and bars leave
- The window the app opens with has a **Full screen** button.
- Fit frames the model in the part of the screen the bars leave
free.
- Meta Quest: open the site in the Quest browser; buttons and pick distances
are bigger, and the numpad is on.
@@ -428,20 +496,21 @@ OpenCascade (via replicad) running in a Web Worker; the UI is plain DOM over a
three.js view. Units are millimetres internally; the display unit is a setting.
**Interaction model.**
- Nothing selected → the left column shows creation tools: Sketch, Freeform,
- Nothing selected → the line at the bottom has every tool (one that needs a pick asks for it as it starts): Sketch, Freeform,
Extrude, Revolve, Sweep, Loft, Shell, Transform ▸ (Move/Rotate, Scale,
Translate, Mirror, Rotate Around Axis, Patterns), Boolean ▸ (Union,
Subtract, Intersect), Construct ▸ (planes, axes), Insert ▸ (variables,
images, files), Tools ▸ (Offset Face, Offset Edge, Split Body, Fill to Plane, Thread,
Repair Body…).
- Something selected → only tools valid for it are shown (unusable ones are
hidden, not greyed). Faces get a drag arrow (offset), straight edges a
Move/Rotate gimbal (Fillet / Chamfer in the list), bodies a gimbal
(move/rotate, with Copy). A sketch region gets Extrude's arrow plus
Revolve / Sweep / Loft.
- Something selected → each group lists the tools valid for it first, then
its other tools (those ask for their own pick). The pick is dragged by
itself or by its handle: faces an arrow (offset), edges a dot (fillet,
inward a chamfer), bodies a gimbal (move/rotate, with Copy; its middle dot
moves the pivot). A sketch region gets Extrude's arrow plus Revolve /
Sweep / Loft.
- Every operation is a *feature* in History; editing a feature replays
everything after it.
- Values: type while dragging, or in the bottom panel; expressions and
- Values: type while dragging, or tap a number on the line at the bottom (the tool's options); expressions and
variables are accepted everywhere a number is.
**Project file (`.super`, JSON).**
@@ -479,6 +548,12 @@ three.js view. Units are millimetres internally; the display unit is a setting.
`parallel`), `axis`, `moveFace` (face / edge / vertex), `scaleFace`,
`replaceFace`, `deleteGeom`, `freeform` (`cage`, `surface`, `thickness`,
`symmetry {origin, normal}`), `thread`, `repair`, `import`, `image`.
- Beside `features`, the project holds `joints` (`type`: `fixed`, `hinge`,
`slide`, `screw`; the two bodies `a` and `b`; the joint's line `origin`,
`axis`; `min`, `max`; a screw's `pitch`; `drive {joint, ratio}`), `ground`
(the body that stands still) and `pose {values, exploded}` (each joint's
value by its id: degrees, or mm for a slide). They move what is shown, not
the model.
- Faces and edges are referenced by geometry, not index:
faces `{body, center, normal, area}`, edges `{body, mid, dir, length}`.
- `exprs` maps a field path (`"distance"`, `"op.translate.2"`) to an
+1 -1
View File
@@ -1,6 +1,6 @@
# Architecture
supergeometry.app is a static web app. There is no server: everything (geometry kernel
superGeometry.app is a static web app. There is no server: everything (geometry kernel
included) runs in the browser, so it can be hosted for free and works offline.
```
+38 -18
View File
@@ -4,22 +4,31 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<meta name="theme-color" content="#1f2125" />
<meta name="color-scheme" content="dark" />
<!-- Already dark: browser dark-mode add-ons (they lighten dark fills, and washed the wheels out) leave it as it is. -->
<meta name="darkreader-lock" />
<!-- The first paint, before the app's stylesheet is in (a reload, More → Update):
the app's grey, and the search engines' text hidden - not black text on white. -->
<style>
html, body { margin: 0; height: 100%; background: #2b2d31; color: #e8e9ec; }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }
</style>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="description" content="Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download." />
<link rel="canonical" href="https://supergeometry.app/" />
<!-- Link previews (WhatsApp, Reddit, Discord, X, Facebook...). -->
<meta property="og:type" content="website" />
<meta property="og:site_name" content="supergeometry.app" />
<meta property="og:site_name" content="superGeometry.app" />
<meta property="og:url" content="https://supergeometry.app/" />
<meta property="og:title" content="supergeometry.app - Free 3D CAD and 3D modeling in your browser" />
<meta property="og:title" content="Free 3D CAD modeling on any device" />
<meta property="og:description" content="Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download." />
<meta property="og:image" content="https://supergeometry.app/og-image.png" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta property="og:image:alt" content="supergeometry.app - free 3D CAD in your browser" />
<meta property="og:image:alt" content="Free 3D CAD modeling on any device" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="supergeometry.app - Free 3D CAD and 3D modeling in your browser" />
<meta name="twitter:title" content="Free 3D CAD modeling on any device" />
<meta name="twitter:description" content="Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download." />
<meta name="twitter:image" content="https://supergeometry.app/og-image.png" />
<!-- What it is, for search engines: a free design app that runs in the browser. -->
@@ -27,7 +36,7 @@
{
"@context": "https://schema.org",
"@type": "WebApplication",
"name": "supergeometry.app",
"name": "superGeometry.app",
"url": "https://supergeometry.app/",
"description": "Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download.",
"applicationCategory": "DesignApplication",
@@ -46,15 +55,15 @@
<link rel="manifest" href="./manifest.webmanifest" />
<link rel="icon" href="./icon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="./apple-touch-icon.png" />
<title>supergeometry.app - Free 3D CAD and 3D modeling in your browser</title>
<title>Free 3D CAD modeling on any device</title>
</head>
<body>
<!-- What the app is, as text (the app itself is a 3D canvas and buttons):
for search engines and screen readers. Not shown on screen. -->
<main class="sr-only" aria-label="About supergeometry.app">
<h1>supergeometry.app - free 3D CAD in your browser</h1>
<main class="sr-only" aria-label="About superGeometry.app">
<h1>Free 3D CAD modeling on any device</h1>
<p>
supergeometry.app is a free 3D design (CAD) and 3D modeling app that runs in your web browser, on a computer
superGeometry.app is a free 3D design (CAD) and 3D modeling app that runs in your web browser, on a computer
(Windows, Mac, Linux, Chromebook), an iPad or Android tablet, a phone, or a VR headset like the Meta Quest 3.
No account, no download, no subscription. Your work stays on your device.
</p>
@@ -79,8 +88,8 @@
<div id="pins"></div>
<header id="topbar">
<div class="brand"><img class="brand-icon" src="icon.svg" alt="supergeometry.app" width="30" height="30" /><span class="brand-name">supergeometry<span class="brand-tld">.app</span></span></div>
<input id="project-name" class="project-name" spellcheck="false" autocomplete="off" title="Project name - click to rename" aria-label="Project name" />
<div class="brand"><img class="brand-icon" src="icon.svg" alt="superGeometry.app" width="30" height="30" /><span class="brand-name">superGeometry<span class="brand-tld">.app</span></span></div>
<span id="project-name" class="project-name" role="textbox" tabindex="0" spellcheck="false" title="Project name - click to rename" aria-label="Project name"></span>
<div class="menu-wrap">
<button id="file-btn" class="text-btn">File</button>
<div id="file-menu" class="menu" hidden>
@@ -91,25 +100,34 @@
<button id="m-stl">Export STL</button>
<button id="m-step">Export STEP</button>
<button id="m-3mf">Export 3MF</button>
<button id="m-glb">Export GLB</button>
<button id="m-each">Export each body separately…</button>
<hr />
<button id="m-dxf">Export DXF (sketch)</button>
<button id="m-svg">Export SVG (sketch)</button>
</div>
</div>
<button id="items-btn" class="text-btn" title="Items (bodies, sketches, planes)">Items</button>
<button id="history-btn" class="text-btn" title="History (every step in order)">History</button>
<button id="vr-btn" class="text-btn vr-btn" title="View the model in the headset" hidden>Enter VR</button>
<div class="menu-wrap">
<button id="more-btn" class="text-btn">More</button>
<div id="more-menu" class="menu" hidden>
<button id="m-fullscreen">Fullscreen<span class="menu-soon">F11</span></button>
<button id="m-install" hidden>Install app <span class="menu-soon">Home screen</span></button>
<button id="m-help">Help</button>
<button id="m-hints">Guide text <span class="menu-soon" id="m-hints-state"></span></button>
<button id="m-tutorial">Tutorial <span class="menu-soon">soon</span></button>
<button id="m-update">Update</button>
<button id="m-about">About supergeometry.app</button>
<button id="m-donate">Boost / Donate / Support <span class="menu-soon" id="m-donate-arrow">▸</span></button>
<hr />
<button id="m-offline" class="menu-toggle" role="switch">Offline mode <span class="menu-soon" id="m-offline-state"></span><span class="switch"></span></button>
<hr />
<button id="m-hints" class="menu-toggle" role="switch">Guide text <span class="menu-soon" id="m-hints-state"></span><span class="switch"></span></button>
<button id="m-tutorial">Tutorial <span class="menu-soon">a bolt and nut</span></button>
<hr />
<button id="m-help">Help</button>
<button id="m-feedback">Feedback <span class="menu-soon">Bug / Idea</span></button>
<button id="m-about">About</button>
<button id="m-donate">Support <span class="menu-soon" id="m-donate-arrow">▸</span></button>
<div id="m-donate-list" class="menu-sub" hidden>
<button id="m-support-makerworld">MakerWorld - Boost <span class="menu-soon">↗</span></button>
<button id="m-support-bmc">Buy Me a Coffee <span class="menu-soon">↗</span></button>
<button id="m-support-stripe">Card (Stripe) <span class="menu-soon">↗</span></button>
</div>
<hr />
<div class="menu-note" id="m-version"></div>
@@ -129,6 +147,8 @@
<div id="viewcube-host"></div>
<nav id="right-col" aria-label="View settings"></nav>
<!-- Isolate, Measure, Section: always there, at the middle of the left edge. -->
<nav id="left-col" aria-label="Isolate, measure, section"></nav>
<div id="popover" hidden></div>
<nav id="toolbar" aria-label="Tools"></nav>
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "supergeometry",
"version": "0.3.0",
"version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "supergeometry",
"version": "0.3.0",
"version": "0.6.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@fontsource/bebas-neue": "^5.3.0",
+5 -2
View File
@@ -1,7 +1,7 @@
{
"name": "supergeometry",
"private": true,
"version": "0.3.0",
"version": "0.6.0",
"description": "Free, browser-based solid modeler for every device.",
"license": "AGPL-3.0-or-later",
"type": "module",
@@ -9,7 +9,10 @@
"dev": "vite --host",
"build": "tsc --noEmit && vite build",
"preview": "vite preview --host",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"check": "tsx scripts/check.ts",
"render": "tsx scripts/render.ts",
"live": "tsx scripts/live.ts"
},
"dependencies": {
"@fontsource/bebas-neue": "^5.3.0",
+20
View File
@@ -16,3 +16,23 @@
/assets/*
Cache-Control: public, max-age=31536000, immutable
/sw.js
Cache-Control: no-cache
/offline-files.json
Cache-Control: no-cache
/version.json
Cache-Control: no-cache
# Security, on every file.
# - What the page may load and run: its own files only. No script written into the page runs (a project file from
# someone else that got markup onto the page could do nothing with it), no script from another site, no plugins.
# 'unsafe-eval' is for the geometry engine, which builds part of itself as it starts ('wasm-unsafe-eval': its
# WebAssembly). Pictures and the Browser window's pages may come from anywhere: they are what the user opens.
# - Files are what they say they are (nosniff); other sites are told only the site's address, not the page's.
/*
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: http:; font-src 'self' data:; connect-src 'self' data: blob:; worker-src 'self' blob:; frame-src https: http:; media-src 'self' data: blob:; object-src 'none'; base-uri 'self'; form-action 'none'
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 26 KiB

+241 -3
View File
@@ -1,5 +1,243 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="14" fill="#1f2125"/>
<path d="M32.00 10.00 L20.23 25.20 L43.77 25.20Z" fill="#a9cbff"/><path d="M12.95 21.00 L32.00 10.00 L20.23 25.20Z" fill="#bcd6ff"/><path d="M32.00 10.00 L51.05 21.00 L43.77 25.20Z" fill="#8bb8ff"/><path d="M20.23 25.20 L43.77 25.20 L32.00 45.60Z" fill="#5c9dff"/><path d="M51.05 21.00 L51.05 43.00 L43.77 25.20Z" fill="#3d8bff"/><path d="M51.05 43.00 L43.77 25.20 L32.00 45.60Z" fill="#3478e6"/><path d="M12.95 43.00 L12.95 21.00 L20.23 25.20Z" fill="#6aa5ff"/><path d="M12.95 43.00 L20.23 25.20 L32.00 45.60Z" fill="#4a8ff5"/><path d="M51.05 43.00 L32.00 54.00 L32.00 45.60Z" fill="#2a63c4"/><path d="M32.00 54.00 L12.95 43.00 L32.00 45.60Z" fill="#2457ad"/>
<path d="M32.00 10.00 L51.05 21.00 L51.05 43.00 L32.00 54.00 L12.95 43.00 L12.95 21.00Z M43.77 25.20 L32.00 45.60 L20.23 25.20Z M32.00 10.00 L20.23 25.20 M32.00 10.00 L43.77 25.20 M51.05 21.00 L43.77 25.20 M51.05 43.00 L43.77 25.20 M51.05 43.00 L32.00 45.60 M32.00 54.00 L32.00 45.60 M12.95 43.00 L32.00 45.60 M12.95 43.00 L20.23 25.20 M12.95 21.00 L20.23 25.20" fill="none" stroke="#1f2125" stroke-width="1.1" stroke-linejoin="round"/>
<rect width="64" height="64" rx="14" fill="#1f2125"/>
<g stroke-width=".2" stroke-linejoin="round">
<path d="M19.8 47.9L26.4 55L20.8 54.6Z" fill="#ce362d" stroke="#ce362d"/>
<path d="M19.8 47.9L20.8 54.6L15.2 52Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M50 42.5L55.1 44.4L60 49.4Z" fill="#ac2c25" stroke="#ac2c25"/>
<path d="M23.7 41.6L24.8 48.4L19.8 47.9Z" fill="#da3c31" stroke="#da3c31"/>
<path d="M21.6 48L21 47.7L20.5 47.4L20.2 47.2L23.7 41.6L24.8 48.4L21.8 48.1Z" fill="#ffc442" stroke="#ffc442"/>
<path d="M21.4 45.2L21.5 45.2L22.1 45.6L22.7 45.9L23.3 46.2L23.9 46.5L24.5 46.8L24.5 46.9L23.7 41.8L23.6 41.7Z" fill="#2d66c7" stroke="#2d66c7"/>
<path d="M19.8 47.9L24.8 48.4L26.4 55Z" fill="#e2483d" stroke="#e2483d"/>
<path d="M25 49.8L24.4 49.5L23.9 49.2L23.3 48.9L22.7 48.6L22.2 48.3L21.8 48.1L24.8 48.4L25.2 49.9Z" fill="#ffcc57" stroke="#ffcc57"/>
<path d="M50 42.5L60 49.4L54.4 47.3Z" fill="#87211c" stroke="#87211c"/>
<path d="M19.2 40.9L23.7 41.6L19.8 47.9Z" fill="#8e241e" stroke="#8e241e"/>
<path d="M20 47.1L19.7 46.9L19.2 40.9L23.7 41.6L20.2 47.2Z" fill="#ac7a12" stroke="#ac7a12"/>
<path d="M19.4 43.9L19.9 44.2L20.5 44.5L21 44.9L21.4 45.2L23.6 41.7L23.3 41.5L19.2 40.9Z" fill="#163d82" stroke="#163d82"/>
<path d="M50.5 38.8L55.1 44.4L50 42.5Z" fill="#9d2821" stroke="#9d2821"/>
<path d="M23 34.5L26.8 33.8L23.7 41.6Z" fill="#dc3f35" stroke="#dc3f35"/>
<path d="M23 34.5L26.8 33.8L23.7 41.6Z" fill="#ffc648" stroke="#ffc648"/>
<path d="M19.1 33.7L23 34.5L23.7 41.6Z" fill="#7f1f1a" stroke="#7f1f1a"/>
<path d="M19.1 33.7L23 34.5L23.7 41.6Z" fill="#9c6b09" stroke="#9c6b09"/>
<path d="M21.2 37.3L21.1 37L21 36.4L20.9 35.9L20.7 35.3L20.6 34.8L20.5 34.2L20.5 34L19.1 33.7Z" fill="#123675" stroke="#123675"/>
<path d="M19.1 33.7L23.7 41.6L19.2 40.9Z" fill="#8b231d" stroke="#8b231d"/>
<path d="M19.1 33.7L23.7 41.6L19.2 40.9Z" fill="#a87710" stroke="#a87710"/>
<path d="M19.2 40.9L23.3 41.5L23.2 41.5L22.6 41.1L22.1 40.7L21.6 40.4L21.5 39.8L21.4 39.3L21.4 38.7L21.3 38.1L21.2 37.6L21.2 37.3L19.1 33.7Z" fill="#153c7f" stroke="#153c7f"/>
<path d="M14.7 45.6L19.8 47.9L15.2 52Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M23.7 41.6L29.8 46.2L24.8 48.4Z" fill="#e0453b" stroke="#e0453b"/>
<path d="M23.7 41.6L29.8 46.2L24.8 48.4Z" fill="#ffca52" stroke="#ffca52"/>
<path d="M24.5 46.9L25 46.9L25.6 47L26.2 47L26.7 47L27.3 47.1L27.8 47.1L29.8 46.2L23.9 41.8L23.7 41.8L23.7 41.8Z" fill="#3871d0" stroke="#3871d0"/>
<path d="M24.8 48.4L29.8 46.2L26.4 55Z" fill="#e44b3f" stroke="#e44b3f"/>
<path d="M28.2 50.1L27.7 50.1L27.2 50L26.6 50L26.1 49.9L25.5 49.9L25.2 49.9L24.8 48.4L29.8 46.2L28.3 50.1Z" fill="#ffce5b" stroke="#ffce5b"/>
<path d="M28.4 47.2L29 47.2L29.4 47.2L29.8 46.2L27.8 47.1L27.9 47.1Z" fill="#3e76d6" stroke="#3e76d6"/>
<path d="M22.8 27.3L26.8 33.8L23 34.5Z" fill="#d93a30" stroke="#d93a30"/>
<path d="M22.8 27.3L26.8 33.8L23 34.5Z" fill="#ffc33f" stroke="#ffc33f"/>
<path d="M22.9 32.1L23.1 31.9L23.6 31.5L24.1 31.1L24.6 30.7L24.8 30.6L22.8 27.3Z" fill="#2b64c5" stroke="#2b64c5"/>
<path d="M22.8 27.3L23 34.5L19.1 33.7Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M22.8 27.3L23 34.5L19.1 33.7Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M19.1 33.7L20.5 34L20.4 33.6L20.3 33L20.8 32.9L21.2 32.7L21.7 32.5L22.2 32.3L22.6 32.2L22.9 32.1L22.8 27.3Z" fill="#123574" stroke="#123574"/>
<path d="M26.8 33.8L28.1 40.1L23.7 41.6Z" fill="#eb564a" stroke="#eb564a"/>
<path d="M23.7 41.6L26.8 33.8L28.1 40.1Z" fill="#ffd56e" stroke="#ffd56e"/>
<path d="M46 37.1L50.5 38.8L50 42.5Z" fill="#7f1f1a" stroke="#7f1f1a"/>
<path d="M14.7 38.9L19.2 40.9L19.8 47.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M19.5 46.7L19 46.2L18.6 45.9L14.7 38.9L19.2 40.9L19.7 46.9Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M16.9 40.7L17.1 41.3L17.2 41.8L17.8 42.3L18.3 42.8L18.9 43.3L19.4 43.8L19.4 43.9L19.2 40.9L16.7 39.8L16.8 40.1Z" fill="#123574" stroke="#123574"/>
<path d="M22.8 27.3L26 27.1L26.8 33.8Z" fill="#dd4035" stroke="#dd4035"/>
<path d="M22.8 27.3L26 27.1L26.8 33.8Z" fill="#ffc749" stroke="#ffc749"/>
<path d="M22.8 27.3L24.8 30.6L25.1 30.4L25.5 30.1L25.9 29.8L26.3 29.5L26.3 29.5L26 27.1Z" fill="#326bcb" stroke="#326bcb"/>
<path d="M42.3 31.2L46.2 32.7L50.5 38.8Z" fill="#80201a" stroke="#80201a"/>
<path d="M50 42.5L54.4 47.3L48.8 44.9Z" fill="#82201b" stroke="#82201b"/>
<path d="M25.6 20L26 27.1L22.8 27.3Z" fill="#cf362d" stroke="#cf362d"/>
<path d="M22.8 27.3L25.2 21.2L25.7 20.9L25.7 20.9L26 27.1Z" fill="#f4b937" stroke="#f4b937"/>
<path d="M25.3 24.5L24.8 24.8L24.3 25.1L23.8 25.4L23.4 25.7L22.8 27.3L26 27.1L25.9 24.2L25.9 24.2Z" fill="#275ebc" stroke="#275ebc"/>
<path d="M23.7 41.6L28.1 40.1L29.8 46.2Z" fill="#ef5b4f" stroke="#ef5b4f"/>
<path d="M23.7 41.6L28.1 40.1L29.8 46.2Z" fill="#ffd978" stroke="#ffd978"/>
<path d="M29.8 46.2L28.8 42.4L28.8 42.4L28.2 42.4L27.7 42.3L27.1 42.2L26.6 42.1L26 42.1L25.5 42L24.9 41.9L24.3 41.8L23.9 41.8Z" fill="#5189e6" stroke="#5189e6"/>
<path d="M14.7 38.9L19.8 47.9L14.7 45.6Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M17.9 45.2L17.4 44.7L16.8 44.2L16.2 43.7L15.7 43.2L15.1 42.7L14.7 42.4L14.7 38.9L18.6 45.9L18.4 45.7Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M23.1 19.9L25.6 20L22.8 27.3Z" fill="#9e2821" stroke="#9e2821"/>
<path d="M23 22.5L23.3 22.3L23.7 22L24.2 21.7L24.6 21.5L25.1 21.2L25.2 21.2L22.8 27.3Z" fill="#be891b" stroke="#be891b"/>
<path d="M23.4 25.7L23 26L22.8 26.1L22.8 27.3L23.4 25.7Z" fill="#1b4590" stroke="#1b4590"/>
<path d="M19.6 26.5L22.8 27.3L19.1 33.7Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M19.6 26.5L22.8 27.3L19.1 33.7Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M20.8 26.8L20.6 26.9L20.2 27L19.7 27.2L19.5 27.3L19.1 33.7L22.8 27.3Z" fill="#123574" stroke="#123574"/>
<path d="M19.1 33.7L19.2 40.9L14.7 38.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M19.1 33.7L19.2 40.9L14.7 38.9Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M16.2 37.2L16.3 37.6L16.4 38.3L16.5 38.9L16.6 39.5L16.7 39.8L19.2 40.9L19.1 33.7Z" fill="#123574" stroke="#123574"/>
<path d="M42.3 31.2L50.5 38.8L46 37.1Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M26 27.1L29.2 25.9L26.8 33.8Z" fill="#e64d42" stroke="#e64d42"/>
<path d="M26 27.1L29.2 25.9L26.8 33.8Z" fill="#ffd060" stroke="#ffd060"/>
<path d="M26 27.1L26.3 29.5L26.3 29.5L26.8 29.6L27.3 29.7L27.7 29.8L28 29.9L29.2 25.9Z" fill="#427ad8" stroke="#427ad8"/>
<path d="M42.1 26.2L46.2 32.7L42.3 31.2Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M25.6 20L29.2 25.9L26 27.1Z" fill="#e1473c" stroke="#e1473c"/>
<path d="M26 27.1L25.7 20.9L25.7 20.9L26.2 20.9L29.2 25.9Z" fill="#ffcb55" stroke="#ffcb55"/>
<path d="M27.9 24.5L27.4 24.4L26.9 24.3L26.4 24.3L25.9 24.2L25.9 24.2L26 27.1L29.2 25.9L28.4 24.6L28.4 24.6Z" fill="#3a72d2" stroke="#3a72d2"/>
<path d="M20.6 19.3L23.1 19.9L22.8 27.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M21.6 23.1L22 22.9L22.4 22.7L22.9 22.5L23 22.5L22.8 27.3Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M22.6 26.2L22.5 26.3L22.8 27.3L22.8 26.1Z" fill="#123574" stroke="#123574"/>
<path d="M20.6 19.3L22.8 27.3L19.6 26.5Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M20 23.5L20 23.5L20.6 23.4L21.1 23.2L21.6 23.1L21.6 23.1L22.8 27.3L19.6 26.5Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M21.6 26.5L21.1 26.7L20.8 26.8L22.8 27.3L22.5 26.3L22.1 26.4Z" fill="#123574" stroke="#123574"/>
<path d="M24.1 12.3L25.6 20L23.1 19.9Z" fill="#992720" stroke="#992720"/>
<path d="M29.8 46.2L32 52.3L26.4 55Z" fill="#e75045" stroke="#e75045"/>
<path d="M31.2 50L30.6 50L30 50.1L29.4 50.1L28.8 50.1L28.3 50.1L29.8 46.2L31.2 50Z" fill="#ffd165" stroke="#ffd165"/>
<path d="M29.4 47.2L29.6 47.2L30.2 47.2L30.2 47.2L29.8 46.2Z" fill="#457cdb" stroke="#457cdb"/>
<path d="M25.6 20L28.1 19.5L29.2 25.9Z" fill="#eb564a" stroke="#eb564a"/>
<path d="M27.2 21.2L27.7 21.4L28.1 21.6L28.5 21.7L29.2 25.9L26.2 20.9L26.2 20.9L26.7 21.1Z" fill="#ffd56f" stroke="#ffd56f"/>
<path d="M28.8 24.8L28.4 24.6L29.2 25.9L29.1 24.9Z" fill="#4b83e1" stroke="#4b83e1"/>
<path d="M27.2 12.3L28.1 19.5L25.6 20Z" fill="#de4338" stroke="#de4338"/>
<path d="M24.1 12.3L25.7 12.3L25.6 20Z" fill="#a52a23" stroke="#a52a23"/>
<path d="M25.7 12.3L27.2 12.3L25.6 20Z" fill="#a52a23" stroke="#a52a23"/>
<path d="M26.8 33.8L32.6 37.4L28.1 40.1Z" fill="#e64e42" stroke="#e64e42"/>
<path d="M26.8 33.8L32.6 37.4L28.1 40.1Z" fill="#ffd061" stroke="#ffd061"/>
<path d="M28.1 40.1L32.6 37.4L27.6 34.2L27.7 34.7L27.8 35.3L27.9 35.8L28 36.3L28.1 36.9L28.2 37.4L28.3 38L28.9 37.6L29.5 37.2L30.1 36.8L30.8 36.5L30.9 36.4L32.6 37.4L28.1 40.1Z" fill="#427ad9" stroke="#427ad9"/>
<path d="M29.2 25.9L30.7 31.8L26.8 33.8Z" fill="#e95347" stroke="#e95347"/>
<path d="M29.2 25.9L30.7 31.8L26.8 33.8Z" fill="#ffd36a" stroke="#ffd36a"/>
<path d="M28 29.9L28.2 29.9L28.8 29.9L29.3 29.8L29.8 29.8L30.2 29.8L29.2 25.9Z" fill="#487fde" stroke="#487fde"/>
<path d="M24.1 12.3L23.1 19.9L20.6 19.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M16.3 25.3L19.6 26.5L19.1 33.7Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M16.3 25.3L19.6 26.5L19.1 33.7Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M19.3 27.3L18.8 27.5L18.4 27.6L18 27.8L17.5 27.9L17.2 28L19.1 33.7L19.5 27.3Z" fill="#123574" stroke="#123574"/>
<path d="M41.5 35.4L46 37.1L50 42.5Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M42.8 36.3L42.9 36.5L41.5 35.4L42.5 35.8L42.6 35.9Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M35.7 18.7L38.2 19.3L42.1 26.2Z" fill="#88221c" stroke="#88221c"/>
<path d="M9.7 44L14.7 45.6L15.2 52Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M15.2 32.1L19.1 33.7L14.7 38.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M15.2 32.1L19.1 33.7L14.7 38.9Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M15.6 33L15.7 33.6L15.8 34.2L15.9 34.7L15.9 35.3L16 35.9L16.1 36.5L16.2 37L16.2 37.2L19.1 33.7L15.5 32.2L15.5 32.4Z" fill="#123574" stroke="#123574"/>
<path d="M38.9 25L42.1 26.2L42.3 31.2Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M39.5 26.2L39.9 26.5L40.4 26.8L40.5 27.2L40.6 27.6L40.6 28.1L40.7 28.3Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M45 40.4L50 42.5L48.8 44.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M20.9 12.3L22.5 12.3L20.6 19.3Z" fill="#d6382e" stroke="#d6382e"/>
<path d="M22.5 12.3L24.1 12.3L20.6 19.3Z" fill="#d6382e" stroke="#d6382e"/>
<path d="M28.1 19.5L30.7 18.7L29.2 25.9Z" fill="#ea5448" stroke="#ea5448"/>
<path d="M28.5 21.7L28.6 21.7L29 21.8L29.4 22L29.9 22.1L30 22.1L29.2 25.9Z" fill="#ffd46c" stroke="#ffd46c"/>
<path d="M29.2 24.9L29.1 24.9L29.2 25.9L29.4 25Z" fill="#4981df" stroke="#4981df"/>
<path d="M35.7 18.7L42.1 26.2L38.9 25Z" fill="#83201b" stroke="#83201b"/>
<path d="M28.1 40.1L32.6 37.4L29.8 46.2Z" fill="#e85145" stroke="#e85145"/>
<path d="M28.1 40.1L32.6 37.4L29.8 46.2Z" fill="#ffd266" stroke="#ffd266"/>
<path d="M29.8 46.2L32.5 37.8L32.2 38.2L31.7 38.7L31.3 39.3L30.9 39.8L30.4 40.3L30 40.9L29.6 41.4L29.2 41.9L28.8 42.4L28.8 42.4Z" fill="#457ddc" stroke="#457ddc"/>
<path d="M27.2 12.3L30.7 18.7L28.1 19.5Z" fill="#df4439" stroke="#df4439"/>
<path d="M33.6 12.3L38.2 19.3L35.7 18.7Z" fill="#982620" stroke="#982620"/>
<path d="M20.6 19.3L19.6 26.5L16.3 25.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M17.1 24.2L17.5 24.1L18 24L18.5 23.9L19 23.8L19.5 23.6L20 23.5L19.6 26.5L16.3 25.3Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M16.3 25.3L19.1 33.7L15.2 32.1Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M16.3 25.3L19.1 33.7L15.2 32.1Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M16.6 28.1L16.1 28.2L15.9 28.2L15.4 31.2L15.4 31.3L15.5 31.8L15.5 32.2L19.1 33.7L17.2 28L17.1 28Z" fill="#123574" stroke="#123574"/>
<path d="M27.2 12.3L28.8 12.3L30.7 18.7Z" fill="#e3493e" stroke="#e3493e"/>
<path d="M28.8 12.3L30.4 12.3L30.7 18.7Z" fill="#e3493e" stroke="#e3493e"/>
<path d="M30.4 12.3L32 12.3L35.7 18.7Z" fill="#e34a3f" stroke="#e34a3f"/>
<path d="M32 12.3L33.6 12.3L35.7 18.7Z" fill="#e34a3f" stroke="#e34a3f"/>
<path d="M26.8 33.8L30.7 31.8L32.6 37.4Z" fill="#e95348" stroke="#e95348"/>
<path d="M26.8 33.8L30.7 31.8L32.6 37.4Z" fill="#ffd36b" stroke="#ffd36b"/>
<path d="M32.6 37.4L30.8 32L30.3 32.3L29.7 32.6L29.1 32.9L28.6 33.1L28 33.4L27.4 33.7L27.6 34.2L27.6 34.2L30.9 36.4L31.3 36.2L31.8 35.9L32.1 35.8L32.6 37.4Z" fill="#4880de" stroke="#4880de"/>
<path d="M20.9 12.3L20.6 19.3L18.1 18.6Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M17.7 12.3L19.3 12.3L15.5 18.6Z" fill="#e95247" stroke="#e95247"/>
<path d="M19.3 12.3L20.9 12.3L15.5 18.6Z" fill="#e95247" stroke="#e95247"/>
<path d="M42.3 31.2L46 37.1L41.5 35.4Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M41.8 33.8L41.9 33.9L42 34.3L42.2 34.7L42.3 35.1L42.5 35.5L42.5 35.8L41.5 35.4Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M41.5 35.4L50 42.5L45 40.4Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M42.9 36.6L43.1 37L43.2 37.3L43.3 37.6L43.4 38L43.3 37.9L41.5 35.4L42.9 36.5Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M17.7 12.3L15.5 18.6L13 19.1Z" fill="#ff7466" stroke="#ff7466"/>
<path d="M14.7 38.9L14.7 45.6L9.7 44Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M14.4 41.7L14.3 41.1L14.1 40.6L14 40L13.9 39.7L14.7 38.9L14.7 42.4L14.5 42.2Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M9.7 44L15.2 52L9.6 50.2Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M30.4 12.3L33.2 18.4L30.7 18.7Z" fill="#f26154" stroke="#f26154"/>
<path d="M30.4 12.3L35.7 18.7L33.2 18.4Z" fill="#d6382f" stroke="#d6382f"/>
<path d="M20.9 12.3L18.1 18.6L15.5 18.6Z" fill="#dd4136" stroke="#dd4136"/>
<path d="M30.7 18.7L32.5 24.7L29.2 25.9Z" fill="#eb564a" stroke="#eb564a"/>
<path d="M30 22.1L30.4 22.1L30.9 22.2L31.5 22.2L31.7 22.3L32.5 24.7L29.2 25.9Z" fill="#ffd570" stroke="#ffd570"/>
<path d="M30.8 25.1L30.2 25.1L29.7 25L29.4 25L29.2 25.9L31.2 25.2Z" fill="#4c83e1" stroke="#4c83e1"/>
<path d="M18.1 18.6L20.6 19.3L16.3 25.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M16.6 24.5L16.7 24.4L17.1 24.3L17.1 24.2L16.3 25.3Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M13 19.1L15.5 18.6L9.9 25.6Z" fill="#ff7466" stroke="#ff7466"/>
<path d="M35.7 24.3L38.9 25L42.3 31.2Z" fill="#90241e" stroke="#90241e"/>
<path d="M37.9 25.2L38.4 25.5L38.9 25.8L39.4 26.1L39.5 26.2L40.7 28.3L40.7 28.5L40.8 28.9L40.9 29.4L41 29.8L41.1 29.9L35.7 24.3L37 24.6L37.4 24.8Z" fill="#af7c13" stroke="#af7c13"/>
<path d="M29.2 25.9L34.6 30.2L30.7 31.8Z" fill="#ee5a4e" stroke="#ee5a4e"/>
<path d="M30.7 31.8L29.2 25.9L34.6 30.2Z" fill="#ffd876" stroke="#ffd876"/>
<path d="M30.2 29.8L30.4 29.8L30.9 29.8L31.4 29.8L32 29.9L32.5 29.9L33 29.9L33.5 30L34 30L34.4 30L29.2 25.9Z" fill="#5087e5" stroke="#5087e5"/>
<path d="M35.7 18.7L38.9 25L35.7 24.3Z" fill="#9b2721" stroke="#9b2721"/>
<path d="M35.7 23.8L35.8 23.8L36.4 24.2L36.9 24.5L37 24.6L35.7 24.3Z" fill="#ba8619" stroke="#ba8619"/>
<path d="M15.5 18.6L18.1 18.6L16.3 25.3Z" fill="#ca352c" stroke="#ca352c"/>
<path d="M16.3 24.7L16.3 24.7L16.6 24.5L16.3 25.3Z" fill="#f0b535" stroke="#f0b535"/>
<path d="M11.4 31.3L15.2 32.1L14.7 38.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M13.4 35.9L13.4 35.9L13.3 35.3L13.2 34.8L13.1 34.3L13 33.7L12.9 33.2L12.8 32.6L12.7 32.1L12.5 31.5L12.5 31.5L15.2 32.1L14.7 38.9Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M30.7 18.7L33.2 18.4L35.7 24.3Z" fill="#eb5549" stroke="#eb5549"/>
<path d="M34.8 23.3L35 23.4L35.4 23.5L35.7 24.3Z" fill="#ffd56e" stroke="#ffd56e"/>
<path d="M33.2 18.4L35.7 18.7L35.7 24.3Z" fill="#cb352c" stroke="#cb352c"/>
<path d="M35.4 23.5L35.4 23.6L35.7 23.8L35.7 24.3Z" fill="#f1b535" stroke="#f1b535"/>
<path d="M29.2 25.9L32.5 24.7L34.6 30.2Z" fill="#e95347" stroke="#e95347"/>
<path d="M29.2 25.9L32.5 24.7L34.6 30.2Z" fill="#ffd36a" stroke="#ffd36a"/>
<path d="M32.3 25.2L31.8 25.2L31.3 25.2L31.2 25.2L29.2 25.9L34.4 30L34.5 30L34.5 29.9L32.7 25.3Z" fill="#4880de" stroke="#4880de"/>
<path d="M30.7 18.7L35.7 24.3L32.5 24.7Z" fill="#ed594d" stroke="#ed594d"/>
<path d="M31.7 22.3L32 22.3L32.5 22.5L33 22.7L33.5 22.9L34 23L34.5 23.2L34.8 23.3L35.7 24.3L32.5 24.7Z" fill="#ffd775" stroke="#ffd775"/>
<path d="M35.7 24.3L42.3 31.2L38.5 30Z" fill="#8b231d" stroke="#8b231d"/>
<path d="M35.7 24.3L41.1 29.9L41.1 30.2L41.1 30.6L41.2 30.9L38.5 30Z" fill="#a97710" stroke="#a97710"/>
<path d="M15.5 18.6L13.1 24.9L9.9 25.6Z" fill="#fe7264" stroke="#fe7264"/>
<path d="M38.5 30L42.3 31.2L41.5 35.4Z" fill="#88221c" stroke="#88221c"/>
<path d="M41.3 31.4L41.3 31.7L41.4 32.1L41.5 32.5L41.6 32.8L41.7 33.2L41.8 33.6L41.8 33.8L41.5 35.4L38.5 30L41.2 30.9L41.2 31Z" fill="#a6740e" stroke="#a6740e"/>
<path d="M15.5 18.6L16.3 25.3L13.1 24.9Z" fill="#a22922" stroke="#a22922"/>
<path d="M15.3 25L15.8 24.9L16.3 24.7L16.3 25.3L15 25.2Z" fill="#c28d1d" stroke="#c28d1d"/>
<path d="M32.6 37.4L34.9 42.7L29.8 46.2Z" fill="#e74f44" stroke="#e74f44"/>
<path d="M32.6 37.4L34.9 42.7L29.8 46.2Z" fill="#ffd164" stroke="#ffd164"/>
<path d="M29.8 46.2L31.9 44.8L32.3 44.3L32.7 43.7L33.1 43.2L33.6 42.6L34 42L34.4 41.5L32.6 37.4L32.6 37.4L32.7 37.6L32.6 37.6L32.5 37.8Z" fill="#447cda" stroke="#447cda"/>
<path d="M29.8 46.2L37.6 48L32 52.3Z" fill="#ed594d" stroke="#ed594d"/>
<path d="M32.5 48.2L32 48.8L31.6 49.4L31.2 50L31.2 50L29.8 46.2L33.3 47L32.9 47.5Z" fill="#ffd774" stroke="#ffd774"/>
<path d="M30.2 47.2L30.2 47.2L30.7 46.6L30.7 46.4L29.8 46.2Z" fill="#4e86e4" stroke="#4e86e4"/>
<path d="M16.3 25.3L15.2 32.1L11.4 31.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M12.5 31.5L12.5 31L12.4 30.4L12.3 30.2L16.3 25.3L15.2 32.1L12.5 31.5Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M15.1 28.4L15.1 29L15.2 29.6L15.3 30.1L15.3 30.7L15.4 31.2L15.9 28.2L15.6 28.3Z" fill="#123574" stroke="#123574"/>
<path d="M30.7 31.8L34.6 30.2L32.6 37.4Z" fill="#ef5c50" stroke="#ef5c50"/>
<path d="M30.7 31.8L34.6 30.2L32.6 37.4Z" fill="#ffd979" stroke="#ffd979"/>
<path d="M32.6 37.4L34.5 30.5L34.2 30.6L33.7 30.8L33.1 31.1L32.5 31.3L32 31.5L31.4 31.8L30.8 32L30.8 32L32.1 35.8L32.4 35.7L32.9 35.4L33.2 35.3L32.6 37.4Z" fill="#5289e7" stroke="#5289e7"/>
<path d="M10.2 37.6L14.7 38.9L9.7 44Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M13.9 39.5L13.8 39L13.7 38.6L14.7 38.9L13.9 39.7Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M11.4 31.3L14.7 38.9L10.2 37.6Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M13.7 38.5L13.6 38L13.6 37.4L13.5 36.9L13.5 36.4L13.4 35.9L14.7 38.9L13.7 38.6Z" fill="#9a6a08" stroke="#9a6a08"/>
<path d="M39.9 40.3L45 40.4L48.8 44.9Z" fill="#8b231d" stroke="#8b231d"/>
<path d="M9.9 25.6L13.1 24.9L11.4 31.3Z" fill="#f96c5e" stroke="#f96c5e"/>
<path d="M12.2 28L12.1 27.5L12.1 27.1L12 26.6L12.5 26.3L12.8 26.1L12.2 28.2Z" fill="#ffe395" stroke="#ffe395"/>
<path d="M9.9 25.6L11.4 31.3L7.5 32Z" fill="#f6675a" stroke="#f6675a"/>
<path d="M13.1 24.9L16.3 25.3L11.4 31.3Z" fill="#9e2821" stroke="#9e2821"/>
<path d="M12.3 29.9L12.3 29.4L12.3 28.9L12.2 28.4L12.2 28.2L12.8 26.1L12.9 26L13.4 25.8L13.8 25.6L14.3 25.4L14.8 25.2L15 25.2L16.3 25.3L12.3 30.2Z" fill="#be891b" stroke="#be891b"/>
<path d="M32.5 24.7L35.7 24.3L34.6 30.2Z" fill="#ee5a4e" stroke="#ee5a4e"/>
<path d="M32.5 24.7L35.7 24.3L34.6 30.2Z" fill="#ffd876" stroke="#ffd876"/>
<path d="M35.2 26.1L34.8 26L34.3 25.8L33.8 25.6L33.3 25.5L32.8 25.3L32.7 25.3L34.5 29.9L34.6 29.6L34.7 29.4L35.3 26.2Z" fill="#5087e5" stroke="#5087e5"/>
<path d="M29.8 46.2L34.9 42.7L37.6 48Z" fill="#e2483d" stroke="#e2483d"/>
<path d="M35.2 44.3L34.8 44.8L34.5 45.3L34.1 45.9L33.7 46.4L33.3 46.9L33.3 47L29.8 46.2L34.9 42.7L35.5 43.9Z" fill="#ffcc56" stroke="#ffcc56"/>
<path d="M30.7 46.4L31.1 46L31.5 45.4L31.9 44.9L31.9 44.8L29.8 46.2Z" fill="#3b73d3" stroke="#3b73d3"/>
<path d="M35.7 24.3L38.5 30L34.6 30.2Z" fill="#d93a30" stroke="#d93a30"/>
<path d="M35.7 24.3L38.5 30L34.6 30.2Z" fill="#ffc33f" stroke="#ffc33f"/>
<path d="M34.7 29.4L34.8 29.2L35 28.9L35.2 28.5L35.4 28.1L35.6 27.7L35.9 27.3L36.1 26.9L36.3 26.5L35.8 26.3L35.3 26.2Z" fill="#2b64c5" stroke="#2b64c5"/>
<path d="M34.6 30.2L38.5 30L41.5 35.4Z" fill="#c8342b" stroke="#c8342b"/>
<path d="M34.6 30.2L38.5 30L41.5 35.4Z" fill="#edb233" stroke="#edb233"/>
<path d="M39.2 33.7L39.2 33.6L39.1 33.1L38.9 32.7L38.8 32.3L38.7 31.9L38.6 31.5L38.5 31L38.4 30.6L38.3 30.2L37.7 30.2L37.1 30.3L36.6 30.3L36 30.3L35.4 30.3L34.8 30.4L34.8 30.4Z" fill="#265bb5" stroke="#265bb5"/>
<path d="M41.5 35.4L45 40.4L39.9 40.3Z" fill="#92251f" stroke="#92251f"/>
<path d="M41.5 35.4L43.3 37.9L43 38.1L42.5 38.2L42.1 38.4L41.7 38.6L41.3 38.7L40.8 38.9L40.4 39.1L40.3 39.1Z" fill="#b17e14" stroke="#b17e14"/>
<path d="M34.6 30.2L37.1 35.4L32.6 37.4Z" fill="#ea5448" stroke="#ea5448"/>
<path d="M34.6 30.2L37.1 35.4L32.6 37.4Z" fill="#ffd46c" stroke="#ffd46c"/>
<path d="M32.6 37.4L37.1 35.4L34.7 30.4L34.5 30.5L33.2 35.3L33.5 35.2L34.1 34.9L34.2 35.4L34.4 35.8L33.9 36.3L33.5 36.7L33.1 37.1L33 37.2L32.6 37.4Z" fill="#4981df" stroke="#4981df"/>
<path d="M7.5 32L11.4 31.3L5.8 38.4Z" fill="#f56659" stroke="#f56659"/>
<path d="M39.9 40.3L48.8 44.9L43.2 44.9Z" fill="#9d2821" stroke="#9d2821"/>
<path d="M34.6 30.2L41.5 35.4L37.1 35.4Z" fill="#ca352c" stroke="#ca352c"/>
<path d="M37.1 35.4L34.6 30.2L41.5 35.4Z" fill="#efb435" stroke="#efb435"/>
<path d="M37.1 35.4L39.6 35.4L39.5 35.2L39.4 34.8L39.4 34.4L39.3 34L39.2 33.7L34.8 30.4L34.7 30.4Z" fill="#265cb8" stroke="#265cb8"/>
<path d="M5.8 38.4L10.2 37.6L9.7 44Z" fill="#b52f27" stroke="#b52f27"/>
<path d="M11.4 31.3L10.2 37.6L5.8 38.4Z" fill="#ca352c" stroke="#ca352c"/>
<path d="M9.7 44L9.6 50.2L4 51.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
<path d="M32.6 37.4L39.9 40.3L34.9 42.7Z" fill="#f46356" stroke="#f46356"/>
<path d="M38.5 40.6L38 41.1L37.9 41.3L34.9 42.7L32.6 37.4L39.1 39.9L38.9 40.2Z" fill="#ffde85" stroke="#ffde85"/>
<path d="M34.4 41.5L34.4 41.5L34.9 41L35.3 40.5L35.8 40.1L36.3 39.6L36.7 39.1L36.8 39L32.6 37.4L32.6 37.4L32.8 37.5L32.7 37.6Z" fill="#5a91ee" stroke="#5a91ee"/>
<path d="M32.6 37.4L37.1 35.4L39.9 40.3Z" fill="#e0453a" stroke="#e0453a"/>
<path d="M39.3 39.8L39.1 39.9L32.6 37.4L37.1 35.4L39.5 39.5Z" fill="#ffca52" stroke="#ffca52"/>
<path d="M36.8 39L37.1 38.7L37.5 38.3L37.9 37.8L38.3 37.4L37.1 35.4L33 37.2L32.8 37.5Z" fill="#3870d0" stroke="#3870d0"/>
<path d="M37.1 35.4L41.5 35.4L39.9 40.3Z" fill="#c6342b" stroke="#c6342b"/>
<path d="M40 39.3L39.7 39.5L39.5 39.5L37.1 35.4L41.5 35.4L40.3 39.1Z" fill="#ebb133" stroke="#ebb133"/>
<path d="M38.3 37.4L38.3 37.4L38.7 37.2L39.1 37L39.5 36.9L40 36.7L39.8 36.3L39.7 35.9L39.6 35.5L39.6 35.4L37.1 35.4Z" fill="#255ab4" stroke="#255ab4"/>
<path d="M5.8 38.4L9.7 44L4.6 44.7Z" fill="#a82b24" stroke="#a82b24"/>
<path d="M4.6 44.7L9.7 44L4 51.3Z" fill="#9e2822" stroke="#9e2822"/>
<path d="M34.9 42.7L39.9 40.3L37.6 48Z" fill="#f15f53" stroke="#f15f53"/>
<path d="M37.2 42L36.8 42.4L36.4 42.9L36 43.3L35.6 43.8L35.5 43.9L34.9 42.7L37.9 41.3L37.6 41.6Z" fill="#ffdb7f" stroke="#ffdb7f"/>
<path d="M39.9 40.3L43.2 44.9L37.6 48Z" fill="#d4382e" stroke="#d4382e"/>
<path d="M16.7 9L34.6 9L34.1 12.5L17.2 12.5Z" fill="#ffd34d" stroke="#ffd34d"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 22 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#FFDD00"/><path transform="translate(5 5) scale(.9167)" fill="#000" d="M20.216 6.415l-.132-.666c-.119-.598-.388-1.163-1.001-1.379-.197-.069-.42-.098-.57-.241-.152-.143-.196-.366-.231-.572-.065-.378-.125-.756-.192-1.133-.057-.325-.102-.69-.25-.987-.195-.4-.597-.634-.996-.788a5.723 5.723 0 00-.626-.194c-1-.263-2.05-.36-3.077-.416a25.834 25.834 0 00-3.7.062c-.915.083-1.88.184-2.75.5-.318.116-.646.256-.888.501-.297.302-.393.77-.177 1.146.154.267.415.456.692.58.36.162.737.284 1.123.366 1.075.238 2.189.331 3.287.37 1.218.05 2.437.01 3.65-.118.299-.033.598-.073.896-.119.352-.054.578-.513.474-.834-.124-.383-.457-.531-.834-.473-.466.074-.96.108-1.382.146-1.177.08-2.358.082-3.536.006a22.228 22.228 0 01-1.157-.107c-.086-.01-.18-.025-.258-.036-.243-.036-.484-.08-.724-.13-.111-.027-.111-.185 0-.212h.005c.277-.06.557-.108.838-.147h.002c.131-.009.263-.032.394-.048a25.076 25.076 0 013.426-.12c.674.019 1.347.067 2.017.144l.228.031c.267.04.533.088.798.145.392.085.895.113 1.07.542.055.137.08.288.111.431l.319 1.484a.237.237 0 01-.199.284h-.003c-.037.006-.075.01-.112.015a36.704 36.704 0 01-4.743.295 37.059 37.059 0 01-4.699-.304c-.14-.017-.293-.042-.417-.06-.326-.048-.649-.108-.973-.161-.393-.065-.768-.032-1.123.161-.29.16-.527.404-.675.701-.154.316-.199.66-.267 1-.069.34-.176.707-.135 1.056.087.753.613 1.365 1.37 1.502a39.69 39.69 0 0011.343.376.483.483 0 01.535.53l-.071.697-1.018 9.907c-.041.41-.047.832-.125 1.237-.122.637-.553 1.028-1.182 1.171-.577.131-1.165.2-1.756.205-.656.004-1.31-.025-1.966-.022-.699.004-1.556-.06-2.095-.58-.475-.458-.54-1.174-.605-1.793l-.731-7.013-.322-3.094c-.037-.351-.286-.695-.678-.678-.336.015-.718.3-.678.679l.228 2.185.949 9.112c.147 1.344 1.174 2.068 2.446 2.272.742.12 1.503.144 2.257.156.966.016 1.942.053 2.892-.122 1.408-.258 2.465-1.198 2.616-2.657.34-3.332.683-6.663 1.024-9.995l.215-2.087a.484.484 0 01.39-.426c.402-.078.787-.212 1.074-.518.455-.488.546-1.124.385-1.766zm-1.478.772c-.145.137-.363.201-.578.233-2.416.359-4.866.54-7.308.46-1.748-.06-3.477-.254-5.207-.498-.17-.024-.353-.055-.47-.18-.22-.236-.111-.71-.054-.995.052-.26.152-.609.463-.646.484-.057 1.046.148 1.526.22.577.088 1.156.159 1.737.212 2.48.226 5.002.19 7.472-.14.45-.06.899-.13 1.345-.21.399-.072.84-.206 1.08.206.166.281.188.657.162.974a.544.544 0 01-.169.364zm-6.159 3.9c-.862.37-1.84.788-3.109.788a5.884 5.884 0 01-1.569-.217l.877 9.004c.065.78.717 1.38 1.5 1.38 0 0 1.243.065 1.658.065.447 0 1.786-.065 1.786-.065.783 0 1.434-.6 1.499-1.38l.94-9.95a3.996 3.996 0 00-1.322-.238c-.826 0-1.491.284-2.26.613z"/></svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#635BFF"/><path transform="translate(8 7) scale(.75)" fill="#fff" d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.594-7.305h.003z"/></svg>

Before

Width:  |  Height:  |  Size: 659 B

+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "supergeometry.app",
"short_name": "supergeometry",
"name": "superGeometry.app",
"short_name": "superGeometry",
"description": "Free 3D CAD and 3D modeling in your browser, for phone, tablet, computer and VR.",
"start_url": "./",
"display": "standalone",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 87 KiB

+105
View File
@@ -0,0 +1,105 @@
// Offline mode (More → Offline mode). Registered only while it's on.
//
// The page asks it to download the app's files (the list the build writes,
// offline-files.json) into one store per version. Files are then served from
// that store, so the app opens and works with no connection. The page itself
// is fetched from the site first while online (so a new version shows up),
// and from the store when there's no connection.
const PREFIX = "sg-offline-";
const scope = self.registration.scope;
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
async function tell(msg) {
for (const c of await self.clients.matchAll({ includeUncontrolled: true })) c.postMessage(msg);
}
let running = null;
/** Store every file of the site's current version. `keep`: the version the open page runs (not removed). */
async function download(fresh, keep) {
let list;
try {
list = await (await fetch(new URL("offline-files.json", scope).href, { cache: "no-store" })).json();
} catch {
await tell({ type: "offline-failed", reason: "offline" });
return;
}
const name = PREFIX + list.build;
if (fresh) await caches.delete(name);
const store = await caches.open(name);
let done = 0;
try {
for (const f of list.files) {
const url = new URL(f, scope).href;
if (!(await store.match(url))) {
// A file an older version already has (the same name means the same contents) is copied over.
const same = f !== "./" && f !== "index.html" && !fresh ? await caches.match(url, { ignoreVary: true }) : null;
const res = same ?? (await fetch(url, { cache: "no-cache" }));
if (!res.ok) throw new Error(String(res.status));
await store.put(url, res);
}
done++;
await tell({ type: "offline-progress", done, total: list.files.length });
}
} catch {
await tell({ type: "offline-failed", reason: "network" });
return;
}
for (const k of await caches.keys()) if (k.startsWith(PREFIX) && k !== name && k !== PREFIX + keep) await caches.delete(k);
await tell({ type: "offline-ready", build: list.build });
}
self.addEventListener("message", (e) => {
if (e.data?.type !== "download") return;
running ??= download(!!e.data.fresh, e.data.keep).finally(() => (running = null));
e.waitUntil(running);
});
/** The page from the store (the newest version stored). */
async function storedPage() {
const names = (await caches.keys()).filter((k) => k.startsWith(PREFIX));
for (const n of names.reverse()) {
const hit = (await (await caches.open(n)).match(scope)) ?? (await (await caches.open(n)).match(new URL("index.html", scope).href));
if (hit) return hit;
}
return Response.error();
}
self.addEventListener("fetch", (e) => {
const req = e.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== location.origin) return;
// The update check always asks the site.
if (url.searchParams.has("check") || url.pathname.endsWith("offline-files.json")) return;
if (req.mode === "navigate") {
// Online: the site's page (a new version shows up). Offline or very slow: the stored one.
e.respondWith(
new Promise((resolve) => {
let settled = false;
const fallback = () => {
if (settled) return;
settled = true;
storedPage().then(resolve);
};
const timer = setTimeout(fallback, 6000);
fetch(req)
.then((res) => {
clearTimeout(timer);
if (settled) return;
settled = true;
resolve(res);
})
.catch(() => {
clearTimeout(timer);
fallback();
});
}),
);
return;
}
e.respondWith(caches.match(req, { ignoreSearch: true, ignoreVary: true }).then((hit) => hit ?? fetch(req)));
});
+146
View File
@@ -0,0 +1,146 @@
// Check a project from the command line: rebuild it step by step and say what
// each step did (its error, the bodies it made, changed or took away) and how
// sound each body is at the end.
//
// npx tsx scripts/check.ts project.super step by step, then the bodies
// npx tsx scripts/check.ts project.super --end only the bodies at the end
// npx tsx scripts/check.ts project.super --json the same, as JSON
// npx tsx scripts/check.ts project.super --png a.png and a picture of it (see render.ts)
//
// Exit code 1 when a step fails or a body isn't sound.
import { readFileSync } from "node:fs";
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import { parseProject } from "../src/doc/store";
import { debugBodies, healthReport, regenerate } from "../src/kernel/engine";
import type { BodyHealth } from "../src/kernel/protocol";
import type { Feature } from "../src/doc/types";
import { renderPNG, type RenderOptions } from "./render";
export interface StepReport {
index: number;
id: string;
name: string;
type: string;
off?: boolean;
error?: string;
note?: string;
/** Bodies it made, took away, or changed (volume before → after, mm³). */
made: string[];
gone: string[];
changed: { body: string; from: number; to: number }[];
/** Bodies that were sound before it and aren't after. */
broke: string[];
ms: number;
}
export interface CheckReport {
name: string;
steps?: StepReport[];
bodies: BodyHealth[];
errors: { step: string; message: string }[];
ok: boolean;
}
/** Every body's health after the steps (name from the rebuild). */
function bodiesNow(names: Map<string, string>): BodyHealth[] {
return [...debugBodies()].map(([id, s]) => healthReport(id, names.get(id) ?? id, s));
}
export async function checkProject(features: Feature[], name: string, stepwise = true): Promise<CheckReport> {
const steps: StepReport[] = [];
if (stepwise) {
let before = new Map<string, BodyHealth>();
for (let i = 0; i < features.length; i++) {
const f = features[i];
const t0 = performance.now();
const r = await regenerate(features.slice(0, i + 1));
const names = new Map(r.bodies.map((b) => [b.id, b.name]));
const now = new Map(bodiesNow(names).map((h) => [h.id, h]));
const step: StepReport = { index: i + 1, id: f.id, name: f.name, type: f.type, made: [], gone: [], changed: [], broke: [], ms: Math.round(performance.now() - t0) };
if (f.suppressed) step.off = true;
const err = r.errors.find((e) => e.featureId === f.id);
if (err) step.error = err.message;
const note = r.notes?.find((e) => e.featureId === f.id);
if (note) step.note = note.message;
for (const [id, h] of now) {
const was = before.get(id);
if (!was) step.made.push(h.name);
else if (Math.abs(was.volume - h.volume) > 1e-6 * Math.max(1, was.volume) || was.faces !== h.faces) step.changed.push({ body: h.name, from: was.volume, to: h.volume });
if (was?.healthy && !h.healthy) step.broke.push(h.name);
if (!was && !h.healthy) step.broke.push(h.name);
}
for (const [id, h] of before) if (!now.has(id)) step.gone.push(h.name);
steps.push(step);
before = now;
}
}
const r = await regenerate(features);
const names = new Map(r.bodies.map((b) => [b.id, b.name]));
const bodies = bodiesNow(names);
const byId = new Map(features.map((f) => [f.id, f]));
const errors = r.errors.map((e) => ({ step: byId.get(e.featureId)?.name ?? e.featureId, message: e.message }));
return { name, ...(stepwise ? { steps } : {}), bodies, errors, ok: !errors.length && bodies.every((b) => b.healthy) };
}
const n = (v: number) => (Math.abs(v) >= 100 ? v.toFixed(0) : Math.abs(v) >= 1 ? v.toFixed(2) : v.toPrecision(3));
/** The report as lines to read. */
export function reportText(rep: CheckReport): string {
const out: string[] = [`Project: ${rep.name}`];
if (rep.steps) {
out.push("", "Steps:");
for (const s of rep.steps) {
const what: string[] = [];
if (s.off) what.push("switched off");
if (s.made.length) what.push(`made ${s.made.join(", ")}`);
for (const c of s.changed) what.push(`${c.body} ${c.to >= c.from ? "+" : ""}${n(c.to - c.from)} mm³`);
if (s.gone.length) what.push(`took away ${s.gone.join(", ")}`);
if (s.broke.length) what.push(`!! not sound after it: ${s.broke.join(", ")}`);
if (s.note) what.push(`note: ${s.note}`);
if (s.error) what.push(`ERROR: ${s.error}`);
out.push(`${String(s.index).padStart(3)}. ${s.name} [${s.type}]${what.length ? " - " + what.join("; ") : ""} (${s.ms} ms)`);
}
}
out.push("", "Bodies:");
if (!rep.bodies.length) out.push(" (none)");
for (const b of rep.bodies) {
const size = b.box[1].map((v, k) => n(v - b.box[0][k])).join(" x ");
const bad: string[] = [];
if (!b.valid) bad.push("invalid");
if (b.solids !== 1) bad.push(`${b.solids} solids`);
if (b.openEdges) bad.push(`${b.openEdges} open edges`);
if (b.thin) bad.push(`${b.thin} hair-thin faces`);
if (!(b.volume > 0)) bad.push("no volume");
out.push(` ${b.healthy ? "ok " : "BAD "} ${b.name}: ${n(b.volume)} mm³, ${b.faces} faces, ${b.edges} edges, ${size} mm${bad.length ? " - " + bad.join(", ") : ""}`);
}
if (rep.errors.length) {
out.push("", "Errors:");
for (const e of rep.errors) out.push(` ${e.step}: ${e.message}`);
}
out.push("", rep.ok ? "All sound." : "Not all sound.");
return out.join("\n");
}
// ------------------------------------------------------------------ command line
if (process.argv[1]?.replace(/\\/g, "/").endsWith("scripts/check.ts")) {
const args = process.argv.slice(2);
const file = args.find((a) => !a.startsWith("--") && !/\.png$/i.test(a));
if (!file) {
console.log("Usage: npx tsx scripts/check.ts <project.super> [--end] [--json] [--png out.png] [--view iso|front|top|right|...]");
process.exit(2);
}
const doc = parseProject(readFileSync(file, "utf8"));
setOC(await (opencascade as unknown as () => Promise<any>)());
const rep = await checkProject(doc.features, doc.name, !args.includes("--end"));
console.log(args.includes("--json") ? JSON.stringify(rep, null, 2) : reportText(rep));
const png = args[args.indexOf("--png") + 1];
if (args.includes("--png") && png) {
const view = args.includes("--view") ? (args[args.indexOf("--view") + 1] as RenderOptions["view"]) : "iso";
const hidden = new Set(doc.hidden ?? []);
renderPNG([...debugBodies()].filter(([id]) => !hidden.has(id)).map(([id, shape]) => ({ shape, color: doc.colors?.[id] })), png, { view });
console.log(`Picture: ${png}`);
}
process.exit(rep.ok ? 0 : 1);
}
+13 -10
View File
@@ -1,15 +1,18 @@
// Make the PNG app icons (home screen / install) from the shapes in public/icon.svg.
// Make the PNG app icons (home screen / install) from the paths in public/icon.svg
// (scripts/logo.py writes that file).
// Run: node scripts/icons.mjs
import { deflateSync } from "node:zlib";
import { writeFileSync } from "node:fs";
import { readFileSync, writeFileSync } from "node:fs";
const hex = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
const BG = hex("#1f2125");
const shapes = [
[hex("#3d8bff"), [[32, 10], [51, 21], [51, 43], [32, 54], [13, 43], [13, 21]]],
[hex("#8bb8ff"), [[32, 10], [51, 21], [32, 32], [13, 21]]],
[hex("#2a63c4"), [[32, 32], [32, 54], [13, 43], [13, 21]]],
];
const svg = readFileSync("public/icon.svg", "utf8");
const BG = hex(svg.match(/<rect[^>]*fill="(#[0-9a-f]{6})"/i)[1]);
// Every filled path, in drawing order, with its bounding box (to skip it quickly).
const shapes = [...svg.matchAll(/<path d="M([^"]+)Z" fill="(#[0-9a-f]{6})"/gi)].map(([, d, fill]) => {
const P = d.split("L").map((q) => q.trim().split(/\s+/).map(Number));
const xs = P.map((p) => p[0]), ys = P.map((p) => p[1]);
return [hex(fill), P, [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]];
});
const inPoly = (x, y, P) => {
let c = false;
for (let i = 0, j = P.length - 1; i < P.length; j = i++) {
@@ -35,7 +38,7 @@ function render(n, { rounded = true, scale = 1 } = {}) {
// The logo, scaled about the middle (smaller for maskable icons).
const lu = 32 + (u - 32) / scale, lv = 32 + (v - 32) / scale;
let c = BG;
for (const [col, P] of shapes) if (inPoly(lu, lv, P)) c = col;
for (const [col, P, b] of shapes) if (lu >= b[0] && lu <= b[2] && lv >= b[1] && lv <= b[3] && inPoly(lu, lv, P)) c = col;
r += c[0]; g += c[1]; b += c[2]; a += 255;
}
const k = S * S, o = (y * n + x) * 4;
@@ -71,7 +74,7 @@ function png(w, h, rgba) {
writeFileSync("public/icon-192.png", render(192));
writeFileSync("public/icon-512.png", render(512));
// Maskable: full square, logo inside the safe circle.
writeFileSync("public/icon-maskable-512.png", render(512, { rounded: false, scale: 0.8 }));
writeFileSync("public/icon-maskable-512.png", render(512, { rounded: false, scale: 0.75 }));
// iOS rounds the corners itself.
writeFileSync("public/apple-touch-icon.png", render(180, { rounded: false }));
console.log("icons written");
+52
View File
@@ -0,0 +1,52 @@
// Is the push live? Compares the commit superGeometry.app was built from
// (its /version.json) with main here.
//
// npx tsx scripts/live.ts once
// npx tsx scripts/live.ts --wait until it is (up to 20 minutes)
// npx tsx scripts/live.ts --site http://localhost:4173
import { execSync } from "node:child_process";
const args = process.argv.slice(2);
const site = (args.includes("--site") ? args[args.indexOf("--site") + 1] : "https://supergeometry.app").replace(/\/$/, "");
const git = (cmd: string) => {
try {
return execSync(`git ${cmd}`, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
} catch {
return "";
}
};
const want = git("rev-parse origin/main");
const short = (c: string) => c.slice(0, 7);
interface Version {
version: string;
commit: string;
subject: string;
script: string;
built: string;
}
async function live(): Promise<Version | null> {
try {
const r = await fetch(`${site}/version.json?t=${Date.now()}`, { cache: "no-store" });
if (!r.ok) return null;
return (await r.json()) as Version;
} catch {
return null;
}
}
const until = Date.now() + 20 * 60_000;
for (;;) {
const v = await live();
if (v?.commit && v.commit === want) {
console.log(`Live: ${short(v.commit)} ${v.subject} (built ${v.built}, ${v.script})`);
process.exit(0);
}
if (!args.includes("--wait") || Date.now() > until) {
if (!v) console.log(`${site} has no version.json yet (built before it was added), main is ${short(want)}`);
else console.log(`Not live yet: the site is ${short(v.commit)} ${v.subject} (built ${v.built}), main is ${short(want)} ${git(`log -1 --format=%s ${want}`)}`);
process.exit(1);
}
await new Promise((r) => setTimeout(r, 20_000));
}
+176
View File
@@ -0,0 +1,176 @@
"""superGeometry.app logo: a faceted red cape blowing in the wind, a yellow clasp, and a yellow
hexagon with a blue G printed on the cloth (it folds and shades with the facets).
Run: python scripts/logo.py (writes public/icon.svg; then node scripts/icons.mjs for the PNGs)"""
import math
import sys
TILE = "#1f2125"
RED = ("#7e1f1a", "#d8392f", "#ff7466")
YEL = ("#9a6a08", "#ffc23d", "#ffe9a3")
BLU = ("#123574", "#2a63c4", "#6ea4ff")
CLASP = "#ffd34d"
def stroke(pl, t):
"""A thick polyline (miter joins, butt ends) as one polygon."""
h = t / 2
def nrm(a, b):
dx, dy = b[0] - a[0], b[1] - a[1]; L = math.hypot(dx, dy)
return (-dy / L, dx / L)
left, right = [], []
n = len(pl)
for i in range(n):
if i == 0: m = nrm(pl[0], pl[1]); k = 1
elif i == n - 1: m = nrm(pl[-2], pl[-1]); k = 1
else:
a, b = nrm(pl[i - 1], pl[i]), nrm(pl[i], pl[i + 1])
m = (a[0] + b[0], a[1] + b[1]); L = math.hypot(*m); m = (m[0] / L, m[1] / L)
k = 1 / (m[0] * a[0] + m[1] * a[1])
left.append((pl[i][0] + m[0] * h * k, pl[i][1] + m[1] * h * k))
right.append((pl[i][0] - m[0] * h * k, pl[i][1] - m[1] * h * k))
return left + right[::-1]
def hexpts(cx, cy, r, angles):
return [(cx + r * math.cos(math.radians(a)), cy + r * math.sin(math.radians(a))) for a in angles]
def lerp(a, b, t): return a + (b - a) * t
def mix(c1, c2, t):
a = [int(c1[i:i + 2], 16) for i in (1, 3, 5)]; b = [int(c2[i:i + 2], 16) for i in (1, 3, 5)]
return "#" + "".join(f"{round(lerp(x, y, t)):02x}" for x, y in zip(a, b))
def tone(pal, s):
return mix(pal[0], pal[1], s / 0.55) if s < 0.55 else mix(pal[1], pal[2], (s - 0.55) / 0.45)
def width(v): return lerp(0.3, 1.0, v ** 0.8)
def surf(u, v, wind=1.0, folds=1.0):
x = (u - 0.5) * 2 * width(v) + wind * 0.3 * v * v - 0.12 * v * (1 - u)
y = v * 1.6 - wind * 0.32 * v * v * u + 0.1 * v ** 3 * math.cos(u * math.pi * 3 + 1.8)
z = folds * (v ** 0.7) * math.sin(u * math.pi * 3 + v * 1.8) * 0.3
return (x, y, z)
def flat_to_uv(p):
"""A point on the cloth laid flat (X across from the middle, Y down) to its (u, v)."""
X, Y = p
v = Y / 1.6
return (0.5 + X / (2 * width(v)), v)
def densify(P, step=0.02):
out = []
for i in range(len(P)):
a, b = P[i], P[(i + 1) % len(P)]
n = max(1, int(math.dist(a, b) / step))
out += [(lerp(a[0], b[0], k / n), lerp(a[1], b[1], k / n)) for k in range(n)]
return out
def clip(subject, tri):
"""Sutherland-Hodgman: the part of a polygon inside a triangle (counter-clockwise or not)."""
area = (tri[1][0] - tri[0][0]) * (tri[2][1] - tri[0][1]) - (tri[1][1] - tri[0][1]) * (tri[2][0] - tri[0][0])
sgn = 1 if area > 0 else -1
out = subject
for i in range(3):
a, b = tri[i], tri[(i + 1) % 3]
inside = lambda p: sgn * ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])) >= 0
src, out = out, []
if not src: break
for j in range(len(src)):
p, q = src[j], src[(j + 1) % len(src)]
if inside(q):
if not inside(p): out.append(cross(p, q, a, b))
out.append(q)
elif inside(p):
out.append(cross(p, q, a, b))
return out
def cross(p, q, a, b):
d1 = (q[0] - p[0], q[1] - p[1]); d2 = (b[0] - a[0], b[1] - a[1])
den = d1[0] * d2[1] - d1[1] * d2[0]
t = ((a[0] - p[0]) * d2[1] - (a[1] - p[1]) * d2[0]) / den
return (p[0] + t * d1[0], p[1] + t * d1[1])
def logo(nu=10, nv=6, badge_y=0.9, badge_r=0.6):
# the print, laid flat, then into (u, v)
hexa = [flat_to_uv(p) for p in densify(hexpts(0, badge_y, badge_r, [-90, -30, 30, 90, 150, 210]))]
g = [flat_to_uv(p) for p in densify(gmark_flat(0, badge_y, badge_r * 0.77, badge_r * 0.3))]
L = (-0.5, -0.6, 0.62); n = math.sqrt(sum(c * c for c in L)); L = tuple(c / n for c in L)
UV = [[(i / nu, j / nv) for i in range(nu + 1)] for j in range(nv + 1)]
tris = []
for j in range(nv):
for i in range(nu):
a, b, c, d = UV[j][i], UV[j][i + 1], UV[j + 1][i + 1], UV[j + 1][i]
for t in ((a, b, c), (a, c, d)) if (i + j) % 2 == 0 else ((a, b, d), (b, c, d)):
P = [surf(*q) for q in t]
e1 = [P[1][k] - P[0][k] for k in range(3)]; e2 = [P[2][k] - P[0][k] for k in range(3)]
nn = (e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0])
m = math.sqrt(sum(q * q for q in nn)) or 1
nn = tuple(q / m for q in nn)
if nn[2] < 0: nn = tuple(-q for q in nn)
s = max(0.0, sum(nn[k] * L[k] for k in range(3)))
s = min(1, max(0, (s - 0.25) / 0.7))
tris.append((sum(q[2] for q in P) / 3, s, t, P))
tris.sort(key=lambda q: q[0])
proj = lambda p: (p[0], p[1] - 0.35 * p[2])
pts = [proj(p) for *_, P in tris for p in P]
x0, x1 = min(p[0] for p in pts), max(p[0] for p in pts)
y0, y1 = min(p[1] for p in pts), max(p[1] for p in pts)
k = min(56 / (x1 - x0), 49 / (y1 - y0))
ox = 32 - (x0 + x1) / 2 * k
tx = lambda p: (ox + p[0] * k, 12.3 + (p[1] - y0) * k)
out = []
for _, s, t, P in tris:
S = [tx(proj(p)) for p in P]
# the facet's own affine map from (u, v) to the picture
(u0, v0), (u1, v1), (u2, v2) = t
det = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)
def amap(q, S=S, u0=u0, v0=v0, u1=u1, v1=v1, u2=u2, v2=v2, det=det):
a = ((q[0] - u0) * (v2 - v0) - (u2 - u0) * (q[1] - v0)) / det
b = ((u1 - u0) * (q[1] - v0) - (q[0] - u0) * (v1 - v0)) / det
return (S[0][0] + a * (S[1][0] - S[0][0]) + b * (S[2][0] - S[0][0]),
S[0][1] + a * (S[1][1] - S[0][1]) + b * (S[2][1] - S[0][1]))
out.append((tone(RED, s), S))
for pal, poly in ((YEL, hexa), (BLU, g)):
c = clip(poly, list(t))
if len(c) >= 3:
out.append((tone(pal, s), [amap(q) for q in c]))
top = [tx(proj(surf(0, 0))), tx(proj(surf(1, 0)))]
out.append((CLASP, [(top[0][0] - 1, 9), (top[1][0] + 1, 9), (top[1][0] + 0.5, 12.5), (top[0][0] - 0.5, 12.5)]))
return out
def gmark_flat(cx, cy, r, t):
rr = r - t / 2
P = hexpts(cx, cy, rr, [-30, -90, -150, 150, 90, 30])
P.append((cx + rr * math.cos(math.radians(30)), cy))
P.append((cx + rr * 0.05, cy))
return stroke(P, t)
def svg(shapes, tile=True):
parts = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">']
if tile: parts.append(f'<rect width="64" height="64" rx="14" fill="{TILE}"/>')
# each facet is also stroked in its own colour, so no hairline seams show between them
parts.append('<g stroke-width=".2" stroke-linejoin="round">')
num = lambda a: f"{a:.1f}".rstrip("0").rstrip(".")
for c, P in shapes:
parts.append(f'<path d="M{"L".join(num(x) + " " + num(y) for x, y in P)}Z" fill="{c}" stroke="{c}"/>')
return "\n".join(parts) + "\n</g>\n</svg>\n"
if __name__ == "__main__":
out = sys.argv[1] if len(sys.argv) > 1 else "public/icon.svg"
with open(out, "w", encoding="utf-8", newline="\n") as f:
f.write(svg(logo()))
print("wrote", out)
+269
View File
@@ -0,0 +1,269 @@
// A picture of solids without a browser: the bodies meshed, drawn shaded with
// their edges by a small software renderer, and written as a PNG.
//
// npx tsx scripts/render.ts project.super out.png [--view iso|front|back|top|bottom|left|right] [--size 800]
// import { renderPNG } from "./render"; renderPNG([{ shape }], "out.png", { view: "front" });
import { writeFileSync } from "node:fs";
import { deflateSync } from "node:zlib";
import type { Shape3D } from "replicad";
type V3 = [number, number, number];
export interface RenderOptions {
view?: "iso" | "front" | "back" | "top" | "bottom" | "left" | "right";
/** Width and height in pixels (default 800). */
size?: number;
/** Background, "#rrggbb" (default light grey). */
background?: string;
/** Edges drawn over the faces (default on). */
edges?: boolean;
}
export interface RenderBody {
shape: Shape3D;
/** "#rrggbb" (default a blue-grey). */
color?: string;
}
// The views: the direction looked from (towards the viewer) and which way is up on the picture.
const VIEWS: Record<NonNullable<RenderOptions["view"]>, { dir: V3; up: V3 }> = {
iso: { dir: [1, -1, 1], up: [0, 0, 1] },
front: { dir: [0, -1, 0], up: [0, 0, 1] },
back: { dir: [0, 1, 0], up: [0, 0, 1] },
top: { dir: [0, 0, 1], up: [0, 1, 0] },
bottom: { dir: [0, 0, -1], up: [0, -1, 0] },
left: { dir: [-1, 0, 0], up: [0, 0, 1] },
right: { dir: [1, 0, 0], up: [0, 0, 1] },
};
const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const norm = (a: V3): V3 => {
const l = Math.hypot(...a) || 1;
return [a[0] / l, a[1] / l, a[2] / l];
};
const rgb = (hex: string): V3 => {
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
const v = m ? parseInt(m[1], 16) : 0x8fa3b8;
return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
};
/** The picture as RGBA pixels (size x size). */
export function renderRGBA(bodies: RenderBody[], o: RenderOptions = {}): { width: number; height: number; data: Uint8Array } {
const size = o.size ?? 800;
const SS = 2; // drawn twice as big, then averaged down (smooth edges)
const W = size * SS;
const view = VIEWS[o.view ?? "iso"];
const fwd = norm(view.dir);
const right = norm(cross(view.up, fwd));
const up = cross(fwd, right);
const bg = rgb(o.background ?? "#eef0f3");
// Meshes in view space: x right, y up, z towards the viewer.
const meshes = bodies.flatMap((b) => {
try {
const m = b.shape.mesh({ tolerance: 0.05, angularTolerance: 0.15 });
let lines: number[] = [];
if (o.edges !== false) {
try {
lines = (b.shape as any).meshEdges({ tolerance: 0.05, angularTolerance: 0.15 }).lines as number[];
} catch {
lines = [];
}
}
return [{ v: m.vertices as number[], t: m.triangles as number[], lines, color: rgb(b.color ?? "#8fa3b8") }];
} catch {
return [];
}
});
const toView = (a: number[], i: number): V3 => {
const p: V3 = [a[i], a[i + 1], a[i + 2]];
return [dot(p, right), dot(p, up), dot(p, fwd)];
};
let lo: V3 = [Infinity, Infinity, Infinity];
let hi: V3 = [-Infinity, -Infinity, -Infinity];
for (const m of meshes)
for (let i = 0; i < m.v.length; i += 3) {
const p = toView(m.v, i);
lo = [Math.min(lo[0], p[0]), Math.min(lo[1], p[1]), Math.min(lo[2], p[2])];
hi = [Math.max(hi[0], p[0]), Math.max(hi[1], p[1]), Math.max(hi[2], p[2])];
}
const color = new Float32Array(W * W * 3);
for (let i = 0; i < W * W; i++) color.set(bg, i * 3);
const depth = new Float32Array(W * W).fill(-Infinity);
if (Number.isFinite(lo[0])) {
// Fit with a margin, centred.
const span = Math.max(hi[0] - lo[0], hi[1] - lo[1]) || 1;
const k = (W * 0.86) / span;
const cx = (lo[0] + hi[0]) / 2;
const cy = (lo[1] + hi[1]) / 2;
const px = (p: V3): V3 => [W / 2 + (p[0] - cx) * k, W / 2 - (p[1] - cy) * k, p[2]];
const light = norm([0.35, 0.55, 1]);
for (const m of meshes) {
const P: V3[] = [];
for (let i = 0; i < m.v.length; i += 3) P.push(px(toView(m.v, i)));
for (let t = 0; t < m.t.length; t += 3) {
const a = P[m.t[t]];
const b = P[m.t[t + 1]];
const c = P[m.t[t + 2]];
// The face's normal in view space (screen y is down: flip it back).
const n = norm(cross(sub([b[0], -b[1], b[2]], [a[0], -a[1], a[2]]), sub([c[0], -c[1], c[2]], [a[0], -a[1], a[2]])));
const facing = n[2] < 0 ? ([-n[0], -n[1], -n[2]] as V3) : n;
const shade = 0.38 + 0.62 * Math.max(0, dot(facing, light));
const col: V3 = [m.color[0] * shade, m.color[1] * shade, m.color[2] * shade];
fillTri(a, b, c, col, color, depth, W);
}
// Edges: dark, drawn where they are not behind a face.
const bias = (hi[2] - lo[2] || 1) * 2e-3;
for (let i = 0; i + 5 < m.lines.length; i += 6) {
const a = px(toView(m.lines, i));
const b = px(toView(m.lines, i + 3));
drawLine(a, b, [40, 44, 52], color, depth, W, bias, SS);
}
}
}
// Average each SS x SS block.
const data = new Uint8Array(size * size * 4);
for (let y = 0; y < size; y++)
for (let x = 0; x < size; x++) {
let r = 0,
g = 0,
b = 0;
for (let j = 0; j < SS; j++)
for (let i = 0; i < SS; i++) {
const q = ((y * SS + j) * W + x * SS + i) * 3;
r += color[q];
g += color[q + 1];
b += color[q + 2];
}
const o4 = (y * size + x) * 4;
data[o4] = r / (SS * SS);
data[o4 + 1] = g / (SS * SS);
data[o4 + 2] = b / (SS * SS);
data[o4 + 3] = 255;
}
return { width: size, height: size, data };
}
function fillTri(a: V3, b: V3, c: V3, col: V3, color: Float32Array, depth: Float32Array, W: number): void {
const x0 = Math.max(0, Math.floor(Math.min(a[0], b[0], c[0])));
const x1 = Math.min(W - 1, Math.ceil(Math.max(a[0], b[0], c[0])));
const y0 = Math.max(0, Math.floor(Math.min(a[1], b[1], c[1])));
const y1 = Math.min(W - 1, Math.ceil(Math.max(a[1], b[1], c[1])));
const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
if (Math.abs(area) < 1e-12) return;
for (let y = y0; y <= y1; y++)
for (let x = x0; x <= x1; x++) {
const px = x + 0.5;
const py = y + 0.5;
const w0 = ((b[0] - px) * (c[1] - py) - (b[1] - py) * (c[0] - px)) / area;
const w1 = ((c[0] - px) * (a[1] - py) - (c[1] - py) * (a[0] - px)) / area;
const w2 = 1 - w0 - w1;
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
const z = w0 * a[2] + w1 * b[2] + w2 * c[2];
const i = y * W + x;
if (z <= depth[i]) continue;
depth[i] = z;
color[i * 3] = col[0];
color[i * 3 + 1] = col[1];
color[i * 3 + 2] = col[2];
}
}
function drawLine(a: V3, b: V3, col: V3, color: Float32Array, depth: Float32Array, W: number, bias: number, thick: number): void {
const steps = Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]))) + 1;
for (let s = 0; s <= steps; s++) {
const t = s / steps;
const x = a[0] + (b[0] - a[0]) * t;
const y = a[1] + (b[1] - a[1]) * t;
const z = a[2] + (b[2] - a[2]) * t;
for (let j = 0; j < thick; j++)
for (let i = 0; i < thick; i++) {
const X = Math.floor(x - thick / 2 + i + 0.5);
const Y = Math.floor(y - thick / 2 + j + 0.5);
if (X < 0 || Y < 0 || X >= W || Y >= W) continue;
const k = Y * W + X;
if (z + bias < depth[k]) continue;
color[k * 3] = col[0];
color[k * 3 + 1] = col[1];
color[k * 3 + 2] = col[2];
}
}
}
// ------------------------------------------------------------------ PNG
const CRC = (() => {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
t[n] = c >>> 0;
}
return t;
})();
function crc32(buf: Uint8Array): number {
let c = 0xffffffff;
for (const b of buf) c = CRC[(c ^ b) & 255] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type: string, data: Uint8Array): Uint8Array {
const out = new Uint8Array(12 + data.length);
const dv = new DataView(out.buffer);
dv.setUint32(0, data.length);
out.set(Buffer.from(type, "ascii"), 4);
out.set(data, 8);
dv.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
return out;
}
/** RGBA pixels as a PNG file. */
export function encodePNG(width: number, height: number, rgba: Uint8Array): Uint8Array {
const raw = new Uint8Array(height * (width * 4 + 1));
for (let y = 0; y < height; y++) raw.set(rgba.subarray(y * width * 4, (y + 1) * width * 4), y * (width * 4 + 1) + 1);
const ihdr = new Uint8Array(13);
const dv = new DataView(ihdr.buffer);
dv.setUint32(0, width);
dv.setUint32(4, height);
ihdr.set([8, 6, 0, 0, 0], 8);
const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())];
const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));
let at = 0;
for (const p of parts) out.set(p, at), (at += p.length);
return out;
}
/** Draw the bodies and write the picture to `file`. */
export function renderPNG(bodies: RenderBody[], file: string, o: RenderOptions = {}): void {
const { width, height, data } = renderRGBA(bodies, o);
writeFileSync(file, encodePNG(width, height, data));
}
// ------------------------------------------------------------------ command line
if (process.argv[1]?.replace(/\\/g, "/").endsWith("scripts/render.ts")) {
const args = process.argv.slice(2);
const [file, out] = args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));
if (!file || !out) {
console.log("Usage: npx tsx scripts/render.ts <project.super> <out.png> [--view iso|front|back|top|bottom|left|right] [--size 800]");
process.exit(2);
}
const { readFileSync } = await import("node:fs");
const opencascade = (await import("replicad-opencascadejs")).default;
const { setOC } = await import("replicad");
const { parseProject } = await import("../src/doc/store");
const { debugBodies, regenerate } = await import("../src/kernel/engine");
const doc = parseProject(readFileSync(file, "utf8"));
setOC(await (opencascade as unknown as () => Promise<any>)());
const r = await regenerate(doc.features);
for (const e of r.errors) console.log(`error in ${e.featureId}: ${e.message}`);
const hidden = new Set(doc.hidden ?? []);
const opt = (k: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
renderPNG(
[...debugBodies()].filter(([id]) => !hidden.has(id)).map(([id, shape]) => ({ shape, color: doc.colors?.[id] })),
out,
{ view: (opt("--view") as RenderOptions["view"]) ?? "iso", size: Number(opt("--size") ?? 800) },
);
console.log(`Picture: ${out}`);
}
+1203 -167
View File
File diff suppressed because it is too large Load Diff
+637
View File
@@ -0,0 +1,637 @@
// Assemblies, in the app: joints between the project's bodies, and the bodies dragged by them.
//
// The bodies are where they were modelled, so there is nothing to put in place. A joint is two taps - a face on
// each of two bodies - and the app says what kind it is from the faces as they stand (see `propose`). A body
// dragged then moves the way its joint lets it. Moving is a pose, not an edit: Home, or leaving Assemblies, has
// every body where it was modelled again.
import { BufferGeometry, Line, LineBasicMaterial, Vector3 } from "three";
import type { ThreadFeature, Vec3 } from "../doc/types";
import { add, cross, dot, len, norm, scale, sub } from "../geom";
import { fmtLen } from "../units";
import type { PanelItem } from "../ui/ui";
import type { ToolPointer } from "../view/input";
import { axisDrag } from "../tools/handles";
import { roundAxis } from "../tools/select";
import { faceIndexOf, faceRefOf, type AppContext, type Tool } from "../tools/tool";
import { inverse, penetrates, Solid } from "./contact";
import { apply, driverOf, effective, JOINT_NAMES, propose, solve, tree, mul, turn, turnAxis, type Joint, type JointType, type Mat4, type PickLine } from "./joints";
interface Pick {
body: string;
face: number;
line: PickLine | null;
}
/** Stop on contact, as it was last set (for this visit to the page). */
let stopOnContact = false;
/** How far into each other two parts may be shown before they count as run into each other (mm): what touches, or sits with a hair of play, is not. */
const CONTACT_TOL = 0.25;
const uid = () => `joint-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const AXIS_COLOR = 0xff9d2e;
export class AssemblyTool implements Tool {
readonly id = "assembly";
/** How far each joint is from home (degrees; mm for a slide). Gone when the tool is left. */
private values: Record<string, number> = {};
/** 0 to 1: how far the bodies are pulled apart. */
private exploded = 0;
private mode: "list" | "add" | "edit" = "list";
private first: Pick | null = null;
private editing: string | null = null;
private axisLine: Line | null = null;
private dragging: {
from: ToolPointer;
joint: Joint;
/** The joint whose own value is set (the dragged one, or the one it follows), and by how much it is followed. */
driver: Joint;
ratio: number;
sign: number;
v0: number;
/** Where it was taken hold of, and the joint's line as it is now (its parent moved, it moved with it). */
grab: Vec3;
origin: Vec3;
axis: Vec3;
/** Round the line: the turn so far, and where the pointer was on the last move. */
turned: number;
last: Vec3 | null;
/** Stop on contact: the pairs of bodies in each other as the drag began (left alone), how each pair stood then, and the last value nothing ran into anything at. */
inEachOther: Set<string>;
stood: Map<string, Mat4>;
free: number;
} | null = null;
private solids = new Map<string, { key: unknown; solid: Solid }>();
/** Each body's middle and size, by its mesh (measured once for each). */
private measured = new Map<string, { key: unknown; center: Vec3; size: number }>();
constructor(private app: AppContext, private start?: { a: { body: string; face: number }; b: { body: string; face: number } }) {}
private get joints(): Joint[] {
return this.app.store.doc.joints ?? [];
}
private get bodies(): string[] {
return this.app.view.bodyList.map((b) => b.id);
}
private nameOf(body: string): string {
return this.app.store.doc.names?.[body] ?? this.app.view.body(body)?.name ?? "a part";
}
enter(): void {
this.app.ui.setTools([{ id: "exit", label: "Exit Assemblies", icon: "exit", shortcut: "Esc", run: () => this.leave() }]);
this.app.ui.setBottom(this.app.bottomTools());
this.app.setSelection([]);
this.app.setHover(null);
// Where the parts were left (asked for: "if i click on assembly again ... it doesnt show what i made before").
this.values = { ...(this.app.store.doc.pose?.values ?? {}) };
this.exploded = this.app.store.doc.pose?.exploded ?? 0;
const s = this.start;
this.start = undefined;
if (s && s.a.body !== s.b.body) this.make(this.pickOf(s.a.body, s.a.face), this.pickOf(s.b.body, s.b.face));
else this.render();
this.show();
}
/** The pose as it is, kept in the project: what is shown after Assemblies is left, and when it is opened again. */
private save(): void {
const values: Record<string, number> = {};
for (const j of this.joints) if (Math.abs(this.values[j.id] ?? 0) > 1e-9) values[j.id] = this.values[j.id];
const pose = Object.keys(values).length || this.exploded > 0 ? { values, ...(this.exploded > 0 ? { exploded: this.exploded } : {}) } : undefined;
if (JSON.stringify(pose) === JSON.stringify(this.app.store.doc.pose)) return;
this.app.store.commit((d) => {
if (pose) d.pose = pose;
else delete d.pose;
});
}
private leave(): void {
this.save();
this.app.setTool(null);
}
exit(): void {
// (The parts stay as they were left: the app shows the project's pose while nothing is being worked on.)
this.dropAxis();
this.app.ui.showPanel(null);
this.app.ui.setHint(null);
this.app.ui.setLabel(0, 0, null);
this.app.setSelection([]);
this.app.setHover(null);
}
key(e: KeyboardEvent): boolean {
if (e.key !== "Escape") return false;
if (this.mode === "list") this.leave();
else this.toList();
return true;
}
/** The model was made again: the bodies are shown at their joints' values still. */
refresh(): void {
// (A pose undone or redone: the parts go where the project has them.)
if (!this.dragging) this.values = { ...(this.app.store.doc.pose?.values ?? {}) };
this.show();
this.render();
}
/** The project's pose, for the app to show when Assemblies is not open (null: all as modelled). */
static posesOf(app: AppContext): Map<string, Mat4> | null {
const pose = app.store.doc.pose;
if (!pose || !app.store.doc.joints?.length) return null;
const t = new AssemblyTool(app);
t.values = { ...pose.values };
t.exploded = pose.exploded ?? 0;
return t.poses();
}
// ------------------------------------------------------------------ what is shown
/** A joint with its line where the faces it was picked by are now (the model changed since: it follows them). */
private live(j: Joint): Joint {
if (!j.refA) return j;
const i = faceIndexOf(this.app, j.refA);
const line = i === null ? null : this.pickOf(j.refA.body, i).line;
if (!line) return j;
const flipped = dot(norm(line.dir), norm(j.axis)) < 0;
return { ...j, origin: line.origin, axis: flipped ? scale(norm(line.dir), -1) : norm(line.dir) };
}
private liveJoints(): Joint[] {
return this.joints.map((j) => this.live(j));
}
private measure(body: string): { center: Vec3; size: number } | null {
const b = this.app.view.body(body);
if (!b) return null;
const was = this.measured.get(body);
if (was && was.key === b.key) return was;
const P = b.positions;
const lo: Vec3 = [Infinity, Infinity, Infinity];
const hi: Vec3 = [-Infinity, -Infinity, -Infinity];
for (let i = 0; i < P.length; i += 3) for (let k = 0; k < 3; k++) (lo[k] = Math.min(lo[k], P[i + k])), (hi[k] = Math.max(hi[k], P[i + k]));
const m = { key: b.key, center: scale(add(lo, hi), 0.5), size: len(sub(hi, lo)) / 2 };
this.measured.set(body, m);
return m;
}
private poses(): Map<string, Mat4> {
const bodies = this.bodies;
const centers: Record<string, Vec3> = {};
const sizes: Record<string, number> = {};
if (this.exploded > 0) {
for (const b of bodies) {
const m = this.measure(b);
if (m) (centers[b] = m.center), (sizes[b] = m.size);
}
}
return solve(this.liveJoints(), bodies, this.values, this.app.store.doc.ground, this.exploded > 0 ? { factor: this.exploded * 0.8, centers, sizes } : undefined);
}
private solid(body: string): Solid | null {
const b = this.app.view.body(body);
if (!b) return null;
const was = this.solids.get(body);
if (was && was.key === b.key) return was.solid;
const solid = new Solid(b.positions, b.indices);
this.solids.set(body, { key: b.key, solid });
return solid;
}
/** Each pair of bodies shown: how the second stands against the first (the second's move, seen from the first). */
private standing(poses: Map<string, Mat4>): Map<string, Mat4> {
const ids = this.bodies.filter((b) => !this.app.view.isHidden(b));
const out = new Map<string, Mat4>();
const I: Mat4 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
for (let i = 0; i < ids.length; i++)
for (let j = i + 1; j < ids.length; j++) {
const a = poses.get(ids[i]);
const b = poses.get(ids[j]);
out.set(`${ids[i]}|${ids[j]}`, a || b ? mul(inverse(a ?? I), b ?? I) : I);
}
return out;
}
/** The pairs of bodies run into each other, of those in `pairs` (all of them; or only those that stand otherwise than in `than`). */
private clashes(pairs: Map<string, Mat4>, than?: Map<string, Mat4>, skip?: Set<string>): Set<string> {
const out = new Set<string>();
for (const [key, m] of pairs) {
if (skip?.has(key)) continue;
const was = than?.get(key);
if (was && was.every((v, i) => Math.abs(v - m[i]) < 1e-9)) continue;
const [a, b] = key.split("|");
const sa = this.solid(a);
const sb = this.solid(b);
if (sa && sb && penetrates(sa, sb, m, CONTACT_TOL)) out.add(key);
}
return out;
}
private show(): void {
const poses = this.poses();
this.app.view.setPoses(poses);
this.placeAxis(poses);
}
private dropAxis(): void {
if (!this.axisLine) return;
this.app.view.overlay.remove(this.axisLine);
this.axisLine.geometry.dispose();
(this.axisLine.material as LineBasicMaterial).dispose();
this.axisLine = null;
}
/** The line of the joint that is open, drawn through the model (with the body that carries it, when that moved). */
private placeAxis(poses: Map<string, Mat4>): void {
this.dropAxis();
const j0 = this.joints.find((x) => x.id === this.editing);
if (!j0 || j0.type === "fixed" || this.mode !== "edit") return;
const j = this.live(j0);
const t = tree(this.liveJoints(), this.bodies, this.app.store.doc.ground);
const child = t.up.get(j.b)?.joint.id === j.id ? j.b : j.a;
const parent = t.up.get(child)?.parent;
const m = (parent && poses.get(parent)) || null;
const o = m ? apply(m, j.origin) : j.origin;
const a = norm(m ? turn(m, j.axis) : j.axis);
const reach = Math.max(this.measure(j.a)?.size ?? 10, this.measure(j.b)?.size ?? 10) * 1.6;
const g = new BufferGeometry().setFromPoints([new Vector3(...add(o, scale(a, -reach))), new Vector3(...add(o, scale(a, reach)))]);
this.axisLine = new Line(g, new LineBasicMaterial({ color: AXIS_COLOR, depthTest: false, transparent: true }));
this.axisLine.renderOrder = 60;
this.app.view.overlay.add(this.axisLine);
this.app.view.requestRender();
}
// ------------------------------------------------------------------ picks
/**
* A flat face's middle: the middle of the box round it (measured along the face). Not its centre of area - a
* nut's top is a ring whose hole the thread runs out of, a little to one side, and its centre of area is a
* quarter of a millimetre off the nut's line; its outline's middle is on it.
*/
private centroid(body: string, face: number): Vec3 | null {
const b = this.app.view.body(body);
const f = b?.faces[face];
const g = b?.faceGroups.find((x) => x.face === face);
if (!b || !f?.plane || !g) return null;
const P = b.positions;
const I = b.indices;
const x = norm(f.plane.xDir);
const y = norm(cross(f.plane.normal, f.plane.xDir));
const o = f.plane.origin;
let u0 = Infinity;
let u1 = -Infinity;
let v0 = Infinity;
let v1 = -Infinity;
for (let k = g.start; k < g.start + g.count; k++) {
const i = I[k];
const d: Vec3 = [P[3 * i] - o[0], P[3 * i + 1] - o[1], P[3 * i + 2] - o[2]];
const u = dot(d, x);
const v = dot(d, y);
u0 = Math.min(u0, u);
u1 = Math.max(u1, u);
v0 = Math.min(v0, v);
v1 = Math.max(v1, v);
}
if (!(u1 >= u0)) return null;
// (On the face's own plane: the drawn points are kept to seven digits, the plane is exact.)
const n = norm(f.plane.normal);
const flat = add(add(o, scale(x, (u0 + u1) / 2)), scale(y, (v0 + v1) / 2));
return add(flat, scale(n, dot(sub(f.center, flat), n)));
}
private pickOf(body: string, face: number): Pick {
const f = this.app.view.body(body)?.faces[face];
let line: PickLine | null = null;
if (f?.round) {
const ax = roundAxis(this.app, body, face);
if (ax) line = { origin: ax.origin, dir: ax.dir, round: true };
} else if (f?.plane) line = { origin: this.centroid(body, face) ?? f.center, dir: f.normal, round: false };
// Any other face that is turned round a line - a thread's flank, a cone: that line, found from its points.
else if (f) {
const b = this.app.view.body(body)!;
const g = b.faceGroups.find((x) => x.face === face);
if (g) {
const seen = new Set<number>();
const pts: Vec3[] = [];
const nrm: Vec3[] = [];
for (let k = g.start; k < g.start + g.count; k++) {
const i = b.indices[k];
if (seen.has(i)) continue;
seen.add(i);
pts.push([b.positions[3 * i], b.positions[3 * i + 1], b.positions[3 * i + 2]]);
nrm.push([b.normals[3 * i], b.normals[3 * i + 1], b.normals[3 * i + 2]]);
}
const ax = turnAxis(pts, nrm);
if (ax) line = { origin: ax.origin, dir: ax.dir, round: true, rough: true };
}
}
return { body, face, line };
}
private faceAt(p: ToolPointer): { body: string; face: number; point: Vec3 } | null {
const h = this.app.view.facesAt(p.x, p.y)[0];
return h && h.kind === "face" ? { body: h.body, face: h.face, point: h.point } : null;
}
hover(p: ToolPointer | null): void {
if (this.mode !== "add") return this.app.setHover(null);
const h = p ? this.faceAt(p) : null;
this.app.setHover(h ? { kind: "face", body: h.body, face: h.face } : null);
}
tap(p: ToolPointer): void {
const h = this.faceAt(p);
if (this.mode === "add") {
if (!h) return;
if (!this.first) {
this.first = this.pickOf(h.body, h.face);
this.app.setSelection([{ kind: "face", body: h.body, face: h.face }]);
return this.render();
}
if (h.body === this.first.body) return this.app.ui.toast("Tap a face of another part: a joint is between two");
return this.make(this.first, this.pickOf(h.body, h.face));
}
// A part tapped: the joint that holds it is opened. Nothing tapped: back to the list.
if (!h) return this.mode === "edit" ? this.toList() : undefined;
const t = tree(this.liveJoints(), this.bodies, this.app.store.doc.ground);
const j = t.up.get(h.body)?.joint ?? this.joints.find((x) => x.a === h.body || x.b === h.body);
if (j) this.open(j.id);
else this.app.ui.toast("No joint holds that part yet. Add joint, then tap it and the part it moves against.");
}
// ------------------------------------------------------------------ joints made and changed
private change(mutate: (joints: Joint[]) => void): void {
this.app.store.commit((d) => {
d.joints ??= [];
mutate(d.joints);
if (!d.joints.length) delete d.joints;
});
}
private patch(id: string, p: Partial<Joint>): void {
this.change((js) => {
const j = js.find((x) => x.id === id);
if (j) Object.assign(j, p);
});
this.show();
this.render();
}
/** The pitch of a thread on either body (mm for each full turn), when one of them is threaded. */
private threadOn(a: string, b: string): number | undefined {
const t = this.app.store.doc.features.find((f): f is ThreadFeature => f.type === "thread" && !f.suppressed && (f.face.body === a || f.face.body === b));
return t ? t.pitch * (t.starts ?? 1) : undefined;
}
private make(a: Pick, b: Pick): void {
const p = propose(a.line, b.line, this.threadOn(a.body, b.body));
const n = this.joints.length + 1;
const refA = faceRefOf(this.app, a.line ? a : b) ?? undefined;
const refB = faceRefOf(this.app, a.line ? b : a) ?? undefined;
const joint: Joint = { id: uid(), name: `Joint ${n}`, type: p.type, a: a.body, b: b.body, origin: p.origin, axis: p.axis, ...(p.pitch ? { pitch: p.pitch } : {}), ...(refA ? { refA } : {}), ...(refB ? { refB } : {}) };
this.change((js) => js.push(joint));
this.first = null;
this.app.setSelection([]);
this.app.ui.toast(`${JOINT_NAMES[p.type]} joint: ${this.nameOf(a.body)} and ${this.nameOf(b.body)}`);
this.open(joint.id);
}
private open(id: string): void {
this.mode = "edit";
this.editing = id;
this.show();
this.render();
}
private toList(): void {
this.save();
this.mode = "list";
this.editing = null;
this.first = null;
this.app.setSelection([]);
this.show();
this.render();
}
private home(): void {
this.values = {};
this.exploded = 0;
this.show();
this.save();
this.render();
}
private setType(j: Joint, type: JointType): void {
delete this.values[j.id];
const pitch = type === "screw" ? (j.pitch ?? this.threadOn(j.a, j.b) ?? 1.5) : undefined;
// (Limits are in the joint's own measure - degrees or mm: another kind of joint starts without them.)
this.patch(j.id, { type, pitch, min: undefined, max: undefined, ...(type === "fixed" ? { drive: undefined } : {}) });
}
private setValue(j: Joint, v: number): void {
const d = driverOf(this.liveJoints(), j.id);
if (!d || !d.ratio) return;
this.values[d.joint.id] = v / d.ratio;
// (Kept in its limits: what is stored is where it is.)
this.values[d.joint.id] = effective(this.liveJoints(), this.values)[d.joint.id] ?? 0;
this.show();
}
// ------------------------------------------------------------------ dragging a part
dragStart(from: ToolPointer): boolean {
if (this.mode === "add" || this.exploded > 0) return false;
const h = this.faceAt(from);
if (!h) return false;
const joints = this.liveJoints();
const t = tree(joints, this.bodies, this.app.store.doc.ground);
// The joint that lets it move: its own, or - held fast to another part - that part's.
let body = h.body;
let up = t.up.get(body);
while (up && up.joint.type === "fixed") (body = up.parent), (up = t.up.get(body));
if (!up) {
if (joints.some((j) => j.a === h.body || j.b === h.body)) this.app.ui.toast("That part stands still: drag the part that moves against it");
return false;
}
const d = driverOf(joints, up.joint.id);
if (!d || !d.ratio) return false;
const poses = this.poses();
const m = poses.get(up.parent) ?? null;
const origin = m ? apply(m, up.joint.origin) : up.joint.origin;
const axis = norm(m ? turn(m, up.joint.axis) : up.joint.axis);
// Stop on contact: what is in each other already is left to be (parts modelled into each other, or touching).
const stood = stopOnContact ? this.standing(poses) : new Map<string, Mat4>();
const inEachOther = stopOnContact ? this.clashes(stood) : new Set<string>();
this.dragging = { from, joint: up.joint, driver: d.joint, ratio: d.ratio, sign: up.joint.b === body ? 1 : -1, v0: effective(joints, this.values)[up.joint.id] ?? 0, grab: h.point, origin, axis, turned: 0, last: null, inEachOther, stood, free: this.values[d.joint.id] ?? 0 };
return true;
}
drag(p: ToolPointer): void {
const g = this.dragging;
if (!g) return;
let moved: number;
if (g.joint.type === "slide") moved = axisDrag(this.app.view, g.grab, g.axis, g.from, p);
else {
// Round the line. Seen along it (enough): by where the pointer is on the plane across it, turn by turn.
// Seen from the side: by how far the pointer went the way the grabbed point goes round.
const centre = add(g.origin, scale(g.axis, dot(sub(g.grab, g.origin), g.axis)));
const arm = sub(g.grab, centre);
const ray = this.app.view.pointerRay(p.x, p.y);
const facing = dot(ray.d, g.axis);
if (Math.abs(facing) > 0.3 && len(arm) > 1e-6) {
const s = dot(sub(centre, ray.o), g.axis) / facing;
const at = sub(add(ray.o, scale(ray.d, s)), centre);
const prev = g.last ?? arm;
g.turned += (Math.atan2(dot(cross(prev, at), g.axis), dot(prev, at)) * 180) / Math.PI;
g.last = at;
moved = g.turned;
} else {
const r = len(arm) || 1;
moved = (axisDrag(this.app.view, g.grab, norm(cross(g.axis, arm)), g.from, p) / r) * (180 / Math.PI);
}
}
const want = g.v0 + g.sign * moved;
this.values[g.driver.id] = want / g.ratio;
// (Kept in the limits: what is stored is what it is, so the next drag starts from there.)
let v = effective(this.liveJoints(), this.values);
this.values[g.driver.id] = v[g.driver.id];
// Stop on contact: a move that runs a part into another goes only as far as it can - found by halving, between
// the last value nothing was run into at and the one asked for.
let stopped = false;
if (stopOnContact) {
const hits = (value: number): boolean => {
this.values[g.driver.id] = value;
return this.clashes(this.standing(this.poses()), g.stood, g.inEachOther).size > 0;
};
const asked = this.values[g.driver.id];
// (The way there is gone in steps - a millimetre, or three degrees, of the dragged joint - so a part is not
// carried through another and out of its far side by one long move.)
const pace = (g.joint.type === "slide" ? 1 : 3) / Math.abs(g.ratio || 1);
const steps = Math.min(40, Math.max(1, Math.ceil(Math.abs(asked - g.free) / pace)));
let lo = g.free;
let hi: number | null = null;
for (let i = 1; i <= steps; i++) {
const at = g.free + ((asked - g.free) * i) / steps;
if (hits(at)) {
hi = at;
break;
}
lo = at;
}
if (hi !== null) {
stopped = true;
let top: number = hi;
for (let i = 0; i < 7; i++) {
const mid: number = (lo + top) / 2;
if (hits(mid)) top = mid;
else lo = mid;
}
}
this.values[g.driver.id] = lo;
g.free = this.values[g.driver.id];
v = effective(this.liveJoints(), this.values);
}
this.show();
const now = v[g.joint.id] ?? 0;
this.app.ui.setLabel(p.x, p.y, `${g.joint.type === "slide" ? fmtLen(now) : `${+now.toFixed(1)}°`}${stopped ? " · contact" : ""}`);
}
up(): void {
if (!this.dragging) return;
this.dragging = null;
this.app.ui.setLabel(0, 0, null);
this.save();
this.render();
}
breakOff(): void {
const g = this.dragging;
if (!g) return;
this.values[g.driver.id] = (g.v0 * 1) / g.ratio;
this.dragging = null;
this.app.ui.setLabel(0, 0, null);
this.show();
}
// ------------------------------------------------------------------ the line at the bottom
private render(): void {
const ui = this.app.ui;
const joints = this.joints;
if (this.mode === "add") {
ui.setHint(this.first ? "Now tap a face of the part it moves against." : "Tap a face of the first part. A round face or a flat one gives the joint its line.");
ui.showPanel({
title: "New joint",
items: [
{ type: "slot", label: "First part", value: this.first ? this.nameOf(this.first.body) : "", active: !this.first, filled: !!this.first, onClick: () => ((this.first = null), this.app.setSelection([]), this.render()) },
{ type: "slot", label: "Second part", value: "", active: !!this.first, filled: false, onClick: () => undefined },
],
onCancel: () => this.toList(),
});
return;
}
const j0 = this.mode === "edit" ? joints.find((x) => x.id === this.editing) : undefined;
if (j0) {
const j = j0;
const turns = j.type === "hinge" || j.type === "screw";
const now = effective(this.liveJoints(), this.values)[j.id] ?? 0;
const limited = j.min !== undefined || j.max !== undefined;
const others = joints.filter((x) => x.id !== j.id && x.type !== "fixed" && x.drive?.joint !== j.id);
const items: PanelItem[] = [{ type: "choice", label: "Type", list: true, options: (Object.keys(JOINT_NAMES) as JointType[]).map((id) => ({ id, label: JOINT_NAMES[id] })), value: j.type, onChange: (id) => this.setType(j, id as JointType) }];
if (j.type !== "fixed") {
items.push({ type: "number", label: turns ? "Angle" : "Distance", value: now, kind: turns ? "angle" : "length", onInput: (v) => (this.setValue(j, v), this.save(), this.render()) });
if (j.type === "screw") items.push({ type: "number", label: "Pitch", value: j.pitch ?? 1.5, kind: "length", min: 0.01, onInput: (v) => v > 0 && this.patch(j.id, { pitch: v }) });
items.push({ type: "toggle", label: "Limits", value: limited, onChange: (on) => this.patch(j.id, on ? { min: turns ? 0 : 0, max: turns ? 90 : 20 } : { min: undefined, max: undefined }) });
if (limited) {
items.push({ type: "number", label: "From", value: j.min ?? 0, kind: turns ? "angle" : "length", onInput: (v) => this.patch(j.id, { min: Math.min(v, j.max ?? v) }) });
items.push({ type: "number", label: "To", value: j.max ?? 0, kind: turns ? "angle" : "length", onInput: (v) => this.patch(j.id, { max: Math.max(v, j.min ?? v) }) });
}
items.push({ type: "button", label: "Flip", icon: "flip", onClick: () => this.patch(j.id, { axis: scale(j.axis, -1) }) });
if (others.length) {
items.push({ type: "choice", label: "Follows", list: true, options: [{ id: "", label: "Nothing" }, ...others.map((x) => ({ id: x.id, label: x.name }))], value: j.drive?.joint ?? "", onChange: (id) => this.patch(j.id, { drive: id ? { joint: id, ratio: j.drive?.ratio ?? 1 } : undefined }) });
if (j.drive) items.push({ type: "number", label: "Ratio", value: j.drive.ratio, kind: "number", onInput: (v) => v && this.patch(j.id, { drive: { joint: j.drive!.joint, ratio: v } }) });
}
}
ui.setHint(j.type === "fixed" ? `${this.nameOf(j.a)} and ${this.nameOf(j.b)} are held together. Change its Type to let them move.` : `Drag ${this.nameOf(j.b)} to move it. Home puts every part back where it was modelled.`);
ui.showPanel({
title: `${j.name}: ${this.nameOf(j.a)} and ${this.nameOf(j.b)}`,
beta: true,
items,
actions: [
{
id: "delete",
label: "Delete joint",
icon: "trash",
run: () => {
this.change((js) => {
const i = js.findIndex((x) => x.id === j.id);
if (i >= 0) js.splice(i, 1);
for (const x of js) if (x.drive?.joint === j.id) delete x.drive;
});
delete this.values[j.id];
this.toList();
},
},
],
onDone: () => this.toList(),
});
return;
}
this.mode = "list";
const held = [...new Set(joints.flatMap((x) => [x.a, x.b]))].filter((b) => this.app.view.body(b));
const ground = this.app.store.doc.ground && held.includes(this.app.store.doc.ground) ? this.app.store.doc.ground : (tree(joints, this.bodies).roots[0] ?? "");
const moved = this.exploded > 0 || Object.values(this.values).some((v) => Math.abs(v) > 1e-9);
const items: PanelItem[] = [
{ type: "button", label: "Add joint", icon: "assembly", primary: !joints.length, onClick: () => (this.home(), (this.mode = "add"), (this.first = null), this.render()) },
{ type: "chips", label: "Joints", empty: "None yet", chips: joints.map((x) => ({ label: `${x.name} · ${JOINT_NAMES[x.type]}`, title: `${this.nameOf(x.a)} and ${this.nameOf(x.b)}`, onClick: () => this.open(x.id) })) },
];
if (joints.length) {
items.push({ type: "slider", label: "Explode", value: Math.round(this.exploded * 100), min: 0, max: 100, step: 1, show: (v) => `${v}%`, onInput: (v) => ((this.exploded = v / 100), this.show()) });
if (held.length > 1) items.push({ type: "choice", label: "Stands still", list: true, options: held.map((b) => ({ id: b, label: this.nameOf(b) })), value: ground, onChange: (id) => (this.app.store.commit((d) => void (d.ground = id)), this.show(), this.render()) });
items.push({ type: "toggle", label: "Stop on contact", value: stopOnContact, onChange: (on) => ((stopOnContact = on), this.render()) });
if (moved) items.push({ type: "button", label: "Home", onClick: () => this.home() });
}
ui.setHint(joints.length ? "Drag a part to move it by its joint. Tap a part to change its joint." : "The parts stay where you modelled them. Add a joint to say how two of them move.");
ui.showPanel({ title: "Assemblies", beta: true, items, onDone: () => this.leave() });
}
}
+183
View File
@@ -0,0 +1,183 @@
// Assemblies: do two bodies run into each other where they are shown?
//
// Asked on every move of a drag, of bodies that are only moved (their meshes stay as they are), so each body's
// mesh is put in a tree of boxes once and the question is asked of the trees. Two bodies are in each other when
// a corner of one is inside the other by more than a little: parts that touch, or sit in each other with a hair
// of play (a nut on its thread), are not - their drawn facets cross here and there without the parts doing so.
import type { Vec3 } from "../doc/types";
import { apply, type Mat4 } from "./joints";
/** A rigid move undone (a turn and a shift: the turn's transpose, the shift taken back through it). */
export function inverse(m: Mat4): Mat4 {
const t: Vec3 = [m[12], m[13], m[14]];
return [m[0], m[4], m[8], 0, m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, -(m[0] * t[0] + m[1] * t[1] + m[2] * t[2]), -(m[4] * t[0] + m[5] * t[1] + m[6] * t[2]), -(m[8] * t[0] + m[9] * t[1] + m[10] * t[2]), 1];
}
const LEAF = 6;
// (Not along an axis: a ray along one runs down the edges and corners of boxy parts, where "how many faces
// did it cross" has no clean answer.)
const RAY: Vec3 = [0.8017837257372732, 0.5345224838248488, 0.2672612419124244];
/** A body's mesh, ready to be asked whether a point is inside it. */
export class Solid {
/** The mesh's corners, each once (or one in every few, of a very fine mesh). */
readonly corners: Float32Array;
readonly lo: Vec3 = [Infinity, Infinity, Infinity];
readonly hi: Vec3 = [-Infinity, -Infinity, -Infinity];
/** The tree: each node's box (6 numbers), and either its two children or its run of triangles. */
private boxes: number[] = [];
private kids: number[] = [];
private tris: Uint32Array;
constructor(private P: Float32Array, private I: Uint32Array) {
const n = Math.floor(I.length / 3);
this.tris = new Uint32Array(n);
const mid = new Float32Array(n * 3);
for (let t = 0; t < n; t++) {
this.tris[t] = t;
for (let k = 0; k < 3; k++) mid[t * 3 + k] = (P[I[t * 3] * 3 + k] + P[I[t * 3 + 1] * 3 + k] + P[I[t * 3 + 2] * 3 + k]) / 3;
}
for (let i = 0; i < P.length; i += 3) for (let k = 0; k < 3; k++) (this.lo[k] = Math.min(this.lo[k], P[i + k])), (this.hi[k] = Math.max(this.hi[k], P[i + k]));
if (n) this.build(0, n, mid);
// Corners: one of each place (a mesh has a corner once for every face that meets there).
const seen = new Set<string>();
const out: number[] = [];
const step = Math.max(1, Math.floor(P.length / 3 / 60000));
for (let i = 0; i < P.length; i += 3 * step) {
const key = `${Math.round(P[i] * 1e4)},${Math.round(P[i + 1] * 1e4)},${Math.round(P[i + 2] * 1e4)}`;
if (seen.has(key)) continue;
seen.add(key);
out.push(P[i], P[i + 1], P[i + 2]);
}
this.corners = new Float32Array(out);
}
private build(from: number, to: number, mid: Float32Array): number {
const node = this.kids.length / 2;
this.kids.push(0, 0);
const b = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
const c = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
for (let s = from; s < to; s++) {
const t = this.tris[s];
for (let v = 0; v < 3; v++) {
const i = this.I[t * 3 + v] * 3;
for (let k = 0; k < 3; k++) (b[k] = Math.min(b[k], this.P[i + k])), (b[3 + k] = Math.max(b[3 + k], this.P[i + k]));
}
for (let k = 0; k < 3; k++) (c[k] = Math.min(c[k], mid[t * 3 + k])), (c[3 + k] = Math.max(c[3 + k], mid[t * 3 + k]));
}
this.boxes.push(...b);
const axis = c[3] - c[0] > c[4] - c[1] ? (c[3] - c[0] > c[5] - c[2] ? 0 : 2) : c[4] - c[1] > c[5] - c[2] ? 1 : 2;
const cut = (c[axis] + c[3 + axis]) / 2;
let m = from;
for (let s = from; s < to; s++) {
if (mid[this.tris[s] * 3 + axis] < cut) {
const w = this.tris[s];
this.tris[s] = this.tris[m];
this.tris[m++] = w;
}
}
if (to - from <= LEAF || m === from || m === to) {
// A leaf: its triangles, marked by a minus.
this.kids[node * 2] = -(from + 1);
this.kids[node * 2 + 1] = to - from;
return node;
}
const l = this.build(from, m, mid);
const r = this.build(m, to, mid);
this.kids[node * 2] = l;
this.kids[node * 2 + 1] = r;
return node;
}
/** How many of the mesh's triangles a ray from `p` goes through: odd, the point is inside. */
inside(p: Vec3): boolean {
if (!this.tris.length) return false;
for (let k = 0; k < 3; k++) if (p[k] < this.lo[k] || p[k] > this.hi[k]) return false;
let crossings = 0;
const stack = [0];
const P = this.P;
const I = this.I;
while (stack.length) {
const node = stack.pop()!;
// The ray and the node's box (the ray goes the positive way along all three).
let t0 = 0;
let t1 = Infinity;
for (let k = 0; k < 3; k++) {
const a = (this.boxes[node * 6 + k] - p[k]) / RAY[k];
const b = (this.boxes[node * 6 + 3 + k] - p[k]) / RAY[k];
t0 = Math.max(t0, a);
t1 = Math.min(t1, b);
}
if (t1 < t0) continue;
const a = this.kids[node * 2];
if (a >= 0) {
stack.push(a, this.kids[node * 2 + 1]);
continue;
}
const from = -a - 1;
const count = this.kids[node * 2 + 1];
for (let s = from; s < from + count; s++) {
const t = this.tris[s] * 3;
const i0 = I[t] * 3;
const i1 = I[t + 1] * 3;
const i2 = I[t + 2] * 3;
// Möller-Trumbore.
const e1x = P[i1] - P[i0];
const e1y = P[i1 + 1] - P[i0 + 1];
const e1z = P[i1 + 2] - P[i0 + 2];
const e2x = P[i2] - P[i0];
const e2y = P[i2 + 1] - P[i0 + 1];
const e2z = P[i2 + 2] - P[i0 + 2];
const px = RAY[1] * e2z - RAY[2] * e2y;
const py = RAY[2] * e2x - RAY[0] * e2z;
const pz = RAY[0] * e2y - RAY[1] * e2x;
const det = e1x * px + e1y * py + e1z * pz;
if (Math.abs(det) < 1e-14) continue;
const inv = 1 / det;
const tx = p[0] - P[i0];
const ty = p[1] - P[i0 + 1];
const tz = p[2] - P[i0 + 2];
const u = (tx * px + ty * py + tz * pz) * inv;
if (u < 0 || u > 1) continue;
const qx = ty * e1z - tz * e1y;
const qy = tz * e1x - tx * e1z;
const qz = tx * e1y - ty * e1x;
const v = (RAY[0] * qx + RAY[1] * qy + RAY[2] * qz) * inv;
if (v < 0 || u + v > 1) continue;
if ((e2x * qx + e2y * qy + e2z * qz) * inv > 0) crossings++;
}
}
return (crossings & 1) === 1;
}
/** Inside, and not within `tol` of the surface (as far as six points round it tell). */
deepInside(p: Vec3, tol: number): boolean {
if (!this.inside(p)) return false;
for (let k = 0; k < 3; k++) {
for (const s of [-tol, tol]) {
const q: Vec3 = [p[0], p[1], p[2]];
q[k] += s;
if (!this.inside(q)) return false;
}
}
return true;
}
}
/**
* Does `b`, moved by `bToA` into `a`'s own space, run into `a`: a corner of either more than `tol` inside the
* other. (Both where they were modelled: `bToA` is none.)
*/
export function penetrates(a: Solid, b: Solid, bToA: Mat4, tol: number): boolean {
const one = (into: Solid, of: Solid, m: Mat4): boolean => {
const C = of.corners;
for (let i = 0; i < C.length; i += 3) {
const p = apply(m, [C[i], C[i + 1], C[i + 2]]);
if (p[0] < into.lo[0] || p[1] < into.lo[1] || p[2] < into.lo[2] || p[0] > into.hi[0] || p[1] > into.hi[1] || p[2] > into.hi[2]) continue;
if (into.deepInside(p, tol)) return true;
}
return false;
};
return one(a, b, bToA) || one(b, a, inverse(bToA));
}
+312
View File
@@ -0,0 +1,312 @@
// Assemblies: how the bodies of a project are held together, and where each is when they move.
//
// The bodies are modelled where they belong, so nothing is put in place: a joint only says how two bodies may
// move against each other - not at all (fixed), round an axis (hinge), along it (slide), or both at once as a
// nut on its thread (screw). Where everything was modelled is home: a joint's value is how far it is from
// there (degrees, or mm for a slide), and all of them at 0 is the model as it was built.
//
// Kinematics only: no weight, no forces. A joint can follow another by a ratio (a gear turning its neighbour).
import type { FaceRef, Vec3 } from "../doc/types";
export type JointType = "fixed" | "hinge" | "slide" | "screw";
export interface Joint {
id: string;
name: string;
type: JointType;
/** The two bodies: `b` moves against `a` (which of them stays still is told by what is grounded). */
a: string;
b: string;
/** The joint's line, where the bodies were modelled: a point on it and its direction. */
origin: Vec3;
axis: Vec3;
/** How far it may go (degrees; mm for a slide). Missing: as far as it is dragged. */
min?: number;
max?: number;
/** A screw's: mm along the axis for each full turn. */
pitch?: number;
/** It follows another joint: its value is that one's, times `ratio` (a gear: minus the teeth's ratio). */
drive?: { joint: string; ratio: number };
/** The faces it was picked by, so its line follows them when the model changes. */
refA?: FaceRef;
refB?: FaceRef;
}
/** A 4 x 4 matrix, column by column (as three.js keeps it). */
export type Mat4 = number[];
export const IDENTITY: Mat4 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
export function mul(a: Mat4, b: Mat4): Mat4 {
const o = new Array<number>(16);
for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) o[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
return o;
}
export function translation(v: Vec3): Mat4 {
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, v[0], v[1], v[2], 1];
}
export function apply(m: Mat4, p: Vec3): Vec3 {
return [m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12], m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13], m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14]];
}
/** A direction through a matrix (its turning only). */
export function turn(m: Mat4, d: Vec3): Vec3 {
return [m[0] * d[0] + m[4] * d[1] + m[8] * d[2], m[1] * d[0] + m[5] * d[1] + m[9] * d[2], m[2] * d[0] + m[6] * d[1] + m[10] * d[2]];
}
const unit = (v: Vec3): Vec3 => {
const l = Math.hypot(v[0], v[1], v[2]) || 1;
return [v[0] / l, v[1] / l, v[2] / l];
};
/** A turn of `deg` round the line through `origin` along `axis`, and `along` mm along it. */
export function about(origin: Vec3, axis: Vec3, deg: number, along = 0): Mat4 {
const [x, y, z] = unit(axis);
const t = (deg * Math.PI) / 180;
const c = Math.cos(t);
const s = Math.sin(t);
const k = 1 - c;
// Rodrigues, column by column.
const r = [c + x * x * k, y * x * k + z * s, z * x * k - y * s, x * y * k - z * s, c + y * y * k, z * y * k + x * s, x * z * k + y * s, y * z * k - x * s, c + z * z * k];
const ro: Vec3 = [r[0] * origin[0] + r[3] * origin[1] + r[6] * origin[2], r[1] * origin[0] + r[4] * origin[1] + r[7] * origin[2], r[2] * origin[0] + r[5] * origin[1] + r[8] * origin[2]];
return [r[0], r[1], r[2], 0, r[3], r[4], r[5], 0, r[6], r[7], r[8], 0, origin[0] - ro[0] + x * along, origin[1] - ro[1] + y * along, origin[2] - ro[2] + z * along, 1];
}
/** What a joint does to its `b` at a value: the move from home. */
export function motion(j: Joint, value: number): Mat4 {
if (j.type === "hinge") return about(j.origin, j.axis, value);
if (j.type === "slide") return about(j.origin, j.axis, 0, value);
if (j.type === "screw") return about(j.origin, j.axis, value, ((j.pitch ?? 1) * value) / 360);
return IDENTITY;
}
const clamp = (j: Joint, v: number): number => Math.min(j.max ?? Infinity, Math.max(j.min ?? -Infinity, v));
/** Each joint's value as it is: its own, kept in its limits - or what the joint it follows gives it. */
export function effective(joints: Joint[], values: Record<string, number>): Record<string, number> {
const by = new Map(joints.map((j) => [j.id, j]));
const out: Record<string, number> = {};
const of = (j: Joint, depth: number): number => {
if (j.id in out) return out[j.id];
const d = j.drive && depth < 32 ? by.get(j.drive.joint) : undefined;
const v = j.type === "fixed" ? 0 : d && d.id !== j.id ? of(d, depth + 1) * j.drive!.ratio : clamp(j, values[j.id] ?? 0);
return (out[j.id] = v);
};
for (const j of joints) of(j, 0);
return out;
}
/** The joint whose own value sets this one's (itself, when it follows no other), and by how much. */
export function driverOf(joints: Joint[], id: string): { joint: Joint; ratio: number } | null {
const by = new Map(joints.map((j) => [j.id, j]));
let j = by.get(id);
let ratio = 1;
for (let i = 0; j && i < 32; i++) {
const d = j.drive ? by.get(j.drive.joint) : undefined;
if (!d || d.id === j.id) return { joint: j, ratio };
ratio *= j.drive!.ratio;
j = d;
}
return null;
}
export interface Tree {
/** Each body's joint towards what is grounded, the body on its other side, and how many joints away the ground is. */
up: Map<string, { joint: Joint; parent: string; depth: number }>;
roots: string[];
}
/**
* The bodies as a tree from what stands still: `ground` when it is given and there, else - in each group of
* bodies joined together - the one that comes first in the project. A joint that would close a ring of bodies
* is left out (the ring's other joints carry it).
*/
export function tree(joints: Joint[], bodies: string[], ground?: string): Tree {
const have = new Set(bodies);
const live = joints.filter((j) => have.has(j.a) && have.has(j.b) && j.a !== j.b);
const up: Tree["up"] = new Map();
const seen = new Set<string>();
const roots: string[] = [];
const order = ground && have.has(ground) ? [ground, ...bodies.filter((b) => b !== ground)] : bodies;
for (const root of order) {
if (seen.has(root) || !live.some((j) => j.a === root || j.b === root)) continue;
roots.push(root);
seen.add(root);
const queue = [root];
while (queue.length) {
const p = queue.shift()!;
const depth = (up.get(p)?.depth ?? 0) + 1;
for (const j of live) {
const c = j.a === p ? j.b : j.b === p ? j.a : null;
if (!c || seen.has(c)) continue;
seen.add(c);
up.set(c, { joint: j, parent: p, depth });
queue.push(c);
}
}
}
return { up, roots };
}
export interface Explode {
/** 0: together. 1: each body a body's width from its neighbour. */
factor: number;
/** Each body's middle and how big it is (the radius of a ball round it), where it was modelled. */
centers: Record<string, Vec3>;
sizes: Record<string, number>;
}
/**
* Where every body is: its move from where it was modelled. Bodies no joint holds (and what is grounded) stay.
* Exploded, each body is pushed off its neighbour along their joint's line (a fixed joint: from middle to middle).
*/
export function solve(joints: Joint[], bodies: string[], values: Record<string, number>, ground?: string, explode?: Explode): Map<string, Mat4> {
const t = tree(joints, bodies, ground);
const v = effective(joints, values);
const out = new Map<string, Mat4>();
const push = new Map<string, Vec3>();
for (const r of t.roots) out.set(r, IDENTITY);
// (Parents before children: by how far from the ground they are.)
const order = [...t.up.entries()].sort((p, q) => p[1].depth - q[1].depth);
for (const [body, { joint, parent }] of order) {
const m = motion(joint, joint.b === body ? v[joint.id] : -v[joint.id]);
out.set(body, mul(out.get(parent) ?? IDENTITY, m));
if (!explode || !(explode.factor > 0)) continue;
const cp = explode.centers[parent];
const cc = explode.centers[body];
const between: Vec3 = cp && cc ? [cc[0] - cp[0], cc[1] - cp[1], cc[2] - cp[2]] : [0, 0, 0];
let dir = unit(joint.axis);
const side = dir[0] * between[0] + dir[1] * between[1] + dir[2] * between[2];
if (joint.type === "fixed" && Math.hypot(...between) > 1e-9) dir = unit(between);
else if (side < 0) dir = [-dir[0], -dir[1], -dir[2]];
const far = explode.factor * ((explode.sizes[parent] ?? 0) + (explode.sizes[body] ?? 0));
const base = push.get(parent) ?? [0, 0, 0];
push.set(body, [base[0] + dir[0] * far, base[1] + dir[1] * far, base[2] + dir[2] * far]);
}
for (const [body, p] of push) out.set(body, mul(translation(p), out.get(body)!));
return out;
}
/** What a face gives a joint: a line (a round face's axis; a flat face's normal through its middle), or nothing. */
export interface PickLine {
origin: Vec3;
dir: Vec3;
round: boolean;
/** Found from the face's drawn points (a thread's flank), not known exactly: good to a twentieth of a millimetre. */
rough?: boolean;
}
/**
* The joint two picks make, as they stand: on one line (two round faces on one axis, two flat faces one above the
* other) - a hinge, or a screw when one of the bodies is threaded; two flat faces side by side - a slide along
* the first's normal; anything else - fixed. Its line is the first pick's.
*/
export function propose(a: PickLine | null, b: PickLine | null, pitch?: number): { type: JointType; origin: Vec3; axis: Vec3; pitch?: number } {
// (The joint's line is the first pick's - or the second's, where only that one is known exactly.)
const line = a && b && a.rough && !b.rough ? b : (a ?? b);
if (!line) return { type: "fixed", origin: [0, 0, 0], axis: [0, 0, 1] };
const axis = unit(line.dir);
const base = { origin: line.origin, axis };
if (!a || !b) return { type: "fixed", ...base };
const da = unit(a.dir);
const d = unit(b.dir);
const parallel = Math.abs(da[0] * d[0] + da[1] * d[1] + da[2] * d[2]) > (a.rough || b.rough ? 0.995 : 0.999);
if (!parallel) return { type: "fixed", ...base };
const w: Vec3 = [b.origin[0] - a.origin[0], b.origin[1] - a.origin[1], b.origin[2] - a.origin[2]];
const along = w[0] * axis[0] + w[1] * axis[1] + w[2] * axis[2];
const off = Math.hypot(w[0] - axis[0] * along, w[1] - axis[1] * along, w[2] - axis[2] * along);
const size = Math.max(1, Math.hypot(...w));
// (To a hundredth of a millimetre and a thousandth of how far apart they are: faces are found by their drawn points.)
if (off < 1e-3 * size + (a.rough || b.rough ? 0.15 : 1e-2)) return pitch ? { type: "screw", ...base, pitch } : { type: "hinge", ...base };
return a.round || b.round ? { type: "fixed", ...base } : { type: "slide", ...base };
}
/**
* The line a face is turned round, from its points and the way it faces at each: a thread's flank, a cone, any
* face made by turning a curve round a line (or screwing it along one). Along that line the face's normals all
* lean the same - so it is the direction their leaning varies least in - and seen along it they all point at it.
* Null where there is no such line (a flat face, a ball, a freeform face).
*/
export function turnAxis(points: Vec3[], normals: Vec3[]): { origin: Vec3; dir: Vec3 } | null {
const n = Math.min(points.length, normals.length);
if (n < 6) return null;
const mean: Vec3 = [0, 0, 0];
for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) mean[k] += normals[i][k] / n;
// How the normals spread, as a symmetric 3 x 3; its axes by Jacobi turns.
const a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
for (let i = 0; i < n; i++) for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) a[r][c] += ((normals[i][r] - mean[r]) * (normals[i][c] - mean[c])) / n;
const v = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
for (let sweep = 0; sweep < 24; sweep++) {
for (const [p, q] of [[0, 1], [0, 2], [1, 2]] as const) {
if (Math.abs(a[p][q]) < 1e-15) continue;
const th = (a[q][q] - a[p][p]) / (2 * a[p][q]);
const tt = Math.sign(th || 1) / (Math.abs(th) + Math.sqrt(th * th + 1));
const c = 1 / Math.sqrt(tt * tt + 1);
const s = tt * c;
for (let k = 0; k < 3; k++) {
const akp = a[k][p];
const akq = a[k][q];
a[k][p] = c * akp - s * akq;
a[k][q] = s * akp + c * akq;
}
for (let k = 0; k < 3; k++) {
const apk = a[p][k];
const aqk = a[q][k];
a[p][k] = c * apk - s * aqk;
a[q][k] = s * apk + c * aqk;
}
for (let k = 0; k < 3; k++) {
const vkp = v[k][p];
const vkq = v[k][q];
v[k][p] = c * vkp - s * vkq;
v[k][q] = s * vkp + c * vkq;
}
}
}
const ev = [a[0][0], a[1][1], a[2][2]];
const lo = ev.indexOf(Math.min(...ev));
const hi = Math.max(...ev);
const mid = ev.filter((_, i) => i !== lo).reduce((p, q) => Math.min(p, q));
// Round a line: no spread along it, and a spread both ways across it (a face that only bends one way has none).
if (!(hi > 1e-6) || ev[lo] > 0.02 * hi || mid < 0.05 * hi) return null;
const dir = unit([v[0][lo], v[1][lo], v[2][lo]]);
// Across the line: each normal's part there points along a line through the axis. Where those lines meet.
const x = unit(Math.abs(dir[0]) < 0.9 ? [0, -dir[2], dir[1]] : [-dir[2], 0, dir[0]]);
const y: Vec3 = [dir[1] * x[2] - dir[2] * x[1], dir[2] * x[0] - dir[0] * x[2], dir[0] * x[1] - dir[1] * x[0]];
const d3 = (p: Vec3, q: Vec3) => p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
let m00 = 0;
let m01 = 0;
let m11 = 0;
let b0 = 0;
let b1 = 0;
let used = 0;
for (let i = 0; i < n; i++) {
const nx = d3(normals[i], x);
const ny = d3(normals[i], y);
const l = Math.hypot(nx, ny);
if (l < 0.2) continue;
// (The line through the point along its normal: every point c of it has u.c = u.p, u across the normal.)
const ux = -ny / l;
const uy = nx / l;
const k = ux * d3(points[i], x) + uy * d3(points[i], y);
m00 += ux * ux;
m01 += ux * uy;
m11 += uy * uy;
b0 += ux * k;
b1 += uy * k;
used++;
}
const det = m00 * m11 - m01 * m01;
if (used < 6 || Math.abs(det) < 1e-9 * used * used) return null;
const cx = (b0 * m11 - b1 * m01) / det;
const cy = (m00 * b1 - m01 * b0) / det;
// (A point of the line, level with the face's points.)
let along = 0;
for (let i = 0; i < n; i++) along += d3(points[i], dir) / n;
return { origin: [x[0] * cx + y[0] * cy + dir[0] * along, x[1] * cx + y[1] * cy + dir[1] * along, x[2] * cx + y[2] * cy + dir[2] * along], dir };
}
export const JOINT_NAMES: Record<JointType, string> = { fixed: "Fixed", hinge: "Hinge", slide: "Slide", screw: "Screw" };
+317
View File
@@ -0,0 +1,317 @@
// BIM: each body given a real material (with its technical data), and from
// those the technical sheet (parts list, masses, the materials' data) that
// the drawings are made with. Entered from BIM in the left column.
//
// Tap a body (or its row in the card), then a material: it is that material
// from then on - its colour on the model, its mass in the sheet.
import type { MaterialDef } from "../doc/types";
import type { BodyProps } from "../kernel/protocol";
import { el } from "../ui/ui";
import { caretToEnd, textField } from "../ui/textField";
import { icons } from "../ui/icons";
import type { ToolPointer } from "../view/input";
import { hitToSel, type AppContext, type Sel, type Tool } from "../tools/tool";
import { allMaterials, assignMaterial, fmtMass, fmtVolume, massOf, MATERIAL_CLASSES, materialOf, materialRows } from "./materials";
export { fmtArea, fmtMass, fmtVolume } from "./materials";
import { openSheet } from "./sheet";
import { openDrawing } from "./drawing";
import { AssemblyTool } from "../assembly/assemblyTool";
/** Each body's properties, measured on the solids (kept until the project changes). */
export async function measureBodies(app: AppContext): Promise<Map<string, BodyProps>> {
const props = await app.kernel.properties(app.store.doc.features as never);
// Opened right as a project loads, the model on screen may not be this one
// yet: the parts are listed from it, so wait for it (a while at most).
const t0 = performance.now();
const shown = () => new Set(app.view.bodyList.map((b) => b.id));
while (props.some((p) => !shown().has(p.id)) && performance.now() - t0 < 20000) await new Promise((r) => setTimeout(r, 100));
return new Map(props.map((p) => [p.id, p]));
}
export class BimTool implements Tool {
readonly id = "bim";
private card: HTMLElement | null = null;
/** What the card shows (below its grip, name and X). */
private body: HTMLElement | null = null;
private props = new Map<string, BodyProps>();
/** The project the properties were measured for. */
private measured: unknown = null;
private search = "";
/** The material whose technical data is shown open. */
private details: string | null = null;
constructor(private app: AppContext) {}
private get picked(): string[] {
return [...new Set(this.app.selection.flatMap((s) => ("body" in s ? [s.body] : [])))];
}
enter(): void {
this.app.ui.setTools([
{ id: "exit", label: "Exit BIM", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) },
{ id: "bimMaterials", label: "Materials", icon: "bim", active: true, sub: "a material for each body" },
{ id: "bimSheet", label: "Technical Sheet", icon: "sheet", sub: "parts, masses, data", run: () => openSheet(this.app) },
{ id: "bimDrawings", label: "Drawings", icon: "drawing", sub: "views, dimensions, balloons", run: () => openDrawing(this.app) },
{ id: "bimAssemblies", label: "Assemblies", icon: "assembly", sub: "joints: how the parts move", run: () => this.app.setTool(new AssemblyTool(this.app)) },
]);
this.app.ui.setBottom(this.app.bottomTools());
this.app.ui.setHint("Tap a body, then its material. The material's data gives the body its mass.");
this.card = el("div", "bim-card");
this.body = el("div", "bim-inner");
this.card.append(this.header(), this.body);
document.body.append(this.card);
this.putCard(BimTool.spot());
document.body.classList.add("bim-open");
// Bodies picked before: what the materials go to.
const bodies = this.picked;
this.app.setSelection(bodies.map((body) => ({ kind: "body", body })));
this.render();
void this.measure();
}
exit(): void {
this.card?.remove();
this.card = null;
this.body = null;
document.body.classList.remove("bim-open");
this.app.ui.setHint(null);
this.app.setSelection([]);
this.app.setHover(null);
}
key(e: KeyboardEvent): boolean {
if (e.key === "Escape") {
if (this.app.selection.length) this.app.setSelection([]);
else this.app.setTool(null);
this.render();
return true;
}
return false;
}
/** After a rebuild: bodies may have changed size (their mass with them). */
refresh(): void {
this.render();
void this.measure();
}
private async measure(): Promise<void> {
const doc = this.app.store.doc.features;
if (this.measured === doc) return;
this.measured = doc;
try {
const props = await measureBodies(this.app);
if (this.measured !== doc) return;
this.props = props;
this.render();
} catch {
// Measured again after the next change.
this.measured = null;
}
}
private bodyAt(p: ToolPointer): string | null {
const s = hitToSel(this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false, axes: false, images: false }));
return s && "body" in s ? s.body : null;
}
hover(p: ToolPointer | null): void {
const b = p ? this.bodyAt(p) : null;
this.app.setHover(b ? { kind: "body", body: b } : null);
}
tap(p: ToolPointer): void {
const b = this.bodyAt(p);
if (!b) {
this.app.setSelection([]);
return this.render();
}
// Tap: that body (or another one added to it, with the first still picked: one tap each).
const now = this.picked;
const next: Sel[] = now.includes(b) ? now.filter((x) => x !== b).map((body) => ({ kind: "body", body })) : [...now, b].map((body) => ({ kind: "body", body }));
this.app.setSelection(next);
this.render();
}
private give(m: MaterialDef | null): void {
const bodies = this.picked;
if (!bodies.length) return this.app.ui.toast("Tap a body first (or its row above)");
this.app.store.commit((d) => assignMaterial(d, bodies, m));
this.app.ui.toast(m ? `${bodies.length === 1 ? "It is" : `${bodies.length} bodies are`} ${m.name} now` : "Material taken off");
this.render();
}
// ---- The card's top: a grip to drag it anywhere (it opens there again), its name, X to leave BIM.
private static POS = "sg-bim-card";
private static spot(): { x: number; y: number } | null {
try {
return JSON.parse(localStorage.getItem(BimTool.POS) ?? "{}")?.[document.documentElement.dataset.screen ?? "desktop"] ?? null;
} catch {
return null;
}
}
private header(): HTMLElement {
const head = el("div", "bim-head");
const grip = el("div", "bim-grip");
grip.append(el("span", ""));
const title = el("span", "panel-title", "Materials");
const x = el("button", "bim-close");
x.innerHTML = icons.close;
x.title = "Exit BIM";
x.setAttribute("aria-label", "Exit BIM");
x.addEventListener("click", () => this.app.setTool(null));
head.append(grip, title, x);
let drag: { id: number; dx: number; dy: number } | null = null;
head.addEventListener("pointerdown", (e) => {
if (!this.card || (e.target as HTMLElement).closest(".bim-close")) return;
e.preventDefault();
const r = this.card.getBoundingClientRect();
drag = { id: e.pointerId, dx: e.clientX - r.left, dy: e.clientY - r.top };
head.setPointerCapture(e.pointerId);
});
head.addEventListener("pointermove", (e) => {
if (drag?.id === e.pointerId) this.putCard({ x: e.clientX - drag.dx, y: e.clientY - drag.dy });
});
const end = (e: PointerEvent) => {
if (drag?.id !== e.pointerId || !this.card) return;
drag = null;
try {
const all = JSON.parse(localStorage.getItem(BimTool.POS) ?? "{}") ?? {};
all[document.documentElement.dataset.screen ?? "desktop"] = { x: this.card.offsetLeft, y: this.card.offsetTop };
localStorage.setItem(BimTool.POS, JSON.stringify(all));
} catch {
// private window: not remembered
}
};
head.addEventListener("pointerup", end);
head.addEventListener("pointercancel", end);
return head;
}
/** The card at a spot, kept whole on screen (null: where it opens by default). */
private putCard(at: { x: number; y: number } | null): void {
const c = this.card;
if (!c || !at) return;
c.style.width = `${c.offsetWidth}px`;
c.style.right = "auto";
c.style.bottom = "auto";
c.style.left = `${Math.round(Math.max(4, Math.min(window.innerWidth - c.offsetWidth - 4, at.x)))}px`;
c.style.top = `${Math.round(Math.max(4, Math.min(window.innerHeight - c.offsetHeight - 4, at.y)))}px`;
}
private render(): void {
const card = this.body;
if (!card) return;
const doc = this.app.store.doc;
const keep = card.querySelector<HTMLElement>(".bim-materials")?.scrollTop ?? 0;
card.innerHTML = "";
// ---- The bodies, each with its material and mass.
const bodies = this.app.view.bodyList.filter((b) => !doc.hidden.includes(b.id));
const picked = new Set(this.picked);
const list = el("div", "bim-bodies");
bodies.forEach((b, i) => {
const m = materialOf(doc, b.id);
const p = this.props.get(b.id);
const row = el("button", `bim-body${picked.has(b.id) ? " on" : ""}`);
const dot = el("span", "bim-swatch");
dot.style.background = doc.colors?.[b.id] ?? "#b9bec7";
const text = el("span", "bim-body-text");
text.append(el("span", "bim-body-name", `${i + 1}. ${doc.names?.[b.id] ?? b.name}`), el("span", "bim-sub", m ? m.name : "No material yet"));
const mass = el("span", "bim-mass", m && p ? fmtMass(massOf(m, p.volume)) : p ? fmtVolume(p.volume) : "");
row.append(dot, text, mass);
row.addEventListener("click", () => {
this.app.setSelection([{ kind: "body", body: b.id }]);
this.render();
});
list.append(row);
});
if (!bodies.length) list.append(el("div", "bim-sub", "No bodies yet: make one, then give it a material."));
card.append(list);
// ---- What's picked, and what it weighs.
const sel = this.picked;
const now = sel.map((id) => materialOf(doc, id));
const same = now.every((m) => m?.id === now[0]?.id) ? now[0] : undefined;
const info = el("div", "bim-picked");
if (!sel.length) info.append(el("span", "bim-sub", "Tap a body, or its row, to give it a material."));
else {
const kg = sel.reduce((s, id) => {
const m = materialOf(doc, id);
const p = this.props.get(id);
return m && p ? s + massOf(m, p.volume) : s;
}, 0);
const known = sel.every((id) => materialOf(doc, id) && this.props.get(id));
info.append(el("span", "", `${sel.length === 1 ? "1 body" : `${sel.length} bodies`} picked${known ? ` · ${fmtMass(kg)}` : ""}`));
if (now.some(Boolean)) {
const off = el("button", "text-btn", "Take off material");
off.addEventListener("click", () => this.give(null));
info.append(off);
}
}
card.append(info);
// ---- The library, by class; search to narrow it.
const find = textField("bim-search");
find.placeholder = "Search materials (steel, PLA, oak…)";
find.value = this.search;
find.addEventListener("input", () => {
this.search = find.value;
this.render();
const again = this.card?.querySelector<HTMLElement>(".bim-search");
again?.focus();
if (again) caretToEnd(again);
});
card.append(find);
const box = el("div", "bim-materials");
const q = this.search.trim().toLowerCase();
const all = allMaterials(doc).filter((m) => !q || `${m.name} ${m.category} ${m.standard ?? ""}`.toLowerCase().includes(q));
const classes = [...MATERIAL_CLASSES, ...new Set(all.map((m) => m.category).filter((c) => !(MATERIAL_CLASSES as readonly string[]).includes(c)))];
for (const c of classes) {
const ms = all.filter((m) => m.category === c);
if (!ms.length) continue;
box.append(el("div", "bim-class", c));
for (const m of ms) {
const row = el("div", `bim-material${same?.id === m.id ? " on" : ""}`);
const pick = el("button", "bim-material-pick");
const sw = el("span", "bim-swatch");
sw.style.background = m.color;
const text = el("span", "bim-body-text");
text.append(el("span", "bim-body-name", m.name), el("span", "bim-sub", `${m.density} kg/m³${m.standard ? ` · ${m.standard}` : ""}`));
pick.append(sw, text);
pick.addEventListener("click", () => this.give(m));
const more = el("button", `bim-info${this.details === m.id ? " on" : ""}`, "i");
more.title = "Technical data";
more.addEventListener("click", () => {
this.details = this.details === m.id ? null : m.id;
this.render();
});
row.append(pick, more);
box.append(row);
if (this.details === m.id) box.append(dataTable(m));
}
}
if (!all.length) box.append(el("div", "bim-sub", "No material by that name."));
card.append(box);
box.scrollTop = keep;
}
}
/** A material's technical data, by group (identity, physical, thermal). */
export function dataTable(m: MaterialDef): HTMLElement {
const t = el("div", "bim-data");
for (const g of materialRows(m)) {
t.append(el("div", "bim-data-group", g.group));
for (const [k, v] of g.rows) {
const r = el("div", "bim-data-row");
r.append(el("span", "", k), el("span", "", v));
t.append(r);
}
}
return t;
}
+2116
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+215
View File
@@ -0,0 +1,215 @@
// Real materials for bodies (BIM). Like a material in the big BIM tools,
// each one carries more than a look: who it is (identity: name, class, the
// standard its grade comes from), how it shows (a colour, see-through for
// glass), and its technical data - physical (density, stiffness, strength)
// and thermal (conductivity, specific heat, expansion). A body's mass, the
// technical sheet and the drawings' parts list are worked out from them.
//
// Values: strengths are the minimums the named standard gives the grade,
// where it has one; the rest are typical values for the material. Thermal
// values for building materials are the ISO 10456 design values. A supplier's
// own data sheet comes first wherever it differs. A ductile metal's
// compressive strength is its yield; wood's are along the grain; an
// insulation's compressive strength is the stress that squeezes it by 10 %.
import type { MaterialDef, ProjectDoc } from "../doc/types";
import { trim, UNIT_LABEL, UNIT_MM, units } from "../units";
export const MATERIAL_CLASSES = ["Metal", "Plastic", "Composite", "Concrete & masonry", "Wood", "Glass & stone", "Ceramic & other", "Insulation & boards"] as const;
export const MATERIALS: MaterialDef[] = [
// ---- Metals
{ id: "steel-s235", name: "Structural steel S235JR", category: "Metal", standard: "EN 10025-2", color: "#8f959c", density: 7850, youngs: 210, poisson: 0.3, yield: 235, tensile: 360, compressive: 235, elongation: 26, expansion: 12, conductivity: 53, specificHeat: 440, melting: 1500 },
{ id: "steel-s355", name: "Structural steel S355J2", category: "Metal", standard: "EN 10025-2", color: "#888e96", density: 7850, youngs: 210, poisson: 0.3, yield: 355, tensile: 470, compressive: 355, elongation: 22, expansion: 12, conductivity: 53, specificHeat: 440, melting: 1500 },
{ id: "ss-304", name: "Stainless steel 1.4301 (304)", category: "Metal", standard: "EN 10088-2", color: "#b8bec5", density: 7900, youngs: 200, poisson: 0.3, yield: 210, tensile: 520, compressive: 210, elongation: 45, expansion: 16, conductivity: 15, specificHeat: 500, melting: 1450 },
{ id: "ss-316", name: "Stainless steel 1.4401 (316)", category: "Metal", standard: "EN 10088-2", color: "#b3b9c0", density: 8000, youngs: 200, poisson: 0.3, yield: 220, tensile: 520, compressive: 220, elongation: 40, expansion: 16, conductivity: 15, specificHeat: 500, melting: 1400 },
{ id: "al-6061", name: "Aluminium EN AW-6061-T6", category: "Metal", standard: "EN 755-2", color: "#c9ced4", density: 2700, youngs: 70, poisson: 0.3, yield: 240, tensile: 260, compressive: 240, elongation: 10, expansion: 23, conductivity: 167, specificHeat: 896, melting: 650 },
{ id: "al-6082", name: "Aluminium EN AW-6082-T6", category: "Metal", standard: "EN 1999-1-1", color: "#c4c9cf", density: 2700, youngs: 70, poisson: 0.3, yield: 260, tensile: 310, compressive: 260, elongation: 10, expansion: 23, conductivity: 170, specificHeat: 900, melting: 650 },
{ id: "cast-iron", name: "Grey cast iron EN-GJL-250", category: "Metal", standard: "EN 1561", color: "#5d6066", density: 7200, youngs: 110, poisson: 0.26, tensile: 250, compressive: 840, elongation: 0.5, expansion: 11, conductivity: 48, specificHeat: 460, melting: 1200 },
{ id: "brass", name: "Brass CW614N (CuZn39Pb3)", category: "Metal", standard: "EN 12164", color: "#c9a64e", density: 8470, youngs: 96, poisson: 0.34, yield: 250, tensile: 430, compressive: 250, elongation: 15, expansion: 21, conductivity: 113, specificHeat: 377, melting: 900 },
{ id: "copper", name: "Copper Cu-ETP (CW004A)", category: "Metal", standard: "EN 13601", color: "#b87333", density: 8930, youngs: 117, poisson: 0.34, yield: 70, tensile: 200, compressive: 70, elongation: 40, expansion: 17, conductivity: 390, specificHeat: 385, melting: 1083 },
{ id: "ti-5", name: "Titanium Grade 5 (Ti-6Al-4V)", category: "Metal", standard: "ASTM B348", color: "#8c8e91", density: 4430, youngs: 114, poisson: 0.34, yield: 828, tensile: 895, compressive: 970, elongation: 10, expansion: 8.6, conductivity: 6.7, specificHeat: 526, melting: 1660 },
{ id: "steel-c45", name: "Carbon steel C45 (1045)", category: "Metal", standard: "EN 10083-2", color: "#868c93", density: 7850, youngs: 210, poisson: 0.29, yield: 340, tensile: 620, compressive: 340, elongation: 14, expansion: 11.5, conductivity: 50, specificHeat: 486, melting: 1500 },
{ id: "steel-42crmo4", name: "Alloy steel 42CrMo4 (4140), quenched & tempered", category: "Metal", standard: "EN 10083-3", color: "#7f858c", density: 7850, youngs: 210, poisson: 0.29, yield: 650, tensile: 900, compressive: 650, elongation: 12, expansion: 12.3, conductivity: 42.6, specificHeat: 473, melting: 1450 },
{ id: "tool-d2", name: "Tool steel 1.2379 (D2)", category: "Metal", standard: "ISO 4957", note: "Hardened, 58-62 HRC", color: "#73797f", density: 7700, youngs: 210, poisson: 0.3, compressive: 2200, elongation: 1, expansion: 10.5, conductivity: 20, specificHeat: 460, melting: 1420 },
{ id: "ss-303", name: "Stainless steel 1.4305 (303)", category: "Metal", standard: "EN 10088-3", color: "#bac0c7", density: 7900, youngs: 193, poisson: 0.29, yield: 190, tensile: 500, compressive: 190, elongation: 35, expansion: 17.3, conductivity: 16.2, specificHeat: 500, melting: 1420 },
{ id: "ss-17-4", name: "Stainless steel 1.4542 (17-4 PH), H900", category: "Metal", standard: "EN 10088-3", color: "#a9afb6", density: 7780, youngs: 197, poisson: 0.27, yield: 1170, tensile: 1310, compressive: 1170, elongation: 10, expansion: 10.8, conductivity: 18.3, specificHeat: 460, melting: 1440 },
{ id: "ductile-iron", name: "Ductile iron EN-GJS-400-15", category: "Metal", standard: "EN 1563", color: "#63666c", density: 7100, youngs: 169, poisson: 0.275, yield: 250, tensile: 400, compressive: 700, elongation: 15, expansion: 12.5, conductivity: 36, specificHeat: 515, melting: 1150 },
{ id: "al-5052", name: "Aluminium EN AW-5052-H32", category: "Metal", standard: "EN 485-2", color: "#ccd1d7", density: 2680, youngs: 70, poisson: 0.33, yield: 193, tensile: 228, compressive: 193, elongation: 12, expansion: 23.8, conductivity: 138, specificHeat: 880, melting: 650 },
{ id: "al-7075", name: "Aluminium EN AW-7075-T6", category: "Metal", standard: "EN 755-2", color: "#c2c7cd", density: 2810, youngs: 71.7, poisson: 0.33, yield: 503, tensile: 572, compressive: 503, elongation: 11, expansion: 23.6, conductivity: 130, specificHeat: 960, melting: 635 },
{ id: "al-2024", name: "Aluminium EN AW-2024-T3", category: "Metal", standard: "EN 485-2", color: "#c0c5cb", density: 2780, youngs: 73.1, poisson: 0.33, yield: 345, tensile: 483, compressive: 345, elongation: 18, expansion: 23.2, conductivity: 121, specificHeat: 875, melting: 640 },
{ id: "al-cast", name: "Cast aluminium EN AC-46500 (A380)", category: "Metal", standard: "EN 1706", color: "#b7bcc2", density: 2760, youngs: 71, poisson: 0.33, yield: 160, tensile: 324, compressive: 160, elongation: 3.5, expansion: 21.8, conductivity: 96, specificHeat: 963, melting: 595 },
{ id: "bronze", name: "Phosphor bronze CuSn8 (CW453K)", category: "Metal", standard: "EN 1652", color: "#b0884a", density: 8800, youngs: 115, poisson: 0.34, yield: 260, tensile: 390, compressive: 260, elongation: 45, expansion: 17, conductivity: 67, specificHeat: 380, melting: 1000 },
{ id: "ti-2", name: "Titanium Grade 2 (commercially pure)", category: "Metal", standard: "ASTM B348", color: "#96989b", density: 4510, youngs: 105, poisson: 0.37, yield: 275, tensile: 345, compressive: 275, elongation: 20, expansion: 8.6, conductivity: 16.4, specificHeat: 523, melting: 1665 },
{ id: "mg-az31", name: "Magnesium AZ31B", category: "Metal", standard: "ASTM B90", color: "#a7aaa8", density: 1770, youngs: 45, poisson: 0.35, yield: 200, tensile: 260, compressive: 97, elongation: 15, expansion: 26, conductivity: 96, specificHeat: 1000, melting: 630 },
{ id: "zamak3", name: "Zinc die-cast Zamak 3 (ZP3)", category: "Metal", standard: "EN 12844", color: "#a3a7ad", density: 6600, youngs: 96, poisson: 0.27, yield: 208, tensile: 283, compressive: 414, elongation: 10, expansion: 27.4, conductivity: 113, specificHeat: 419, melting: 387 },
{ id: "inconel-718", name: "Nickel alloy 718", category: "Metal", standard: "ASTM B637", color: "#9a9c98", density: 8190, youngs: 200, poisson: 0.29, yield: 1035, tensile: 1240, compressive: 1035, elongation: 12, expansion: 13, conductivity: 11.4, specificHeat: 435, melting: 1336 },
{ id: "lead", name: "Lead", category: "Metal", color: "#6e7279", density: 11340, youngs: 16, poisson: 0.44, yield: 5, tensile: 18, compressive: 5, elongation: 50, expansion: 29, conductivity: 35, specificHeat: 128, melting: 327 },
{ id: "tungsten", name: "Tungsten", category: "Metal", color: "#7d7f82", density: 19300, youngs: 411, poisson: 0.28, yield: 750, tensile: 980, compressive: 750, elongation: 2, expansion: 4.5, conductivity: 173, specificHeat: 134, melting: 3422 },
{ id: "gold", name: "Gold (fine)", category: "Metal", color: "#d4af37", density: 19300, youngs: 79, poisson: 0.42, yield: 25, tensile: 120, compressive: 25, elongation: 40, expansion: 14.2, conductivity: 318, specificHeat: 129, melting: 1064 },
{ id: "silver", name: "Silver (fine)", category: "Metal", color: "#c9cbcd", density: 10490, youngs: 83, poisson: 0.37, yield: 55, tensile: 140, compressive: 55, elongation: 45, expansion: 18.9, conductivity: 429, specificHeat: 235, melting: 962 },
// ---- Plastics (typical values; a printed part is weaker than a moulded one)
{ id: "pla", name: "PLA", category: "Plastic", color: "#e9e4d8", density: 1240, youngs: 3.5, poisson: 0.36, yield: 50, tensile: 50, compressive: 80, bending: 80, elongation: 6, expansion: 68, conductivity: 0.13, specificHeat: 1800, melting: 160, maxTemp: 50 },
{ id: "petg", name: "PETG", category: "Plastic", color: "#cfe3e8", opacity: 0.85, density: 1270, youngs: 2, poisson: 0.38, yield: 50, tensile: 50, compressive: 55, bending: 70, elongation: 80, expansion: 68, conductivity: 0.2, specificHeat: 1200, maxTemp: 70 },
{ id: "abs", name: "ABS", category: "Plastic", color: "#d9d4c7", density: 1050, youngs: 2.3, poisson: 0.35, yield: 40, tensile: 40, compressive: 65, bending: 65, elongation: 20, expansion: 90, conductivity: 0.17, specificHeat: 1400, maxTemp: 80 },
{ id: "pa6", name: "Nylon PA6 (dry)", category: "Plastic", color: "#e8e2d0", density: 1140, youngs: 3, poisson: 0.39, yield: 80, tensile: 80, compressive: 90, bending: 110, elongation: 30, expansion: 80, conductivity: 0.25, specificHeat: 1700, melting: 220, maxTemp: 100 },
{ id: "pc", name: "Polycarbonate (PC)", category: "Plastic", color: "#dfe8ee", opacity: 0.6, density: 1200, youngs: 2.4, poisson: 0.37, yield: 62, tensile: 65, compressive: 80, bending: 93, elongation: 110, expansion: 70, conductivity: 0.2, specificHeat: 1200, maxTemp: 125 },
{ id: "pmma", name: "Acrylic (PMMA)", category: "Plastic", color: "#e3f1f3", opacity: 0.4, density: 1190, youngs: 3.2, poisson: 0.37, tensile: 70, compressive: 110, bending: 110, elongation: 4, expansion: 70, conductivity: 0.19, specificHeat: 1470, maxTemp: 80 },
{ id: "pom", name: "Acetal (POM)", category: "Plastic", color: "#f1efe9", density: 1410, youngs: 2.9, poisson: 0.35, yield: 65, tensile: 65, compressive: 110, bending: 90, elongation: 40, expansion: 110, conductivity: 0.31, specificHeat: 1470, melting: 175, maxTemp: 100 },
{ id: "epdm", name: "Rubber (EPDM)", category: "Plastic", standard: "ISO 10456", color: "#2e2f31", density: 1150, youngs: 0.005, poisson: 0.49, tensile: 10, elongation: 300, expansion: 160, conductivity: 0.25, specificHeat: 1000, maxTemp: 130 },
{ id: "asa", name: "ASA", category: "Plastic", color: "#d6d2c8", density: 1070, youngs: 2, poisson: 0.36, yield: 45, tensile: 45, compressive: 60, bending: 70, elongation: 25, expansion: 95, conductivity: 0.17, specificHeat: 1300, maxTemp: 85 },
{ id: "tpu", name: "TPU (flexible, Shore 95A)", category: "Plastic", color: "#d9dde0", density: 1210, youngs: 0.026, poisson: 0.48, tensile: 35, elongation: 550, expansion: 150, conductivity: 0.2, specificHeat: 1800, maxTemp: 80 },
{ id: "resin-sla", name: "Photopolymer resin (SLA, standard)", category: "Plastic", note: "Typical cured values; each resin's data sheet differs", color: "#c9ccd0", density: 1180, youngs: 2.8, poisson: 0.35, tensile: 60, compressive: 90, bending: 100, elongation: 6, expansion: 80, conductivity: 0.2, specificHeat: 1300, maxTemp: 60 },
{ id: "pa12", name: "Nylon PA12", category: "Plastic", note: "Printed (SLS) parts are lighter: about 950 kg/m³", color: "#ecebe6", density: 1010, youngs: 1.7, poisson: 0.4, yield: 45, tensile: 48, compressive: 60, bending: 60, elongation: 20, expansion: 110, conductivity: 0.23, specificHeat: 1700, melting: 178, maxTemp: 100 },
{ id: "pa66", name: "Nylon PA66 (dry)", category: "Plastic", color: "#ebe5d4", density: 1140, youngs: 3, poisson: 0.39, yield: 85, tensile: 85, compressive: 100, bending: 120, elongation: 25, expansion: 80, conductivity: 0.25, specificHeat: 1700, melting: 260, maxTemp: 110 },
{ id: "hdpe", name: "Polyethylene HDPE", category: "Plastic", color: "#f0efea", density: 950, youngs: 1, poisson: 0.42, yield: 26, tensile: 30, compressive: 25, bending: 35, elongation: 600, expansion: 120, conductivity: 0.48, specificHeat: 1900, melting: 130, maxTemp: 80 },
{ id: "ldpe", name: "Polyethylene LDPE", category: "Plastic", color: "#f2f1ec", opacity: 0.85, density: 920, youngs: 0.25, poisson: 0.45, yield: 10, tensile: 10, compressive: 10, elongation: 500, expansion: 200, conductivity: 0.33, specificHeat: 2300, melting: 110, maxTemp: 60 },
{ id: "pp", name: "Polypropylene (PP)", category: "Plastic", color: "#ece9e0", density: 905, youngs: 1.5, poisson: 0.42, yield: 32, tensile: 33, compressive: 45, bending: 45, elongation: 300, expansion: 100, conductivity: 0.22, specificHeat: 1920, melting: 165, maxTemp: 100 },
{ id: "pet", name: "PET", category: "Plastic", color: "#d8e8ec", opacity: 0.7, density: 1380, youngs: 2.8, poisson: 0.38, yield: 55, tensile: 55, compressive: 80, bending: 90, elongation: 70, expansion: 70, conductivity: 0.24, specificHeat: 1100, melting: 255, maxTemp: 70 },
{ id: "pvc", name: "PVC (rigid)", category: "Plastic", color: "#d5d7d9", density: 1400, youngs: 3, poisson: 0.38, yield: 50, tensile: 50, compressive: 65, bending: 80, elongation: 40, expansion: 70, conductivity: 0.17, specificHeat: 900, maxTemp: 60 },
{ id: "ptfe", name: "PTFE", category: "Plastic", color: "#f4f3ef", density: 2200, youngs: 0.5, poisson: 0.46, yield: 12, tensile: 25, compressive: 12, elongation: 300, expansion: 120, conductivity: 0.25, specificHeat: 1000, melting: 327, maxTemp: 260 },
{ id: "peek", name: "PEEK", category: "Plastic", color: "#c9b48e", density: 1300, youngs: 3.6, poisson: 0.4, yield: 97, tensile: 100, compressive: 118, bending: 170, elongation: 30, expansion: 47, conductivity: 0.25, specificHeat: 1340, melting: 343, maxTemp: 250 },
{ id: "hips", name: "Polystyrene (HIPS)", category: "Plastic", color: "#efeeea", density: 1040, youngs: 2, poisson: 0.35, yield: 20, tensile: 26, compressive: 40, bending: 45, elongation: 40, expansion: 80, conductivity: 0.17, specificHeat: 1300, maxTemp: 75 },
{ id: "epoxy", name: "Epoxy resin (cast)", category: "Plastic", color: "#d9c78f", opacity: 0.7, density: 1200, youngs: 3, poisson: 0.35, tensile: 60, compressive: 110, bending: 100, elongation: 4, expansion: 60, conductivity: 0.2, specificHeat: 1100, maxTemp: 100 },
{ id: "silicone", name: "Silicone rubber", category: "Plastic", color: "#d8d4cc", density: 1150, youngs: 0.005, poisson: 0.49, tensile: 7, elongation: 400, expansion: 250, conductivity: 0.2, specificHeat: 1300, maxTemp: 200 },
{ id: "natural-rubber", name: "Natural rubber", category: "Plastic", color: "#3a3631", density: 930, youngs: 0.002, poisson: 0.49, tensile: 20, elongation: 600, expansion: 220, conductivity: 0.13, specificHeat: 1900, maxTemp: 70 },
// ---- Composites (in the plane of the layers; across them far less)
{ id: "cfrp", name: "Carbon fibre / epoxy (quasi-isotropic)", category: "Composite", color: "#2b2d30", density: 1600, youngs: 70, poisson: 0.3, tensile: 600, compressive: 500, bending: 700, elongation: 1, expansion: 2, conductivity: 5, specificHeat: 1000, maxTemp: 120 },
{ id: "gfrp", name: "Glass fibre / epoxy (woven)", category: "Composite", color: "#d9d6c4", density: 1900, youngs: 25, poisson: 0.28, tensile: 350, compressive: 300, bending: 400, elongation: 2, expansion: 12, conductivity: 0.35, specificHeat: 900, maxTemp: 120 },
// ---- Concrete and masonry
{ id: "concrete-c25", name: "Concrete C25/30", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#a3a29d", density: 2400, youngs: 31, poisson: 0.2, tensile: 2.6, compressive: 25, bending: 3.6, expansion: 10, conductivity: 2, specificHeat: 1000 },
{ id: "concrete-c30-rc", name: "Reinforced concrete C30/37 (1 % steel)", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#9c9b96", density: 2500, youngs: 33, poisson: 0.2, tensile: 2.9, compressive: 30, bending: 4.1, expansion: 10, conductivity: 2.3, specificHeat: 1000 },
{ id: "brick", name: "Clay brickwork (outer leaf)", category: "Concrete & masonry", color: "#a55a3f", density: 1700, youngs: 5, poisson: 0.2, compressive: 7, bending: 0.4, expansion: 6, conductivity: 0.77, specificHeat: 800 },
{ id: "concrete-c40", name: "Concrete C40/50", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#a6a5a0", density: 2400, youngs: 35, poisson: 0.2, tensile: 3.5, compressive: 40, bending: 4.9, expansion: 10, conductivity: 2, specificHeat: 1000 },
{ id: "aac", name: "Aerated concrete block (AAC)", category: "Concrete & masonry", color: "#e2e0da", density: 500, youngs: 1.75, poisson: 0.2, tensile: 0.5, compressive: 4, bending: 0.8, expansion: 8, conductivity: 0.13, specificHeat: 1000 },
// ---- Wood
{ id: "c24", name: "Softwood C24", category: "Wood", standard: "EN 338", color: "#d8b77e", density: 420, youngs: 11, bending: 24, tensile: 14.5, compressive: 21, expansion: 5, conductivity: 0.12, specificHeat: 1600 },
{ id: "d30", name: "Hardwood D30 (oak)", category: "Wood", standard: "EN 338", color: "#a97a4c", density: 640, youngs: 11, bending: 30, tensile: 18, compressive: 24, expansion: 5, conductivity: 0.18, specificHeat: 1600 },
{ id: "plywood", name: "Plywood", category: "Wood", standard: "ISO 10456", color: "#cfa86f", density: 500, youngs: 8, tensile: 30, compressive: 25, bending: 40, expansion: 7, conductivity: 0.13, specificHeat: 1600 },
{ id: "gl24h", name: "Glulam GL24h", category: "Wood", standard: "EN 14080", color: "#d9b97f", density: 420, youngs: 11.5, bending: 24, tensile: 19.2, compressive: 24, expansion: 5, conductivity: 0.12, specificHeat: 1600 },
// (Species: typical values at 12 % moisture, along the grain.)
{ id: "pine", name: "Pine", category: "Wood", color: "#ddbd85", density: 520, youngs: 12, tensile: 100, compressive: 45, bending: 80, expansion: 5, conductivity: 0.13, specificHeat: 1600 },
{ id: "spruce", name: "Spruce", category: "Wood", color: "#e3c995", density: 450, youngs: 10, tensile: 90, compressive: 40, bending: 70, expansion: 5, conductivity: 0.12, specificHeat: 1600 },
{ id: "beech", name: "Beech", category: "Wood", color: "#d2a77a", density: 720, youngs: 14, tensile: 135, compressive: 55, bending: 110, expansion: 5, conductivity: 0.17, specificHeat: 1600 },
{ id: "birch", name: "Birch", category: "Wood", color: "#e0c69d", density: 670, youngs: 14, tensile: 140, compressive: 55, bending: 115, expansion: 5, conductivity: 0.15, specificHeat: 1600 },
{ id: "maple", name: "Maple (hard)", category: "Wood", color: "#e6cfa6", density: 705, youngs: 12.6, tensile: 110, compressive: 54, bending: 109, expansion: 5, conductivity: 0.16, specificHeat: 1600 },
{ id: "ash", name: "Ash", category: "Wood", color: "#dbc296", density: 680, youngs: 12.3, tensile: 110, compressive: 51, bending: 103, expansion: 5, conductivity: 0.16, specificHeat: 1600 },
{ id: "walnut", name: "Walnut", category: "Wood", color: "#6b4a33", density: 610, youngs: 11.6, tensile: 100, compressive: 52, bending: 101, expansion: 5, conductivity: 0.14, specificHeat: 1600 },
{ id: "cherry", name: "Cherry", category: "Wood", color: "#a0603f", density: 560, youngs: 10.3, tensile: 90, compressive: 49, bending: 85, expansion: 5, conductivity: 0.13, specificHeat: 1600 },
{ id: "mahogany", name: "Mahogany", category: "Wood", color: "#80422e", density: 590, youngs: 10, tensile: 90, compressive: 46, bending: 80, expansion: 5, conductivity: 0.13, specificHeat: 1600 },
{ id: "teak", name: "Teak", category: "Wood", color: "#a87a45", density: 650, youngs: 12.3, tensile: 100, compressive: 55, bending: 97, expansion: 5, conductivity: 0.15, specificHeat: 1600 },
{ id: "balsa", name: "Balsa", category: "Wood", color: "#ead9b4", density: 160, youngs: 3.7, tensile: 20, compressive: 12, bending: 20, expansion: 5, conductivity: 0.05, specificHeat: 1600 },
{ id: "bamboo", name: "Bamboo", category: "Wood", color: "#d9c28a", density: 700, youngs: 17, tensile: 150, compressive: 60, bending: 140, expansion: 4, conductivity: 0.17, specificHeat: 1600 },
{ id: "mdf", name: "MDF", category: "Wood", color: "#b99a74", density: 750, youngs: 3.5, bending: 30, expansion: 8, conductivity: 0.14, specificHeat: 1700 },
{ id: "chipboard", name: "Particle board (chipboard)", category: "Wood", standard: "ISO 10456", color: "#c8a878", density: 600, youngs: 2.5, bending: 13, expansion: 10, conductivity: 0.14, specificHeat: 1700 },
{ id: "osb", name: "OSB", category: "Wood", standard: "ISO 10456", color: "#c69e62", density: 650, youngs: 4.9, bending: 20, expansion: 8, conductivity: 0.13, specificHeat: 1700 },
// ---- Glass and stone
{ id: "glass", name: "Float glass (soda-lime)", category: "Glass & stone", standard: "EN 572-1", color: "#bfdde0", opacity: 0.3, density: 2500, youngs: 70, poisson: 0.2, compressive: 1000, bending: 45, expansion: 9, conductivity: 1, specificHeat: 720, maxTemp: 200 },
{ id: "granite", name: "Granite", category: "Glass & stone", standard: "ISO 10456", color: "#8b8580", density: 2700, youngs: 50, poisson: 0.25, tensile: 10, compressive: 150, bending: 15, expansion: 8, conductivity: 2.8, specificHeat: 1000 },
{ id: "glass-tempered", name: "Toughened glass", category: "Glass & stone", standard: "EN 12150-1", color: "#bcdade", opacity: 0.3, density: 2500, youngs: 70, poisson: 0.2, compressive: 1000, bending: 120, expansion: 9, conductivity: 1, specificHeat: 720, maxTemp: 250 },
{ id: "borosilicate", name: "Borosilicate glass", category: "Glass & stone", color: "#cfe6e8", opacity: 0.3, density: 2230, youngs: 64, poisson: 0.2, compressive: 1000, bending: 45, expansion: 3.3, conductivity: 1.14, specificHeat: 830, maxTemp: 450 },
{ id: "marble", name: "Marble", category: "Glass & stone", standard: "ISO 10456", color: "#e7e4de", density: 2800, youngs: 50, poisson: 0.27, tensile: 8, compressive: 100, bending: 12, expansion: 7, conductivity: 3.5, specificHeat: 1000 },
{ id: "limestone", name: "Limestone (hard)", category: "Glass & stone", standard: "ISO 10456", color: "#d8cfb8", density: 2200, youngs: 40, poisson: 0.25, tensile: 6, compressive: 80, bending: 10, expansion: 6, conductivity: 1.7, specificHeat: 1000 },
{ id: "sandstone", name: "Sandstone", category: "Glass & stone", standard: "ISO 10456", color: "#cdb48a", density: 2600, youngs: 20, poisson: 0.25, tensile: 4, compressive: 60, bending: 7, expansion: 11, conductivity: 2.3, specificHeat: 1000 },
{ id: "slate", name: "Slate", category: "Glass & stone", standard: "ISO 10456", color: "#4f5559", density: 2400, youngs: 80, poisson: 0.25, tensile: 20, compressive: 140, bending: 50, expansion: 9, conductivity: 2.2, specificHeat: 1000 },
// ---- Ceramics and the rest
{ id: "alumina", name: "Alumina ceramic (99.5 %)", category: "Ceramic & other", color: "#f1efe8", density: 3890, youngs: 370, poisson: 0.22, tensile: 260, compressive: 2600, bending: 379, expansion: 8.1, conductivity: 30, specificHeat: 880, melting: 2072, maxTemp: 1650 },
{ id: "porcelain", name: "Porcelain", category: "Ceramic & other", color: "#f3f2ee", density: 2400, youngs: 70, poisson: 0.17, compressive: 500, bending: 70, expansion: 6, conductivity: 1.5, specificHeat: 1085, maxTemp: 1000 },
{ id: "cardboard", name: "Cardboard", category: "Ceramic & other", color: "#b8946a", density: 700, youngs: 3, tensile: 20, conductivity: 0.07, specificHeat: 1400, maxTemp: 150 },
{ id: "leather", name: "Leather", category: "Ceramic & other", color: "#8a5a3b", density: 860, youngs: 0.1, tensile: 20, elongation: 50, conductivity: 0.16, specificHeat: 1500, maxTemp: 100 },
// ---- Insulation and boards
{ id: "plasterboard", name: "Gypsum plasterboard", category: "Insulation & boards", standard: "ISO 10456", color: "#ece9e2", density: 900, youngs: 2, compressive: 5, bending: 5, expansion: 16, conductivity: 0.25, specificHeat: 1000, maxTemp: 50 },
{ id: "mineral-wool", name: "Mineral wool", category: "Insulation & boards", color: "#d8c27a", density: 30, compressive: 0.01, conductivity: 0.035, specificHeat: 1030, maxTemp: 700 },
{ id: "eps", name: "Expanded polystyrene (EPS)", category: "Insulation & boards", color: "#f3f3f0", density: 20, youngs: 0.004, compressive: 0.1, bending: 0.15, expansion: 60, conductivity: 0.035, specificHeat: 1450, maxTemp: 80 },
{ id: "xps", name: "Extruded polystyrene (XPS)", category: "Insulation & boards", color: "#9fc3e0", density: 35, youngs: 0.015, compressive: 0.3, bending: 0.4, expansion: 70, conductivity: 0.034, specificHeat: 1450, maxTemp: 75 },
{ id: "pir", name: "PIR foam board", category: "Insulation & boards", color: "#e6d9a8", density: 30, youngs: 0.005, compressive: 0.12, expansion: 60, conductivity: 0.022, specificHeat: 1400, maxTemp: 100 },
{ id: "glass-wool", name: "Glass wool", category: "Insulation & boards", color: "#e7d38a", density: 20, conductivity: 0.035, specificHeat: 1030, maxTemp: 250 },
{ id: "wood-fibre", name: "Wood fibre insulation", category: "Insulation & boards", color: "#b8925e", density: 160, compressive: 0.1, conductivity: 0.04, specificHeat: 2100, maxTemp: 100 },
{ id: "cork", name: "Cork board", category: "Insulation & boards", standard: "ISO 10456", color: "#a87b52", density: 120, youngs: 0.02, compressive: 0.1, conductivity: 0.04, specificHeat: 1560, maxTemp: 110 },
];
/** Every material the project can use: the library, and its own. */
export function allMaterials(doc: ProjectDoc): MaterialDef[] {
return [...MATERIALS, ...(doc.customMaterials ?? [])];
}
/** The material given to a body (undefined: none yet). */
export function materialOf(doc: ProjectDoc, body: string): MaterialDef | undefined {
const id = doc.materials?.[body];
return id ? allMaterials(doc).find((m) => m.id === id) : undefined;
}
/** The technical data of a material, as rows to show: [label, value with its unit]. Only what it has. */
export function materialRows(m: MaterialDef): { group: string; rows: [string, string][] }[] {
const n = (v: number) => String(Math.round(v * 1000) / 1000);
const row = (label: string, v: number | undefined, unit: string): [string, string][] => (v === undefined ? [] : [[label, `${n(v)} ${unit}`.trim()]]);
const groups = [
{ group: "Identity", rows: [["Class", m.category], ...(m.standard ? [["Standard", m.standard]] : []), ...(m.note ? [["Note", m.note]] : [])] as [string, string][] },
{
group: "Physical",
rows: [
...row("Density", m.density, "kg/m³"),
...row("Young's modulus", m.youngs, "GPa"),
...row("Poisson's ratio", m.poisson, ""),
...row("Yield strength", m.yield, "MPa"),
...row("Tensile strength", m.tensile, "MPa"),
...row("Compressive strength", m.compressive, "MPa"),
...row("Bending strength", m.bending, "MPa"),
...row("Elongation at break", m.elongation, "%"),
],
},
{
group: "Thermal",
rows: [
...row("Thermal conductivity", m.conductivity, "W/(m·K)"),
...row("Specific heat", m.specificHeat, "J/(kg·K)"),
...row("Thermal expansion", m.expansion, "µm/(m·K)"),
...row("Melting point", m.melting, "°C"),
...row("Max service temperature", m.maxTemp, "°C"),
],
},
];
return groups.filter((g) => g.rows.length);
}
/** Mass in kg of `volumeMM3` cubic millimetres of it. */
export function massOf(m: MaterialDef, volumeMM3: number): number {
return volumeMM3 * 1e-9 * m.density;
}
/** A mass for people: g under a kilo, kg up to a tonne, t above. */
export function fmtMass(kg: number): string {
if (kg < 1) return `${trim(kg * 1000, 1)} g`;
if (kg < 1000) return `${trim(kg, 3)} kg`;
return `${trim(kg / 1000, 3)} t`;
}
export function fmtVolume(mm3: number): string {
const k = UNIT_MM[units()];
return `${trim(mm3 / (k * k * k), 3)} ${UNIT_LABEL[units()]}³`;
}
export function fmtArea(mm2: number): string {
const k = UNIT_MM[units()];
return `${trim(mm2 / (k * k), 3)} ${UNIT_LABEL[units()]}²`;
}
/** Give bodies a material (its colour, and see-through for glass, come with it); null takes it away. */
export function assignMaterial(d: ProjectDoc, bodies: string[], m: MaterialDef | null): void {
const materials = { ...(d.materials ?? {}) };
const colors = { ...(d.colors ?? {}) };
const opacity = { ...(d.opacity ?? {}) };
for (const b of bodies) {
if (!m) {
delete materials[b];
continue;
}
materials[b] = m.id;
colors[b] = m.color;
if (m.opacity !== undefined) opacity[b] = m.opacity;
else delete opacity[b];
}
d.materials = materials;
d.colors = colors;
d.opacity = opacity;
}
+222
View File
@@ -0,0 +1,222 @@
// The technical sheet: the project as a document. A title block (who, what,
// which revision), the parts list - each body with its item number, material,
// volume, area, mass, centre of mass and size - and the technical data of
// every material used. The item numbers are the ones the drawings' balloons
// point to: the drawings show the shapes, this sheet says what they are made of.
//
// It prints (or saves as a PDF from the print window) and its parts list
// downloads as a spreadsheet (CSV).
import type { ProjectInfo } from "../doc/types";
import type { BodyProps } from "../kernel/protocol";
import { el } from "../ui/ui";
import { textField } from "../ui/textField";
import { trim, UNIT_LABEL, UNIT_MM, units } from "../units";
import type { AppContext } from "../tools/tool";
import { dataTable, fmtArea, fmtMass, fmtVolume, measureBodies } from "./bimTool";
import { massOf, materialOf } from "./materials";
/** One row of the parts list. */
export interface PartRow {
item: number;
id: string;
name: string;
material: string;
volume: number;
area: number;
/** kg; undefined without a material. */
mass?: number;
center: [number, number, number];
size: [number, number, number];
}
/** The parts list: every body shown, numbered as in the drawings. */
export function partsList(app: AppContext, props: Map<string, BodyProps>): PartRow[] {
const doc = app.store.doc;
return app.view.bodyList
.filter((b) => !doc.hidden.includes(b.id) && props.has(b.id))
.map((b, i) => {
const p = props.get(b.id)!;
const m = materialOf(doc, b.id);
return {
item: i + 1,
id: b.id,
name: doc.names?.[b.id] ?? b.name,
material: m?.name ?? "",
volume: p.volume,
area: p.area,
mass: m ? massOf(m, p.volume) : undefined,
center: p.center,
size: [p.box[1][0] - p.box[0][0], p.box[1][1] - p.box[0][1], p.box[1][2] - p.box[0][2]],
};
});
}
const len = (mm: number) => trim(mm / UNIT_MM[units()], 2);
let afterPrint: (() => void) | null = null;
/**
* The print window, with `cls` on the page while it is up (the styles for printing go by it) and `extra` (a style,
* the sheets to print) in the page that long. Put right when printing is over, not when print() returns: on a phone
* print() returns at once, before the preview has drawn the page - what it then drew was the page put back already
* (a blank sheet, or the app itself).
*/
export function printPage(cls: string, ...extra: HTMLElement[]): void {
afterPrint?.();
let over = false;
const tidy = () => {
if (over) return;
over = true;
afterPrint = null;
removeEventListener("afterprint", tidy);
removeEventListener("focus", late);
document.body.classList.remove(cls);
for (const e of extra) e.remove();
};
// (A browser that never says printing is over: tidied when the app is come back to, a moment after.)
const late = () => setTimeout(() => !matchMedia("print").matches && tidy(), 1500);
afterPrint = tidy;
document.body.classList.add(cls);
addEventListener("afterprint", tidy);
const t0 = performance.now();
try {
window.print();
} catch {
tidy();
return;
}
// (print() that waited for the window to close - a computer's browser: over now, whether or not it said so.)
if (performance.now() - t0 > 400) tidy();
else addEventListener("focus", late);
}
export async function openSheet(app: AppContext): Promise<void> {
document.querySelector(".bim-sheet")?.remove();
const back = el("div", "bim-sheet");
const bar = el("div", "bim-sheet-bar");
const close = el("button", "text-btn", "Close");
const print = el("button", "text-btn", "Print / PDF");
const csv = el("button", "text-btn", "Parts list (CSV)");
bar.append(el("span", "bim-sheet-name", "Technical Sheet"), print, csv, close);
const paper = el("div", "bim-paper");
paper.append(el("div", "bim-sub", "Measuring the bodies…"));
back.append(bar, paper);
document.body.append(back);
const shut = () => {
back.remove();
window.removeEventListener("keydown", onKey, true);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") (e.preventDefault(), e.stopPropagation(), shut());
};
window.addEventListener("keydown", onKey, true);
close.addEventListener("click", shut);
print.addEventListener("click", () => printPage("printing-sheet"));
let rows: PartRow[] = [];
try {
rows = partsList(app, await measureBodies(app));
} catch (err) {
paper.innerHTML = "";
paper.append(el("div", "bim-sub", `The bodies could not be measured: ${err instanceof Error ? err.message : String(err)}`));
return;
}
csv.addEventListener("click", () => {
const u = UNIT_LABEL[units()];
const q = (s: string) => `"${s.replace(/"/g, '""')}"`;
const k = UNIT_MM[units()];
const lines = [
["Item", "Name", "Material", `Volume (${u}3)`, `Area (${u}2)`, "Mass (kg)", `Centre of mass X (${u})`, `Y (${u})`, `Z (${u})`, `Size X (${u})`, `Size Y (${u})`, `Size Z (${u})`].join(","),
...rows.map((r) =>
[r.item, q(r.name), q(r.material), trim(r.volume / k ** 3, 4), trim(r.area / k ** 2, 4), r.mass === undefined ? "" : trim(r.mass, 4), ...r.center.map(len), ...r.size.map(len)].join(","),
),
];
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([lines.join("\r\n")], { type: "text/csv" }));
a.download = `${app.store.doc.name || "project"} - parts list.csv`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
});
paper.innerHTML = "";
render(app, paper, rows);
}
function render(app: AppContext, paper: HTMLElement, rows: PartRow[]): void {
const doc = app.store.doc;
const info: ProjectInfo = doc.info ?? {};
// ---- Title block
const head = el("div", "bim-title-block");
const field = (label: string, value: string, key?: keyof ProjectInfo) => {
const f = el("label", "bim-tb-field");
f.append(el("span", "bim-tb-label", label));
if (!key) f.append(el("span", "bim-tb-value", value));
else {
const input = textField("bim-tb-value");
input.value = value;
input.placeholder = "-";
input.addEventListener("change", () => app.store.commit((d) => (d.info = { ...(d.info ?? {}), [key]: input.value.trim() || undefined })));
f.append(input);
}
head.append(f);
};
field("Project", doc.name || "Untitled");
field("Document", "Technical sheet");
field("Number", info.number ?? "", "number");
field("Revision", info.revision ?? "", "revision");
field("Author", info.author ?? "", "author");
field("Company", info.company ?? "", "company");
field("Date", new Date().toISOString().slice(0, 10));
field("Units", `${UNIT_LABEL[units()]}, kg`);
paper.append(head);
// ---- Parts list
paper.append(el("h2", "bim-h", "1. Parts list"));
const missing = rows.filter((r) => r.mass === undefined).length;
if (missing) paper.append(el("div", "bim-warn", `${missing === 1 ? "1 body has" : `${missing} bodies have`} no material yet: no mass for ${missing === 1 ? "it" : "them"}. Give each body a material in BIM - Materials.`));
const u = UNIT_LABEL[units()];
const t = el("table", "bim-table");
const hr = el("tr", "");
for (const h of ["Item", "Name", "Material", "Volume", "Surface area", "Mass", `Centre of mass (${u})`, `Size X × Y × Z (${u})`]) hr.append(el("th", "", h));
t.append(hr);
for (const r of rows) {
const tr = el("tr", "");
for (const v of [String(r.item), r.name, r.material || "-", fmtVolume(r.volume), fmtArea(r.area), r.mass === undefined ? "-" : fmtMass(r.mass), r.center.map(len).join(", "), r.size.map(len).join(" × ")]) tr.append(el("td", "", v));
t.append(tr);
}
const total = rows.reduce((s, r) => s + (r.mass ?? 0), 0);
const tf = el("tr", "bim-total");
for (const v of ["", `${rows.length} ${rows.length === 1 ? "part" : "parts"}`, "", fmtVolume(rows.reduce((s, r) => s + r.volume, 0)), "", `${fmtMass(total)}${missing ? " +" : ""}`, "", ""]) tf.append(el("td", "", v));
t.append(tf);
const wrap = el("div", "bim-table-wrap");
wrap.append(t);
paper.append(wrap);
// ---- Materials used, with their data
paper.append(el("h2", "bim-h", "2. Materials"));
const used = new Map<string, number[]>();
for (const r of rows) {
const m = materialOf(doc, r.id);
if (m) used.set(m.id, [...(used.get(m.id) ?? []), r.item]);
}
if (!used.size) paper.append(el("div", "bim-sub", "No materials given yet."));
const grid = el("div", "bim-material-grid");
for (const [, items] of used) {
const m = materialOf(doc, rows.find((r) => r.item === items[0])!.id)!;
const c = el("div", "bim-material-card");
const h = el("div", "bim-material-head");
const sw = el("span", "bim-swatch");
sw.style.background = m.color;
h.append(sw, el("b", "", m.name));
c.append(h, el("div", "bim-sub", `Items ${items.join(", ")}`), dataTable(m));
grid.append(c);
}
paper.append(grid);
paper.append(
el(
"div",
"bim-foot",
"Strengths are the minimums of the standard named, where the grade has one; other values are typical (thermal values of building materials: ISO 10456 design values). A supplier's data sheet comes first where it differs. Masses are worked out from each body's measured volume and its material's density.",
),
);
}
+116
View File
@@ -0,0 +1,116 @@
// Where the drawing sheet is seen from: how close (screen pixels per mm of
// paper) and which point of the paper is in the middle of the screen. The
// sheet is shown through its SVG viewBox, so lines stay sharp at any zoom and
// moving round never redraws the sheet.
export class SheetCamera {
/** Pixels per mm. */
z = 1;
/** The paper point (mm) in the middle of the screen. */
cx = 0;
cy = 0;
/** Showing all of the sheet (and kept so when the window or sheet changes size). */
fitted = true;
/** The screen area (px) and the sheet (mm). */
vw = 1;
vh = 1;
W = 420;
H = 297;
/** Room round the sheet when it is all in view (px). */
static MARGIN = 16;
/** Pixels per mm with all of the sheet in view. */
fitZoom(): number {
const m = SheetCamera.MARGIN;
return Math.max(1e-3, Math.min((this.vw - 2 * m) / this.W, (this.vh - 2 * m) / this.H));
}
/** How far it may go: a quarter of the whole sheet out, 60 times in (and at least 40 px a mm). */
minZoom(): number {
return this.fitZoom() / 4;
}
maxZoom(): number {
return Math.max(this.fitZoom() * 60, 40);
}
/** All of the sheet, in the middle. */
fit(): void {
this.z = this.fitZoom();
this.cx = this.W / 2;
this.cy = this.H / 2;
this.fitted = true;
}
/** The screen area changed size: still all of the sheet if it was, else the same middle and zoom. */
resize(vw: number, vh: number): void {
this.vw = Math.max(1, vw);
this.vh = Math.max(1, vh);
if (this.fitted) this.fit();
else this.clamp();
}
/** Another sheet size (A3 to A4…): all of it. */
setSheet(W: number, H: number): void {
if (W === this.W && H === this.H) return;
this.W = W;
this.H = H;
this.fit();
}
/** A screen point (px from the area's top left) on the paper (mm). */
toPaper(px: number, py: number): [number, number] {
return [this.cx + (px - this.vw / 2) / this.z, this.cy + (py - this.vh / 2) / this.z];
}
/** A paper point on the screen. */
toScreen(x: number, y: number): [number, number] {
return [this.vw / 2 + (x - this.cx) * this.z, this.vh / 2 + (y - this.cy) * this.z];
}
/** Closer (k > 1) or further, keeping the paper under the screen point where it is. */
zoomAt(px: number, py: number, k: number): void {
const [x, y] = this.toPaper(px, py);
this.z = Math.min(this.maxZoom(), Math.max(this.minZoom(), this.z * k));
this.cx = x - (px - this.vw / 2) / this.z;
this.cy = y - (py - this.vh / 2) / this.z;
this.fitted = false;
this.clamp();
}
/** The paper moved with the finger by (dx, dy) screen pixels. */
panBy(dx: number, dy: number): void {
this.cx -= dx / this.z;
this.cy -= dy / this.z;
this.fitted = false;
this.clamp();
}
/** The sheet never goes out of sight: the middle of the screen stays over it. */
clamp(): void {
this.cx = Math.min(this.W, Math.max(0, this.cx));
this.cy = Math.min(this.H, Math.max(0, this.cy));
}
/** How close, against all of the sheet in view (1: fitted). */
ratio(): number {
return this.z / this.fitZoom();
}
/** The SVG viewBox for what's in view. */
viewBox(): string {
const w = this.vw / this.z;
const h = this.vh / this.z;
const r = (v: number) => Math.round(v * 1e4) / 1e4;
return `${r(this.cx - w / 2)} ${r(this.cy - h / 2)} ${r(w)} ${r(h)}`;
}
/** The state, to go smoothly from one to another. */
get state(): { z: number; cx: number; cy: number } {
return { z: this.z, cx: this.cx, cy: this.cy };
}
/** Part way (t: 0 to 1) from one state to another: zoom evenly in scale, the middle so the view glides. */
blend(a: { z: number; cx: number; cy: number }, b: { z: number; cx: number; cy: number }, t: number): void {
this.z = a.z * Math.pow(b.z / a.z, t);
this.cx = a.cx + (b.cx - a.cx) * t;
this.cy = a.cy + (b.cy - a.cy) * t;
}
}
+519
View File
@@ -0,0 +1,519 @@
// The console's handle on the app: `sg` - read what's there and work the tools
// without tapping at pixels. For checking the app by hand or by script (the
// browser's console, or a test driving the page). Type sg.help() to list it.
//
// sg.state() the project, tool, hint, panel, selection, errors, bodies
// sg.select(sg.sel.body("Box")) pick something (as a tap would)
// sg.actions() what the picked thing offers (left column, bottom bar)
// sg.run("Project as Sketch") run one (by id or label, also in sub-menus)
// sg.panel() the open tool's window: slots, values, choices
// sg.set("XY") sg.set("Height", 2) sg.set("Sink in", true)
// sg.pick(sg.sel.face("Box", 3)) give the waiting slot a face / edge / plane…
// sg.done() sg.cancel() await sg.idle() await sg.health()
import type { App } from "./app";
import type { ToolItem, PanelItem } from "./ui/ui";
import type { Feature } from "./doc/types";
import type { Sel } from "./tools/tool";
import type { SweepWord } from "./ui/sentence";
import type { PickHit } from "./view/viewport";
import type { ProjectDoc } from "./doc/types";
import { parseProject } from "./doc/store";
import { newProjectId } from "./doc/library";
// (The app's insides it reads: kept out of the classes' public faces on purpose.)
interface Insides {
tool: { id: string; editingId?: string; activeSketch?: string; slots?: { label: string; accept(h: PickHit): boolean; multi?: boolean }[]; active?: number; advance?(): void; render?(): void; update?(): void };
regenerate(): Promise<void>;
undo(): void;
redo(): void;
switchProject(doc: ProjectDoc, id: string): Promise<void>;
}
interface UIInsides {
toolItems: ToolItem[];
bottomItems: ToolItem[];
panelSpec: { title: string; items?: PanelItem[]; fields?: { label: string; value: number; onInput(v: number): void }[]; actions?: ToolItem[]; onDone?(): void; onCancel?(): void } | null;
hintText: string | null;
recentToasts?: string[];
}
interface Listed {
id: string;
label: string;
/** Where it sits: "Sketch › Rectangle". */
path: string;
disabled?: boolean;
why?: string;
item: ToolItem;
}
function flatten(items: ToolItem[], path: string[] = []): Listed[] {
// (Separators have no label.)
return items.filter((it) => it.label).flatMap((it) => [
{ id: it.id, label: it.label, path: [...path, it.label].join(" › "), ...(it.disabled ? { disabled: true, why: it.why } : {}), item: it },
...flatten(it.children ?? [], [...path, it.label]),
]);
}
const plain = (l: Listed[]) => l.map(({ item: _, ...rest }) => rest);
const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
export function installDebug(app: App): void {
const inside = app as unknown as Insides;
const ui = app.ui as unknown as UIInsides;
const features = () => app.store.doc.features;
/** A step or body by id or name. */
const featureOf = (key: string): Feature | undefined => features().find((f) => f.id === key) ?? features().find((f) => same(f.name, key));
const bodyId = (key: string): string => {
const list = app.view.bodyList;
const names = app.store.doc.names ?? {};
return list.find((b) => b.id === key)?.id ?? list.find((b) => same(names[b.id] ?? b.name, key))?.id ?? key;
};
const panelItems = (): PanelItem[] => {
const spec = ui.panelSpec;
if (!spec) return [];
const fields: PanelItem[] = (spec.fields ?? []).map((f) => ({ type: "number", label: f.label, value: f.value, onInput: f.onInput }));
return [...fields, ...(spec.items ?? [])];
};
const shown = (): ToolItem[] => [...ui.toolItems, ...ui.bottomItems, ...(ui.panelSpec?.actions ?? [])];
const sg = {
app,
/** What's there now, in one look. */
state() {
const r = app.result;
const byId = new Map(features().map((f) => [f.id, f.name]));
return {
project: app.store.doc.name,
tool: inside.tool.id,
editing: inside.tool.editingId ?? inside.tool.activeSketch ?? null,
hint: ui.hintText,
panel: ui.panelSpec?.title ?? null,
selection: app.selection,
steps: features().length,
errors: (r?.errors ?? []).map((e) => `${byId.get(e.featureId) ?? e.featureId}: ${e.message}`),
notes: (r?.notes ?? []).map((e) => `${byId.get(e.featureId) ?? e.featureId}: ${e.message}`),
toasts: ui.recentToasts?.slice(-5) ?? [],
bodies: sg.bodies(),
};
},
/** The steps in History: id, name, type, switched off, its error. */
steps() {
const errs = new Map((app.result?.errors ?? []).map((e) => [e.featureId, e.message]));
return features().map((f, i) => ({ i: i + 1, id: f.id, name: f.name, type: f.type, ...(f.suppressed ? { off: true } : {}), ...(errs.has(f.id) ? { error: errs.get(f.id) } : {}) }));
},
/** A step as stored (by id or name). */
step: (key: string) => featureOf(key),
/** The bodies shown: id, name, how many faces and edges, hidden. */
bodies() {
const names = app.store.doc.names ?? {};
const hidden = new Set(app.store.doc.hidden);
return app.view.bodyList.map((b) => ({ id: b.id, name: names[b.id] ?? b.name, faces: b.faces.length, edges: b.edges.length, ...(hidden.has(b.id) ? { hidden: true } : {}) }));
},
/** Each body measured on the solid: valid, closed, solids, faces, volume, box. */
health: () => app.kernel.health(features()),
/** The main tools (the left column with nothing picked, with their sub-menus). */
tools: () => plain(flatten(app.mainTools())),
/** What's offered now: the left column (what the picked thing offers), the bottom bar, the open window's buttons. */
actions: () => plain(flatten(shown())),
/** Run a tool or action by id or label (what's offered now first, then the main tools). */
run(key: string): string {
const all = [...flatten(shown()), ...flatten(app.mainTools())];
const hit = all.find((x) => x.id === key) ?? all.find((x) => same(x.label, key)) ?? all.find((x) => same(x.path, key));
if (!hit) return `No "${key}" here. sg.actions() / sg.tools() list what there is.`;
if (hit.disabled) return `"${hit.label}" is off: ${hit.why ?? "(no reason given)"}`;
if (!hit.item.run) return `"${hit.label}" opens a menu: ${(hit.item.children ?? []).map((c) => c.label).join(", ")}`;
hit.item.run();
return `ran ${hit.path}`;
},
/** The sentence bar: what it says now (its words, where each is). */
sentence: () => app.sentence.describe(),
/**
* Every tool, from every kind of pick there is in the model, started
* through the line at the bottom - and in each every option tried (each
* choice, switch, number, blank). Lists what did nothing, what threw, and
* for each tool whether it has a handle on the model, a value box, and
* lit picks while it is open (what a tool that takes a distance should
* have). Changes nothing for good: each tool is cancelled, each step
* undone. `only`: just the picks named ("face", "edge", "body"...).
* `options` false: the tools are only started and looked at (much quicker).
*/
async sweep(only?: string[], options = true): Promise<{ started: number; nothing: string[]; errors: string[]; options: string[]; audit: { pick: string; tool: string; handle: boolean; box: boolean; lit: boolean; numbers: number }[] }> {
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const errors: string[] = [];
const onError = (e: ErrorEvent) => errors.push(`${e.message}`);
const onReject = (e: PromiseRejectionEvent) => errors.push(String((e.reason as Error)?.message ?? e.reason));
addEventListener("error", onError);
addEventListener("unhandledrejection", onReject);
const steps = app.store.doc.features.length;
const state = () => app.sentence.state;
const settle = async () => {
app.sentence.changed();
await wait(120);
await Promise.race([sg.idle(), wait(4000)]);
};
const reset = async () => {
for (const d of Array.from(document.querySelectorAll<HTMLElement>(".dialog-back .dialog, .bim-sheet")).reverse()) {
const b = Array.from(d.querySelectorAll("button")).find((x) => /^(Cancel|Close)/i.test(x.textContent?.trim() ?? "") || /close/i.test(x.className) || /close/i.test(x.title));
b?.click();
await wait(120);
}
for (let i = 0; i < 4 && inside.tool.id !== "select"; i++) {
document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
await wait(150);
}
for (let i = 0; i < 3; i++) {
const s = state();
if (!s?.about.startsWith("tool:")) break;
(s.cancel ?? s.done)?.();
await wait(200);
}
if (inside.tool.id !== "select") app.setTool(null);
while (app.store.doc.features.length > steps) {
inside.undo();
await wait(120);
}
if (app.isolated) app.isolate(null);
await Promise.race([sg.idle(), wait(4000)]);
};
const snap = () => JSON.stringify([inside.tool.id, ui.panelSpec?.title ?? null, app.store.doc.features.length, app.selection, document.querySelectorAll(".dialog, .menu:not([hidden]), .ref-win, .bim-sheet").length, ui.recentToasts?.length ?? 0, !!app.isolated, !!app.section, app.varsOn, JSON.stringify(app.store.doc), ui.hintText]);
const leaves = () => {
const out: { path: string; key: string }[] = [];
const walk = (ws: SweepWord[], path: string[]) => {
for (const w of ws) {
if (w.kids?.length) walk(w.kids, [...path, w.label]);
else if (w.run || w.value) out.push({ path: [...path, w.label].join(" > "), key: w.key });
}
};
for (const g of state()?.groups ?? []) walk(g.words, [g.cap]);
return out;
};
const find = (key: string): SweepWord | null => {
let hit: SweepWord | null = null;
const walk = (ws: SweepWord[]) => {
for (const w of ws) {
if (w.key === key) hit = w;
if (w.kids) walk(w.kids);
}
};
for (const g of state()?.groups ?? []) walk(g.words);
return hit;
};
// The picks there are in this model.
const bodies = app.view.bodyList;
const picks: [string, Sel[]][] = [["nothing", []]];
const b0 = bodies[0];
if (b0) {
const flat = b0.faces.findIndex((f) => f.type === "PLANE");
const straight = b0.edges.findIndex((e) => e.type === "LINE");
if (flat >= 0) picks.push(["face", [{ kind: "face", body: b0.id, face: flat }]]);
if (straight >= 0) picks.push(["edge", [{ kind: "edge", body: b0.id, edge: straight }]]);
picks.push(["corner", [{ kind: "vertex", body: b0.id, vertex: 0 }]], ["body", [{ kind: "body", body: b0.id }]]);
if (bodies[1]) picks.push(["two bodies", [{ kind: "body", body: b0.id }, { kind: "body", body: bodies[1].id }]]);
}
for (const b of bodies) {
const round = b.faces.findIndex((f) => f.type !== "PLANE");
const rim = b.edges.findIndex((e) => e.type === "CIRCLE");
if (round >= 0 && !picks.some((p) => p[0] === "round face")) picks.push(["round face", [{ kind: "face", body: b.id, face: round }]]);
if (rim >= 0 && !picks.some((p) => p[0] === "round edge")) picks.push(["round edge", [{ kind: "edge", body: b.id, edge: rim }]]);
}
const loose = features().find((f) => f.type === "sketch" && !features().some((g) => JSON.stringify(g).includes(`"sketch":"${f.id}"`) && g.id !== f.id));
if (loose) picks.push(["sketch shape", [{ kind: "profile", sketch: loose.id, region: 0 }]]);
picks.push(["plane", [{ kind: "plane", id: "XY" }]]);
// (Things that open a chooser of the device's, which cannot be closed from here.)
const skip = /-image$|-file$|insert-project$|refImage$|browser$|custom/i;
const out = { started: 0, nothing: [] as string[], errors: [] as string[], options: [] as string[], audit: [] as { pick: string; tool: string; handle: boolean; box: boolean; lit: boolean; numbers: number }[] };
for (const [name, sel] of picks) {
if (only && !only.includes(name)) continue;
await reset();
app.setSelection(sel);
await settle();
for (const leaf of leaves()) {
if (skip.test(leaf.key)) continue;
await reset();
app.setSelection(sel);
await settle();
const w = find(leaf.key);
if (!w) {
out.nothing.push(`${name}: ${leaf.path} (not offered a second time)`);
continue;
}
const before = snap();
const e0 = errors.length;
try {
if (w.value) w.value.put(w.value.now + (w.value.max !== undefined && w.value.now >= w.value.max ? -1 : 1));
else w.run?.();
} catch (err) {
out.errors.push(`${name}: ${leaf.path}: ${(err as Error).message}`);
continue;
}
await settle();
if (errors.length > e0) out.errors.push(`${name}: ${leaf.path}: ${errors.slice(e0).join("; ")}`);
if (snap() === before) {
out.nothing.push(`${name}: ${leaf.path}`);
continue;
}
out.started++;
const s = state();
if (!s?.about.startsWith("tool:")) continue;
// What a tool that takes a size should have: a handle on the model, a box for the value, its picks lit.
const numbers = s.words.filter((x) => x.value && (x.value.kind === "length" || x.value.kind === "angle")).length;
out.audit.push({ pick: name, tool: leaf.path.split(" > ").pop()!, handle: Array.from(app.view.helpers).some((h) => /Handle|Gimbal/.test(h.constructor.name)), box: Array.from(document.querySelectorAll<HTMLElement>(".dim-widget")).some((d) => d.getBoundingClientRect().width > 0), lit: app.selection.length > 0 || ((app.view as unknown as { highlightGroup?: { children: unknown[] } }).highlightGroup?.children.length ?? 0) > 0, numbers });
if (!options) continue;
// Every option of it.
for (const key of s.words.map((x) => x.key)) {
const at = () => state()?.words.find((x) => x.key === key);
const it = at();
if (!it) continue;
const what = `${name}: ${leaf.path}: ${it.cap ?? it.label}`;
const e1 = errors.length;
try {
if (it.kind === "choice" && it.kids) {
const first = it.kids.find((k) => k.on)?.key;
for (const kid of it.kids.map((k) => k.key)) {
const k = at()?.kids?.find((x) => x.key === kid);
if (!k || k.on) continue;
k.run?.();
await settle();
if (inside.tool.id === "select") break;
const now = at()?.kids?.find((x) => x.key === kid);
if (k.kind === "verb" && now && !now.on) out.options.push(`${what} > ${k.label}: not set`);
}
const back = at()?.kids?.find((x) => x.key === first);
if (back && !back.on) (back.run?.(), await settle());
} else if (it.kind === "toggle") {
const was = !!it.on;
it.run?.();
await settle();
const now = at();
if (now && !!now.on === was) out.options.push(`${what}: switch did not flip`);
now?.run?.();
await settle();
} else if (it.kind === "value" && it.value) {
const v = it.value;
v.put(v.kind === "int" ? v.now + 1 : v.kind === "angle" ? v.now + 5 : v.now === 0 ? 3 : v.now * 1.25);
await settle();
const now = at();
if (now?.value && now.value.now === v.now && (v.max === undefined || v.now < v.max)) out.options.push(`${what}: value did not change`);
} else if (it.kind === "slot") {
it.run?.();
await settle();
}
} catch (err) {
out.options.push(`${what}: ${(err as Error).message}`);
}
if (errors.length > e1) out.options.push(`${what}: ${errors.slice(e1).join("; ")}`);
if (inside.tool.id === "select") break;
}
}
}
await reset();
app.setSelection([]);
removeEventListener("error", onError);
removeEventListener("unhandledrejection", onReject);
return out;
},
/** The reference image windows and their tabs; refAdd(name, dataUrl) opens one as Insert › Reference Image does. */
refImages: () => app.refImages.describe(),
refAdd: (name: string, src: string) => void app.refImages.add(name, src),
/** Pick things, as taps would (sg.sel builds them). */
select(...sel: Sel[]) {
app.setSelection(sel);
return app.selection;
},
/** Things to pick, by name or id. */
sel: {
body: (body: string): Sel => ({ kind: "body", body: bodyId(body) }),
face: (body: string, face: number): Sel => ({ kind: "face", body: bodyId(body), face }),
edge: (body: string, edge: number): Sel => ({ kind: "edge", body: bodyId(body), edge }),
vertex: (body: string, vertex: number): Sel => ({ kind: "vertex", body: bodyId(body), vertex }),
/** A sketch's closed shape (regions counted as the sketch finds them). */
profile: (sketch: string, region = 0): Sel => ({ kind: "profile", sketch: featureOf(sketch)?.id ?? sketch, region }),
curve: (sketch: string, entity: string): Sel => ({ kind: "curve", sketch: featureOf(sketch)?.id ?? sketch, entity }),
plane: (id: string): Sel => ({ kind: "plane", id: featureOf(id)?.id ?? id }),
axis: (id: string): Sel => ({ kind: "axis", id: featureOf(id)?.id ?? id }),
origin: (): Sel => ({ kind: "origin" }),
},
/** A body's faces: index, type, centre, normal, area (to find the one to pick). */
faces(body: string) {
return (app.view.body(bodyId(body))?.faces ?? []).map((f, i) => ({ i, type: f.type, center: f.center, normal: f.normal, area: +f.area.toFixed(3), ...(f.round ? { round: f.round } : {}) }));
},
/** A body's edges: index, type, ends. */
edges(body: string) {
return (app.view.body(bodyId(body))?.edges ?? []).map((e, i) => ({ i, type: e.type, start: e.start, mid: e.mid, end: e.end, length: +e.length.toFixed(3) }));
},
/** The open tool's window: title, rows (slots, numbers, choices, toggles), buttons. */
panel() {
const spec = ui.panelSpec;
if (!spec) return null;
return {
title: spec.title,
rows: panelItems().map((it) => {
switch (it.type) {
case "number":
case "slider":
case "toggle":
return { type: it.type, label: it.label, value: it.value };
case "slot":
return { type: it.type, label: it.label, value: it.value, ...(it.active ? { waiting: true } : {}), filled: it.filled };
case "choice":
return { type: it.type, label: it.label ?? "", value: it.value, options: it.options.map((o) => o.label) };
case "button":
return { type: it.type, label: it.label };
case "chips":
return { type: it.type, label: it.label ?? "", chips: it.chips.map((c) => c.label + (c.on ? " (on)" : "")) };
default:
return { type: (it as { type: string }).type };
}
}),
buttons: (spec.actions ?? []).map((a) => a.label),
};
},
/**
* Set a row of the open window by its label: a number, a toggle, a choice
* (or just a choice's option: sg.set("XY")), a slot to fill next, a button.
*/
set(label: string, value?: number | boolean | string): string {
const items = panelItems();
const row = items.find((it) => "label" in it && it.label && same(it.label, label));
if (row) {
switch (row.type) {
case "number":
case "slider":
row.onInput(Number(value));
return `${row.label} = ${value}`;
case "toggle":
row.onChange(value === undefined ? !row.value : !!value);
return `${row.label} ${value === undefined ? !row.value : !!value ? "on" : "off"}`;
case "choice": {
const o = row.options.find((x) => x.id === value || same(x.label, String(value)));
if (!o) return `${row.label}: no "${value}" (${row.options.map((x) => x.label).join(", ")})`;
row.onChange(o.id);
return `${row.label} = ${o.label}`;
}
case "slot":
row.onClick();
return `${row.label}: waiting for a pick`;
case "button":
row.onClick();
return `pressed ${row.label}`;
}
}
// An option of a choice with no label (the X / Y / Z, XY / XZ / YZ by a slot), or a chip.
for (const it of items) {
if (it.type === "choice") {
const o = it.options.find((x) => same(x.label, label));
if (o) {
it.onChange(o.id);
return `chose ${o.label}`;
}
}
if (it.type === "chips") {
const c = it.chips.find((x) => same(x.label, label));
if (c) {
c.onClick();
return `tapped ${c.label}`;
}
}
}
const btn = ui.panelSpec?.actions?.find((a) => same(a.label, label) || a.id === label);
if (btn?.run) {
btn.run();
return `pressed ${btn.label}`;
}
return `No "${label}" in the window. sg.panel() lists its rows.`;
},
/** Give the open tool's waiting slot a pick (a face, edge, profile, plane…), as a tap on it would. */
pick(sel: Sel, point?: [number, number, number]): string {
const t = inside.tool;
const slot = t.slots?.[t.active ?? -1];
if (!slot) return "No slot waiting (sg.set(<slot label>) makes one wait).";
let at = point;
if (!at && (sel.kind === "face" || sel.kind === "edge")) {
const b = app.view.body(sel.body);
at = sel.kind === "face" ? b?.faces[sel.face]?.center : b?.edges[sel.edge]?.mid;
}
const hit = { ...sel, point: at ?? [0, 0, 0] } as PickHit;
if (!slot.accept(hit)) return `${slot.label} doesn't take that.`;
t.advance?.();
t.render?.();
t.update?.();
return `${slot.label}: picked`;
},
/** Done / Cancel in the open tool's window. */
done(): string {
const spec = ui.panelSpec;
if (!spec?.onDone) return "No window with Done open.";
spec.onDone();
return `done: ${spec.title}`;
},
cancel(): string {
const spec = ui.panelSpec;
if (spec?.onCancel) spec.onCancel();
else app.setTool(null);
return "cancelled";
},
undo: () => inside.undo(),
redo: () => inside.redo(),
/** Wait until the geometry engine has nothing left to do (and the page has drawn it). */
async idle(timeoutMs = 30000): Promise<boolean> {
const k = app.kernel as unknown as { pending: Map<number, unknown>; regenRunning: boolean };
const t0 = performance.now();
let quiet = 0;
while (performance.now() - t0 < timeoutMs) {
await new Promise((r) => setTimeout(r, 50));
quiet = k.pending.size || k.regenRunning ? 0 : quiet + 1;
if (quiet >= 3) return true;
}
return false;
},
/** The project as saved (JSON). */
save: () => JSON.stringify(app.store.doc),
/**
* Open a project (its JSON, as text or object) as a new one in the
* library, as File → Open does; the one open now is kept. Resolves once
* it is built.
*/
async load(project: string | object, name?: string): Promise<string> {
const doc = parseProject(typeof project === "string" ? project : JSON.stringify(project));
if (name) doc.name = name;
await inside.switchProject(doc, newProjectId());
await sg.idle();
return doc.name;
},
/** What there is, with one line each. */
help(): number {
const lines: string[] = Object.entries(sg as Record<string, unknown>)
.filter(([k]) => k !== "app")
.map(([k, v]) => (typeof v === "function" ? `sg.${k}(${((v as () => void).toString().match(/^[^(]*\(([^)]*)\)/)?.[1] ?? "").replace(/\s+/g, " ")})` : `sg.${k}`));
console.log(lines.join("\n"));
return lines.length;
},
};
(window as unknown as { sg: typeof sg }).sg = sg;
}
+20 -15
View File
@@ -19,7 +19,7 @@ const dist = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b
function worldCage(doc: ProjectDoc, body: string): { feature: FreeformFeature; cage: Cage; m: number[] } | null {
const ff = freeformBodies(doc.features).get(body);
if (!ff || ff.feature.id !== body) return null;
return { feature: ff.feature, m: ff.m, cage: { faces: ff.feature.cage.faces, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) } };
return { feature: ff.feature, m: ff.m, cage: { ...ff.feature.cage, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) } };
}
/** The open-border cage edges under the picked body edges (null if one isn't on a border). */
@@ -41,12 +41,6 @@ function cageEdgesAt(cage: Cage, picks: Vec3[]): Set<string> | null {
export type ConnectResult = { doc: ProjectDoc; body: string } | { error: string };
/** Can these picked edges be connected (for showing the button)? */
export function canConnect(doc: ProjectDoc, picks: PickedEdge[]): boolean {
const bodies = [...new Set(picks.map((p) => p.body))];
return picks.length >= 2 && bodies.length <= 2 && bodies.every((b) => !!worldCage(doc, b));
}
/**
* Connect the picked border edges. They must make two runs with the same
* number of edges (two edges, two rows, or two hole rims), on one freeform or
@@ -88,12 +82,19 @@ export function connectEdges(doc: ProjectDoc, picks: PickedEdge[]): ConnectResul
}
if (!Q) return { doc: store(doc, P.feature, next, P.m), body: P.feature.id };
// Two freeforms → one: the later step keeps it, the earlier one goes.
const ia = doc.features.indexOf(P.feature);
const ib = doc.features.indexOf(Q.feature);
const [keep, drop, mKeep] = ia < ib ? [Q.feature, P.feature, Q.m] : [P.feature, Q.feature, P.m];
const users = doc.features.filter((f) => f !== drop && JSON.stringify(f).includes(`"${drop.id}`) && !(f.type === "transform" && !f.copy && ["move", "scale", "mirror", "scaleXYZ"].includes(f.op.kind)));
// (By id: an edited freeform's feature here is its step with the edits put in, not the step itself.)
const at = (id: string) => doc.features.findIndex((f) => f.id === id);
const [keep, drop, mKeep] = at(P.feature.id) < at(Q.feature.id) ? [Q.feature, P.feature, Q.m] : [P.feature, Q.feature, P.m];
// Its Edit Freeform steps and its own moves are in the merged cage: they don't keep it from going.
const users = doc.features.filter(
(f) =>
f.id !== drop.id &&
!(f.type === "freeformEdit" && (f.target === drop.id || f.target === keep.id)) &&
JSON.stringify(f).includes(`"${drop.id}"`) &&
!(f.type === "transform" && !f.copy && ["move", "scale", "mirror", "scaleXYZ"].includes(f.op.kind)),
);
if (users.length) return { error: `“${drop.name}” is used by “${users[0].name}” later on - it can't be merged into the other surface` };
const out = store(doc, keep, next, mKeep, { surface: !!(keep.surface || drop.surface) });
const out = store({ ...doc, features: doc.features.filter((f) => !(f.type === "freeformEdit" && f.target === drop.id)) }, keep, next, mKeep, { surface: !!(keep.surface || drop.surface) });
// The dropped one's own moves go with it (they are already in the merged cage).
out.features = out.features
.filter((f) => f.id !== drop.id)
@@ -103,9 +104,13 @@ export function connectEdges(doc: ProjectDoc, picks: PickedEdge[]): ConnectResul
return { doc: out, body: keep.id };
}
/** Put a world-space cage back into a freeform step (in its own coordinates). */
/**
* Put a world-space cage back into a freeform step (in its own coordinates).
* Its Edit Freeform steps go: their edits are in that cage already (and a
* later one would otherwise put its own cage back over it).
*/
function store(doc: ProjectDoc, f: FreeformFeature, cage: Cage, m: number[], extra: Partial<FreeformFeature> = {}): ProjectDoc {
const inv = invertAffine(m);
const updated: FreeformFeature = { ...f, ...extra, cage: { faces: cage.faces, verts: cage.verts.map((v) => applyAffine(inv, v)) } };
return { ...doc, features: doc.features.map((x): Feature => (x.id === f.id ? updated : x)) };
const updated: FreeformFeature = { ...f, ...extra, cage: { ...cage, verts: cage.verts.map((v) => applyAffine(inv, v)) } };
return { ...doc, features: doc.features.filter((x) => !(x.type === "freeformEdit" && x.target === f.id)).map((x): Feature => (x.id === f.id ? updated : x)) };
}
+7
View File
@@ -83,6 +83,11 @@ export function freeformBodies(features: readonly Feature[], upto = features.len
out.set(f.id, { feature: f, m: ID });
continue;
}
// An Edit Freeform step: the freeform (and its copies) with the new cage.
if (f.type === "freeformEdit") {
for (const [id, ff] of out) if (ff.feature.id === f.target) out.set(id, { ...ff, feature: { ...ff.feature, ...f.patch } });
continue;
}
if (f.type === "transform") {
const step = stepAffine(f.op);
for (const id of f.bodies) {
@@ -130,6 +135,7 @@ export function detachFreeformCopy(doc: ProjectDoc, bodyId: string, newId: strin
verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)),
// A mirror turns the shape inside out: wind the quads the other way.
faces: ff.feature.cage.faces.map((q) => (flip ? ([q[0], q[3], q[2], q[1]] as typeof q) : ([...q] as typeof q))),
...(ff.feature.cage.creases ? { creases: structuredClone(ff.feature.cage.creases) } : {}),
},
};
const features = [...doc.features];
@@ -145,6 +151,7 @@ export function detachFreeformCopy(doc: ProjectDoc, bodyId: string, newId: strin
names: Object.fromEntries(Object.entries(doc.names ?? {}).map(([k, v]) => [renameIn(`"${k}"`, bodyId, newId).slice(1, -1), v])),
};
if (doc.colors) out.colors = Object.fromEntries(Object.entries(doc.colors).map(([k, v]) => [renameIn(`"${k}"`, bodyId, newId).slice(1, -1), v]));
if (doc.materials) out.materials = Object.fromEntries(Object.entries(doc.materials).map(([k, v]) => [renameIn(`"${k}"`, bodyId, newId).slice(1, -1), v]));
// The copy's name in Items stays what it was.
if (!out.names?.[newId] && doc.names?.[bodyId]) out.names = { ...out.names, [newId]: doc.names[bodyId] };
return { doc: out, id: newId };
+25
View File
@@ -0,0 +1,25 @@
// Edit Freeform steps: each holds the new cage of a freeform (or a Freeform
// Face step) made earlier. Before a rebuild - and wherever a freeform's cage
// is read - the steps that are on are put into what they edit, in order, so
// the shape is the last edit's; deleting or rolling back an edit gives the
// shape as it was before it.
import type { Feature, FreeformEditFeature } from "./types";
/** The steps with their edits put in (the edit steps themselves stay, doing nothing more). */
export function applyFreeformEdits<T extends Feature>(features: readonly T[]): T[] {
const edits = features.filter((f): f is T & FreeformEditFeature => f.type === "freeformEdit" && !f.suppressed && !f.rolledBack);
if (!edits.length) return features as T[];
const patch = new Map<string, FreeformEditFeature["patch"]>();
for (const e of edits) patch.set(e.target, { ...(patch.get(e.target) ?? {}), ...e.patch });
return features.map((f) => {
const p = patch.get(f.id);
return p && (f.type === "freeform" || f.type === "faceFreeform") ? ({ ...f, ...p } as T) : f;
});
}
/** One step as its edits leave it (up to and with the edit `upto`, when given). */
export function editedStep<T extends Feature>(features: readonly Feature[], id: string, upto?: string): T | undefined {
const end = upto ? features.findIndex((f) => f.id === upto) + 1 : features.length;
return applyFreeformEdits(features.slice(0, end > 0 ? end : features.length)).find((f) => f.id === id) as T | undefined;
}
+64 -4
View File
@@ -1,9 +1,13 @@
// Parametric document: evaluate expressions (variables) into feature values and
// re-solve sketch constraints, so the document's numbers are always consistent.
import { transformEntity } from "../sketch/edit";
import { dot, toPlane, toWorld } from "../geom";
import { applyRepeats } from "../sketch/repeat";
import { refill } from "../sketch/fill";
import { solveFine } from "../sketch/constraints";
import { evaluate, setVariables } from "../units";
import type { Feature, ProjectDoc } from "./types";
import { evaluate, setUnits, setVariables } from "../units";
import type { Feature, ProjectDoc, SketchEntity } from "./types";
/** Kind of value stored at a path (for units: lengths are mm, angles degrees). */
export function kindOfPath(path: string): "length" | "angle" | "number" {
@@ -13,7 +17,7 @@ export function kindOfPath(path: string): "length" | "angle" | "number" {
// A turn's pivot point is a length (only its angle is an angle): a pivot
// driven by a variable ("p1") was refused as "can't be evaluated".
if (/angle|rot/i.test(last) && !/origin|translate|center/i.test(last)) return "angle";
if (/count|factor|sides|opacity|taper/i.test(last)) return "number";
if (/count|factor|sides|opacity|taper|starts/i.test(last)) return "number";
return "length";
}
@@ -34,6 +38,9 @@ export function setPath(obj: unknown, path: string, value: unknown): void {
/** Recompute every expression-driven value and re-solve constrained sketches (in place). */
export function resolveDoc(doc: ProjectDoc): string[] {
const problems: string[] = [];
// (Its own unit, before anything is read: the app set it after this ran, so a project whose unit had just changed
// was worked out once more in the old one.)
if (doc.units) setUnits(doc.units);
setVariables(doc.variables ?? []);
for (const f of doc.features as Feature[]) {
for (const [path, expr] of Object.entries(f.exprs ?? {})) {
@@ -41,14 +48,42 @@ export function resolveDoc(doc: ProjectDoc): string[] {
if (v === null) problems.push(`${f.name}: "${expr}" can't be evaluated`);
else setPath(f, path, v);
}
// Curves projected from an earlier sketch: put where that sketch's curves are now (it was changed in History,
// or by a variable - a step before this one, already worked out above).
if (f.type === "sketch" && f.refs?.length) {
const next = refreshRefs(f, doc.features as Feature[]);
if (next && !sameNumbers(f.entities, next, 1e-9)) f.entities = next;
}
// A sketch's patterns that follow a count: the count worked out, their copies made again if it is another number.
if (f.type === "sketch" && f.repeats?.length) {
for (const r of f.repeats) {
const v = evaluate(r.countExpr, "number");
if (v === null) problems.push(`${f.name}: "${r.countExpr}" can't be evaluated`);
else if (!(v >= 1)) problems.push(`${f.name}: a pattern's count is ${Math.round(v)} ("${r.countExpr}") - it has to be at least 1`);
else r.count = Math.round(v);
}
const again = applyRepeats(f.entities, f.constraints ?? [], f.repeats);
if (again) ((f.entities = again.entities), (f.constraints = again.constraints));
}
if (f.type === "sketch" && f.constraints?.length) {
for (const c of f.constraints) {
// A point held where X / Y were typed with a variable.
if (c.type === "fix" && c.at && c.atExpr)
c.at = c.at.map((x, i) => {
const e = c.atExpr![i];
if (!e) return x;
const v = evaluate(e, "length");
if (v === null) problems.push(`${f.name}: "${e}" can't be evaluated`);
return v ?? x;
}) as typeof c.at;
if (!c.expr) continue;
const v = evaluate(c.expr, c.prop === "angle" ? "angle" : "length");
if (v === null) problems.push(`${f.name}: "${c.expr}" can't be evaluated`);
else c.value = v;
}
const r = solveFine(f.entities, f.constraints);
// (Curves that are another sketch's stay where that sketch has them: the rest is solved round them.)
const held = new Set((f.refs ?? []).map((x) => x.id));
const r = solveFine(f.entities, f.constraints, held.size ? { fixed: held } : {});
// Can't all be met: the sketch stays as it was rather than being bent out of shape.
// Met already (only rounding noise in the 14th digit): kept exactly as it
// was - the noise changed the step, and every change anywhere (a colour,
@@ -57,10 +92,35 @@ export function resolveDoc(doc: ProjectDoc): string[] {
if (!r.ok) problems.push(`${f.name}: constraints can't all be met`);
else if (!sameNumbers(f.entities, r.entities, 1e-9)) f.entities = r.entities;
}
// Fill patterns follow their shapes, here too: a shape that changed size by a variable or a dimension has its
// pattern made again (it was only made again when the sketch was changed in the sketch tool).
if (f.type === "sketch" && f.fills?.length) {
const filled = refill(f.entities, f.fills);
if (!sameNumbers(f.entities, filled, 1e-9)) f.entities = filled;
}
}
return problems;
}
/**
* A sketch's curves with those it has from an earlier sketch as that sketch has them now, seen from this one's plane
* (the two parallel: the same shapes, moved and turned into it). Null: none could be found again.
*/
function refreshRefs(f: Extract<Feature, { type: "sketch" }>, all: Feature[]): SketchEntity[] | null {
let changed = false;
const out = f.entities.map((e) => {
const ref = f.refs!.find((r) => r.id === e.id);
if (!ref) return e;
const from = all.find((x) => x.id === ref.sketch);
if (!from || from.type !== "sketch" || from === f) return e;
const src = from.entities.find((x) => x.id === ref.entity);
if (!src || Math.abs(dot(from.plane.normal, f.plane.normal)) < 1 - 1e-9) return e;
changed = true;
return { ...transformEntity(src, (uv) => toPlane(f.plane, toWorld(from.plane, uv))), id: e.id, ...(e.construction ? { construction: true } : { construction: undefined }) } as SketchEntity;
});
return changed ? out : null;
}
/** The same structure with every number within `tol` of the other's. */
function sameNumbers(a: unknown, b: unknown, tol: number): boolean {
if (typeof a === "number" && typeof b === "number") return Math.abs(a - b) <= tol;
+46
View File
@@ -0,0 +1,46 @@
// A variable given another name: every formula that uses it says the new name - other variables' values, steps'
// sizes, a sketch's dimensions and the points placed by it. Nothing changes size. (A variable could only be deleted
// and made again under another name, and everything that used it lost its link to it.)
import type { ProjectDoc } from "./types";
import { RESERVED } from "../units";
/** A name as it stands in a formula: not part of a longer name or a number ("w" in "w2", in "2.5e3"). */
const word = (name: string) => new RegExp(`(^|[^A-Za-z0-9_.])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_])`, "g");
/** `from` replaced by `to` wherever it stands as a name in the formula. */
export function renameIn(expr: string, from: string, to: string): string {
return expr.replace(word(from), (_, before: string) => `${before}${to}`);
}
/** Why `to` can't be a variable's name here (null: it can). */
export function nameProblem(doc: ProjectDoc, from: string, to: string): string | null {
if (!/^[a-z_][a-z0-9_]*$/i.test(to) || RESERVED.test(to)) return "Names use letters, digits and _ (not starting with a digit, and not a unit or a function like sin or pi)";
const twin = doc.variables.find((v) => v.name !== from && v.name.toLowerCase() === to.toLowerCase());
if (twin) return twin.name === to ? `There is a variable ${to} already` : `There is a variable ${twin.name} already: ${to} differs only in its capitals`;
return null;
}
/** The variable `from` called `to` from now on, in place. How many formulas were rewritten (-1: no such variable). */
export function renameVariable(doc: ProjectDoc, from: string, to: string): number {
const v = doc.variables.find((x) => x.name === from);
if (!v || from === to) return v ? 0 : -1;
let n = 0;
const re = (expr: string): string => {
const next = renameIn(expr, from, to);
if (next !== expr) n++;
return next;
};
v.name = to;
for (const x of doc.variables) x.expr = re(x.expr);
for (const f of doc.features) {
if (f.exprs) for (const k of Object.keys(f.exprs)) f.exprs[k] = re(f.exprs[k]);
if (f.type !== "sketch") continue;
for (const r of f.repeats ?? []) r.countExpr = re(r.countExpr);
for (const c of f.constraints ?? []) {
if (c.expr) c.expr = re(c.expr);
if (c.atExpr) c.atExpr = c.atExpr.map((e) => (e ? re(e) : e)) as typeof c.atExpr;
}
}
return n;
}
+64 -7
View File
@@ -54,9 +54,18 @@ const LABELS: Record<FeatureType, string> = {
replaceFace: "Replace Face",
repair: "Repair",
fillToPlane: "Fill to Plane",
fill: "Fill",
connect: "Connect",
faceFreeform: "Freeform Face",
freeformEdit: "Edit Freeform",
thread: "Thread",
imprint: "Project as Edge",
wrap: "Wrap & Emboss",
};
/** Steps still being tried out: shown with a BETA tag wherever they appear. */
export const BETA_TYPES: ReadonlySet<string> = new Set(["connect", "faceFreeform", "imprint", "wrap"]);
/**
* Holds the document and its undo/redo history. Every change goes through
* `commit`, which snapshots the previous state, so undo is exact.
@@ -167,8 +176,9 @@ export class DocStore {
/** Unique id + "Extrude 03"-style name for a new feature. */
newIdentity(type: FeatureType, label = LABELS[type]): { id: string; name: string } {
// One past the highest number in use (a step deleted from the middle doesn't free its number for a duplicate).
const nums = this.doc.features.map((f) => (f.name.startsWith(label + " ") ? Number(f.name.slice(label.length + 1)) : NaN)).filter((x) => Number.isFinite(x));
const n = Math.max(0, this.doc.features.filter((f) => f.name.startsWith(label + " ")).length, ...nums) + 1;
// Only "<label> <number>": "Freeform surface 01" isn't one of the "Freeform"s.
const mine = this.doc.features.filter((f) => f.name.startsWith(label + " ") && /^\d+$/.test(f.name.slice(label.length + 1)));
const n = Math.max(0, mine.length, ...mine.map((f) => Number(f.name.slice(label.length + 1)))) + 1;
return { id: newId(type), name: `${label} ${String(n).padStart(2, "0")}` };
}
@@ -181,6 +191,8 @@ export class DocStore {
const before = this.transientBase ?? pack(this.doc);
const next = unpack(pack(this.doc));
mutate(next);
// With a breakpoint: what's after it stays last, so a new step goes in at the breakpoint.
if (next.features.some((f) => f.rolledBack)) next.features = [...next.features.filter((f) => !f.rolledBack), ...next.features.filter((f) => f.rolledBack)];
this.problems = resolveDoc(next);
const wasLive = this.transientBase !== null;
this.transientBase = null;
@@ -218,6 +230,18 @@ export class DocStore {
this.listeners.forEach((fn) => fn());
}
/**
* What the engine worked out for the project as it is (a sketch's curves
* where the edges they follow are now): taken in as it stands - not a step
* to undo, and nothing for the engine to do again.
*/
adopt(mutate: (doc: ProjectDoc) => void): void {
const next = unpack(pack(this.doc));
mutate(next);
this.doc = next;
this.changed(false);
}
add(feature: Feature): void {
this.commit((d) => d.features.push(feature));
}
@@ -323,15 +347,21 @@ export class DocStore {
if (v === this.edits) this.setSaved(true);
}
private changed(): void {
private changed(tell = true): void {
this.edits++;
this.setSaved(false);
this.listeners.forEach((fn) => fn());
if (tell) this.listeners.forEach((fn) => fn());
clearTimeout(this.saveTimer);
this.saveTimer = window.setTimeout(() => {
const v = this.edits;
const text = JSON.stringify(this.doc);
void idbSet("autosave", text).then(() => this.wrote(v));
// (A write that failed is tried again: left, the name's mark said "Saving…" from then on.)
const write = (tries: number): void =>
void idbSet("autosave", text).then(
() => this.wrote(v),
() => tries > 0 && v === this.edits && window.setTimeout(() => write(tries - 1), 2000),
);
write(3);
this.onSaved?.(text);
// The undo steps less eagerly: they're bigger, and only matter after a reload.
clearTimeout(this.historyTimer);
@@ -367,17 +397,44 @@ export function newId(prefix: string): string {
}
export function parseProject(text: string): ProjectDoc {
return migrate(JSON.parse(text));
let raw: unknown;
try {
raw = JSON.parse(text);
} catch {
// (Not the parser's "Expected ',' or '}' at position 47".)
throw new Error("The file is damaged - cut short, or not a project file");
}
return migrate(raw);
}
// ------------------------------------------------------------------ migration
/** Bring any saved project up to the current format. */
/**
* A project file can come from anyone: what the app later puts on the page as a colour is kept to what a colour
* is ("#rrggbb"), and what it uses as a number is a number. Anything else is dropped (the body is the default grey).
*/
function cleanLooks(doc: ProjectDoc): void {
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
if (doc.colors !== undefined) doc.colors = record(doc.colors) ? Object.fromEntries(Object.entries(doc.colors).filter((e): e is [string, string] => typeof e[1] === "string" && hex.test(e[1]))) : undefined;
if (doc.opacity !== undefined) doc.opacity = record(doc.opacity) ? Object.fromEntries(Object.entries(doc.opacity).filter((e): e is [string, number] => typeof e[1] === "number" && Number.isFinite(e[1]))) : undefined;
if (Array.isArray(doc.customMaterials)) for (const m of doc.customMaterials) if (typeof m.color !== "string" || !hex.test(m.color)) m.color = "#9aa3ad";
}
export function migrate(raw: unknown): ProjectDoc {
const out = migrate0(raw);
cleanLooks(out);
return out;
}
function migrate0(raw: unknown): ProjectDoc {
const doc = raw as ProjectDoc & { version: number };
// "tessel" is the format name of files saved before the rename.
if (!doc || (doc.format !== "super" && (doc.format as string) !== "tessel") || !Array.isArray(doc.features)) throw new Error("Not a supergeometry.app project file");
if (!doc || (doc.format !== "super" && (doc.format as string) !== "tessel") || !Array.isArray(doc.features)) throw new Error("Not a superGeometry.app project file");
if (doc.version === 2) return { ...emptyDoc(), ...doc, format: "super" };
// A newer app saved it: read as an old one, it would come out mangled.
if (doc.version > 2) throw new Error("This project was saved by a newer version of the app - reload the page to update");
// v1: rect {a, b}; extrude profiles referenced entity ids.
const sketches = new Map<string, SketchEntity[]>();
+602 -16
View File
@@ -23,15 +23,23 @@ export type SketchEntity = EntityBase &
/** Arc through a (start), m (any point on it) and b (end). */
| { kind: "arc"; a: Vec2; m: Vec2; b: Vec2 }
| { kind: "circle"; center: Vec2; radius: number }
| { kind: "ellipse"; center: Vec2; rx: number; ry: number; rotation: number }
| { kind: "spline"; points: Vec2[]; closed: boolean; mode: "fit" | "control" }
/**
* `sweep` given: a part of the ellipse, from the angle `a0` on it (0 is the
* end of its rx axis) round by `sweep` (radians, + anticlockwise) - what a
* round edge seen at a slant is, with two ends like the edge. Neither: whole.
*/
| { kind: "ellipse"; center: Vec2; rx: number; ry: number; rotation: number; a0?: number; sweep?: number }
/**
* `z`: how far each of its points is off the sketch's plane (mm along the plane's normal; missing, or not one
* for each point: flat). The curve then runs through space - a path for a sweep, a guide for a loft. Everything
* that works in the plane (shapes to extrude, constraints, snapping, DXF) goes by its shadow on the plane.
*/
| { kind: "spline"; points: Vec2[]; closed: boolean; mode: "fit" | "control"; z?: number[] }
| { kind: "rect"; center: Vec2; w: number; h: number; rotation: number }
| { kind: "polygon"; center: Vec2; radius: number; sides: number; angle: number }
| { kind: "polyline"; points: Vec2[]; closed: boolean }
);
export type EntityKind = SketchEntity["kind"];
/** A sketch region, referenced by where it is rather than an index (see regions.ts). */
export interface RegionRef {
c: Vec2;
@@ -58,6 +66,14 @@ export interface FaceRef {
center: Vec3;
normal: Vec3;
area: number;
/** The step that made the face (only faces made by it are matched; none left: it's gone). */
step?: string;
/**
* Which of that step's faces it is: the sketch curve it was made from (a
* side of an extrusion), or the end of it. Where the face is can change
* (the sketch redrawn, the holes moved past each other); this doesn't.
*/
curve?: string;
}
export interface EdgeRef {
@@ -65,8 +81,13 @@ export interface EdgeRef {
mid: Vec3;
dir: Vec3;
length: number;
/** The steps that made the faces either side of it (sorted). */
steps?: string[];
/** Which faces of those steps it lies between (their curves, see FaceRef; sorted). */
curves?: string[];
}
export type ExtrudeSource =
| { kind: "profile"; sketch: string; regions: RegionRef[] }
| { kind: "face"; face: FaceRef };
@@ -76,6 +97,11 @@ interface FeatureBase {
name: string;
/** Suppressed features are skipped during regeneration. */
suppressed?: boolean;
/**
* After the History's breakpoint: off until the breakpoint is removed (the
* model as it was there). These steps are kept last; new ones go before them.
*/
rolledBack?: boolean;
/**
* Parametric values: field path → expression (e.g. "distance": "depth*2").
* The number at that path is recomputed from the expression on every change.
@@ -102,7 +128,9 @@ export type ConstraintType =
| "symmetric"
| "fix"
| "distance"
| "dim";
| "dim"
| "pattern"
| "follow";
/**
* Sketch constraint. Geometry refs: `pts` (points) and `curves` (entity ids).
@@ -117,8 +145,20 @@ export interface SketchConstraint {
prop?: string;
value?: number;
expr?: string;
/** fix: where the point is held. */
/** fix: where the point is held. pattern: the copy's offset (move), or the centre it turns round (turn). */
at?: Vec2;
/** fix: X / Y of `at` typed with a variable ("Ws/2 - S/2"): the point follows it. */
atExpr?: (string | null)[];
/** pattern: "turn" - the copy is the original turned `value` degrees round `at`; else moved by `at`. */
turn?: boolean;
/** dim: put on by Lock (a locked circle keeps its size) - Unlock takes it off with the lock. */
held?: boolean;
/**
* follow: how the second curve is made from the first - its offset by so much, or its mirror image across a line.
* The copy stays that as the original changes. `loose`: a piece of an offset outline, trimmed to meet its
* neighbours - it stays on the original's offset, its ends where its neighbours put them.
*/
how?: { offset?: number; mirror?: [Vec2, Vec2]; loose?: boolean };
}
export interface SketchFeature extends FeatureBase {
@@ -126,10 +166,83 @@ export interface SketchFeature extends FeatureBase {
plane: PlaneDef;
/** When drawn on a body face, the sketch follows that face when it moves. */
attachedTo?: FaceRef;
/**
* Drawn on a construction plane (its id): the sketch follows the plane when
* it moves - its offset typed again, or driven by a variable.
*/
onPlane?: string;
entities: SketchEntity[];
constraints?: SketchConstraint[];
/**
* Offsets of the outline of the face it's drawn on (a lid's lip 2 mm in
* from the rim): made again from the face as it is on every rebuild, so
* they follow it when it changes size. Their curves are "lnk-<id>-<n>".
*/
outlineOffsets?: OutlineOffset[];
/**
* Curves of the sketch that follow an edge of a body (projected from it):
* put where that edge is on every rebuild, the sketch's dimensions to them
* kept - a hole 10 mm from the wall of another part stays 10 mm from it.
* Their ids begin "ref-".
*/
links?: EdgeLink[];
/** What was done in the sketch, in order (shown under it in History); repeats are counted. */
log?: { op: string; n: number }[];
log?: { op: string; n: number; ids?: string[] }[];
/**
* Fill patterns: closed shapes of the sketch filled with lines or small shapes (see sketch/fill.ts). Each one's
* curves are among `entities`, named "fp-<fill id>-<n>", and are made again when the sketch's curves change.
*/
fills?: SketchFill[];
/**
* Patterns whose count is a variable or a formula (see sketch/repeat.ts): their copies - curves named
* "rp-<pattern>-<copy>-<curve>" - are made again when the count comes to another number.
*/
repeats?: SketchRepeat[];
/**
* Curves projected from another sketch: each is that sketch's curve, seen from this one's plane, and is put there
* again whenever that sketch changes (the two planes parallel).
*/
refs?: SketchRef[];
}
/** A curve of a sketch that is a curve of an earlier sketch, projected (see SketchFeature.refs). */
export interface SketchRef {
/** The curve here. */
id: string;
/** The sketch it comes from, and its curve there. */
sketch: string;
entity: string;
}
/** A sketch pattern that follows its count (a pattern made with a plain number is only its copies). */
export interface SketchRepeat {
id: string;
/** The curves repeated. */
src: string[];
kind: "linear" | "circular";
/** How many there are, the originals counted (worked out from `countExpr`). */
count: number;
countExpr: string;
/** Linear: from one to the next. */
step?: Vec2;
/** Circular: the point they go round, and the angle they are spread over (degrees; 360: all the way). */
at?: Vec2;
angle?: number;
}
/** A closed shape of a sketch filled with a pattern (Fill Pattern). */
export interface SketchFill {
id: string;
/** A point inside the shape it fills. */
at: Vec2;
kind: "lines" | "cross" | "zigzag" | "waves" | "dots" | "hex" | "squares" | "diamonds";
/** Lines: how far apart. Shapes: the gap between one and the next (mm). */
spacing: number;
/** The pattern turned by this much (degrees). */
angle: number;
/** Shapes: how big each is. Zigzag, waves: how big a tooth or a wave is (mm). */
size: number;
}
export interface ExtrudeFeature extends FeatureBase {
@@ -137,19 +250,53 @@ export interface ExtrudeFeature extends FeatureBase {
source: ExtrudeSource;
distance: number;
/** auto: join `target` when distance > 0, cut it when < 0; new body without a target. */
mode: "auto" | "new" | "join" | "cut";
mode: "auto" | "new" | "join" | "cut" | "intersect";
target?: string;
/**
* Auto by the way it goes (extrudes made since this was added): with no body
* of its own (drawn on a plane, not on a face) a new body going +, a cut of
* what it runs into going - (a new body if it runs into nothing). Without
* it, as before: a cut of whatever it runs into, either way - kept so that
* projects made then come out as they were.
*/
byDirection?: boolean;
/**
* How big the far end is, as a fraction of the shape (1 or missing: straight
* sides; 0.5: half size; near 0: to a point - a spire, a pyramid, a cone).
*/
taper?: number;
/** Both ways from the shape: `distance` each side (a boss through its middle plane). */
symmetric?: boolean;
/**
* Where it ends: `distance` (missing too), through everything there is
* (`distance` only gives the way: its sign), or up to `to` - a face (flat or
* round, followed as its body changes) or a plane.
*/
extent?: "distance" | "through" | "to";
to?: { face?: FaceRef; plane?: PlaneDef };
/** It starts this far from the shape, along its normal (missing: at the shape). */
start?: number;
/** Degrees the sides lean in (negative: out) towards the far end - a draft, as for a mould. */
draft?: number;
}
export interface EdgeFeature extends FeatureBase {
type: "fillet" | "chamfer";
edges: EdgeRef[];
radius: number;
/** Chamfer, Two-Distance: the second distance (along the other face); missing: equal distances. */
distance2?: number;
/** Chamfer, Two-Distance: the first distance goes along the other face of each edge.
* Fillet, Variable: the start and end radii swap ends. */
flip?: boolean;
/** Fillet, Variable: the radius at each edge's other end (it runs evenly from radius to this); missing: one radius. */
radius2?: number;
/** Fillet: the sizes are chord widths (straight across the round, face to face), not radii. */
chord?: boolean;
/** Fillet: a smooth (G2) blend, its bend easing in from flat at both faces, not a circular round. */
g2?: boolean;
/** Fillet: where three or more rounded edges meet, they stop this far from the corner and a smooth patch joins them (0 or missing: the usual corner). */
setback?: number;
}
export interface BooleanFeature extends FeatureBase {
@@ -161,11 +308,31 @@ export interface BooleanFeature extends FeatureBase {
keepTarget?: boolean;
/** Subtract / Intersect: the bodies it was changed with stay. */
keepTools?: boolean;
/** Subtract: the gap (mm) the cut leaves between the bodies (missing: none, they meet). */
clearance?: number;
/**
* Subtract: which bodies give way - the body (missing: the usual subtract),
* the bodies it's subtracted with (each cut by the body, which stays), or
* all of them (each cut by every other, half the gap each).
*/
cutFrom?: "body" | "tools" | "all";
/**
* Patterns it used whole (`<pattern step>:<original body>`): the original and
* every copy there was when it was made. They stay whole when the pattern's
* count changes. Worked out by the engine the first time it runs (see bodyList).
*/
whole?: string[];
}
export interface DeleteFeature extends FeatureBase {
type: "delete";
bodies: string[];
/**
* Patterns it used whole (`<pattern step>:<original body>`): the original and
* every copy there was when it was made. They stay whole when the pattern's
* count changes. Worked out by the engine the first time it runs (see bodyList).
*/
whole?: string[];
}
/**
@@ -180,7 +347,7 @@ export interface AxisRef {
export type PathRef = { kind: "sketch"; sketch: string; entities: string[] } | { kind: "edges"; edges: EdgeRef[] };
type BodyMode = "auto" | "new" | "join" | "cut";
type BodyMode = "auto" | "new" | "join" | "cut" | "intersect";
export interface RevolveFeature extends FeatureBase {
type: "revolve";
@@ -200,6 +367,16 @@ export interface SweepFeature extends FeatureBase {
path: PathRef;
mode: BodyMode;
target?: string;
/** The profile's size at the path's end, as a multiple of its size at the start (1 = same size). */
scale?: number;
/** Degrees the profile turns round the path from start to end, evenly along it (0 or missing: none). */
twist?: number;
/** Where the profile starts: where it is (auto), or moved onto the path's nearer end, square to it (start). */
position?: "auto" | "start";
/** The profile turns with the path (normal, the default) or keeps facing the same way (parallel). */
orientation?: "normal" | "parallel";
/** At a sharp corner of the path: rounded (the default) or mitred. */
corner?: "round" | "mitre";
}
export interface LoftFeature extends FeatureBase {
@@ -208,6 +385,20 @@ export interface LoftFeature extends FeatureBase {
ruled: boolean;
mode: BodyMode;
target?: string;
/** Goes on from the last profile back round to the first (a ring, no ends). */
closed?: boolean;
/** A curve the body follows from profile to profile (its centre line). */
guide?: PathRef;
/** Guide curves along its sides: each runs through every profile, and the sides follow them. */
rails?: PathRef[];
/** Connection points: which point of each profile joins which (one point per profile, in `sections` order). */
connections?: Vec3[][];
/** How the body leaves the first profile and meets the last: straight out of it (G1, tangent) or smoother still (G2); missing: free. */
startContinuity?: "g1" | "g2";
endContinuity?: "g1" | "g2";
/** How far that pull reaches (1: a quarter of the way to the next profile). */
startWeight?: number;
endWeight?: number;
}
export interface ShellFeature extends FeatureBase {
@@ -229,6 +420,11 @@ export interface TransformFeature extends FeatureBase {
* freeform copies become freeforms of their own.
*/
link?: boolean;
/**
* A pattern of a hole (its round wall picked): the hole is cut again at each place of the pattern, in the body it
* is in - the body itself is not copied. `bodies` is that one body.
*/
hole?: FaceRef;
op:
| { kind: "move"; translate: Vec3; rotate?: { origin: Vec3; axis: Vec3; angle: number } }
/** `ref`: scaled by reference - the two points picked (center is the first), the distance typed between them. */
@@ -244,6 +440,12 @@ export interface SplitFeature extends FeatureBase {
type: "split";
body: string;
plane: PlaneDef;
/** More planes to cut along at once. */
planes?: PlaneDef[];
/** Bodies it's cut with, along their surfaces (they stay as they are). */
tools?: string[];
/** Cut only with the tools: `plane` isn't one. */
noPlane?: boolean;
}
/** Construction plane. Optionally follows a face (offset along its normal). */
@@ -262,8 +464,12 @@ export interface AxisFeature extends FeatureBase {
type: "axis";
origin: Vec3;
dir: Vec3;
/** What it was made from (its icon): square to a face, along an edge, a round face's middle, two points, two planes. */
kind?: AxisKind;
}
export type AxisKind = "face" | "edge" | "round" | "2pt" | "planes";
/** A body imported from a file. The file content travels inside the project. */
export interface ImportFeature extends FeatureBase {
type: "import";
@@ -271,6 +477,11 @@ export interface ImportFeature extends FeatureBase {
fileName: string;
/** Base64 of the file. */
data: string;
/**
* Each solid in the file is a body of its own (the first has this step's id, the others "<id>:1", "<id>:2"...).
* Missing (files put in before this): all of them one body, as they were - what was built on that body stays.
*/
apart?: boolean;
}
/** A reference image placed on a plane (for tracing). */
@@ -316,7 +527,7 @@ export interface MoveFaceFeature extends FeatureBase {
*/
export interface FreeformFeature extends FeatureBase {
type: "freeform";
cage: { verts: Vec3[]; faces: [number, number, number, number][] };
cage: { verts: Vec3[]; faces: [number, number, number, number][]; creases?: [number, number][] };
/** Made as an open surface on purpose (a sheet): no "not closed" warning. */
surface?: boolean;
/** An open freeform becomes a solid this thick (0 / missing: stays a surface). */
@@ -327,6 +538,19 @@ export interface FreeformFeature extends FeatureBase {
symmetry?: { origin: Vec3; normal: Vec3 };
}
/**
* Edit Freeform done on a freeform (or a Freeform Face step) made earlier: its
* new cage, a step of its own in History. The shape is the earlier step's with
* this put in (see applyFreeformEdits): delete or roll back this step and the
* shape is as it was before the edit.
*/
export interface FreeformEditFeature extends FeatureBase {
type: "freeformEdit";
/** The freeform / Freeform Face step it edits. */
target: string;
patch: Partial<Pick<FreeformFeature, "cage" | "surface" | "thickness" | "thickSide" | "symmetry">> & { grid?: number; more?: FaceRef[] };
}
/**
* Scale one flat face within its own plane (factors along its u and v axes);
* the flat faces around it tilt to follow its edges.
@@ -371,6 +595,11 @@ export interface ThreadFeature extends FeatureBase {
pitch: number;
/** Left-handed (turns the other way). */
left?: boolean;
/**
* How many threads run side by side (missing: 1). `pitch` stays the distance from one crest to the next; one turn
* then moves a nut `starts` pitches along - a jar's lid, on in a quarter turn.
*/
starts?: number;
/** The face as it was picked (for the panel when editing: the face itself is threaded by then). */
round?: { r: number; hole: boolean };
}
@@ -380,18 +609,108 @@ export interface ThreadFeature extends FeatureBase {
* removed, faces fixed and merged, inside-out solids turned - the shape
* itself stays. Turns loose faces (an imported mesh or STEP surface) into a solid.
*/
/**
* Connect: a smooth freeform bridge from one face to another (of two bodies,
* or of one), made again from the faces on every rebuild. Like an extrude it
* joins the bodies (Add / Auto), cuts its way through them (Cut), or is a
* body of its own (New body).
*/
/**
* A face of a body made freeform: its edges stay where they are, and the face
* becomes a smooth surface through a grid of points over it - some of them
* pulled out of it or pushed in.
*/
export interface FaceFreeformFeature extends FeatureBase {
type: "faceFreeform";
face: FaceRef;
/**
* More faces of the body, side by side with `face`, made one smooth
* surface with it (no edge left where they met).
*/
more?: FaceRef[];
/**
* The cage shaping it, laid over the face: points relative to the face's
* middle (so it follows the face when an earlier step moves it). Its border
* runs round the face's edge and stays there; the inside points are moved.
*/
cage: { verts: Vec3[]; faces: [number, number, number, number][] };
/** How many cells across the cage was laid (3, 5, 7, 9). */
grid?: number;
}
export interface ConnectFeature extends FeatureBase {
type: "connect";
faces: [FaceRef, FaceRef];
mode: "auto" | "new" | "join" | "cut";
/** How far the bridge bows out of each face (1: plain; 0: straight across). */
bulge?: number;
/** Its outline, as a fraction of the faces' (1: their own edges). */
size?: number;
/** A curve the bridge follows from one face to the other (a sketch spline, say). */
guide?: PathRef;
}
export interface RepairFeature extends FeatureBase {
type: "repair";
bodies: string[];
}
/**
* Project as Edge: curves drawn onto a body's faces, the faces split along
* them - a sketch's shapes along its normal (onto the faces seen from it), or
* edges along a face's normal (onto that face).
*/
export interface ImprintFeature extends FeatureBase {
type: "imprint";
body: string;
source?: ExtrudeSource;
edges?: EdgeRef[];
/** With edges: the face they are projected onto. */
face?: FaceRef;
}
/**
* Wrap & Emboss: a sketch's shapes wrapped round a round face (lengths kept),
* raised from it (height > 0) or sunk into it (height < 0).
*/
export interface WrapFeature extends FeatureBase {
type: "wrap";
source: ExtrudeSource;
face: FaceRef;
height: number;
}
/**
* Fill: a surface stretched over a network of curves - the boundary (sketch
* curves and body edges that close a loop) and guide curves inside it that
* it passes through.
*/
export interface FillFeature extends FeatureBase {
type: "fill";
boundary: PathRef[];
guides?: PathRef[];
/** Along body edges: just touching (G0), tangent to the face there (G1) or curving on with it (G2). Sketch curves are always G0. */
continuity?: "g0" | "g1" | "g2";
/** One edge's own continuity, by fillEdgeKey (missing: `continuity`). */
edgeContinuity?: Record<string, "g0" | "g1" | "g2">;
}
/** Which boundary edge of a Fill an edge continuity is for. */
export const fillEdgeKey = (r: EdgeRef): string => `${r.body}@${r.mid.map((x) => x.toFixed(3)).join(",")}`;
export type Feature =
| FillFeature
| ImprintFeature
| WrapFeature
| ConnectFeature
| FaceFreeformFeature
| FillToPlaneFeature
| ThreadFeature
| RepairFeature
| ScaleFaceFeature
| ReplaceFaceFeature
| FreeformFeature
| FreeformEditFeature
| DeleteGeomFeature
| MoveFaceFeature
| SketchFeature
@@ -457,12 +776,262 @@ export interface ProjectDoc {
colors?: Record<string, string>;
/** See-through bodies: opacity 0–1 by body id (missing: solid). */
opacity?: Record<string, number>;
/** BIM: the material of each body (a material id, by body id). */
materials?: Record<string, string>;
/** BIM: the project's own materials (beside the library's). */
customMaterials?: MaterialDef[];
/** BIM: what the title block of the technical sheet and the drawings says. */
info?: ProjectInfo;
/** BIM: the project's one drawing, as projects saved before there could be several had it (read as the first of `drawings`). */
drawing?: DrawingOptions;
/** BIM: the project's drawings, each its own sheet. */
drawings?: DrawingOptions[];
/** Assemblies: how the bodies are held together (see assembly/joints.ts). */
joints?: import("../assembly/joints").Joint[];
/** Assemblies: the body that stands still (missing: the first of each group of joined bodies). */
ground?: string;
/** Assemblies: where the parts were left - each joint's value by its id (0, or missing: as modelled), and how far they are pulled apart (0 to 1). */
pose?: { values: Record<string, number>; exploded?: number };
}
/** The body colours offered by the Color tool (first = default). */
/** The drawing sheet: paper size, projection method, scale (missing: the largest that fits), what it shows. */
export interface DrawingOptions {
/** Which drawing of the project it is. */
id?: string;
/** The sheet's title (missing: the project's name). */
title?: string;
size?: "A4" | "A3" | "A2" | "A1" | "A0" | "ANSI A" | "ANSI B" | "ANSI C" | "ANSI D" | "ANSI E";
portrait?: boolean;
angle?: "first" | "third";
scale?: number;
hidden?: boolean;
/** Old projects: the isometric view on or off (now in `views`). */
iso?: boolean;
/** Which views are drawn (missing: all four). */
views?: { front?: boolean; top?: boolean; side?: boolean; iso?: boolean };
/** The bodies drawn (missing: every body shown). */
bodies?: string[];
/** simple / table (with the parts list) / block (with a revision table): a block in the corner; horizontal: a strip along the bottom; vertical: a column down the right, with a revision table. */
titleBlock?: "none" | "border" | "simple" | "table" | "block" | "horizontal" | "vertical";
/** The revision table (Block and Vertical title blocks). */
revisions?: DrawingRevision[];
dateFormat?: "iso" | "dmy" | "mdy";
units?: "mm" | "cm" | "m" | "in";
/** Decimals shown in dimensions. */
precision?: number;
/** Decimals shown in angles. */
anglePrecision?: number;
comma?: boolean;
/** Line widths, mm. */
lines?: { visible?: number; hidden?: number; dims?: number; center?: number; section?: number };
balloons?: boolean;
/** Item numbers moved by hand: where each one's circle is (mm on the paper), by the part it numbers. */
balloonAt?: Record<string, [number, number]>;
/** The overall sizes dimensioned by themselves. */
overall?: boolean;
/** What was changed on an overall size, by its id (overall-width, overall-height, overall-depth): where it sits, its text, taken off. */
overallDims?: Record<string, OverallEdit>;
/** Views moved by hand: mm on the paper, by view. */
moved?: Record<string, [number, number]>;
dims?: DrawingDim[];
notes?: DrawingNote[];
/** Views added by hand: base views and projections. */
extra?: DrawingView[];
/** The isometric view's own scale (missing: picked to fit). */
isoScale?: number;
/** Pictures put on the sheet (a logo, a photo). */
images?: DrawingImage[];
sections?: DrawingSection[];
details?: DrawingDetail[];
/** Centre marks and centrelines. */
marks?: DrawingMark[];
}
/**
* A section view (A-A): the model cut along a line drawn on another view,
* seen square to the cut, lined up with that view.
*/
export interface DrawingSection {
id: string;
letter: string;
/** The view the cut line is on, and the line (that view's coordinates: model mm, y down). */
view: string;
a: [number, number];
b: [number, number];
/** The way the eye looks, on that view (a unit vector square to the line): where its arrows point. */
look: [number, number];
/** How far its middle is from its view's edge (mm on the paper). */
gap: number;
}
/** Which way a base view looks at the model: a side, or an isometric corner (front/back, right/left). */
export type ViewOrient = "front" | "back" | "top" | "bottom" | "left" | "right" | "iso-fr" | "iso-fl" | "iso-br" | "iso-bl";
/**
* A view added by hand: a base view (seen from any side or corner, put
* anywhere), or one projected from another view - square on, lined up with
* it, or from a corner (an isometric one).
*/
export interface DrawingView {
id: string;
/** A base view: the way it looks. */
orient?: ViewOrient;
/** A projection: the view it is projected from, and the way it goes from it on the paper (one of eight). */
view?: string;
dir?: [number, number];
/** Projected square on: how far its middle is from its view's edge (mm on the paper). */
gap?: number;
/** A base view or an isometric projection: where its middle is on the paper. */
at?: [number, number];
/** Its own scale (missing: the sheet's; a lined-up projection always has its view's). */
scale?: number;
}
/** A picture on the sheet (mm on the paper), kept as a data URL. */
export interface DrawingImage {
id: string;
x: number;
y: number;
w: number;
h: number;
src: string;
}
/** A detail view (B): a circle of another view drawn bigger. */
export interface DrawingDetail {
id: string;
letter: string;
view: string;
/** The circle (the view's coordinates). */
c: [number, number];
r: number;
/** Its scale (missing: twice its view's). */
scale?: number;
/** Where its middle is on the paper. */
at: [number, number];
}
/** A centre mark on a circle, or a centreline from a to b (a view's coordinates). */
export interface DrawingMark {
id: string;
view: string;
/** cross: an intersection mark - where two edges would meet (a corner rounded off), `c`, from the near ends `a` and `b`. */
kind: "center" | "line" | "cross";
c?: [number, number];
r?: number;
a?: [number, number];
b?: [number, number];
}
/** An overall size moved or given text by hand (the rest follows the model). */
export interface OverallEdit extends DimText {
offset?: number;
slide?: number;
/** Taken off (Overall sizes, switched off and on, brings it back). */
hidden?: boolean;
}
/** What a dimension adds to its value: text before and after, a tolerance. */
export interface DimText {
prefix?: string;
suffix?: string;
/** Symmetrical (± up), deviation (+up / -down), limits (the largest and smallest sizes), basic (boxed). */
tol?: { kind: "sym" | "dev" | "limits" | "basic"; up?: number; down?: number };
}
/**
* A dimension put on a drawing: its points in its view's own coordinates
* (model mm, y down), so it stays on its edge at any scale or place of the view.
*/
export interface DrawingDim extends DimText {
id: string;
view: string;
/** Angle: from ray c→a to ray c→b, its arc `offset` mm (on the paper) from c. */
kind: "length" | "distance" | "radius" | "diameter" | "angle";
a: [number, number];
b?: [number, number];
/** Circle (radius, diameter): its centre and radius. */
c?: [number, number];
r?: number;
/** How far out from what it measures (mm on the paper); for a circle, past it. */
offset: number;
/** Circle: the leader's direction (radians). */
angle?: number;
/** A length or distance: its value moved along its line from the middle (mm on the paper, towards b); past an end, the line runs out to it. */
slide?: number;
/** An arc's angle: a point on the arc, so the angle goes round the way the arc does (past 180° too). */
through?: [number, number];
/** A min-max distance: the nearest and the farthest points of the two things it was measured between (a and b are one pair). */
minmax?: { min: [[number, number], [number, number]]; max: [[number, number], [number, number]] };
/** A min-max distance showing the farthest. */
max?: boolean;
}
/** A note on the sheet (mm on the paper). */
export interface DrawingNote {
id: string;
x: number;
y: number;
text: string;
/** How tall its letters are, mm on the paper (missing: 3.5). */
size?: number;
/** What it points at: a point on a view (that view's coordinates), its leader drawn to it. */
to?: { view: string; p: [number, number] };
}
/** A row of a drawing's revision table. */
export interface DrawingRevision {
rev: string;
note?: string;
date?: string;
by?: string;
}
/** The title block: who made it, for whom, which revision. */
export interface ProjectInfo {
author?: string;
company?: string;
number?: string;
revision?: string;
}
/**
* A real material (see src/bim/materials.ts). Strengths in MPa, stiffness in
* GPa, density in kg/m³, conductivity in W/(m·K), specific heat in J/(kg·K),
* expansion in µm/(m·K). What isn't known is left out.
*/
export interface MaterialDef {
id: string;
name: string;
category: string;
/** The standard the grade is defined in (or the data comes from). */
standard?: string;
note?: string;
/** How a body of it shows: "#rrggbb", and how see-through (glass). */
color: string;
opacity?: number;
density: number;
youngs?: number;
poisson?: number;
yield?: number;
tensile?: number;
compressive?: number;
bending?: number;
expansion?: number;
conductivity?: number;
specificHeat?: number;
/** Elongation at break, %. */
elongation?: number;
/** Melting point (a metal's: where it starts to melt), °C. */
melting?: number;
/** The warmest it is used at for long (a plastic's: about where it starts to soften under load), °C. */
maxTemp?: number;
}
/** The body colours offered by the Color tool: seven, Custom the eighth (no Grey - a body is grey until given one; a tap on its lit colour makes it grey again). Bodies given another before keep it (shown as Custom). */
export const DEFAULT_BODY_COLOR = "#b9bec7";
export const BODY_COLORS: { name: string; hex: string }[] = [
// Soft, muted tones (easy on the eyes, still easy to tell apart).
{ name: "Grey", hex: "#b9bec7" },
{ name: "Red", hex: "#b9726b" },
{ name: "Orange", hex: "#c29069" },
{ name: "Yellow", hex: "#c4b277" },
@@ -470,8 +1039,6 @@ export const BODY_COLORS: { name: string; hex: string }[] = [
{ name: "Teal", hex: "#71a39c" },
{ name: "Blue", hex: "#7c98c2" },
{ name: "Violet", hex: "#9a8bc0" },
{ name: "Pink", hex: "#bb8aa9" },
{ name: "Brown", hex: "#93806e" },
];
/** The first, brighter palette → its softer version (projects saved before keep their choice). */
@@ -494,10 +1061,11 @@ export function bodyColor(hex: string | undefined): string | undefined {
/** The see-through levels offered next to Color (1 = solid). */
export const BODY_OPACITY: { name: string; value: number }[] = [
// (Named by how see-through, as the Transparency list says: 25% lets a little through.)
{ name: "Solid", value: 1 },
{ name: "75%", value: 0.75 },
{ name: "25%", value: 0.75 },
{ name: "50%", value: 0.5 },
{ name: "25%", value: 0.25 },
{ name: "75%", value: 0.25 },
];
export interface HistoryGroup {
@@ -519,3 +1087,21 @@ export interface ItemFolder {
export function emptyDoc(): ProjectDoc {
return { format: "super", version: 2, name: "Untitled", features: [], variables: [], views: [], units: "mm", hidden: [], pins: [], names: {} };
}
/** A sketch curve that follows a body's edge (see SketchFeature.links). */
export interface EdgeLink {
/** The curve. */
id: string;
edge: EdgeRef;
}
/** An offset of a face outline in a sketch on that face (see SketchFeature.outlineOffsets). */
export interface OutlineOffset {
id: string;
/** Positive grows a closed outline outward, negative goes inside it. */
distance: number;
/** Where the outline was tapped (sketch coordinates): the loop nearest it is offset. */
at: Vec2;
/** Just the edge nearest `at`, not the whole loop it is part of (Offset Edge's "Edge"). */
single?: boolean;
}
+173
View File
@@ -0,0 +1,173 @@
// The project's unit changed: every formula keeps the size it had.
//
// A plain number in a formula is in the unit in use ("160" is 160 mm, or 160 in). So with the unit changed from mm to
// inches, a variable od = 160 was 160 inches from then on, and the whole model 25 times its size. Here each formula
// that would change is written so that it does not: its plain lengths get the unit they were typed in ("160 mm",
// "od / 2 + 5 mm"). What is no length - a count, a factor, an angle - is left as it is.
import { kindOfPath } from "./params";
import { namesIn } from "./varAnchors";
import type { ProjectDoc, Units, Variable } from "./types";
import { UNIT_MM, valueAt } from "../units";
const NUM = String.raw`(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`;
/** Rewrites the project's formulas for a change of unit (in place). Returns how many it could not keep as they were. */
export function keepSizes(doc: ProjectDoc, from: Units, to: Units): { changed: number; lost: number } {
const out = { changed: 0, lost: 0 };
if (from === to) return out;
const sFrom = UNIT_MM[from];
const sTo = UNIT_MM[to];
const old: Variable[] = doc.variables.map((v) => ({ ...v }));
const vars = doc.variables;
const same = (a: number, b: number) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
/** How a formula's size goes with the unit in use: 0 not at all, 1 in step with it; NaN neither (or it can't be read). */
const degree = (text: string): number => {
const a = valueAt(text, sFrom, vars);
const b = valueAt(text, sFrom * 2, vars);
if (a === null || b === null) return NaN;
return same(a, b) ? 0 : same(b, 2 * a) ? 1 : NaN;
};
/** One part of a sum, its size fixed to the unit it was typed in. */
const pin = (term: string): string | null => {
const want = valueAt(term, sFrom, vars);
if (want === null) return null;
// (The spaces round it stay where they were.)
const [, pre, core, post] = /^(\s*)(.*?)(\s*)$/s.exec(term)!;
const lead = new RegExp(String.raw`^(-?\s*${NUM})(\s*(?:[*/].*)?)$`, "is").exec(core);
const tries = [...(lead ? [`${lead[1]} ${from}${lead[2]}`] : []), `(${core}) ${from}`];
for (const t of tries) {
const got = valueAt(t, sTo, vars);
if (got !== null && same(got, want) && degree(t) === 0) return pre + t + post;
}
return null;
};
/** A formula with each part that goes with the unit fixed to it - into its brackets where a part is mixed. */
const fixed = (expr: string): string => {
if (degree(expr) === 0) return expr;
return terms(expr)
.map((t) => {
if (t.op) return t.text;
const d = degree(t.text);
if (d === 0) return t.text;
const whole = d === 1 ? pin(t.text) : null;
if (whole) return whole;
// Mixed (a length with its unit beside a plain one, inside brackets): each bracket's own parts.
const inner = brackets(t.text, fixed);
return degree(inner) === 1 ? (pin(inner) ?? inner) : inner;
})
.join("");
};
const rewrite = (expr: string, was: number | null): string => {
if (was === null) return expr;
const now = valueAt(expr, sTo, vars);
if (now !== null && same(now, was)) return expr;
const next = fixed(expr);
const got = valueAt(next, sTo, vars);
if (got !== null && same(got, was)) {
out.changed++;
return next;
}
// (Not a sum of plain parts - "a * b" of two lengths: the whole of it, if that is in step with the unit.)
const whole = degree(expr) === 1 ? pin(expr) : null;
if (whole) {
out.changed++;
return whole;
}
out.lost++;
return expr;
};
// What each formula comes to now, before anything is touched.
const before = new Map<string, number | null>();
for (const v of old) before.set(`v:${v.name}`, valueAt(v.expr, sFrom, old));
// Variables used as a count, a factor or an angle somewhere (and the ones those are made from) stay as they are:
// "6" with a unit after it is no count. Where one of them is used as a length, that place is fixed instead.
const plain = new Set<string>();
const mark = (expr: string) => {
for (const n of namesIn(expr)) {
if (plain.has(n)) continue;
const v = old.find((x) => x.name === n);
if (!v) continue;
plain.add(n);
mark(v.expr);
}
};
for (const f of doc.features) {
for (const [path, expr] of Object.entries(f.exprs ?? {})) if (kindOfPath(path) !== "length") mark(expr);
if (f.type === "sketch") for (const c of f.constraints ?? []) if (c.expr && c.prop === "angle") mark(c.expr);
}
// Variables first, each after the ones it is made from (so those are already as they will be).
const done = new Set<string>();
for (let pass = 0; pass <= vars.length; pass++) {
for (const v of vars) {
if (done.has(v.name)) continue;
const needs = namesIn(v.expr).filter((n) => n !== v.name && vars.some((x) => x.name === n));
if (pass < vars.length && needs.some((n) => !done.has(n))) continue;
done.add(v.name);
if (!plain.has(v.name)) v.expr = rewrite(v.expr, before.get(`v:${v.name}`) ?? null);
}
}
// Then every size that follows a formula.
const length = (expr: string) => rewrite(expr, valueAt(expr, sFrom, old));
for (const f of doc.features) {
for (const [path, expr] of Object.entries(f.exprs ?? {})) if (kindOfPath(path) === "length") f.exprs![path] = length(expr);
if (f.type !== "sketch") continue;
for (const c of f.constraints ?? []) {
if (c.expr && c.prop !== "angle") c.expr = length(c.expr);
if (c.atExpr) c.atExpr = c.atExpr.map((e) => (e ? length(e) : e));
}
}
return out;
}
/** A formula as the parts of its sum: each part, and the + or - between them (brackets kept whole). */
function terms(expr: string): { text: string; op: boolean }[] {
const out: { text: string; op: boolean }[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < expr.length; i++) {
const c = expr[i];
if (c === "(") depth++;
else if (c === ")") depth--;
else if ((c === "+" || c === "-") && depth === 0) {
const before = expr.slice(start, i).trimEnd();
// A sign, not a sum: at the start, after another operator, or the exponent of 1e-3.
if (!before || /[-+*/^(]$/.test(before) || (/\de$/i.test(before) && /^\d/.test(expr.slice(i + 1)))) continue;
out.push({ text: expr.slice(start, i), op: false }, { text: c, op: true });
start = i + 1;
}
}
out.push({ text: expr.slice(start), op: false });
return out;
}
/**
* A part of a formula with what is inside each of its outermost brackets put through `each` - the values of min(...)
* and max(...) one by one.
*/
function brackets(text: string, each: (inner: string) => string): string {
let out = "";
let depth = 0;
let start = 0;
let many = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (c === "(") {
if (depth++ === 0) {
many = /\b(min|max)\s*$/i.test(text.slice(0, i));
out += text.slice(start, i + 1);
start = i + 1;
}
} else if (c === ")") {
if (--depth === 0) {
out += each(text.slice(start, i));
start = i;
}
} else if ((c === "," || c === ";") && depth === 1 && many) {
out += each(text.slice(start, i)) + c;
start = i + 1;
}
}
return out + text.slice(start);
}
+25 -4
View File
@@ -63,7 +63,10 @@ export function usesOf(features: readonly Feature[]): Map<string, VarUse[]> {
if (f.suppressed) continue;
for (const [path, expr] of Object.entries(f.exprs ?? {})) for (const n of namesIn(expr)) add1(n, { feature: f.id, where: path, kind: kindOfPath(path), expr });
if (f.type === "sketch")
for (const c of f.constraints ?? []) if (c.expr) for (const n of namesIn(c.expr)) add1(n, { feature: f.id, where: c.id, kind: c.prop === "angle" ? "angle" : "length", expr: c.expr! });
for (const c of f.constraints ?? []) {
if (c.expr) for (const n of namesIn(c.expr)) add1(n, { feature: f.id, where: c.id, kind: c.prop === "angle" ? "angle" : "length", expr: c.expr! });
for (const x of c.atExpr ?? []) if (x) for (const n of namesIn(x)) add1(n, { feature: f.id, where: c.id, kind: "length", expr: x });
}
}
return out;
}
@@ -273,7 +276,8 @@ export function useSpot(u: VarUse, features: readonly Feature[], world: AnchorWo
if (!f) return null;
if (f.type === "sketch") {
const c = f.constraints?.find((x) => x.id === u.where);
const at = c && dimSpot(c, f.entities);
// (A point placed by it - X typed as "pcd / 2": at that point. It had no tag at all.)
const at = c && (dimSpot(c, f.entities) ?? (c.type === "fix" && c.at ? c.at : null));
if (!at) return null;
const p = toWorld(world.sketchPlanes[f.id] ?? f.plane, at);
// A construction line is no part of a body: it stays where it was drawn
@@ -305,7 +309,12 @@ export function useSpot(u: VarUse, features: readonly Feature[], world: AnchorWo
const plane = world.planes?.find((x) => x.id === f.id);
if (plane) return plane.plane.origin;
const b = bodyOf(f);
return b ? bodyMiddle(world, b) : null;
const mid = b ? bodyMiddle(world, b) : null;
if (mid) return mid;
// A pattern whose copies have since gone into another body (holes cut with them): on what it turns about, or at
// its first copy's place - the count of a ring of holes had no tag.
if (f.type === "transform" && f.op.kind === "circular") return f.op.axis.origin;
return null;
}
export interface VarTag {
@@ -326,7 +335,7 @@ export interface VarTag {
/** One tag per variable. */
export function variableTags(variables: readonly Variable[], features: readonly Feature[], world: AnchorWorld): VarTag[] {
const uses = usesOf(features);
return variables.map((v) => {
const tags: VarTag[] = variables.map((v) => {
// Its tag at the use that says most where it acts: a turn's pivot, then a
// step's value, then a dimension of the shape, then a construction line -
// where it's the value itself before where it's part of a formula.
@@ -349,4 +358,16 @@ export function variableTags(variables: readonly Variable[], features: readonly
const to = variables.filter((w) => madeFrom(w.name, variables).includes(v.name)).map((w) => w.name);
return { name: v.name, marks, to, kind: kindOfVariable(v.name, variables, uses), at: spots[0] ?? null, others: spots.slice(1), from: madeFrom(v.name, variables) };
});
// One that only other variables are made from (a wall that the hub's size is worked out from) has no place of its
// own: it goes by the first of those that has one (the tags there fan out), so it can be tapped like the rest.
for (let pass = 0; pass < tags.length; pass++) {
let moved = false;
for (const t of tags) {
if (t.at) continue;
const by = t.to.map((n) => tags.find((x) => x.name === n)).find((x) => x?.at);
if (by?.at) (t.at = by.at), (moved = true);
}
if (!moved) break;
}
return tags;
}
+325 -50
View File
@@ -11,9 +11,17 @@ export interface Cage {
verts: Vec3[];
/** Quads, as vertex indices in order around the face. */
faces: [number, number, number, number][];
/**
* Sharp edges: cage edges the surface keeps a crease along instead of
* rounding over - it follows them as an open border is followed (a smooth
* curve through the edge's points), and where three or more meet, or one
* ends at a corner of the border, the point is a corner. One on its own,
* ending in the middle of the surface, fades out there.
*/
creases?: [number, number][];
}
export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere";
export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere" | "torus";
// ------------------------------------------------------------- primitives
@@ -95,6 +103,32 @@ export function cylinderCage(d = 40, h = 40, rows = 2, at: Vec3 = [0, 0, 0]): Ca
return { verts, faces };
}
/**
* A ring (a torus) lying on `at`: `d` across the outside, `t` thick (its
* tube), 8 faces round the ring and 2·rows round the tube (4 at least).
* Every point has four faces round it, so it comes out smooth all over.
*/
export function torusCage(d = 40, t = 12, rows = 2, at: Vec3 = [0, 0, 0]): Cage {
const N = 8;
const M = Math.max(4, 2 * Math.round(rows));
const R = Math.max(0.01, (d - t) / 2);
// A cage a little bigger round the tube than the tube: subdivision shrinks it.
const r = (t / 2) * (M <= 4 ? 1.3 : 1.12);
const verts: Vec3[] = [];
for (let i = 0; i < N; i++)
for (let j = 0; j < M; j++) {
const a = (i / N) * Math.PI * 2;
const b = (j / M) * Math.PI * 2;
const w = R + Math.cos(b) * r;
verts.push([at[0] + Math.cos(a) * w, at[1] + Math.sin(a) * w, at[2] + t / 2 + Math.sin(b) * r]);
}
const id = (i: number, j: number) => (i % N) * M + (j % M);
const faces: Cage["faces"] = [];
// (Wound so the normals point out of the tube.)
for (let i = 0; i < N; i++) for (let j = 0; j < M; j++) faces.push([id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)]);
return { verts, faces };
}
/**
* Close an 8-point rim with a 2×2 grid of quads: its corners are rim points
* 1, 3, 5, 7, its edge midpoints rim 0, 2, 4, 6, and a new centre point.
@@ -120,6 +154,7 @@ function capGrid(verts: Vec3[], faces: Cage["faces"], R: number, N: number, z: n
export function shapeCage(kind: Exclude<CagePrimitive, "plane">, size: Vec3, rows = 2): Cage {
const r = Math.max(1, Math.round(rows));
if (kind === "box") return boxCage(size, r);
if (kind === "torus") return torusCage(size[0], size[2], r);
if (kind === "sphere") {
const c = sphereCage(size[0]);
return { faces: c.faces, verts: c.verts.map((v) => [v[0], (v[1] * size[1]) / size[0], (v[2] * size[2]) / size[0]] as Vec3) };
@@ -140,6 +175,8 @@ export function primitiveCage(kind: CagePrimitive, at: Vec3 = [0, 0, 0]): Cage {
return cylinderCage(40, 40, 2, at);
case "sphere":
return sphereCage(40, at);
case "torus":
return torusCage(40, 12, 2, at);
}
}
@@ -152,13 +189,21 @@ export interface Subdivided {
grids: number[][][];
/** Size of each grid side in cells (2^levels). */
n: number;
/** The sharp edges at this level (as "a,b" with a < b), where the cage has some. */
creased?: Set<string>;
}
const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
const mul3 = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];
/** Catmull–Clark, `levels` times. Boundary edges (open sheets) stay sharp B-spline curves. */
export function subdivide(cage: Cage, levels = 3): Subdivided {
/**
* Catmull–Clark, `levels` times. Boundary edges (open sheets) stay sharp
* B-spline curves. `sharp`: border points the border passes through as a
* corner (a sheet laid over a face: the face's own corners).
*/
export function subdivide(cage: Cage, levels = 3, sharp?: Set<number>): Subdivided {
// Sharp edges, as they are at each level (each is two at the next).
let creased = new Set((cage.creases ?? []).map(([a, b]) => (a < b ? `${a},${b}` : `${b},${a}`)));
let points = cage.verts.map((p) => [...p] as Vec3);
let grids = cage.faces.map((f) => [
[f[0], f[3]],
@@ -189,7 +234,7 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
for (const [key, fs] of edgeFaces) {
const [a, b] = key.split(",").map(Number);
const mid = mul3(add3(points[a], points[b]), 0.5);
edgePos.set(key, fs.length === 2 ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid);
edgePos.set(key, fs.length === 2 && !creased.has(key) ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid);
}
// Vertex points.
const vFaces = new Map<number, number[]>();
@@ -200,10 +245,15 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
const es = vEdges.get(v);
const fs = vFaces.get(v);
if (!es || !fs) return p;
const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1);
const border = es.filter((k) => edgeFaces.get(k)!.length === 1);
const crease = creased.size ? es.filter((k) => creased.has(k) && edgeFaces.get(k)!.length === 2) : [];
// (A sharp edge is followed as the border is. Three or more at a point, sharp or border: a corner.)
if (crease.length && border.length + crease.length > 2) return p;
const boundary = crease.length ? [...border, ...crease] : border;
if (boundary.length >= 2) {
// Boundary: a cubic B-spline along the border; a corner (two faces meet at an angle) stays put.
if (fs.length === 1) return p;
// (Told which points are corners: only those - a sheet's own corner on a round edge isn't one.)
if (!crease.length && (sharp ? sharp.has(v) : fs.length === 1)) return p;
const others = boundary.slice(0, 2).map((k) => {
const [a, b] = k.split(",").map(Number);
return points[a === v ? b : a];
@@ -232,10 +282,20 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) ng[2 * i + 1][2 * j + 1] = faceIdx[qi++];
return ng;
});
if (creased.size) {
const halves = new Set<string>();
for (const key of creased) {
const m = edgeIdx.get(key);
if (m === undefined) continue;
const [a, b] = key.split(",").map(Number);
halves.add(ekey(a, m)).add(ekey(m, b));
}
creased = halves;
}
points = next;
n = N;
}
return { points, grids, n };
return { points, grids, n, ...(creased.size ? { creased } : {}) };
}
/**
@@ -247,7 +307,7 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
* Inside: (n²·p + 4·Σ edge neighbours + Σ diagonal neighbours) / (n(n+5)).
* Along an open border: (prev + 4·p + next) / 6. Corners of a sheet stay.
*/
export function limitPoints(s: Subdivided): Vec3[] {
export function limitPoints(s: Subdivided, sharp?: Set<number>): Vec3[] {
const P = s.points;
const quads: number[][] = [];
for (const g of s.grids) for (let i = 0; i < s.n; i++) for (let j = 0; j < s.n; j++) quads.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]);
@@ -269,12 +329,28 @@ export function limitPoints(s: Subdivided): Vec3[] {
if (edgeCount.get(ekey(v, a)) === 1) border[v].push(a);
if (edgeCount.get(ekey(v, b)) === 1) border[v].push(b);
}
// Sharp edges: followed as the border is.
const sharpAt = P.map(() => [] as number[]);
for (const key of s.creased ?? []) {
const [a, b] = key.split(",").map(Number);
if (edgeCount.get(key) !== 2) continue;
sharpAt[a].push(b);
sharpAt[b].push(a);
}
return P.map((p, v) => {
if (!faces[v]) return p;
const bd = [...new Set(border[v])];
const open = [...new Set(border[v])];
const cr = sharpAt[v];
if (cr.length) {
// Two (sharp or border) through the point: on that curve. More: a corner. One, in the middle: it fades out (smooth).
const through = [...new Set([...open, ...cr])];
if (through.length > 2) return p;
if (through.length === 2) return [0, 1, 2].map((k) => (P[through[0]][k] + 4 * p[k] + P[through[1]][k]) / 6) as Vec3;
}
const bd = open;
if (bd.length) {
// On an open border: a corner (one face) stays; otherwise the border curve's point.
if (faces[v] === 1 || bd.length !== 2) return p;
if ((sharp ? sharp.has(v) : faces[v] === 1) || bd.length !== 2) return p;
return [0, 1, 2].map((k) => (P[bd[0]][k] + 4 * p[k] + P[bd[1]][k]) / 6) as Vec3;
}
const n = nbE[v].size;
@@ -287,6 +363,62 @@ export function limitPoints(s: Subdivided): Vec3[] {
});
}
/**
* A sheet whose smooth border runs THROUGH the cage's border points (as
* drawn, a smooth surface's border only comes near them) and turns a corner
* where they do: the cage with its border points moved to where they pull the
* border onto the old ones, and the corners. For a sheet laid over a face,
* whose border points lie on the face's edge - so does the surface's then.
*/
export function borderThrough(cage: Cage): { cage: Cage; sharp: Set<number> } {
const next = new Map<number, number>();
for (const [a, b] of boundaryEdges(cage)) next.set(a, b);
const prev = new Map<number, number>();
for (const [a, b] of next) prev.set(b, a);
const P = cage.verts;
const sharp = new Set<number>();
for (const [v, n] of next) {
const p = prev.get(v);
if (p === undefined) continue;
const d1 = [0, 1, 2].map((k) => P[v][k] - P[p][k]);
const d2 = [0, 1, 2].map((k) => P[n][k] - P[v][k]);
const l = Math.hypot(...d1) * Math.hypot(...d2);
const cos = l > 0 ? (d1[0] * d2[0] + d1[1] * d2[1] + d1[2] * d2[2]) / l : 1;
if (cos < Math.cos((25 * Math.PI) / 180)) sharp.add(v);
}
// The border's point at a control point is (before + 4·it + after) / 6:
// solved for the control points that put it on the old point (it settles in
// a few rounds: each point depends mostly on itself).
const C = P.map((p) => [...p] as Vec3);
const free = [...next.keys()].filter((v) => !sharp.has(v) && prev.has(v));
for (let round = 0; round < 60; round++)
for (const v of free) {
const a = C[prev.get(v)!];
const b = C[next.get(v)!];
C[v] = [0, 1, 2].map((k) => (6 * P[v][k] - a[k] - b[k]) / 4) as Vec3;
}
return { cage: { verts: C, faces: cage.faces }, sharp };
}
/** The points along a subdivided sheet's open border, as pieces [from, to]. */
export function borderPieces(s: Subdivided): [Vec3, Vec3][] {
const count = new Map<string, [number, number]>();
const seen = new Map<string, number>();
for (const g of s.grids)
for (let i = 0; i < s.n; i++)
for (let j = 0; j < s.n; j++) {
const q = [g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]];
for (let k = 0; k < 4; k++) {
const a = q[k];
const b = q[(k + 1) % 4];
const key = a < b ? `${a},${b}` : `${b},${a}`;
seen.set(key, (seen.get(key) ?? 0) + 1);
count.set(key, [a, b]);
}
}
return [...count].filter(([k]) => seen.get(k) === 1).map(([, [a, b]]) => [s.points[a], s.points[b]]);
}
// ------------------------------------------------------- subdivision plan
//
// Catmull–Clark and the limit points are fixed weighted sums of the cage
@@ -344,7 +476,7 @@ function compose(a: Rows, b: Rows): Rows {
/** The layout key of a cage: its faces (positions don't matter). */
export function layoutKey(cage: Cage): string {
return `${cage.verts.length}|${cage.faces.join(";")}`;
return `${cage.verts.length}|${cage.faces.join(";")}${cage.creases?.length ? `|${cage.creases.join(";")}` : ""}`;
}
/**
@@ -362,11 +494,14 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
[f[1], f[2]],
]);
let n = 1;
// Sharp edges (see subdivide), as pairs: the numbering of a level's edges changes with it.
let sharpPairs: [number, number][] = (cage.creases ?? []).map(([a, b]) => [a, b]);
const addTo = (m: Map<number, number>, i: number, w: number) => m.set(i, (m.get(i) ?? 0) + w);
for (let lvl = 0; lvl < levels; lvl++) {
const quads: number[][] = [];
for (const g of grids) for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) quads.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]);
const ekey = (a: number, b: number) => (a < b ? a * count + b : b * count + a);
const creased = new Set(sharpPairs.map(([a, b]) => ekey(a, b)));
// Edges in first-seen order (subdivide numbers its edge points that way).
const edgeFaces = new Map<number, number[]>();
quads.forEach((q, qi) => {
@@ -396,9 +531,12 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
if (!es.length || !fs.length) {
m.set(v, 1);
} else {
const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1);
if (boundary.length >= 2) {
if (fs.length === 1) m.set(v, 1);
const border = es.filter((k) => edgeFaces.get(k)!.length === 1);
const crease = creased.size ? es.filter((k) => creased.has(k) && edgeFaces.get(k)!.length === 2) : [];
const boundary = crease.length ? [...border, ...crease] : border;
if (crease.length && boundary.length > 2) m.set(v, 1);
else if (boundary.length >= 2) {
if (!crease.length && fs.length === 1) m.set(v, 1);
else {
addTo(m, v, 0.75);
for (const k of boundary.slice(0, 2)) {
@@ -424,7 +562,7 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
for (const [key, fs] of edgeFaces) {
const [a, b] = ends(key);
const m = new Map<number, number>();
if (fs.length === 2) {
if (fs.length === 2 && !creased.has(key)) {
addTo(m, a, 0.25);
addTo(m, b, 0.25);
for (const f of fs) for (const q of quads[f]) addTo(m, q, 0.0625);
@@ -445,6 +583,14 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
const edgeIdx = new Map<number, number>();
let e = count;
for (const key of edgeFaces.keys()) edgeIdx.set(key, e++);
if (sharpPairs.length) {
const halves: [number, number][] = [];
for (const [a, b] of sharpPairs) {
const mid = edgeIdx.get(ekey(a, b));
if (mid !== undefined) halves.push([a, mid], [mid, b]);
}
sharpPairs = halves;
}
let qi = 0;
const N = 2 * n;
const faceBase = e;
@@ -480,12 +626,24 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
if (edgeCount.get(ek(v, a)) === 1) border[v].push(a);
if (edgeCount.get(ek(v, b)) === 1) border[v].push(b);
}
const sharpAt: number[][] = Array.from({ length: count }, () => []);
for (const [a, b] of sharpPairs) {
if (edgeCount.get(ek(a, b)) !== 2) continue;
sharpAt[a].push(b);
sharpAt[b].push(a);
}
const lim = new RowBuilder();
for (let v = 0; v < count; v++) {
const m = new Map<number, number>();
const bd = [...new Set(border[v])];
const nE = nbE[v].size;
if (!faces[v] || (bd.length && (faces[v] === 1 || bd.length !== 2)) || (!bd.length && nE !== faces[v])) m.set(v, 1);
const through = sharpAt[v].length ? [...new Set([...bd, ...sharpAt[v]])] : [];
if (through.length > 2) m.set(v, 1);
else if (through.length === 2) {
addTo(m, through[0], 1 / 6);
addTo(m, v, 4 / 6);
addTo(m, through[1], 1 / 6);
} else if (!faces[v] || (bd.length && (faces[v] === 1 || bd.length !== 2)) || (!bd.length && nE !== faces[v])) m.set(v, 1);
else if (bd.length) {
addTo(m, bd[0], 1 / 6);
addTo(m, v, 4 / 6);
@@ -558,37 +716,6 @@ export function smoothNormals(pos: Float32Array, tri: Uint32Array, out?: Float32
return nrm;
}
/** Triangles of the subdivided surface (for the live preview). */
export function previewMesh(s: Subdivided): { positions: Float32Array; normals: Float32Array; indices: Uint32Array } {
const positions = new Float32Array(s.points.flat());
const idx: number[] = [];
for (const g of s.grids)
for (let i = 0; i < s.n; i++)
for (let j = 0; j < s.n; j++) {
const a = g[i][j];
const b = g[i + 1][j];
const c = g[i + 1][j + 1];
const d = g[i][j + 1];
idx.push(a, b, c, a, c, d);
}
// Smooth normals: area-weighted average of the triangles around each point.
const nrm = new Float32Array(positions.length);
for (let t = 0; t < idx.length; t += 3) {
const [a, b, c] = [idx[t], idx[t + 1], idx[t + 2]].map((k) => s.points[k]);
const u: Vec3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const v: Vec3 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
const n: Vec3 = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
for (const k of [idx[t], idx[t + 1], idx[t + 2]]) for (let q = 0; q < 3; q++) nrm[k * 3 + q] += n[q];
}
for (let k = 0; k < nrm.length; k += 3) {
const l = Math.hypot(nrm[k], nrm[k + 1], nrm[k + 2]) || 1;
nrm[k] /= l;
nrm[k + 1] /= l;
nrm[k + 2] /= l;
}
return { positions, normals: nrm, indices: new Uint32Array(idx) };
}
/** Cage edges (each once), for drawing and picking. */
export function cageEdges(cage: Cage): [number, number][] {
const seen = new Set<string>();
@@ -647,13 +774,65 @@ export function moveTurnScale(pts: Vec3[], mode: "move" | "turn" | "scale", [x,
/** Remove faces; points no face uses any more go too (indices are renumbered). */
export function deleteFaces(cage: Cage, faces: number[]): Cage {
const drop = new Set(faces);
return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)) });
return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)), creases: cage.creases });
}
function compact(cage: Cage): Cage {
const used = [...new Set(cage.faces.flat())].sort((a, b) => a - b);
const map = new Map(used.map((v, i) => [v, i]));
return { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) };
const out: Cage = { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) };
return withCreases(out, (cage.creases ?? []).flatMap(([a, b]) => (map.has(a) && map.has(b) ? [[map.get(a)!, map.get(b)!] as [number, number]] : [])));
}
/** The cage with these sharp edges - those that are edges of it (none: no list at all). */
export function withCreases(cage: Cage, creases: [number, number][]): Cage {
const { creases: _old, ...rest } = cage;
if (!creases.length) return rest;
const edges = new Set<string>();
for (const f of cage.faces) for (let k = 0; k < 4; k++) edges.add(ekey(f[k], f[(k + 1) % 4]));
const seen = new Set<string>();
const kept = creases.filter(([a, b]) => edges.has(ekey(a, b)) && !seen.has(ekey(a, b)) && !!seen.add(ekey(a, b)));
return kept.length ? { ...rest, creases: kept } : rest;
}
/**
* A cage made from another by a tool (a loop added, faces pulled out, a hole
* filled...) with the other's sharp edges on it: each where it still is - the
* same edge, or, where the tool cut it (a loop across it), the pieces of it.
* Found by where the points are: the tools number points as they please.
*/
export function carryCreases(prev: Cage, next: Cage): Cage {
if (next.creases || !prev.creases?.length) return next;
const at = new Map<string, number>();
const pos = (p: Vec3) => `${p[0].toFixed(6)},${p[1].toFixed(6)},${p[2].toFixed(6)}`;
next.verts.forEach((p, i) => at.set(pos(p), i));
const edges = new Set<string>();
for (const f of next.faces) for (let k = 0; k < 4; k++) edges.add(ekey(f[k], f[(k + 1) % 4]));
const out: [number, number][] = [];
for (const [a, b] of prev.creases) {
const [pa, pb] = [prev.verts[a], prev.verts[b]];
const [ia, ib] = [at.get(pos(pa)), at.get(pos(pb))];
if (ia === undefined || ib === undefined) continue;
if (edges.has(ekey(ia, ib))) {
out.push([ia, ib]);
continue;
}
// Cut: the points of the new cage along it, in order, joined where they are edges.
const d: Vec3 = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]];
const l2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if (l2 < 1e-18) continue;
const on: { i: number; t: number }[] = [];
next.verts.forEach((q, i) => {
const w: Vec3 = [q[0] - pa[0], q[1] - pa[1], q[2] - pa[2]];
const t = (w[0] * d[0] + w[1] * d[1] + w[2] * d[2]) / l2;
if (t < -1e-9 || t > 1 + 1e-9) return;
const off = Math.hypot(w[0] - d[0] * t, w[1] - d[1] * t, w[2] - d[2] * t);
if (off < Math.sqrt(l2) * 1e-6) on.push({ i, t });
});
on.sort((x, y) => x.t - y.t);
for (let k = 0; k + 1 < on.length; k++) if (edges.has(ekey(on[k].i, on[k + 1].i))) out.push([on[k].i, on[k + 1].i]);
}
return withCreases(next, out);
}
const ekey = (a: number, b: number) => (a < b ? `${a},${b}` : `${b},${a}`);
@@ -717,7 +896,7 @@ export function refineCage(cage: Cage): Cage {
const s = subdivide(cage, 1);
const faces: Cage["faces"] = [];
for (const g of s.grids) for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) faces.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]);
return compact({ verts: s.points, faces });
return compact({ verts: s.points, faces, creases: [...(s.creased ?? [])].map((k) => k.split(",").map(Number) as [number, number]) });
}
/**
@@ -1162,6 +1341,102 @@ const cross3 = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[
// ------------------------------------------------- adding cage detail
/**
* Take an edge loop out: the loop of edges through a-b (straight on through
* each point four edges meet at, round the shape or from border to border)
* goes, and the two faces either side of each of its edges become one. The
* points of the loop go with it. Null where the loop cannot be followed (a
* point on it where three or five edges meet), or where an edge of it is on
* the border.
*/
/**
* The loop of edges through a-b: straight on through each point four edges
* meet at, round the shape or from border to border. Null where it cannot be
* followed (a point where three or five edges meet) - or, `lenient`, the part
* of it that can.
*/
export function edgeLoopOf(cage: Cage, a: number, b: number, lenient = false): [number, number][] | null {
const efs = edgeFaceMap(cage);
if (!efs.has(ekey(a, b))) return null;
const around = new Map<number, number[]>();
for (const key of efs.keys()) {
const [p, q] = key.split(",").map(Number);
around.set(p, [...(around.get(p) ?? []), q]);
around.set(q, [...(around.get(q) ?? []), p]);
}
// From `from` on through `at`: the edge at `at` that shares no face with the one arrived by.
const onward = (from: number, at: number): number | null | undefined => {
const ns = around.get(at) ?? [];
const border = ns.filter((n) => efs.get(ekey(at, n))!.length === 1);
// (At the border the loop ends: its last point has the two border edges and the one arrived by.)
if (border.length) return ns.length === 3 && border.length === 2 ? null : undefined;
if (ns.length !== 4) return undefined;
const mine = new Set(efs.get(ekey(from, at)));
const next = ns.filter((n) => n !== from && !efs.get(ekey(at, n))!.some((f) => mine.has(f)));
return next.length === 1 ? next[0] : undefined;
};
const loop: [number, number][] = [[a, b]];
const seen = new Set([ekey(a, b)]);
let closed = false;
for (const dir of [0, 1]) {
let [from, at] = dir ? [b, a] : [a, b];
for (let guard = 0; guard < cage.verts.length + 2; guard++) {
const next = onward(from, at);
if (next === undefined) {
if (lenient) break;
return null;
}
if (next === null) break;
if (seen.has(ekey(at, next))) {
closed = true;
break;
}
seen.add(ekey(at, next));
loop.push([at, next]);
[from, at] = [at, next];
}
if (closed) break;
}
return loop;
}
export function removeEdgeLoop(cage: Cage, a: number, b: number): Cage | null {
const efs = edgeFaceMap(cage);
const loop = edgeLoopOf(cage, a, b);
if (!loop) return null;
const gone = new Set<number>();
const made: Quad[] = [];
for (const [p, q] of loop) {
const fs = efs.get(ekey(p, q))!;
if (fs.length !== 2) return null;
// The face that winds p then q, and the one that winds q then p: p-q-c-d and q-p-e-f.
const turn = (f: Quad, x: number, y: number): Quad | null => {
for (let k = 0; k < 4; k++) if (f[k] === x && f[(k + 1) % 4] === y) return [f[k], f[(k + 1) % 4], f[(k + 2) % 4], f[(k + 3) % 4]];
return null;
};
const A = turn(cage.faces[fs[0]], p, q) ?? turn(cage.faces[fs[1]], p, q);
const B = turn(cage.faces[fs[0]], q, p) ?? turn(cage.faces[fs[1]], q, p);
if (!A || !B) return null;
made.push([A[3], B[2], B[3], A[2]]);
gone.add(fs[0]).add(fs[1]);
}
// (A face on both sides of two loop edges - a loop one face wide round a corner - cannot be merged twice.)
if (gone.size !== loop.length * 2) return null;
// Sharp edges the loop crossed: each was cut in two at a point of the loop - with that point gone, it is one again.
const onLoop = new Set(loop.flat());
const creases: [number, number][] = [];
const cutAt = new Map<number, number[]>();
for (const [p, q] of cage.creases ?? []) {
if (onLoop.has(p) && onLoop.has(q)) continue;
if (onLoop.has(p)) cutAt.set(p, [...(cutAt.get(p) ?? []), q]);
else if (onLoop.has(q)) cutAt.set(q, [...(cutAt.get(q) ?? []), p]);
else creases.push([p, q]);
}
for (const ends of cutAt.values()) if (ends.length === 2) creases.push([ends[0], ends[1]]);
const out = compact({ verts: cage.verts, faces: [...cage.faces.filter((_, i) => !gone.has(i)), ...made], creases });
return out.faces.length ? out : null;
}
type Quad = Cage["faces"][number];
/** Faces using each edge. */
+289
View File
@@ -0,0 +1,289 @@
// Connect: a smooth bridge from one face to another. The faces' own outlines
// are swept along a curve (the guide the user drew, or one that leaves each
// face straight out of it): the bridge starts and ends exactly on the faces,
// so joined to them it leaves no step.
import type { Vec3 } from "../doc/types";
const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const mul = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];
const len = (a: Vec3) => Math.hypot(a[0], a[1], a[2]);
const unit = (a: Vec3): Vec3 => mul(a, 1 / (len(a) || 1));
const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
/**
* A guide curve as a function of 0..1 (by length): run from the end nearer
* A's middle, and moved (gradually, end to end) so it starts at A's middle and
* ends at B's. With `da0`/`db0`: for `ease` along it from each end, eased
* from the way it leaves A (arrives at B) onto the curve.
*/
export function guideCurve(pts: Vec3[], ca: Vec3, cb: Vec3, da0?: Vec3, db0?: Vec3, ease = 0): (t: number) => Vec3 {
const p = oriented(pts, ca, cb);
const acc = [0];
for (let i = 1; i < p.length; i++) acc.push(acc[i - 1] + len(sub(p[i], p[i - 1])));
const total = acc[acc.length - 1] || 1;
const da = sub(ca, p[0]);
const db = sub(cb, p[p.length - 1]);
const on = (t: number) => {
const want = Math.max(0, Math.min(1, t)) * total;
let i = 1;
while (i < p.length - 1 && acc[i] < want) i++;
const f = Math.max(0, Math.min(1, acc[i] > acc[i - 1] ? (want - acc[i - 1]) / (acc[i] - acc[i - 1]) : 0));
// Smoothly through the points (Catmull-Rom), not straight from one to the
// next: the corners between straight pieces read as turns far too tight.
const P0 = p[Math.max(0, i - 2)];
const P1 = p[i - 1];
const P2 = p[i];
const P3 = p[Math.min(p.length - 1, i + 1)];
const f2 = f * f;
const f3 = f2 * f;
const q = mul(add(add(mul(P1, 2), mul(sub(P2, P0), f)), add(mul(add(sub(mul(P0, 2), mul(P1, 5)), sub(mul(P2, 4), P3)), f2), mul(add(sub(mul(P1, 3), P0), sub(P3, mul(P2, 3))), f3))), 0.5);
const s = want / total;
return add(q, add(mul(da, 1 - s), mul(db, s)));
};
if (!da0 || !db0 || !(ease > 0)) return on;
// Near each end, a smooth curve from straight out of the face onto the
// guide (meeting it going its way): the bridge leaves the face square, with no kink.
const w = Math.min(0.45, ease / total);
const slope = (t: number) => mul(sub(on(t + 1e-4), on(t - 1e-4)), w / 2e-4);
const hermite = (p0: Vec3, t0: Vec3, p1: Vec3, t1: Vec3) => (s: number) =>
add(add(mul(p0, 2 * s ** 3 - 3 * s ** 2 + 1), mul(t0, s ** 3 - 2 * s ** 2 + s)), add(mul(p1, -2 * s ** 3 + 3 * s ** 2), mul(t1, s ** 3 - s ** 2)));
const ta = slope(w);
const tb = slope(1 - w);
const startA = hermite(ca, mul(unit(da0), len(ta)), on(w), ta);
const intoB = hermite(on(1 - w), tb, cb, mul(unit(db0), -len(tb)));
return (t: number) => (t < w ? startA(t / w) : t > 1 - w ? intoB((t - (1 - w)) / w) : on(t));
}
/** The bridge's two outlines: points round each, from its middle, as they lie at that end. */
export interface Rings {
a: Vec3[];
b: Vec3[];
}
interface Frame {
r: Vec3;
s: Vec3;
t: Vec3;
}
/**
* `n` + 1 points along a curve, and at each the directions across it carried
* along from the start without twisting about the curve (double reflection) -
* the way the sweep carries the bridge's outline.
*/
function carried(c: (t: number) => Vec3, n: number): { P: Vec3[]; F: Frame[] } {
const P = Array.from({ length: n + 1 }, (_, i) => c(i / n));
const T = P.map((_, i) => unit(sub(P[Math.min(n, i + 1)], P[Math.max(0, i - 1)])));
const seed: Vec3 = Math.abs(T[0][0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
let r = unit(sub(seed, mul(T[0], dot(seed, T[0]))));
const F: Frame[] = [{ r, s: cross(T[0], r), t: T[0] }];
for (let i = 0; i < n; i++) {
const v1 = sub(P[i + 1], P[i]);
const c1 = dot(v1, v1);
let next = r;
if (c1 > 1e-24) {
const rL = sub(r, mul(v1, (2 / c1) * dot(v1, r)));
const tL = sub(T[i], mul(v1, (2 / c1) * dot(v1, T[i])));
const v2 = sub(T[i + 1], tL);
const c2 = dot(v2, v2);
next = c2 > 1e-24 ? sub(rL, mul(v2, (2 / c2) * dot(v2, rL))) : rL;
}
const t = T[i + 1];
r = unit(sub(next, mul(t, dot(next, t))));
F.push({ r, s: cross(t, r), t });
}
return { P, F };
}
/** The directions across a curve at `n` + 1 points along it, carried without twisting (as the sweep carries the bridge's outline). */
export const carriedFrames = (c: (t: number) => Vec3, n: number): Frame[] => carried(c, n).F;
/**
* Whether a curve (0..1) never turns tighter than the bridge is wide: at each
* point its radius more than how far the outline reaches towards the middle
* of the turn (with a little to spare). Tighter, the outline's inner side
* runs backwards and the bridge folds through itself. The outline is taken
* where the sweep has carried it by then - turned with the curve (measured as
* it lay at the faces, an arch's top went unchecked) - and as far between the
* two ends' outlines as the point is along the curve (A's at A, B's at B).
*/
export function gentle(c: (t: number) => Vec3, rings: Rings, spare = 1.1): boolean {
const N = 200;
const { P, F } = carried(c, N);
const across = (ring: Vec3[], f: Frame) => ring.map((p): Vec3 => [dot(p, f.r), dot(p, f.s), dot(p, f.t)]);
const ends = [across(rings.a, F[0]), across(rings.b, F[N])];
const h = 1 / N;
for (let i = 1; i < N; i++) {
const v = mul(sub(P[i + 1], P[i - 1]), 1 / (2 * h));
const a = mul(add(sub(P[i + 1], mul(P[i], 2)), P[i - 1]), 1 / (h * h));
const k = len(cross(v, a));
if (k < 1e-12) continue;
// Towards the middle of the turn: the part of `a` across the curve.
const n = unit(sub(a, mul(v, dot(v, a) / dot(v, v))));
const f = F[i];
const nl: Vec3 = [dot(n, f.r), dot(n, f.s), dot(n, f.t)];
const [ra, rb] = ends.map((ring) => ring.reduce((m, p) => Math.max(m, dot(p, nl)), 0));
if (len(v) ** 3 / k < spare * (ra + (rb - ra) * (i / N))) return false;
}
return true;
}
/** A curve from `ca` to `cb` that leaves along `na` and arrives against `nb`, each held for `lead`. */
function hermite(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3, lead: number): (t: number) => Vec3 {
const T0 = mul(unit(na), lead);
const T1 = mul(unit(nb), -lead);
return (t: number) => {
const h00 = 2 * t ** 3 - 3 * t ** 2 + 1;
const h10 = t ** 3 - 2 * t ** 2 + t;
const h01 = -2 * t ** 3 + 3 * t ** 2;
const h11 = t ** 3 - t ** 2;
return add(add(mul(ca, h00), mul(T0, h10)), add(mul(cb, h01), mul(T1, h11)));
};
}
/**
* With no guide: a curve from A's middle to B's that leaves A along `na` and
* arrives at B against `nb`, bowing out by `bulge` (1: plain) - but never
* turning tighter than the bridge is wide (see gentle): a tighter turn folds
* the bridge's inside, however little the bulge. `gentle` false: none of
* these curves is (the faces too close, or too far to the side of each other,
* for their width) - the plain one, for the caller to do better by.
*/
export function plainSpine(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3, bulge: number, rings: Rings): { along: (t: number) => Vec3; gentle: boolean } {
const gap = len(sub(cb, ca)) || 1;
// The bulge asked for, else the nearest to it (more, or less) that turns gently enough.
const want = gap * Math.max(0.05, bulge);
for (let k = 0; k < 40; k++)
for (const lead of k ? [want * 1.06 ** k, want / 1.06 ** k] : [want]) {
const c = hermite(ca, na, cb, nb, lead);
if (gentle(c, rings)) return { along: c, gentle: true };
}
return { along: hermite(ca, na, cb, nb, want), gentle: false };
}
/**
* Two arcs of circles, one out of A along `na` and one into B against `nb`,
* meeting smoothly half way: of the ways from one face to the other this
* turns the least tightly (well less than the plain curve at its tightest),
* so it fits where that one would fold. Null where there is none (B straight
* behind A).
*/
export function arcSpine(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3): ((t: number) => Vec3) | null {
const T0 = unit(na);
const T1 = unit(mul(nb, -1));
const v = sub(cb, ca);
const vv = dot(v, v);
if (vv < 1e-18) return null;
// (Equal chords: the corner points ca + d T0 and cb - d T1 are d from the ends and 2d apart.)
const q = 1 - dot(T0, T1);
const vt = dot(v, add(T0, T1));
let d: number;
if (q < 1e-9) {
const ahead = dot(v, T0);
if (ahead <= 1e-9) return null;
d = vv / (4 * ahead);
} else d = (-vt + Math.sqrt(vt * vt + 2 * q * vv)) / (2 * q);
if (!(d > 1e-9) || !Number.isFinite(d)) return null;
const J = mul(add(add(ca, mul(T0, d)), sub(cb, mul(T1, d))), 0.5);
// The arc from A, leaving along T, to B: its length, and the point `s` along it.
const arc = (A: Vec3, T: Vec3, B: Vec3) => {
const w = sub(B, A);
const ahead = dot(w, T);
const side = sub(w, mul(T, ahead));
const off = len(side);
if (off < 1e-9 * (len(w) || 1)) return { length: Math.abs(ahead), at: (s: number) => add(A, mul(T, s * Math.sign(ahead || 1))) };
const n = mul(side, 1 / off);
const r = dot(w, w) / (2 * off);
return { length: r * 2 * Math.atan2(off, ahead), at: (s: number) => add(A, mul(add(mul(T, Math.sin(s / r)), mul(n, 1 - Math.cos(s / r))), r)) };
};
const out = arc(ca, T0, J);
const back = arc(cb, mul(T1, -1), J);
const total = out.length + back.length;
if (!(total > 0)) return null;
return (t: number) => {
const s = Math.max(0, Math.min(1, t)) * total;
return s <= out.length ? out.at(s) : back.at(total - s);
};
}
/**
* For a bridge too wide to turn with its curve (it would fold): the direction
* its outline can keep facing instead, all the way, sliding along the curve
* without turning - a sheared bridge, thinner where the curve leans. Only
* where both ends face nearly the same way (`ta`, `tb`: the way the curve
* leaves A and arrives at B), the curve never runs across that direction (the
* bridge would thin to nothing), and it gets further along it than the two
* outlines lean apart (`reach`: how far they reach from their middles).
*/
export function slideAxis(c: (t: number) => Vec3, ta: Vec3, tb: Vec3, reach: number, least = 0.2): Vec3 | null {
const a = unit(ta);
const b = unit(tb);
const cos = dot(a, b);
if (cos < 0.94) return null;
const d = unit(add(a, b));
if (dot(sub(c(1), c(0)), d) < 2 * reach * Math.sqrt(Math.max(0, 1 - cos * cos))) return null;
const N = 200;
let prev = c(0);
for (let i = 1; i <= N; i++) {
const p = c(i / N);
const step = sub(p, prev);
const L = len(step);
if (L > 1e-12 && dot(step, d) / L < least) return null;
prev = p;
}
return d;
}
/** The plain curve (its bulge as asked, else the nearest less of it) that a bridge can slide along (see slideAxis). */
export function slidingSpine(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3, bulge: number, reach: number): { along: (t: number) => Vec3; axis: Vec3 } | null {
const gap = len(sub(cb, ca)) || 1;
const want = gap * Math.max(0.05, bulge);
for (let k = 0; k < 40; k++) {
const c = hermite(ca, na, cb, nb, want / 1.06 ** k);
const axis = slideAxis(c, na, mul(nb, -1), reach);
if (axis) return { along: c, axis };
}
return null;
}
/** `n` points evenly along a polyline (by length), its ends kept. */
export function evenly(pts: Vec3[], n: number): Vec3[] {
const acc = [0];
for (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + len(sub(pts[i], pts[i - 1])));
const total = acc[acc.length - 1];
if (!(total > 0)) return pts;
const out: Vec3[] = [];
let i = 1;
for (let k = 0; k < n; k++) {
const want = (total * k) / (n - 1);
while (i < pts.length - 1 && acc[i] < want) i++;
const f = acc[i] > acc[i - 1] ? Math.max(0, Math.min(1, (want - acc[i - 1]) / (acc[i] - acc[i - 1]))) : 0;
out.push(add(pts[i - 1], mul(sub(pts[i], pts[i - 1]), f)));
}
return out;
}
/** A guide's points run from the end nearer A to the end nearer B. */
export function oriented(pts: Vec3[], ca: Vec3, cb: Vec3): Vec3[] {
return len(sub(pts[0], ca)) + len(sub(pts[pts.length - 1], cb)) <= len(sub(pts[pts.length - 1], ca)) + len(sub(pts[0], cb)) ? pts : [...pts].reverse();
}
/**
* A polyline (run from A to B) rounded off `passes` times - each point
* towards its neighbours' middle - its ends kept, and still leaving the first
* along `da` and arriving at the last against `db` (held by points out past
* each end that don't move): its tight turns open out, its ends stay square.
*/
export function smoothed(pts: Vec3[], passes: number, da: Vec3, db: Vec3): Vec3[] {
const step = len(sub(pts[1], pts[0])) || 1;
const n = pts.length;
const before = Array.from({ length: n }, (_, k) => sub(pts[0], mul(unit(da), step * (n - k))));
const after = Array.from({ length: n }, (_, k) => add(pts[n - 1], mul(unit(db), step * (k + 1))));
let p = [...before, ...pts, ...after];
const fixed = (i: number) => i <= n || i >= 2 * n - 1;
for (let k = 0; k < passes; k++) p = p.map((q, i) => (fixed(i) ? q : mul(add(add(p[i - 1], p[i + 1]), mul(q, 2)), 0.25)));
return p.slice(n, 2 * n);
}
+352
View File
@@ -0,0 +1,352 @@
// The cage Freeform Face shapes a flat face with: a grid of quads over the
// face whose border runs round the face's edge (on a rectangle, a plain grid;
// on a round or odd-shaped face, a grid stretched to fit it). The border
// points stay where they are - the face's edges don't move - and the inside
// points are moved like any freeform cage's.
import type { Vec3 } from "../doc/types";
import { cross, dot, norm, sub, xDirFor } from "../geom";
import type { Cage } from "./cage";
type P2 = [number, number];
/** The outer outline of a set of triangles, in order (anticlockwise about `normal`), in the plane's 2D. */
function outline(tris: [Vec3, Vec3, Vec3][], uv: (p: Vec3) => P2): P2[] {
const key = (p: P2) => `${Math.round(p[0] * 1e5)},${Math.round(p[1] * 1e5)}`;
const at = new Map<string, P2>();
const uses = new Map<string, number>();
const dir = new Map<string, string>();
for (const t of tris) {
const q = t.map(uv);
// Each triangle anticlockwise in the plane.
const area = (q[1][0] - q[0][0]) * (q[2][1] - q[0][1]) - (q[2][0] - q[0][0]) * (q[1][1] - q[0][1]);
if (Math.abs(area) < 1e-14) continue;
const r = area > 0 ? q : [q[0], q[2], q[1]];
for (let k = 0; k < 3; k++) {
const a = key(r[k]);
const b = key(r[(k + 1) % 3]);
if (a === b) continue;
at.set(a, r[k]);
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
uses.set(e, (uses.get(e) ?? 0) + 1);
dir.set(`${a}>${b}`, b);
}
}
// Border edges (used once), followed head to tail.
const next = new Map<string, string>();
for (const [k, b] of dir) {
const a = k.slice(0, k.indexOf(">"));
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
if (uses.get(e) === 1) next.set(a, b);
}
const loops: P2[][] = [];
const seen = new Set<string>();
for (const start of next.keys()) {
if (seen.has(start)) continue;
const loop: P2[] = [];
let k: string | undefined = start;
while (k && !seen.has(k)) {
seen.add(k);
loop.push(at.get(k)!);
k = next.get(k);
}
if (loop.length >= 3) loops.push(loop);
}
const signed = (l: P2[]) => l.reduce((s, p, i) => s + p[0] * l[(i + 1) % l.length][1] - l[(i + 1) % l.length][0] * p[1], 0) / 2;
// The outer one: the biggest (anticlockwise).
loops.sort((a, b) => Math.abs(signed(b)) - Math.abs(signed(a)));
const outer = loops[0] ?? [];
return signed(outer) < 0 ? outer.reverse() : outer;
}
/**
* `n` + 1 points along a polyline, both ends included: evenly by length, then
* the one nearest each corner on the way moved onto it - the grid's border
* goes through the face's corners (an L's inward one too), so the smooth
* surface laid on the grid can have its border on the face's edges.
*/
function resample(pts: P2[], n: number): P2[] {
const out = evenly(pts, n);
const acc = [0];
for (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
const total = acc[acc.length - 1];
const used = new Set<number>();
for (let i = 1; i < pts.length - 1 && total > 0; i++) {
const d1 = [pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]];
const d2 = [pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]];
const turn = Math.abs(Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]));
if (turn < (25 * Math.PI) / 180) continue;
// (The sample whose place along the side is nearest: the order of the points stays.)
const k = Math.round((acc[i] / total) * n);
if (k < 1 || k > n - 1 || used.has(k)) continue;
used.add(k);
out[k] = [pts[i][0], pts[i][1]];
}
return out;
}
/** `n` + 1 points evenly along a polyline (by length), both ends included. */
function evenly(pts: P2[], n: number): P2[] {
const acc = [0];
for (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
const total = acc[acc.length - 1];
const out: P2[] = [];
let i = 1;
for (let k = 0; k <= n; k++) {
const want = (total * k) / n;
while (i < pts.length - 1 && acc[i] < want) i++;
const f = acc[i] > acc[i - 1] ? (want - acc[i - 1]) / (acc[i] - acc[i - 1]) : 0;
const t = Math.max(0, Math.min(1, f));
out.push([pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * t, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * t]);
}
return out;
}
/**
* Ways to choose the four points of the outline where the grid's sides meet
* (best first): the face's own
* outward corners when it has four or more (the four best spread), else
* spread evenly (a round face).
*/
function fourCorners(loop: P2[], acc: number[], total: number): number[][] {
const N = loop.length;
const turn = loop.map((p, i) => {
const a = loop[(i + N - 1) % N];
const b = loop[(i + 1) % N];
const d1 = [p[0] - a[0], p[1] - a[1]];
const d2 = [b[0] - p[0], b[1] - p[1]];
// (Signed: turning in, at a corner going into the face like an L's, is negative.)
return Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]);
});
// Only outward corners: an inward one (an L's) stays along a side.
let corners = loop.map((_, i) => i).filter((i) => turn[i] > (25 * Math.PI) / 180);
if (corners.length > 16) corners = corners.sort((a, b) => turn[b] - turn[a]).slice(0, 16).sort((a, b) => a - b);
const cand = [...corners];
// Too few corners: points evenly round it to choose from too.
if (corners.length < 4)
for (let k = 0; k < 32; k++) {
const want = (total * k) / 32;
let i = 0;
while (i < N - 1 && acc[i + 1] <= want) i++;
if (!cand.includes(i)) cand.push(i);
}
cand.sort((a, b) => a - b);
const isCorner = new Set(corners);
const gap = (i: number, j: number) => (acc[j] - acc[i] + total) % total;
const all: { q: number[]; score: number }[] = [];
const C = cand.length;
for (let a = 0; a < C; a++)
for (let b = a + 1; b < C; b++)
for (let c = b + 1; c < C; c++)
for (let d = c + 1; d < C; d++) {
const q = [cand[a], cand[b], cand[c], cand[d]];
const m = Math.min(gap(q[0], q[1]), gap(q[1], q[2]), gap(q[2], q[3]), gap(q[3], q[0]));
const score = m / total + 0.2 * q.filter((i) => isCorner.has(i)).length;
all.push({ q, score });
}
// Best first (the next ones are tried when a grid on the best won't fit the face).
return all.sort((a, b) => b.score - a.score).slice(0, 12).map((x) => x.q);
}
/**
* A cage over the flat face made of `tris` (points relative to `center`):
* `n` cells across its longer way.
*/
export function faceCage(tris: [Vec3, Vec3, Vec3][], center: Vec3, normal: Vec3, n = 5): Cage | null {
const nn = norm(normal);
const u = xDirFor(nn);
const v = norm(cross(nn, u));
const uv = (p: Vec3): P2 => [dot(sub(p, center), u), dot(sub(p, center), v)];
const drawn = outline(tris, uv);
if (drawn.length < 3) return null;
// Points along its straight edges too (a triangle's outline is three points:
// nowhere for a fourth corner of the grid to go but a point along an edge).
const around = drawn.reduce((t, p, i) => t + Math.hypot(drawn[(i + 1) % drawn.length][0] - p[0], drawn[(i + 1) % drawn.length][1] - p[1]), 0);
const loop: P2[] = [];
drawn.forEach((p, i) => {
const q = drawn[(i + 1) % drawn.length];
const pieces = Math.max(1, Math.ceil((Math.hypot(q[0] - p[0], q[1] - p[1]) / around) * 32));
for (let k = 0; k < pieces; k++) loop.push([p[0] + ((q[0] - p[0]) * k) / pieces, p[1] + ((q[1] - p[1]) * k) / pieces]);
});
const N = loop.length;
const acc = [0];
for (let i = 1; i <= N; i++) acc.push(acc[i - 1] + Math.hypot(loop[i % N][0] - loop[i - 1][0], loop[i % N][1] - loop[i - 1][1]));
const total = acc[N];
for (const cs of fourCorners(loop, acc, total)) {
// The four sides, each from one corner to the next.
const side = (a: number, b: number): P2[] => {
const out: P2[] = [];
for (let i = a; ; i = (i + 1) % N) {
out.push(loop[i]);
if (i === b) break;
}
return out;
};
const sides = [0, 1, 2, 3].map((k) => side(cs[k], cs[(k + 1) % 4]));
const length = (s: P2[]) => s.reduce((t, p, i) => (i ? t + Math.hypot(p[0] - s[i - 1][0], p[1] - s[i - 1][1]) : 0), 0);
const Lu = (length(sides[0]) + length(sides[2])) / 2;
const Lv = (length(sides[1]) + length(sides[3])) / 2;
const big = Math.max(Lu, Lv);
const nu = Math.max(2, Math.round((n * Lu) / big));
const nv = Math.max(2, Math.round((n * Lv) / big));
const bottom = resample(sides[0], nu);
const right = resample(sides[1], nv);
const top = resample(sides[2], nu).reverse();
const left = resample(sides[3], nv).reverse();
// Coons: the inside blended from the four sides.
const id = (i: number, j: number) => j * (nu + 1) + i;
const at: P2[] = [];
for (let j = 0; j <= nv; j++)
for (let i = 0; i <= nu; i++) {
const s = i / nu;
const t = j / nv;
if (j === 0) at.push(bottom[i]);
else if (j === nv) at.push(top[i]);
else if (i === 0) at.push(left[j]);
else if (i === nu) at.push(right[j]);
else {
const c = (k: 0 | 1) =>
(1 - t) * bottom[i][k] + t * top[i][k] + (1 - s) * left[j][k] + s * right[j][k] -
((1 - s) * (1 - t) * bottom[0][k] + s * (1 - t) * bottom[nu][k] + (1 - s) * t * top[0][k] + s * t * top[nu][k]);
at.push([c(0), c(1)]);
}
}
// A face that isn't convex (an L): the blend can put points outside it.
// Evened out (each inside point to the middle of its four neighbours) a
// step at a time, till they're all on the face (evened out all the way they
// can end up outside again); never: null (a coarser grid may do).
const inside = (p: P2) => {
let w = false;
for (let a = 0, b = N - 1; a < N; b = a++) {
const [pa, pb] = [loop[a], loop[b]];
if (pa[1] > p[1] !== pb[1] > p[1] && p[0] < ((pb[0] - pa[0]) * (p[1] - pa[1])) / (pb[1] - pa[1]) + pa[0]) w = !w;
}
return w;
};
const allIn = () => at.every((p, k) => k % (nu + 1) === 0 || k % (nu + 1) === nu || k <= nu || k >= nv * (nu + 1) || inside(p));
for (let round = 0; round < 400 && !allIn(); round++)
for (let j = 1; j < nv; j++)
for (let i = 1; i < nu; i++) {
const q = [at[id(i - 1, j)], at[id(i + 1, j)], at[id(i, j - 1)], at[id(i, j + 1)]];
at[id(i, j)] = [(q[0][0] + q[1][0] + q[2][0] + q[3][0]) / 4, (q[0][1] + q[1][1] + q[2][1] + q[3][1]) / 4];
}
if (!allIn()) continue;
const verts: Vec3[] = at.map((p) => [u[0] * p[0] + v[0] * p[1], u[1] * p[0] + v[1] * p[1], u[2] * p[0] + v[2] * p[1]]);
const faces: [number, number, number, number][] = [];
for (let j = 0; j < nv; j++) for (let i = 0; i < nu; i++) faces.push([id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)]);
return { verts, faces };
}
return null;
}
/**
* Freeform Face over several faces side by side (a top and the side it bends
* into): one way they all face - the middle of their normals - to lay one grid
* over all of them, seen along it.
*/
export function facesNormal(normals: Vec3[]): Vec3 {
const s = normals.reduce((a, n) => {
const m = norm(n);
return [a[0] + m[0], a[1] + m[1], a[2] + m[2]] as Vec3;
}, [0, 0, 0] as Vec3);
return norm(s);
}
/**
* How far along `normal` from `p` the faces made of `tris` are (the nearest
* way; null when no triangle is under or over it).
*/
export function toFaces(p: Vec3, normal: Vec3, tris: [Vec3, Vec3, Vec3][]): number | null {
let best: number | null = null;
for (const [a, b, c] of tris) {
// Where the line p + t·normal meets the triangle's plane, and whether that is inside it.
const e1 = sub(b, a);
const e2 = sub(c, a);
const h = cross(normal, e2);
const det = dot(e1, h);
if (Math.abs(det) < 1e-12) continue;
const s = sub(p, a);
const u = dot(s, h) / det;
const q = cross(s, e1);
const v = dot(normal, q) / det;
const eps = 1e-6;
if (u < -eps || v < -eps || u + v > 1 + eps) continue;
const t = dot(e2, q) / det;
if (best === null || Math.abs(t) < Math.abs(best)) best = t;
}
return best;
}
/** A grid laid flat (points relative to `center`) put down onto the faces it was laid over, each point straight along `normal`. */
export function liftOnto(cage: Cage, center: Vec3, normal: Vec3, tris: [Vec3, Vec3, Vec3][]): Cage {
const n = norm(normal);
return {
faces: cage.faces,
verts: cage.verts.map((v) => {
const t = toFaces([center[0] + v[0], center[1] + v[1], center[2] + v[2]], n, tris);
return t === null || Math.abs(t) < 1e-9 ? v : ([v[0] + n[0] * t, v[1] + n[1] * t, v[2] + n[2] * t] as Vec3);
}),
};
}
/**
* Where the outline of faces side by side turns sharply (a top meeting the
* side it bends into: its outline turns down there), the nearest border point
* of the grid goes right onto that corner - the smooth surface's border bends
* only at its points, and would cut the corner off the body's edge. (Points
* relative to `center`.)
*/
export function onCorners(cage: Cage, center: Vec3, tris: [Vec3, Vec3, Vec3][]): Cage {
const key = (p: Vec3) => p.map((x) => Math.round(x * 1e4)).join(",");
const at = new Map<string, Vec3>();
const uses = new Map<string, number>();
for (const t of tris)
for (let k = 0; k < 3; k++) {
const a = key(t[k]);
const b = key(t[(k + 1) % 3]);
if (a === b) continue;
at.set(a, t[k]);
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
uses.set(e, (uses.get(e) ?? 0) + 1);
}
const nb = new Map<string, string[]>();
for (const [e, c] of uses) {
if (c !== 1) continue;
const [a, b] = e.split("|");
nb.set(a, [...(nb.get(a) ?? []), b]);
nb.set(b, [...(nb.get(b) ?? []), a]);
}
const corners: Vec3[] = [];
for (const [k, ns] of nb) {
if (ns.length !== 2) continue;
const p = at.get(k)!;
const d1 = norm(sub(p, at.get(ns[0])!));
const d2 = norm(sub(at.get(ns[1])!, p));
if (dot(d1, d2) < Math.cos((25 * Math.PI) / 180)) corners.push(p);
}
const border = new Set<number>();
const count = new Map<string, number>();
for (const f of cage.faces)
for (let k = 0; k < 4; k++) {
const a = f[k];
const b = f[(k + 1) % 4];
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
count.set(e, (count.get(e) ?? 0) + 1);
}
for (const [e, c] of count) if (c === 1) for (const v of e.split("|")) border.add(Number(v));
const verts = cage.verts.map((v) => [...v] as Vec3);
const taken = new Set<number>();
for (const c of corners) {
const rel = sub(c, center);
let best = -1;
let bd = Infinity;
for (const i of border) {
const d = Math.hypot(verts[i][0] - rel[0], verts[i][1] - rel[1], verts[i][2] - rel[2]);
if (d < bd) ((bd = d), (best = i));
}
if (best < 0 || taken.has(best)) continue;
taken.add(best);
verts[best] = rel;
}
return { faces: cage.faces, verts };
}
+229
View File
@@ -0,0 +1,229 @@
// More file formats: GLB out (glTF's one-file form, for the web, AR and
// renderers) and 3MF in (slicer files: the exact model packed in one of ours,
// else its meshes).
// ------------------------------------------------------------------ unzip
/** The files of a ZIP archive (what 3MF is), by name. */
export async function unzip(bytes: Uint8Array): Promise<Map<string, Uint8Array>> {
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
let end = -1;
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 65557); i--)
if (dv.getUint32(i, true) === 0x06054b50) {
end = i;
break;
}
if (end < 0) throw new Error("it isn't a ZIP-based file, or it is damaged");
const count = dv.getUint16(end + 10, true);
let at = dv.getUint32(end + 16, true);
const out = new Map<string, Uint8Array>();
const dec = new TextDecoder();
for (let k = 0; k < count; k++) {
if (dv.getUint32(at, true) !== 0x02014b50) throw new Error("the file is damaged");
const method = dv.getUint16(at + 10, true);
const packed = dv.getUint32(at + 20, true);
const n = dv.getUint16(at + 28, true);
const extra = dv.getUint16(at + 30, true);
const comment = dv.getUint16(at + 32, true);
const local = dv.getUint32(at + 42, true);
const name = dec.decode(bytes.subarray(at + 46, at + 46 + n));
const start = local + 30 + dv.getUint16(local + 26, true) + dv.getUint16(local + 28, true);
const data = bytes.subarray(start, start + packed);
if (!name.endsWith("/")) out.set(name, method === 8 ? await inflate(data) : data);
at += 46 + n + extra + comment;
}
return out;
}
async function inflate(d: Uint8Array): Promise<Uint8Array> {
const s = new Blob([d as BlobPart]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
return new Uint8Array(await new Response(s).arrayBuffer());
}
// -------------------------------------------------------------------- 3MF
const UNIT_MM: Record<string, number> = { micron: 0.001, millimeter: 1, centimeter: 10, inch: 25.4, foot: 304.8, meter: 1000 };
const attrs = (s: string) => Object.fromEntries([...s.matchAll(/([\w:]+)\s*=\s*"([^"]*)"/g)].map((m) => [m[1].replace(/^\w+:/, ""), m[2]]));
type M = number[];
/** 3MF's 3×4 matrix ("m00 m01 m02 m10 … m32"), points as rows: p·M. */
const matrix = (t?: string): M => (t ? t.trim().split(/\s+/).map(Number) : [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
const apply = (m: M, p: number[]) => [p[0] * m[0] + p[1] * m[3] + p[2] * m[6] + m[9], p[0] * m[1] + p[1] * m[4] + p[2] * m[7] + m[10], p[0] * m[2] + p[1] * m[5] + p[2] * m[8] + m[11]];
/** a then b. */
const compose = (a: M, b: M): M => {
const r: M = [];
for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) r[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j];
const t = apply(b, [a[9], a[10], a[11]]);
return [...r, ...t];
};
/**
* A 3MF file as something to import: the exact STEP model when it carries one
* (ours do), else its meshes - each build item, its components placed - as a
* binary STL, in millimetres.
*/
export async function read3mf(bytes: Uint8Array): Promise<{ format: "step" | "stl"; bytes: Uint8Array }> {
const files = await unzip(bytes);
for (const [name, data] of files) if (/\.(step|stp)$/i.test(name)) return { format: "step", bytes: data };
const modelName = [...files.keys()].find((n) => /^\/?3D\/.*\.model$/i.test(n));
if (!modelName) throw new Error("it has no 3D model in it");
const xml = new TextDecoder().decode(files.get(modelName));
const unit = UNIT_MM[attrs(xml.match(/<(?:\w+:)?model\b([^>]*)>/)?.[1] ?? "").unit ?? "millimeter"] ?? 1;
type Obj = { v: number[][]; t: number[][]; parts: { id: string; m: M }[] };
const objects = new Map<string, Obj>();
for (const o of xml.matchAll(/<(?:\w+:)?object\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?object>)/g)) {
const body = o[2] ?? "";
const v = [...body.matchAll(/<(?:\w+:)?vertex\b([^>]*)>/g)].map((m) => {
const a = attrs(m[1]);
return [Number(a.x), Number(a.y), Number(a.z)];
});
const t = [...body.matchAll(/<(?:\w+:)?triangle\b([^>]*)>/g)].map((m) => {
const a = attrs(m[1]);
return [Number(a.v1), Number(a.v2), Number(a.v3)];
});
const parts = [...body.matchAll(/<(?:\w+:)?component\b([^>]*)>/g)].map((m) => {
const a = attrs(m[1]);
return { id: a.objectid, m: matrix(a.transform) };
});
objects.set(attrs(o[1]).id, { v, t, parts });
}
const tris: number[][][] = [];
const add = (id: string, m: M, depth: number) => {
const o = objects.get(id);
if (!o || depth > 16) return;
for (const [a, b, c] of o.t) {
if (![a, b, c].every((k) => Number.isInteger(k) && k >= 0 && k < o.v.length)) continue;
tris.push([a, b, c].map((k) => apply(m, o.v[k]).map((x) => x * unit)));
}
for (const p of o.parts) add(p.id, compose(p.m, m), depth + 1);
};
const items = [...xml.matchAll(/<(?:\w+:)?item\b([^>]*)>/g)].map((m) => attrs(m[1]));
if (items.length) for (const it of items) add(it.objectid, matrix(it.transform), 0);
else for (const id of objects.keys()) add(id, matrix(), 0);
if (!tris.length) throw new Error("it has no triangles in it");
return { format: "stl", bytes: stlOf(tris) };
}
/** Triangles as a binary STL (normals left zero: readers work them out). */
function stlOf(tris: number[][][]): Uint8Array {
const buf = new ArrayBuffer(84 + tris.length * 50);
const dv = new DataView(buf);
dv.setUint32(80, tris.length, true);
let o = 84;
for (const t of tris) {
o += 12;
for (const p of t) for (const x of p) (dv.setFloat32(o, x, true), (o += 4));
o += 2;
}
return new Uint8Array(buf);
}
// -------------------------------------------------------------------- GLB
export interface GlbBody {
name: string;
positions: Float32Array;
indices: Uint32Array;
/** "#rrggbb" */
color?: string;
opacity?: number;
}
/** sRGB "#rrggbb" to glTF's linear colour. */
const linear = (hex: string) =>
[1, 3, 5].map((i) => {
const c = parseInt(hex.slice(i, i + 2), 16) / 255;
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
/**
* The bodies as one GLB: a mesh each (smooth normals, its colour), named,
* under a root that turns Z up into glTF's Y up and millimetres into metres.
*/
export function glb(bodies: GlbBody[], title: string): Uint8Array {
const chunks: Uint8Array[] = [];
let length = 0;
const views: object[] = [];
const accessors: object[] = [];
const push = (data: ArrayBufferView, target: number) => {
const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
views.push({ buffer: 0, byteOffset: length, byteLength: bytes.length, target });
chunks.push(bytes);
length += bytes.length;
const pad = (4 - (length % 4)) % 4;
if (pad) (chunks.push(new Uint8Array(pad)), (length += pad));
return views.length - 1;
};
const meshes: object[] = [];
const materials: object[] = [];
const nodes: object[] = [{ name: title, rotation: [-Math.SQRT1_2, 0, 0, Math.SQRT1_2], scale: [0.001, 0.001, 0.001], children: bodies.map((_, i) => i + 1) }];
bodies.forEach((b, i) => {
const p = b.positions;
const n = new Float32Array(p.length);
// Smooth normals: each corner's, from the triangles round it (weighted by their size).
for (let t = 0; t < b.indices.length; t += 3) {
const [a, c, d] = [b.indices[t], b.indices[t + 1], b.indices[t + 2]];
const u = [p[3 * c] - p[3 * a], p[3 * c + 1] - p[3 * a + 1], p[3 * c + 2] - p[3 * a + 2]];
const v = [p[3 * d] - p[3 * a], p[3 * d + 1] - p[3 * a + 1], p[3 * d + 2] - p[3 * a + 2]];
const x = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
for (const k of [a, c, d]) for (let j = 0; j < 3; j++) n[3 * k + j] += x[j];
}
for (let k = 0; k < n.length; k += 3) {
const l = Math.hypot(n[k], n[k + 1], n[k + 2]) || 1;
n[k] /= l;
n[k + 1] /= l;
n[k + 2] /= l;
}
const min = [Infinity, Infinity, Infinity];
const max = [-Infinity, -Infinity, -Infinity];
for (let k = 0; k < p.length; k += 3)
for (let j = 0; j < 3; j++) {
min[j] = Math.min(min[j], p[k + j]);
max[j] = Math.max(max[j], p[k + j]);
}
const count = p.length / 3;
accessors.push({ bufferView: push(new Float32Array(p), 34962), componentType: 5126, count, type: "VEC3", min, max });
accessors.push({ bufferView: push(n, 34962), componentType: 5126, count, type: "VEC3" });
accessors.push({ bufferView: push(new Uint32Array(b.indices), 34963), componentType: 5125, count: b.indices.length, type: "SCALAR" });
const alpha = b.opacity ?? 1;
materials.push({
name: b.name,
pbrMetallicRoughness: { baseColorFactor: [...linear(b.color ?? "#b8bcc6"), alpha], metallicFactor: 0, roughnessFactor: 0.6 },
...(alpha < 1 ? { alphaMode: "BLEND" } : {}),
});
meshes.push({ name: b.name, primitives: [{ attributes: { POSITION: 3 * i, NORMAL: 3 * i + 1 }, indices: 3 * i + 2, material: i }] });
nodes.push({ name: b.name, mesh: i });
});
const json = {
asset: { version: "2.0", generator: "superGeometry.app" },
scene: 0,
scenes: [{ name: title, nodes: [0] }],
nodes,
meshes,
materials,
accessors,
bufferViews: views,
buffers: [{ byteLength: length }],
};
let jsonBytes = new TextEncoder().encode(JSON.stringify(json));
const jpad = (4 - (jsonBytes.length % 4)) % 4;
if (jpad) {
const padded = new Uint8Array(jsonBytes.length + jpad).fill(0x20);
padded.set(jsonBytes);
jsonBytes = padded;
}
const total = 12 + 8 + jsonBytes.length + 8 + length;
const out = new Uint8Array(total);
const dv = new DataView(out.buffer);
dv.setUint32(0, 0x46546c67, true); // "glTF"
dv.setUint32(4, 2, true);
dv.setUint32(8, total, true);
dv.setUint32(12, jsonBytes.length, true);
dv.setUint32(16, 0x4e4f534a, true); // "JSON"
out.set(jsonBytes, 20);
let o = 20 + jsonBytes.length;
dv.setUint32(o, length, true);
dv.setUint32(o + 4, 0x004e4942, true); // "BIN"
o += 8;
for (const c of chunks) (out.set(c, o), (o += c.length));
return out;
}
+180 -27
View File
@@ -1,26 +1,58 @@
// Insert menu: files (STEP/STL/OBJ/DXF/projects), images, variables.
import { migrate, newId } from "../doc/store";
import { newId, parseProject } from "../doc/store";
import type { Feature, ImageFeature, PlaneDef, SketchEntity, SketchFeature } from "../doc/types";
import { GROUND } from "../geom";
import { uid } from "../sketch/edit";
import type { AppContext } from "../tools/tool";
import { bareExpr, evaluate, fmtLen, setVariables, withUnitOf } from "../units";
import { bareExpr, evaluate, fmtLen, RESERVED, setVariables, withUnitOf } from "../units";
import { namesIn } from "../doc/varAnchors";
import { nameProblem, renameVariable } from "../doc/renameVariable";
import { DIALOG_ACTION } from "../ui/dialogAction";
import { read3mf } from "./formats";
import { parseSVG } from "./svg";
/**
* What a file picker is told to offer. On an iPad or iPhone, nothing: told a list of endings (".stl,.step,.super"),
* the Files window there greys out every file whose kind it has no name for - STL and STEP files and the app's own
* projects could not be tapped (reported from an iPad, files in iCloud Drive). Every file can be picked there, and
* one that is not of a kind the app reads is said so once picked. (A list of kinds alone, "image/*", is understood.)
*/
export function acceptFor(accept: string): string {
const apple = /iPad|iPhone|iPod/.test(navigator.userAgent) || (/Macintosh/.test(navigator.userAgent) && navigator.maxTouchPoints > 1);
return apple && accept.split(",").some((a) => a.trim().startsWith(".")) ? "" : accept;
}
export function pickFile(accept: string): Promise<File | null> {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = accept;
input.accept = acceptFor(accept);
input.onchange = () => resolve(input.files?.[0] ?? null);
input.click();
});
}
/** Why a mesh / STEP file can't be what it says (null: it looks right). */
function unreadable(bytes: Uint8Array, format: "step" | "stl"): string | null {
if (format === "step") {
const head = new TextDecoder().decode(bytes.subarray(0, 4096));
if (!/ISO-10303-21/.test(head)) return "it isn't a STEP file";
if (!new TextDecoder().decode(bytes).includes("DATA;")) return "the file is damaged (it has no shapes in it)";
return null;
}
// Binary STL: 80 bytes, a triangle count, 50 bytes per triangle.
if (bytes.length >= 84) {
const n = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(80, true);
if (n > 0 && 84 + n * 50 === bytes.length) return null;
}
const text = new TextDecoder().decode(bytes);
if (/\bfacet\b/i.test(text) && /\bvertex\b/i.test(text)) return null;
return bytes.length ? "it isn't an STL file, or it is damaged" : "the file is empty";
}
export async function insertFile(app: AppContext): Promise<void> {
const file = await pickFile(".step,.stp,.stl,.obj,.dxf,.svg,.dwg,.super,.tessel");
const file = await pickFile(".step,.stp,.stl,.obj,.3mf,.dxf,.svg,.dwg,.super,.tessel");
if (!file) return;
const ext = file.name.split(".").pop()!.toLowerCase();
try {
@@ -45,17 +77,25 @@ export async function insertFile(app: AppContext): Promise<void> {
return;
}
if (ext === "super" || ext === "tessel") {
insertProject(app, migrate(JSON.parse(await file.text())).features, file.name);
insertProject(app, parseProject(await file.text()).features, file.name);
return;
}
// (Any file can be picked on an iPad: see acceptFor.)
if (!["step", "stp", "stl", "obj", "3mf"].includes(ext)) return app.ui.toast(`Could not insert ${file.name}: it is not a kind of file the app reads (STEP, STL, OBJ, 3MF, DXF, SVG or a project)`, "error");
let bytes: Uint8Array = new Uint8Array(await file.arrayBuffer());
let format: "step" | "stl" = ext === "stl" ? "stl" : "step";
if (ext === "obj") {
bytes = objToStl(new TextDecoder().decode(bytes));
format = "stl";
}
// 3MF: the exact model packed in it (ours), else its meshes.
if (ext === "3mf") ({ format, bytes } = await read3mf(bytes));
// A damaged or wrong file stops here, not as a failed step in History
// (that kept the broken file in the project).
const why = unreadable(bytes, format);
if (why) return app.ui.toast(`Could not insert ${file.name}: ${why}`, "error");
app.ui.setStatus(`Importing ${file.name}…`);
app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes) });
app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes), apart: true });
app.ui.setStatus(null);
} catch (err) {
app.ui.setStatus(null);
@@ -76,14 +116,32 @@ function insertProject(app: AppContext, features: Feature[], name: string): void
export async function insertImage(app: AppContext, plane: PlaneDef = GROUND): Promise<ImageFeature | null> {
const file = await pickFile("image/*");
if (!file) return null;
const src = await new Promise<string>((resolve) => {
let src = await new Promise<string>((resolve) => {
const r = new FileReader();
r.onload = () => resolve(r.result as string);
r.readAsDataURL(file);
});
const img = new Image();
img.src = src;
await img.decode();
try {
await img.decode();
} catch {
app.ui.toast(`${file.name} can't be shown here - save it as JPG or PNG first (an iPhone's HEIC photos too)`, "error");
return null;
}
// A phone photo (4000 px, 12 MB) kept whole went into the project and was
// saved again on every change, and wider than a phone can draw (4096 px):
// 2048 px across is plenty to trace over.
const MAX = 2048;
const k = Math.min(1, MAX / Math.max(img.width, img.height));
if (k < 1 || file.size > 2e6) {
const c = document.createElement("canvas");
c.width = Math.round(img.width * k);
c.height = Math.round(img.height * k);
c.getContext("2d")!.drawImage(img, 0, 0, c.width, c.height);
// PNG keeps see-through parts (a logo); a photo is smaller as JPEG.
src = file.type === "image/png" ? c.toDataURL("image/png") : c.toDataURL("image/jpeg", 0.85);
}
const width = 100;
const f: ImageFeature = { ...app.store.newIdentity("image"), type: "image", plane, src, width, height: (width * img.height) / img.width, opacity: 0.8 };
app.store.add(f);
@@ -91,29 +149,70 @@ export async function insertImage(app: AppContext, plane: PlaneDef = GROUND): Pr
return f;
}
/** Create a named variable (optionally from a field's current value); returns its name. */
/**
* Create a named variable (optionally from a field's current value); returns
* its name. "Add Another" at the top makes it and opens a fresh one (a window
* needs twenty: the dialog had to be reopened from the card each time) - the
* name returned is still the first one's, the one made from the field's value.
*/
export async function createVariable(app: AppContext, value = ""): Promise<string | null> {
let first: string | null = null;
let name = "";
for (;;) {
const r = await createOne(app, name, value);
first ??= r.made;
// A bad name or value: the next window has what was typed, to put right (after OK too: the window closed, and
// what was typed was gone).
const again = !r.made && !!(r.typed.name.trim() || r.typed.expr.trim());
if (!r.another && !again) return first;
[name, value] = r.made ? ["", ""] : [r.typed.name, r.typed.expr];
}
}
async function createOne(app: AppContext, name: string, value: string): Promise<{ made: string | null; another: boolean; typed: { name: string; expr: string } }> {
const list = app.store.doc.variables;
const note = list.length ? `Existing: ${list.map((v) => `${v.name} = ${v.expr}`).join(", ")}` : "Use variables in any field, e.g. width*2 or wall + 1mm.";
const v = await app.ui.dialog("Create Variable", [
{ key: "name", label: "Name", value: "", placeholder: "width" },
{ key: "name", label: "Name", value: name, placeholder: "width" },
{ key: "expr", label: "Value", value, placeholder: "40 or 1.5in or depth/2" },
], note);
if (!v) return null;
], note, { label: "Add Another", icon: "variableNew" });
if (!v) return { made: null, another: false, typed: { name: "", expr: "" } };
return { made: makeVariable(app, list, v), another: !!v[DIALOG_ACTION], typed: { name: v.name, expr: v.expr } };
}
function makeVariable(app: AppContext, list: AppContext["store"]["doc"]["variables"], v: Record<string, string>): string | null {
const name = v.name.trim();
if (!/^[a-z_][a-z0-9_]*$/i.test(name) || /^(mm|cm|m|in|ft)$/i.test(name)) {
app.ui.toast("Names use letters, digits and _ (not starting with a digit, not a unit)", "error");
// (A variable called sin or pi hid the function: sin(30) stopped working.)
if (!/^[a-z_][a-z0-9_]*$/i.test(name) || RESERVED.test(name)) {
app.ui.toast("Names use letters, digits and _ (not starting with a digit, and not a unit or a function like sin or pi)", "error");
return null;
}
// (od and Od would be two variables, and one typed for the other is a wrong size with nothing said.)
const twin = list.find((x) => x.name !== name && x.name.toLowerCase() === name.toLowerCase());
if (twin) {
app.ui.toast(`There is a variable ${twin.name} already: ${name} differs only in its capitals`, "error");
return null;
}
const was = list.find((x) => x.name === name);
const next = [...list.filter((x) => x.name !== name), { name, expr: v.expr.trim() || "0" }];
setVariables(next);
if (evaluate(v.expr || "0") === null) {
// (An angle - "30 deg" - is a value too: it was refused here, and taken in the list of them all.)
if (evaluate(v.expr || "0") === null && evaluate(v.expr || "0", "angle") === null) {
setVariables(list);
app.ui.toast(`"${v.expr}" isn't a valid value`, "error");
const unknown = namesIn(v.expr).filter((x) => x !== name && !next.some((y) => y.name === x) && !RESERVED.test(x));
app.ui.toast(
new RegExp(`(^|[^A-Za-z0-9_])${name}($|[^A-Za-z0-9_])`).test(v.expr)
? `${name} can't use itself`
: unknown.length
? `${unknown.join(", ")}: no variable has that name`
: `"${v.expr}" isn't a valid value`,
"error",
);
return null;
}
app.store.commit((d) => (d.variables = next));
app.ui.toast(`${name} = ${v.expr}`);
// (One there already by that name is changed, and said so.)
app.ui.toast(was && was.expr !== v.expr.trim() ? `${name} changed: ${was.expr} → ${v.expr.trim()}` : `${name} = ${v.expr}`);
return name;
}
@@ -138,26 +237,80 @@ export async function editVariables(app: AppContext): Promise<void> {
// Shown without the unit in use ("220"): a plain number keeps the unit it had.
const next = list.filter((x) => v[x.name]?.trim()).map((x) => ({ name: x.name, expr: withUnitOf(v[x.name], x.expr) }));
setVariables(next);
const bad = next.find((x) => evaluate(x.expr) === null);
// (An angle - "30 deg" - is a value too: it was refused as a length.)
const bad = next.find((x) => evaluate(x.expr) === null && evaluate(x.expr, "angle") === null);
if (bad) {
setVariables(list);
return app.ui.toast(`"${bad.expr}" isn't a valid value for ${bad.name}`, "error");
// (Said as it is: another variable still uses the one being deleted.)
const lost = list.filter((x) => !next.some((y) => y.name === x.name)).find((x) => new RegExp(`(^|[^A-Za-z0-9_])${x.name}($|[^A-Za-z0-9_])`).test(bad.expr));
return app.ui.toast(lost ? `${bad.name} uses ${lost.name} (${bad.name} = ${bad.expr}): change ${bad.name} first` : `"${bad.expr}" isn't a valid value for ${bad.name}`, "error");
}
if (next.some((x, i) => x.name !== list[i]?.name || x.expr !== list[i]?.expr) || next.length !== list.length) app.store.commit((d) => (d.variables = next));
// Deleted while steps still use it: they keep the sizes they have now, as
// plain numbers (else every rebuild said "can't be evaluated").
const gone = list.filter((x) => !next.some((y) => y.name === x.name)).map((x) => x.name);
// (Capitals count: W deleted is not w deleted.)
const uses = (expr: string) => gone.some((n) => new RegExp(`(^|[^A-Za-z0-9_])${n}($|[^A-Za-z0-9_])`).test(expr));
let kept = 0;
if (next.some((x, i) => x.name !== list[i]?.name || x.expr !== list[i]?.expr) || next.length !== list.length)
app.store.commit((d) => {
d.variables = next;
for (const f of d.features) {
for (const [path, expr] of Object.entries(f.exprs ?? {})) if (uses(expr)) (delete f.exprs![path], kept++);
// (A sketch pattern that followed it: its copies stay as they are, plain curves from now on.)
if (f.type === "sketch" && f.repeats?.some((r) => uses(r.countExpr))) {
kept += f.repeats.filter((r) => uses(r.countExpr)).length;
f.repeats = f.repeats.filter((r) => !uses(r.countExpr));
if (!f.repeats.length) delete f.repeats;
}
if (f.type === "sketch")
for (const c of f.constraints ?? []) {
if (c.expr && uses(c.expr)) (delete c.expr, kept++);
// (A point placed by it too: left, every rebuild said it can't be evaluated.)
if (c.atExpr?.some((e) => e && uses(e))) {
c.atExpr = c.atExpr.map((e) => (e && uses(e) ? null : e));
if (!c.atExpr.some((e) => e)) delete c.atExpr;
kept++;
}
}
}
});
if (kept) app.ui.toast(`${gone.join(", ")} deleted - the ${kept === 1 ? "size" : `${kept} sizes`} that used ${gone.length > 1 ? "them" : "it"} ${kept === 1 ? "keeps its value" : "keep their values"}`);
}
if (!v[DIALOG_ACTION]) return;
await createVariable(app);
}
}
export async function editImage(app: AppContext, f: ImageFeature): Promise<void> {
const v = await app.ui.dialog("Image", [
{ key: "width", label: "Width (mm)", value: String(f.width) },
{ key: "opacity", label: "Opacity (0–1)", value: String(f.opacity) },
]);
/**
* Rename Variables: each variable's name in a box, to change. Everything that uses a renamed variable - other
* variables, steps' sizes, sketch dimensions - says its new name; nothing changes size. (A variable could only be
* deleted and made again under another name, and what used it lost its link to it.)
*/
export async function renameVariables(app: AppContext): Promise<void> {
const list = app.store.doc.variables;
if (!list.length) return;
const v = await app.ui.dialog(
"Rename Variables",
list.map((x) => ({ key: x.name, label: `${x.name} = ${bareExpr(x.expr)}`, value: x.name })),
"Type a new name over an old one. Everything that uses it follows, and nothing changes size.",
);
if (!v) return;
const width = Number(v.width) || f.width;
app.store.update(f.id, { width, height: (f.height * width) / f.width, opacity: Math.min(1, Math.max(0.05, Number(v.opacity) || f.opacity)) });
const wanted = list.map((x) => ({ from: x.name, to: (v[x.name] ?? x.name).trim() || x.name })).filter((x) => x.from !== x.to);
if (!wanted.length) return;
// Tried on a copy first: all of them, or none (two swapping names go by way of a spare one).
const trial = structuredClone(app.store.doc);
const spare = (i: number) => `__renaming_${i}__`;
wanted.forEach((w, i) => renameVariable(trial, w.from, spare(i)));
for (const [i, w] of wanted.entries()) {
const problem = nameProblem(trial, spare(i), w.to);
if (problem) return app.ui.toast(`${w.from} → ${w.to}: ${problem}`, "error");
renameVariable(trial, spare(i), w.to);
}
app.store.commit((d) => {
d.variables = trial.variables;
d.features = trial.features;
});
app.ui.toast(wanted.length === 1 ? `${wanted[0].from} is ${wanted[0].to} now, everywhere it is used` : `${wanted.length} variables renamed, everywhere they are used`);
}
// -------------------------------------------------------------------- DXF
+335
View File
@@ -0,0 +1,335 @@
// DXF of a drawing sheet (for CAD programs): the sheet's SVG read back and
// written as AutoCAD R12 DXF, millimetres, y up. Lines, arcs and circles stay
// exact; text stays text; arrowheads are solids; the hatching of a section is
// written out as lines; a detail view is cut to its circle. Layers by kind of
// line: VISIBLE, THIN (dimensions, the frame, hatching), HIDDEN (dashed),
// CENTER (centrelines), TEXT.
type M = [number, number, number, number, number, number];
type P = [number, number];
const n = (v: number) => (Math.abs(v) < 1e-9 ? "0" : String(Math.round(v * 1e5) / 1e5));
const deg = (r: number) => ((((r * 180) / Math.PI) % 360) + 360) % 360;
const mul = (a: M, b: M): M => [a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1], a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3], a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]];
const apply = (m: M, p: P): P => [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]];
const ID: M = [1, 0, 0, 1, 0, 0];
/** A transform="…" (rotate and translate, as the sheet writes them). */
function transformOf(t: string | undefined): M {
let m = ID;
if (!t) return m;
for (const [, k, args] of t.matchAll(/(rotate|translate|matrix|scale)\(([^)]*)\)/g)) {
const a = args.split(/[\s,]+/).filter(Boolean).map(Number);
if (k === "translate") m = mul(m, [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0]);
else if (k === "scale") m = mul(m, [a[0], 0, 0, a[1] ?? a[0], 0, 0]);
else if (k === "matrix") m = mul(m, a as M);
else {
const r = ((a[0] ?? 0) * Math.PI) / 180;
const [cx, cy] = [a[1] ?? 0, a[2] ?? 0];
m = mul(m, mul([1, 0, 0, 1, cx, cy], mul([Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0], [1, 0, 0, 1, -cx, -cy])));
}
}
return m;
}
const unescape = (s: string) =>
s
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&apos;|&#39;/g, "'")
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
.replace(/&amp;/g, "&");
/** Text as R12 writes it: Ø ± ° as its codes, other letters past ASCII as \U+XXXX. */
const dxfText = (s: string) =>
s.replace(/[^\x20-\x7e]/gu, (c) => (c === "Ø" || c === "ø" || c === "⌀" ? "%%c" : c === "±" ? "%%p" : c === "°" ? "%%d" : `\\U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`));
interface Style {
stroke: string;
width: number;
dash: string;
fill: string;
m: M;
/** Cut to this circle (a detail view). */
clip?: { c: P; r: number };
/** Filled with this hatch (its angle, degrees). */
hatch?: number;
}
/** A segment a→b cut to a circle: the parts inside. */
function clipToCircle(a: P, b: P, c: P, r: number): [P, P][] {
const d: P = [b[0] - a[0], b[1] - a[1]];
const f: P = [a[0] - c[0], a[1] - c[1]];
const A = d[0] * d[0] + d[1] * d[1];
if (A < 1e-18) return [];
const B = 2 * (f[0] * d[0] + f[1] * d[1]);
const C = f[0] * f[0] + f[1] * f[1] - r * r;
const disc = B * B - 4 * A * C;
if (disc <= 0) return [];
const s = Math.sqrt(disc);
const t0 = Math.max(0, (-B - s) / (2 * A));
const t1 = Math.min(1, (-B + s) / (2 * A));
if (t1 <= t0) return [];
return [
[
[a[0] + d[0] * t0, a[1] + d[1] * t0],
[a[0] + d[0] * t1, a[1] + d[1] * t1],
],
];
}
/** The sheet (its SVG, mm, y down, `H` tall) as a DXF file's text. */
export function sheetToDXF(svg: string): string {
const vb = /viewBox="([^"]+)"/.exec(svg)?.[1].split(/\s+/).map(Number) ?? [0, 0, 420, 297];
const H = vb[3];
const flip = (p: P): P => [p[0], H - p[1]];
const out: string[] = [];
const head = (type: string, layer: string) => out.push("0", type, "8", layer);
const layerOf = (s: Style): string | null => {
if (s.dash === "3 1") return "HIDDEN";
if (s.dash && s.dash !== "none") return /^(8 |1\.5 1 6)/.test(s.dash) ? "CENTER" : null;
return s.width >= 0.4 ? "VISIBLE" : "THIN";
};
const line = (a: P, b: P, s: Style, layer: string) => {
const segs: [P, P][] = s.clip ? clipToCircle(a, b, s.clip.c, s.clip.r) : [[a, b]];
for (const [p, q] of segs) {
const [P1, P2] = [flip(apply(s.m, p)), flip(apply(s.m, q))];
if (Math.hypot(P2[0] - P1[0], P2[1] - P1[1]) < 1e-6) continue;
head("LINE", layer);
out.push("10", n(P1[0]), "20", n(P1[1]), "30", "0", "11", n(P2[0]), "21", n(P2[1]), "31", "0");
}
};
/** A circle's arc from angle a0 sweeping by `sweep` (SVG's angles, y down), or the whole circle. */
const arc = (c: P, r: number, a0: number, sweep: number, s: Style, layer: string) => {
if (s.clip) {
// Cut to a detail's circle: as short lines.
const k = Math.max(8, Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * 96));
let prev: P = [c[0] + r * Math.cos(a0), c[1] + r * Math.sin(a0)];
for (let i = 1; i <= k; i++) {
const t = a0 + (sweep * i) / k;
const q: P = [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)];
line(prev, q, s, layer);
prev = q;
}
return;
}
const C = flip(apply(s.m, c));
const rot = Math.atan2(s.m[1], s.m[0]);
if (Math.abs(Math.abs(sweep) - Math.PI * 2) < 1e-9) {
head("CIRCLE", layer);
out.push("10", n(C[0]), "20", n(C[1]), "30", "0", "40", n(r));
return;
}
// y flipped: SVG's angle t is -t; the DXF arc runs counter-clockwise.
const s0 = -(a0 + rot);
const s1 = -(a0 + sweep + rot);
const [from, to] = sweep >= 0 ? [s1, s0] : [s0, s1];
head("ARC", layer);
out.push("10", n(C[0]), "20", n(C[1]), "30", "0", "40", n(r), "50", n(deg(from)), "51", n(deg(to)));
};
const solid = (pts: P[], s: Style, layer: string) => {
const q = pts.map((p) => flip(apply(s.m, p)));
const c = [q[0], q[1], q[q.length - 1], q.length > 3 ? q[2] : q[q.length - 1]];
head("SOLID", layer);
out.push("10", n(c[0][0]), "20", n(c[0][1]), "30", "0", "11", n(c[1][0]), "21", n(c[1][1]), "31", "0", "12", n(c[2][0]), "22", n(c[2][1]), "32", "0", "13", n(c[3][0]), "23", n(c[3][1]), "33", "0");
};
/** Hatch lines inside the loops (even-odd), every 2.5 mm at `angle` degrees from the vertical, as the sheet's pattern. */
const hatchLines = (loops: P[][], angle: number, s: Style) => {
const r = (angle * Math.PI) / 180;
// In the pattern's own frame the lines are x = 2.5k.
const toPat = (p: P): P => [p[0] * Math.cos(r) + p[1] * Math.sin(r), -p[0] * Math.sin(r) + p[1] * Math.cos(r)];
const fromPat = (p: P): P => [p[0] * Math.cos(r) - p[1] * Math.sin(r), p[0] * Math.sin(r) + p[1] * Math.cos(r)];
const edges: [P, P][] = [];
for (const l of loops) for (let i = 0; i < l.length; i++) edges.push([toPat(l[i]), toPat(l[(i + 1) % l.length])]);
if (!edges.length) return;
const xs = edges.flatMap(([a, b]) => [a[0], b[0]]);
for (let k = Math.ceil(Math.min(...xs) / 2.5); k * 2.5 <= Math.max(...xs); k++) {
const x = k * 2.5;
const ys: number[] = [];
for (const [a, b] of edges) if (a[0] <= x !== b[0] <= x) ys.push(a[1] + ((x - a[0]) / (b[0] - a[0])) * (b[1] - a[1]));
ys.sort((p, q) => p - q);
for (let i = 0; i + 1 < ys.length; i += 2) line(fromPat([x, ys[i]]), fromPat([x, ys[i + 1]]), s, "THIN");
}
};
const pathOf = (d: string, s: Style) => {
const layer = s.hatch === undefined ? layerOf(s) : "THIN";
const filled = s.fill !== "none" && s.fill !== "transparent" && !s.fill.startsWith("url(");
const stroked = s.stroke !== "none";
if (!layer || (!stroked && !filled && s.hatch === undefined)) return;
const loops: P[][] = [];
let cur: P = [0, 0];
let start: P = [0, 0];
let loop: P[] = [];
const toks = d.match(/[MLHVAZmlhvaz]|-?(?:\d+\.?\d*|\.\d+)(?:e-?\d+)?/g) ?? [];
let i = 0;
let cmd = "";
const num = () => Number(toks[i++]);
const close = () => {
if (loop.length > 1) loops.push(loop);
loop = [];
};
while (i < toks.length) {
if (/[A-Za-z]/.test(toks[i])) cmd = toks[i++];
const C = cmd.toUpperCase();
if (C === "Z") {
if (stroked && s.hatch === undefined) line(cur, start, s, layer);
cur = start;
close();
continue;
}
if (C === "M") {
close();
cur = start = [num(), num()];
loop = [cur];
cmd = cmd === "m" ? "l" : "L";
continue;
}
let next: P;
if (C === "L") next = [num(), num()];
else if (C === "H") next = [num(), cur[1]];
else if (C === "V") next = [cur[0], num()];
else if (C === "A") {
const rx = num();
num();
num();
const large = num();
const sweepF = num();
next = [num(), num()];
// The circle through cur and next (SVG's endpoint form, rx = ry).
const dx = (cur[0] - next[0]) / 2;
const dy = (cur[1] - next[1]) / 2;
const r = Math.max(rx, Math.hypot(dx, dy));
const h = Math.sqrt(Math.max(0, r * r - dx * dx - dy * dy)) / Math.hypot(dx, dy || 1e-30);
const sg = large === sweepF ? 1 : -1;
const c: P = [(cur[0] + next[0]) / 2 + sg * h * -dy, (cur[1] + next[1]) / 2 + sg * h * dx];
const a0 = Math.atan2(cur[1] - c[1], cur[0] - c[0]);
let sw = Math.atan2(next[1] - c[1], next[0] - c[0]) - a0;
if (sweepF && sw < 0) sw += Math.PI * 2;
if (!sweepF && sw > 0) sw -= Math.PI * 2;
if (stroked && s.hatch === undefined) arc(c, r, a0, sw, s, layer);
for (let k = 1; k <= 12; k++) loop.push([c[0] + r * Math.cos(a0 + (sw * k) / 12), c[1] + r * Math.sin(a0 + (sw * k) / 12)]);
cur = next;
continue;
} else {
i++;
continue;
}
if (stroked && s.hatch === undefined) line(cur, next, s, layer);
loop.push(next);
cur = next;
}
close();
if (s.hatch !== undefined) return hatchLines(loops, s.hatch, s);
// A small filled shape, no outline (an arrowhead): a solid.
if (filled && !stroked) for (const l of loops) if (l.length >= 3 && l.length <= 4) solid(l, s, "THIN");
};
// ---- Walk the elements, styles and transforms handed down through groups.
const clips = new Map<string, { c: P; r: number }>();
for (const [, id, body] of svg.matchAll(/<clipPath id="([^"]+)">(.*?)<\/clipPath>/gs)) {
const c = /<circle cx="([-\d.]+)" cy="([-\d.]+)" r="([-\d.]+)"/.exec(body);
if (c) clips.set(id, { c: [Number(c[1]), Number(c[2])], r: Number(c[3]) });
}
const hatches = new Map<string, number>();
for (const [, id, a] of svg.matchAll(/<pattern id="([^"]+)"[^>]*patternTransform="rotate\(([-\d.]+)\)"/g)) hatches.set(id, Number(a));
const body = svg.replace(/<defs>.*?<\/defs>/gs, "").replace(/<clipPath[^>]*>.*?<\/clipPath>/gs, "").replace(/<pattern[^>]*>.*?<\/pattern>/gs, "");
const stack: Style[] = [{ stroke: "none", width: 0.25, dash: "", fill: "#000", m: ID }];
const attrs = (s: string) => Object.fromEntries([...s.matchAll(/([\w:-]+)="([^"]*)"/g)].map(([, k, v]) => [k, v]));
const styled = (a: Record<string, string>, up: Style): Style => {
const s: Style = {
stroke: a.stroke ?? up.stroke,
width: a["stroke-width"] !== undefined ? Number(a["stroke-width"]) : up.width,
dash: a["stroke-dasharray"] ?? up.dash,
fill: a.fill ?? up.fill,
m: a.transform ? mul(up.m, transformOf(a.transform)) : up.m,
clip: up.clip,
hatch: up.hatch,
};
const cp = /url\(#([^)]+)\)/.exec(a["clip-path"] ?? "")?.[1];
if (cp && clips.has(cp)) s.clip = clips.get(cp);
const hp = /url\(#([^)]+)\)/.exec(a.fill ?? "")?.[1];
s.hatch = hp && hatches.has(hp) ? hatches.get(hp) : undefined;
return s;
};
const tagRe = /<(\/?)([a-zA-Z]+)([^>]*?)(\/?)>|([^<]+)/g;
let textOf: { a: Record<string, string>; s: Style; t: string } | null = null;
for (const m of body.matchAll(tagRe)) {
const [, closing, tag, rest, self, txt] = m;
if (txt !== undefined) {
if (textOf) textOf.t += txt;
continue;
}
if (closing) {
if (tag === "g") stack.length > 1 && stack.pop();
if (tag === "text" && textOf) {
const { a, s, t } = textOf;
textOf = null;
const str = unescape(t).trim();
if (!str) continue;
const p = flip(apply(s.m, [Number(a.x ?? 0), Number(a.y ?? 0)]));
const size = Number(a["font-size"] ?? 3.5);
const rot = -deg(Math.atan2(s.m[1], s.m[0]));
const just = a["text-anchor"] === "middle" ? 1 : a["text-anchor"] === "end" ? 2 : 0;
head("TEXT", "TEXT");
out.push("10", n(p[0]), "20", n(p[1]), "30", "0", "40", n(size * 0.7), "1", dxfText(str), "50", n(((rot % 360) + 360) % 360));
if (just) out.push("72", String(just), "11", n(p[0]), "21", n(p[1]), "31", "0");
}
continue;
}
const a = attrs(rest);
const up = stack[stack.length - 1];
if (tag === "g") {
const s = styled(a, up);
if (!self) stack.push(s);
continue;
}
if (tag === "text") {
textOf = { a, s: styled(a, up), t: "" };
continue;
}
const s = styled(a, up);
if (tag === "path" && a.d) pathOf(a.d, s);
else if (tag === "line") pathOf(`M${a.x1} ${a.y1}L${a.x2} ${a.y2}`, s);
else if (tag === "rect" && s.stroke !== "none") {
const [x, y, w, h] = [Number(a.x ?? 0), Number(a.y ?? 0), Number(a.width), Number(a.height)];
pathOf(`M${x} ${y}L${x + w} ${y}L${x + w} ${y + h}L${x} ${y + h}Z`, { ...s, fill: "none" });
} else if (tag === "circle") {
const layer = layerOf(s);
const filled = s.fill !== "none" && s.fill !== "transparent" && s.fill !== "#fff";
if (layer && (s.stroke !== "none" || filled)) arc([Number(a.cx), Number(a.cy)], Number(a.r), 0, Math.PI * 2, s, s.stroke !== "none" ? layer : "THIN");
}
}
const ltype = (name: string, desc: string, parts: number[]) => ["0", "LTYPE", "2", name, "70", "0", "3", desc, "72", "65", "73", String(parts.length), "40", n(parts.reduce((x, y) => x + Math.abs(y), 0)), ...parts.flatMap((v) => ["49", n(v)])];
const layer = (name: string, color: number, lt: string) => ["0", "LAYER", "2", name, "70", "0", "62", String(color), "6", lt];
return [
"0", "SECTION", "2", "HEADER",
"9", "$ACADVER", "1", "AC1009",
"9", "$INSUNITS", "70", "4",
"9", "$MEASUREMENT", "70", "1",
"9", "$EXTMIN", "10", n(vb[0]), "20", "0", "30", "0",
"9", "$EXTMAX", "10", n(vb[0] + vb[2]), "20", n(H), "30", "0",
"0", "ENDSEC",
"0", "SECTION", "2", "TABLES",
"0", "TABLE", "2", "LTYPE", "70", "3",
...ltype("CONTINUOUS", "Solid line", []),
...ltype("DASHED", "Dashed __ __ __", [3, -1]),
...ltype("CENTER", "Center ____ _ ____", [8, -1.5, 1.5, -1.5]),
"0", "ENDTAB",
"0", "TABLE", "2", "LAYER", "70", "6",
...layer("0", 7, "CONTINUOUS"),
...layer("VISIBLE", 7, "CONTINUOUS"),
...layer("THIN", 8, "CONTINUOUS"),
...layer("HIDDEN", 8, "DASHED"),
...layer("CENTER", 1, "CENTER"),
...layer("TEXT", 7, "CONTINUOUS"),
"0", "ENDTAB",
"0", "ENDSEC",
"0", "SECTION", "2", "ENTITIES",
...out,
"0", "ENDSEC",
"0", "EOF",
"",
].join("\n");
}
+58
View File
@@ -8,6 +8,7 @@
import type { SketchEntity, Vec2 } from "../doc/types";
import { uid } from "../sketch/edit";
import { entityPrims, samplePrim, type Prim } from "../sketch/curves";
/** 2D affine map [a b c d e f]: x' = a x + c y + e, y' = b x + d y + f (SVG's matrix order). */
type M = [number, number, number, number, number, number];
@@ -406,3 +407,60 @@ function shift(e: SketchEntity, dx: number, dy: number): SketchEntity {
return e;
}
}
/**
* A sketch's curves as an SVG file's text: millimetres, the page just round the drawing, up as in the sketch (SVG's
* y runs down, so it is turned over). Lines, circles and arcs stay exact; ellipses and splines are fine polylines.
* Construction curves are in a group of their own, dashed.
*/
export function sketchToSVG(entities: SketchEntity[], title = "Sketch"): string {
const f = (v: number) => String(Math.round(v * 1e4) / 1e4 || 0);
const pt = (p: Vec2) => `${f(p[0])} ${f(-p[1])}`;
let lo: Vec2 = [Infinity, Infinity];
let hi: Vec2 = [-Infinity, -Infinity];
const see = (p: Vec2) => {
lo = [Math.min(lo[0], p[0]), Math.min(lo[1], -p[1])];
hi = [Math.max(hi[0], p[0]), Math.max(hi[1], -p[1])];
};
const TAU = Math.PI * 2;
const draw = (p: Prim): string => {
if (p.t === "line") {
see(p.a);
see(p.b);
return `<path d="M${pt(p.a)} L${pt(p.b)}"/>`;
}
if (p.t === "circle") {
const at = (t: number): Vec2 => [p.c[0] + p.r * Math.cos(t), p.c[1] + p.r * Math.sin(t)];
// (Its whole round counted for the page's size: an arc can bulge past its ends.)
for (const q of samplePrim(p, 0, 1, 32)) see(q);
if (Math.abs(Math.abs(p.sweep) - TAU) < 1e-9) return `<circle cx="${f(p.c[0])}" cy="${f(-p.c[1])}" r="${f(p.r)}"/>`;
// Turned over, anticlockwise in the sketch is clockwise on the page: sweep flag 0 for a positive sweep.
return `<path d="M${pt(at(p.a0))} A${f(p.r)} ${f(p.r)} 0 ${Math.abs(p.sweep) > Math.PI ? 1 : 0} ${p.sweep > 0 ? 0 : 1} ${pt(at(p.a0 + p.sweep))}"/>`;
}
const closed = p.t === "spline" ? p.closed : Math.abs(Math.abs(p.sweep) - TAU) < 1e-9;
let pts = samplePrim(p, 0, 1, p.t === "spline" ? Math.max(64, p.pts.length * 16) : 128);
if (closed && pts.length > 1) pts = pts.slice(0, -1);
pts.forEach(see);
return `<path d="M${pts.map(pt).join(" L")}${closed ? " Z" : ""}"/>`;
};
const solid: string[] = [];
const construction: string[] = [];
for (const e of entities) for (const p of entityPrims(e)) (e.construction ? construction : solid).push(draw(p));
if (!Number.isFinite(lo[0])) [lo, hi] = [[0, 0], [1, 1]];
const pad = Math.max(1, Math.max(hi[0] - lo[0], hi[1] - lo[1]) * 0.02);
const w = hi[0] - lo[0] + pad * 2;
const h = hi[1] - lo[1] + pad * 2;
const stroke = Math.max(0.05, Math.min(0.35, Math.max(w, h) / 600));
const safe = title.replace(/[<>&]/g, "");
return [
`<?xml version="1.0" encoding="UTF-8"?>`,
`<svg xmlns="http://www.w3.org/2000/svg" width="${f(w)}mm" height="${f(h)}mm" viewBox="${f(lo[0] - pad)} ${f(lo[1] - pad)} ${f(w)} ${f(h)}">`,
`<title>${safe}</title>`,
`<g fill="none" stroke="#000" stroke-width="${f(stroke)}" stroke-linecap="round" stroke-linejoin="round">`,
...solid,
`</g>`,
...(construction.length ? [`<g id="construction" fill="none" stroke="#888" stroke-width="${f(stroke)}" stroke-dasharray="${f(stroke * 6)} ${f(stroke * 4)}">`, ...construction, `</g>`] : []),
`</svg>`,
"",
].join("\n");
}
+1 -1
View File
@@ -19,7 +19,7 @@ function modelXml(bodies: MeshBody[], title: string): string {
out.push('<?xml version="1.0" encoding="UTF-8"?>');
out.push('<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">');
out.push(`<metadata name="Title">${esc(title)}</metadata>`);
out.push('<metadata name="Application">supergeometry.app</metadata>');
out.push('<metadata name="Application">superGeometry.app</metadata>');
out.push("<resources>");
if (colors.length) {
out.push('<basematerials id="1">');
+177 -14
View File
@@ -1,5 +1,15 @@
import type { Feature } from "../doc/types";
import type { Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
import type { BodyHealth, BodyMesh, BodyProps, ProjectedView, ViewSpec, Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
/**
* The steps as the engine needs them: a reference image without its picture
* (megabytes the engine never reads, copied across and hashed on every rebuild
* - every step of a drag). The same for every kind of call, so the engine sees
* the same steps each time.
*/
function lean(features: Feature[]): Feature[] {
return features.some((f) => f.type === "image" && f.src) ? features.map((f) => (f.type === "image" ? { ...f, src: "" } : f)) : features;
}
/** Promise-based wrapper around the kernel worker. */
export class KernelClient {
@@ -12,29 +22,120 @@ export class KernelClient {
// Coalesce regenerations: while one runs, only the most recent request waits.
private regenRunning = false;
private regenQueued: { features: Feature[]; resolve: (r: RegenResult | null) => void } | null = null;
private regenQueued: { features: Feature[]; saved: boolean; resolve: (r: RegenResult | null) => void } | null = null;
/** The last answer's meshes by key: the worker sends a mesh once, then just its key. */
private meshes = new Map<number, BodyMesh>();
/**
* The engine (OpenCascade) never hands memory back, and some of its
* operations leak (a union with a freeform body: ~10 MB each time). Past
* this much a spare engine is started, brought up to date in the
* background, and swapped in while nothing is running - a phone would
* otherwise run out after a while of editing.
*/
static RECYCLE_MB = 500;
private last: { features: Feature[]; saved: Feature[] | null } = { features: [], saved: null };
/**
* Some steps cost the engine tens of MB each time they are rebuilt (memory
* it never gets back): dragging one of their sizes, a rebuild per move,
* would fill it in seconds. After a rebuild seen to cost a lot, the next
* previews wait a moment - fewer of them, the drag's last one always shown.
*/
private memoryMB = 0;
/** What the last few rebuilds cost, each (MB; the engine's memory grows in jumps, so one rebuild's own cost says little). */
private costMB = 0;
private restUntil = 0;
/** How long previews rest after a rebuild that cost `mb` of the engine's memory (ms). */
static restFor(mb: number): number {
return mb < 4 ? 0 : Math.min(400, mb * 8);
}
private spare: { worker: Worker; bodies: BodyMesh[] | null } | null = null;
constructor() {
this.start();
}
private handler = (e: MessageEvent<Envelope<Response>>) => {
const cb = this.pending.get(e.data.id);
this.pending.delete(e.data.id);
cb?.(e.data.msg);
};
private start(): void {
// A fresh worker sends every mesh again.
this.meshes = new Map();
this.worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
this.worker.onmessage = (e: MessageEvent<Envelope<Response>>) => {
const cb = this.pending.get(e.data.id);
this.pending.delete(e.data.id);
cb?.(e.data.msg);
this.worker.onmessage = this.handler;
// The engine died without an answer (out of memory, a fault outside any step): what waits on it would wait for
// ever, and "Working…" with it. Everything waiting ends, and a fresh engine is started.
const worker = this.worker;
worker.onerror = (e) => {
if (worker !== this.worker) return;
console.error("The geometry engine stopped:", e.message);
this.stop();
this.onLost?.();
};
this.ready = this.call({ type: "init" }).then((r) => {
if (r.type === "error") throw new Error(r.message);
});
}
/** A spare engine, given the last saved project (and the last preview): it's ready to take over. */
private warmSpare(): void {
if (this.spare) return;
const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
const spare: { worker: Worker; bodies: BodyMesh[] | null } = { worker, bodies: null };
this.spare = spare;
let n = 0;
const waiting = new Map<number, (r: Response) => void>();
worker.onmessage = (e: MessageEvent<Envelope<Response>>) => waiting.get(e.data.id)?.(e.data.msg);
const ask = (msg: Request) =>
new Promise<Response>((resolve) => {
waiting.set(++n, resolve);
worker.postMessage({ id: n, msg } satisfies Envelope<Request>);
});
const { features, saved } = this.last;
(async () => {
if ((await ask({ type: "init" })).type !== "ready") throw new Error("init");
const got = new Map<number, BodyMesh>();
const regen = async (fs: Feature[], asSaved: boolean) => {
const r = await ask({ type: "regenerate", features: lean(fs), saved: asSaved });
if (r.type !== "regenerated") throw new Error("regenerate");
const bodies = r.result.bodies.map((b) => ((b as { same?: boolean }).same ? got.get(b.key)! : b));
for (const b of bodies) got.set(b.key, b);
return bodies;
};
let bodies = saved ? await regen(saved, true) : [];
if (!saved || features !== saved) bodies = await regen(features, false);
if (this.spare !== spare) throw new Error("stopped");
spare.bodies = bodies;
this.swapIfIdle();
})().catch(() => {
worker.terminate();
if (this.spare === spare) this.spare = null;
});
}
/** The spare engine takes over, if it's ready and nothing is running. */
private swapIfIdle(): void {
const s = this.spare;
if (!s?.bodies || this.regenRunning || this.pending.size) return;
this.spare = null;
this.worker.terminate();
this.worker = s.worker;
this.worker.onmessage = this.handler;
this.ready = Promise.resolve();
// It sends meshes it already sent (to us, while warming) as keys only.
this.meshes = new Map(s.bodies.map((b) => [b.key, b]));
}
/**
* Stop whatever the engine is working on (it can't be interrupted mid-way:
* the worker is thrown away and a fresh one started). Waiting calls end empty.
*/
stop(): void {
this.spare?.worker.terminate();
this.spare = null;
this.worker.terminate();
const waiting = [...this.pending.values()];
this.pending.clear();
@@ -49,6 +150,12 @@ export class KernelClient {
/** Told when the kernel starts and stops being busy (to show a busy indicator). */
onBusy: ((busy: boolean) => void) | null = null;
/** Told when the engine died and was started again (what was being made is not made). */
onLost: (() => void) | null = null;
/** Is anything being worked on, or waiting to be? (What the busy indicator is checked against.) */
get busy(): boolean {
return this.pending.size > 0 || this.regenRunning || !!this.regenQueued;
}
private call(msg: Request): Promise<Response> {
const id = this.nextId++;
@@ -66,37 +173,93 @@ export class KernelClient {
* Rebuild geometry. If calls arrive faster than the kernel can answer, the
* intermediate ones resolve with null (they were superseded).
*/
regenerate(features: Feature[]): Promise<RegenResult | null> {
regenerate(features: Feature[], saved = false): Promise<RegenResult | null> {
return new Promise((resolve) => {
if (this.regenRunning) {
this.regenQueued?.resolve(null);
this.regenQueued = { features, resolve };
this.regenQueued = { features, saved, resolve };
return;
}
this.runRegen(features, resolve);
this.runRegen(features, saved, resolve);
});
}
private async runRegen(features: Feature[], resolve: (r: RegenResult | null) => void) {
/** `saved`: the project as saved (not a tool's preview) - the engine keeps its steps for Cancel. */
private async runRegen(features: Feature[], saved: boolean, resolve: (r: RegenResult | null) => void) {
this.regenRunning = true;
await this.ready;
this.running = features;
this.last = { features, saved: saved ? features : this.last.saved };
const worker = this.worker;
const r = await this.call({ type: "regenerate", features });
const r = await this.call({ type: "regenerate", features: lean(features), saved });
// Stopped meanwhile: the fresh worker has its own queue.
if (worker !== this.worker) return resolve(null);
this.running = null;
resolve(r.type === "regenerated" ? r.result : null);
resolve(r.type === "regenerated" ? this.withMeshes(r.result) : null);
if (r.type === "error") console.error(r.message);
if (r.type === "regenerated" && r.result.memoryMB !== undefined) {
// (A fresh engine starts small again: that isn't a rebuild giving memory back.)
const cost = this.memoryMB ? Math.max(0, r.result.memoryMB - this.memoryMB) : 0;
if (r.result.memoryMB < this.memoryMB) this.costMB = 0;
this.memoryMB = r.result.memoryMB;
this.costMB = this.costMB * 0.7 + cost * 0.3;
this.restUntil = performance.now() + KernelClient.restFor(this.costMB);
}
// A preview waiting its turn rests first (whatever is asked meanwhile takes its place).
const rest = this.restUntil - performance.now();
if (this.regenQueued && !this.regenQueued.saved && rest > 0) {
await new Promise((done) => setTimeout(done, rest));
if (worker !== this.worker) return;
}
this.regenRunning = false;
// A big engine: a spare is got ready (also in the middle of a drag, where
// it used to wait for the drag to end), and takes over between two rebuilds.
if (r.type === "regenerated" && (r.result.memoryMB ?? 0) > KernelClient.RECYCLE_MB) this.warmSpare();
this.swapIfIdle();
const q = this.regenQueued;
this.regenQueued = null;
if (q) this.runRegen(q.features, q.resolve);
if (q) this.runRegen(q.features, q.saved, q.resolve);
}
/** Meshes sent as their key only (unchanged bodies): the ones the page has. */
private withMeshes(result: RegenResult): RegenResult {
const bodies = result.bodies.map((b) => {
if (!(b as { same?: boolean }).same) return b;
const had = this.meshes.get(b.key)!;
// (The same object when nothing about it changed: the view keeps what it drew.)
return had.id === b.id && had.name === b.name ? had : { ...had, id: b.id, name: b.name };
});
this.meshes = new Map(bodies.map((b) => [b.key, b]));
return { ...result, bodies };
}
/** The bodies drawn in views, hidden lines found (for BIM drawings). */
async drawing(features: Feature[], views: ViewSpec[], bodies?: string[]): Promise<ProjectedView[]> {
await this.ready;
const r = await this.call({ type: "drawing", features: lean(features), views, bodies });
if (r.type === "drawing") return r.views;
throw new Error(r.type === "error" ? r.message : "Could not draw the views");
}
/** Each body's volume, area, centre of mass and box (for BIM). */
async properties(features: Feature[]): Promise<BodyProps[]> {
await this.ready;
const r = await this.call({ type: "properties", features: lean(features) });
if (r.type === "properties") return r.bodies;
throw new Error(r.type === "error" ? r.message : "Could not measure the bodies");
}
/** Each body's health: valid, closed, solids, faces, volume (the console's sg.health()). */
async health(features: Feature[]): Promise<BodyHealth[]> {
await this.ready;
const r = await this.call({ type: "health", features: lean(features) });
if (r.type === "health") return r.bodies;
throw new Error(r.type === "error" ? r.message : "Could not check the bodies");
}
async export(features: Feature[], format: ExportFormat, bodies?: string[]): Promise<Blob> {
await this.ready;
const r = await this.call({ type: "export", features, format, bodies });
const r = await this.call({ type: "export", features: lean(features), format, bodies });
if (r.type === "exported") return r.blob;
throw new Error(r.type === "error" ? r.message : "Export failed");
}
+4500 -259
View File
File diff suppressed because it is too large Load Diff
+611 -124
View File
@@ -6,10 +6,14 @@
// the body is on (planes → half-spaces, cylinders → infinite cylinders). Changing
// F then only means adding/removing the right slab of E.
import { assembleWire, basicFaceExtrusion, getOC, loft, makeFace, makeBSplineApproximation, makeCylinder, makeLine, makePolygon, makeSphere, measureArea, measureVolume, cast, Vector, type Face, type Shape3D } from "replicad";
import { assembleWire, basicFaceExtrusion, getOC, loft, makeFace, makeBSplineApproximation, makeCylinder, makeLine, makePolygon, makeSphere, measureArea, cast, revolution, Vector, type Edge, type Face, type Shape3D } from "replicad";
import { measureVolume, quickVolume } from "./ocFree";
import type { PlaneDef, Vec3 } from "../doc/types";
import { add, cross, dist, dot, len, norm, scale, sub, xDirFor } from "../geom";
import { subShapes } from "./health";
import { shapeValid, subShapes, validNow } from "./health";
import { faceTriangles } from "./meshing";
import { borderPieces, borderThrough, boundaryEdges, limitPoints, subdivide, type Cage } from "../freeform/cage";
import { cageToShape } from "./freeform";
interface Cyl {
c: Vec3;
@@ -31,16 +35,67 @@ export function sizeOf(body: Shape3D): number {
const key = body.wrapped as object;
let s = sizes.get(key);
if (s === undefined) {
const bb = body.boundingBox;
s = Math.hypot(bb.width, bb.height, bb.depth) || 1;
s = looseSize(body);
sizes.set(key, s);
}
return s;
}
/**
* About how big a shape is (the diagonal of the kernel's quick box: never smaller than the shape, a few percent
* bigger on curved faces). Its exact box takes 0.4 to 1 s on a body with curved faces (a mug with its handle, a
* freeform) - asked for by every step that touched such a body, just to know how big a helper to make.
*/
function looseSize(body: Shape3D): number {
const [lo, hi] = looseBox(body);
return Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1;
}
/**
* The kernel's quick box of a shape, [low corner, high corner]: the shape is all inside it, and it is a little
* bigger than the shape where its faces are curved. For telling shapes apart that can't touch, and how far
* something reaches. (An empty shape: an upside-down box, as the exact one's.)
*/
const looseBoxes = new WeakMap<object, [Vec3, Vec3]>();
export function looseBox(body: Shape3D): [Vec3, Vec3] {
const key = body.wrapped as object;
const had = looseBoxes.get(key);
if (had) return had;
const oc = getOC();
const box = new oc.Bnd_Box();
let out: [Vec3, Vec3] | null = null;
try {
oc.BRepBndLib.Add(body.wrapped, box, false);
if (!box.IsVoid()) {
const [a, b] = [box.CornerMin(), box.CornerMax()];
const got: [Vec3, Vec3] = [
[a.X(), a.Y(), a.Z()],
[b.X(), b.Y(), b.Z()],
];
a.delete();
b.delete();
if ([...got[0], ...got[1]].every(Number.isFinite)) out = got;
}
} catch {
// The exact one, below.
} finally {
box.delete();
}
if (!out) {
const [lo, hi] = body.boundingBox.bounds;
out = [[...lo] as Vec3, [...hi] as Vec3];
}
looseBoxes.set(key, out);
return out;
}
// Each helper solid gets a slightly different size: when two of them end on the
// same far-away plane, the booleans split surfaces and they no longer re-merge.
let jitter = 0;
/** Each step starts the sizes over: what a step builds mustn't depend on which steps were rebuilt before it. */
export function sameSizesAgain(): void {
jitter = 0;
}
const vary = (L: number) => L * (1 + 0.0137 * (jitter = (jitter + 1) % 37));
/** Solid on the positive side of a plane, big enough for `L`. */
@@ -91,12 +146,8 @@ export function onFace(body: Shape3D, F: Face): { p: Vec3; n: Vec3 } {
const p = tup(F.pointOnSurface(0.5, 0.5));
return { p, n: norm(tup(F.normalAt(p))) };
}
let t = F.triangulation();
if (!t || !t.trianglesIndexes.length) {
body.mesh({ tolerance: sizeOf(body) * 1e-3, angularTolerance: 0.3 });
t = F.triangulation();
}
if (t && t.trianglesIndexes.length) {
const t = faceTriangles(F, sizeOf(body));
if (t) {
// Centroid of the biggest triangle: well inside the face.
const v = (i: number): Vec3 => [t!.vertices[3 * i], t!.vertices[3 * i + 1], t!.vertices[3 * i + 2]];
let best: Vec3 = v(0);
@@ -109,7 +160,10 @@ export function onFace(body: Shape3D, F: Face): { p: Vec3; n: Vec3 } {
best = scale(add(add(a, b), c), 1 / 3);
}
}
return { p: best, n: norm(tup(F.normalAt(best))) };
const n = norm(tup(F.normalAt(best)));
// (The mesh's corners are kept to seven digits: the point is put back on the face's own plane.)
const on = tup(F.pointOnSurface(0.5, 0.5));
return { p: sub(best, scale(n, dot(sub(best, on), n))), n };
}
const p = tup(F.pointOnSurface(0.5, 0.5));
return { p, n: norm(tup(F.normalAt(p))) };
@@ -127,6 +181,51 @@ function infiniteCylinder(cy: Cyl, r: number, L0: number): Shape3D {
return makeCylinder(r, 2 * L, sub(cy.c, scale(cy.a, L)), cy.a) as Shape3D;
}
/**
* A conical face's apex, its axis pointing into the half of the cone the face
* is on, and the tangent of its half-angle - from points on it (this kernel
* build can't hand over its cone).
*/
export function coneOf(f: Face): { apex: Vec3; a: Vec3; t: number } | null {
if (f.geomType !== "CONE") return null;
try {
const at = (u: number, v: number) => tup(f.pointOnSurface(u, v));
// A circle round the axis: three points at one height, and its middle.
const centre = (p: Vec3, q: Vec3, r: Vec3): Vec3 => {
const ab = sub(q, p), ac = sub(r, p);
const n = cross(ab, ac);
const nn = dot(n, n);
if (nn < 1e-18) throw new Error("flat");
return add(p, scale(add(scale(cross(n, ab), dot(ac, ac)), scale(cross(ac, n), dot(ab, ab))), 1 / (2 * nn)));
};
const ring = (v: number) => {
const ps = [0.2, 0.5, 0.8].map((u) => at(u, v));
return { c: centre(ps[0], ps[1], ps[2]), p: ps[1] };
};
const lo = ring(0.2), hi = ring(0.8);
const r1 = dist(lo.p, lo.c), r2 = dist(hi.p, hi.c);
const h = dist(lo.c, hi.c);
if (h < 1e-9 || Math.abs(r2 - r1) < 1e-9) return null;
const up = norm(sub(hi.c, lo.c));
// Radius r1 at lo, r2 at hi: none at the apex.
const apex = sub(lo.c, scale(up, (r1 * h) / (r2 - r1)));
const t = Math.abs(r2 - r1) / h;
const a = dot(sub(lo.p, apex), up) > 0 ? up : scale(up, -1);
return t > 1e-9 && t < 1e6 ? { apex, a, t } : null;
} catch {
return null;
}
}
/** The solid inside a cone, from its apex out past `L` (a triangle turned round its axis). */
function infiniteCone(k: { apex: Vec3; a: Vec3; t: number }, L0: number): Shape3D {
const L = vary(L0);
const p = norm(cross(k.a, Math.abs(k.a[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]));
const end = add(k.apex, scale(k.a, L));
const tri = makeFace(assembleWire([makeLine(k.apex, end), makeLine(end, add(end, scale(p, L * k.t))), makeLine(add(end, scale(p, L * k.t)), k.apex)]));
return revolution(tri, k.apex, k.a) as Shape3D;
}
/**
* g, a round face next to flat face F, is a convex fillet that ends on F
* (its axis runs through F, and it rounds the edge between two flat faces it
@@ -143,6 +242,41 @@ function filletEnding(body: Shape3D, F: Face, g: Face, cy: Cyl): [PlaneDef, Plan
return pls;
}
/**
* The plane a curved face g touches all along its one straight edge with F
* (its normal the same the whole way: a curve pulled straight), else null.
*/
function tangentPlaneAlong(F: Face, g: Face): PlaneDef | null {
const shared = g.edges.filter((e) => F.edges.some((fe) => fe.isSame(e)));
if (shared.length !== 1 || shared[0].geomType !== "LINE") return null;
const e = shared[0];
try {
const ns = [0, 0.5, 1].map((t) => norm(tup(g.normalAt(e.pointAt(t)))));
if (ns.some((n) => dot(n, ns[0]) < 1 - 1e-9)) return null;
const dir = norm(tup(e.tangentAt(0.5)));
if (Math.abs(dot(dir, ns[0])) > 1e-6) return null;
return { origin: tup(e.pointAt(0.5)), normal: ns[1], xDir: dir };
} catch {
return null;
}
}
/**
* A flat face drawn inside a bigger flat one (a shape projected onto it): every
* face round it lies in its plane, so moving its plane moves nothing.
*/
export function inFlatFace(body: Shape3D, F: Face): boolean {
if (F.geomType !== "PLANE") return false;
const p = planeOf(F);
const tol = sizeOf(body) * 1e-7;
const ns = neighbours(body, F);
return ns.length > 0 && ns.every((g) => {
if (g.geomType !== "PLANE") return false;
const q = planeOf(g);
return Math.abs(Math.abs(dot(q.normal, p.normal)) - 1) < 1e-9 && Math.abs(dot(sub(q.origin, p.origin), p.normal)) < tol;
});
}
/** Faces sharing an edge with F. */
function neighbours(body: Shape3D, F: Face): Face[] {
const edges = F.edges;
@@ -153,12 +287,12 @@ function neighbours(body: Shape3D, F: Face): Face[] {
* E: the region bounded by F's neighbours' extended surfaces, each on the side
* that contains `q` (a point just inside the body under F). Bounded by a box.
*/
export function extendedRegion(body: Shape3D, F: Face, q: Vec3, L: number): Shape3D {
return regionAround(body, F, neighbours(body, F), q, L);
export function extendedRegion(body: Shape3D, F: Face, q: Vec3, L: number, part?: Vec3[]): Shape3D {
return regionAround(body, F, neighbours(body, F), q, L, part);
}
/** As extendedRegion, bounded by the given faces round F (those along one of its outlines). */
function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number): Shape3D {
function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number, part?: Vec3[]): Shape3D {
const c = body.boundingBox.center as Vec3;
// Bounding box, bigger than the other tools so no faces coincide with theirs.
const big = () => halfSpace({ origin: sub(c, [0, 0, 1.5 * L]), xDir: [1, 0, 0], normal: [0, 0, 1] }, 3 * L);
@@ -189,7 +323,43 @@ function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number): S
const rel = sub(q, cy.c);
const radial = len(sub(rel, scale(cy.a, dot(rel, cy.a))));
(radial < cy.r ? keep : remove).push(infiniteCylinder(cy, cy.r, L));
// A flat face ending on a round boss from one side (a lever's arm on its
// hub): taking the boss out isn't enough, the arm's side faces carry on
// past it and out the far side. The face lies all on one side of the
// boss's axis: the region does too. (`part`: the piece of F it's for, one of F's cells.)
if (radial >= cy.r && F.geomType === "PLANE") {
const off = (p: Vec3) => {
const r = sub(p, cy.c);
return sub(r, scale(cy.a, dot(r, cy.a)));
};
const pts = part ?? F.edges.flatMap((e) => [0, 0.25, 0.5, 0.75].map((t) => tup(e.pointAt(t))));
const d = off(scale(pts.reduce((a, b) => add(a, b), [0, 0, 0] as Vec3), 1 / pts.length));
if (len(d) > cy.r * 1e-3) {
const dn = norm(d);
if (pts.every((p) => dot(off(p), dn) > -cy.r * 1e-6)) keep.push(halfSpace({ origin: cy.c, normal: dn, xDir: xDirFor(dn) }, L));
}
}
} else if (coneOf(g)) {
// A tapered side (a foot stepping in under a cup): it carries on as the
// cone it is - the inside of it kept or taken away as for a cylinder.
// (Treated as any other surface, the region round a cup's floor was open
// above and ran off out of the part.)
const k = coneOf(g)!;
const rel = sub(q, k.apex);
const along = dot(rel, k.a);
const radial = len(sub(rel, scale(k.a, along)));
const reach = len(sub(c, k.apex)) + 2 * L;
(along > 0 && radial < along * k.t ? keep : remove).push(infiniteCone(k, reach));
} else {
// A curve pulled straight (a spline side extruded) meeting F along a
// straight edge: it carries on along its tangent there. Bounded only by
// the flat faces round it, a heel's foot moved down ran off along the heel.
const tangent = tangentPlaneAlong(F, g);
if (tangent) {
const side = dot(sub(q, tangent.origin), tangent.normal) < 0 ? scale(tangent.normal, -1) : tangent.normal;
keep.push(halfSpace({ origin: tangent.origin, normal: side, xDir: xDirFor(side) }, L));
continue;
}
// Any other surface (a twisted corner patch where a chamfer meets a
// fillet, a lofted side) has no one way to carry on: the flat faces
// round it do, and bound the region there. Left open, it would run off
@@ -214,6 +384,245 @@ function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number): S
* radius afterwards - extending a fillet's cylinder through the body would
* carve a tunnel into it.
*/
/**
* The face made a smooth surface through `points` (absolute), its own edges
* kept: the rest of the body is untouched and closes round it again.
*/
export function freeformFace(body: Shape3D, F: Face, points: Vec3[]): Shape3D {
const oc = getOC();
const ex = new oc.TopExp_Explorer(F.wrapped, oc.TopAbs_ShapeEnum.TopAbs_WIRE, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
let wires = 0;
for (; ex.More(); ex.Next()) wires++;
ex.delete();
if (wires !== 1) throw new Error("Faces with holes in them can't be made freeform yet");
// Degree 2 overshoots least between points pulled out together; it can't
// always follow an outline with inward corners (an L): then 3.
for (const degree of [2, 3]) {
try {
const solid = filledFace(body, F, points, degree);
if (validNow(solid.wrapped)) return solid;
} catch {
// the next degree
}
}
throw new Error("This face can't be shaped like that (it would fold over itself) - move the points less, or not past each other");
}
/**
* The face made the cage's own smooth surface (the same patches a freeform
* body is made of), its border on the face's edges: no fitting through
* points, so it comes out the same every time and on any outline the cage
* follows. Throws when the cage's border isn't on the face's edge (a cage
* from before its border followed the face's corners) or the body doesn't
* close round the new surface - the fitted way is tried then.
*/
export function sheetFace(body: Shape3D, F: Face, cage: Cage): Shape3D {
return sheetFaces(body, [F], cage, norm(F.normalAt().toTuple() as Vec3));
}
/**
* Several faces side by side made one smooth surface (sheetFace's way): its
* border on their outer edges, the edges between them gone. `n`: the way they
* face together (the middle of their normals).
*/
export function sheetFaces(body: Shape3D, Fs: Face[], cage: Cage, n: Vec3): Shape3D {
const oc = getOC();
for (const F of Fs) {
const ex = new oc.TopExp_Explorer(F.wrapped, oc.TopAbs_ShapeEnum.TopAbs_WIRE, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
let wires = 0;
for (; ex.More(); ex.Next()) wires++;
ex.delete();
if (wires !== 1) throw new Error("Faces with holes in them can't be made freeform yet");
}
const size = Math.sqrt(Fs.reduce((a, F) => a + measureArea(F), 0));
// (Over several faces the border bends round their corners: it follows the edge a hair less closely.)
const tol = Math.max(5e-3, size * (Fs.length > 1 ? 3e-3 : 1e-3));
// The faces' outer edge, finely (a round edge as short straight pieces) - not the edges between them.
const between = (e: Face["edges"][number]) => Fs.filter((F) => F.edges.some((x) => x.isSame(e))).length > 1;
const outer = Fs.flatMap((F) => F.edges).filter((e) => !between(e));
const edge: [Vec3, Vec3][] = outer.flatMap((e) => {
const pts = Array.from({ length: 257 }, (_, i) => e.pointAt(i / 256).toTuple() as Vec3);
return pts.slice(1).map((q, i) => [pts[i], q] as [Vec3, Vec3]);
});
const onPiece = (p: Vec3, [a, b]: [Vec3, Vec3]): Vec3 => {
const d = sub(b, a);
const l = dot(d, d);
return add(a, scale(d, l > 0 ? Math.max(0, Math.min(1, dot(sub(p, a), d) / l)) : 0));
};
const nearest = (p: Vec3, pieces: [Vec3, Vec3][]) => {
let best: Vec3 = p;
let d = Infinity;
for (const q of pieces) {
const at = onPiece(p, q);
const e = dist(p, at);
if (e < d) ((d = e), (best = at));
}
return { at: best, d };
};
// The cage's border points onto the edge itself (they were laid on the
// face as drawn on screen: a round edge's are a hair inside it).
const borderVerts = new Set(boundaryEdges(cage).flat());
const verts = cage.verts.map((v, i) => {
if (!borderVerts.has(i)) return v;
const hit = nearest(v, edge);
if (hit.d > Math.max(0.2, size * 0.02)) throw new Error("border off the edge");
return hit.at;
});
const through = borderThrough({ verts, faces: cage.faces });
const s = subdivide(through.cage, 3, through.sharp);
s.points = limitPoints(s, through.sharp);
// Its border against the face's edge, both ways round.
const pieces = borderPieces(s);
for (const [a, b] of edge) if (nearest(a, pieces).d > tol || nearest(b, pieces).d > tol) throw new Error("border off the edge");
for (const [a] of pieces) if (nearest(a, edge).d > tol) throw new Error("border off the edge");
// Seen along the face's normal, all of it over the face. By an inward
// corner of the outline a smooth surface swells a little past the edge (a
// lip over it; pushed in, a cut through the wall): those points are drawn
// back onto the edge, at their height. Far past it (a coarse cage whose
// cells reach across the corner): not this way.
const u = xDirFor(n);
const v = norm(cross(n, u));
const flat = edge.map(([a, b]) => [dot(a, u), dot(a, v), dot(b, u), dot(b, v)]);
const onBorder = new Set<Vec3>(pieces.flat());
for (const [k, q] of s.points.entries()) {
// (The border is on the edge already.)
if (onBorder.has(q)) continue;
const x = dot(q, u);
const y = dot(q, v);
let inside = false;
for (const [ax, ay, bx, by] of flat) if (ay > y !== by > y && x < ((bx - ax) * (y - ay)) / (by - ay) + ax) inside = !inside;
if (inside) continue;
// (Counted along the other axis too: a ray through a corner of the outline, or along a piece of it, can miscount.)
let also = false;
for (const [ax, ay, bx, by] of flat) if (ax > x !== bx > x && y < ((by - ay) * (x - ax)) / (bx - ax) + ay) also = !also;
if (also) continue;
const h = dot(sub(q, edge[0][0]), n);
const hit = nearest(sub(q, scale(n, h)), edge);
if (hit.d > Math.max(0.5, size * 0.04)) throw new Error("spills over the edge");
// (A little inside the edge, not on it: the surface between the points mustn't touch the wall below.)
if (hit.d > tol / 4) s.points[k] = add(add(hit.at, scale(norm(sub(hit.at, sub(q, scale(n, h)))), Math.max(0.05, size * 0.004))), scale(n, h));
}
const rim = edge;
const sheet = cageToShape(through.cage, 3, undefined, s);
const progress = new oc.Message_ProgressRange();
const sew = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
try {
const others = body.faces.filter((f) => !Fs.some((F) => f.isSame(F)));
meetsOnlyAt(sheet.wrapped, others, rim, size);
for (const f of others) sew.Add(f.wrapped);
for (const f of sheet.faces) sew.Add(f.wrapped);
sew.Perform(progress);
const shells = subShapes(cast(sew.SewedShape()) as Shape3D, "SHELL");
if (shells.length !== 1) throw new Error("sew");
const fix = new oc.ShapeFix_Solid();
const made = fix.SolidFromShell(shells[0]);
fix.delete();
oc.BRepLib.OrientClosedSolid(oc.TopoDS.Solid(made));
const solid = cast(made) as Shape3D;
if (!(quickVolume(solid) > 0)) throw new Error("volume");
if (!validNow(solid.wrapped)) throw new Error("invalid");
return solid;
} finally {
sew.delete();
progress.delete();
}
}
/**
* A new surface may meet the rest of the body only along the old face's
* edges (`rim`): a point pushed through the far side passes the body's
* checks, but crosses itself. Throws when it meets it anywhere else.
*/
function meetsOnlyAt(surface: unknown, others: Face[], rim: [Vec3, Vec3][], size: number): void {
const away = (p: Vec3) => {
let d = Infinity;
for (const [a, b] of rim) {
const v = sub(b, a);
const l = dot(v, v);
d = Math.min(d, dist(p, add(a, scale(v, l > 0 ? Math.max(0, Math.min(1, dot(sub(p, a), v) / l)) : 0))));
}
return d;
};
const oc = getOC();
const progress = new oc.Message_ProgressRange();
try {
for (const other of others) {
const sec = new oc.BRepAlgoAPI_Section();
try {
sec.Init1(surface as never);
sec.Init2(other.wrapped);
sec.Build(progress);
const cut = cast(sec.Shape());
for (const e of "edges" in cut ? cut.edges : [])
for (const t of [0.25, 0.5, 0.75]) {
const p = e.pointAt(t).toTuple() as Vec3;
if (away(p) > Math.max(0.05, size * 0.01)) throw new Error("crosses");
}
} finally {
sec.delete();
}
}
} finally {
progress.delete();
}
}
function filledFace(body: Shape3D, F: Face, points: Vec3[], degree: number): Shape3D {
const oc = getOC();
const fill = new oc.BRepOffsetAPI_MakeFilling(degree, 15, 2, false, 1e-5, 1e-4, 0.01, 0.1, 8, 9);
const progress = new oc.Message_ProgressRange();
const sew = new oc.BRepBuilderAPI_Sewing(1e-4, true, true, true, false);
try {
for (const e of F.edges) fill.Add(e.wrapped, oc.GeomAbs_Shape.GeomAbs_C0, true);
for (const p of points) {
const g = new oc.gp_Pnt(p[0], p[1], p[2]);
fill.Add(g);
g.delete();
}
fill.Build(progress);
if (!fill.IsDone()) throw new Error("fill");
const filled = fill.Shape();
const others = body.faces.filter((f) => !f.isSame(F));
// The new surface may meet the rest of the body only along its own edges
// (a point pushed through the far side passes the body's checks, but
// crosses itself).
const rim = F.edges.flatMap((e) => Array.from({ length: 41 }, (_, i) => e.pointAt(i / 40).toTuple() as Vec3));
const size = Math.sqrt(measureArea(F));
for (const other of others) {
const sec = new oc.BRepAlgoAPI_Section();
try {
sec.Init1(filled);
sec.Init2(other.wrapped);
sec.Build(progress);
const cut = cast(sec.Shape());
for (const e of "edges" in cut ? cut.edges : [])
for (const t of [0.25, 0.5, 0.75]) {
const p = e.pointAt(t).toTuple() as Vec3;
if (Math.min(...rim.map((q) => dist(p, q))) > Math.max(0.05, size * 0.01)) throw new Error("crosses");
}
} finally {
sec.delete();
}
}
for (const f of others) sew.Add(f.wrapped);
sew.Add(filled);
sew.Perform(progress);
const shells = subShapes(cast(sew.SewedShape()) as Shape3D, "SHELL");
if (shells.length !== 1) throw new Error("sew");
const fix = new oc.ShapeFix_Solid();
const made = fix.SolidFromShell(shells[0]);
fix.delete();
oc.BRepLib.OrientClosedSolid(oc.TopoDS.Solid(made));
const solid = cast(made) as Shape3D;
if (!(quickVolume(solid) > 0)) throw new Error("volume");
return solid;
} finally {
fill.delete();
sew.delete();
progress.delete();
}
}
export function replaceFacePlane(body: Shape3D, F: Face, to: PlaneDef): Shape3D {
if (F.geomType !== "PLANE") throw new Error("Only flat faces can be moved or tilted");
const blends = blendsOf(body, F);
@@ -231,7 +640,7 @@ export function replaceFacePlane(body: Shape3D, F: Face, to: PlaneDef): Shape3D
// (the half-space trick would clip it to its convex part).
const old = planeOf(F);
const nn = norm(to.normal);
if (Math.abs(dot(nn, old.normal)) > 1 - 1e-9 && !convexFace(F)) {
if (Math.abs(dot(nn, old.normal)) > 1 - 1e-9 && !convexFace(F) && !F.clone().innerWires().length) {
const d = dot(sub(to.origin, old.origin), old.normal);
if (Math.abs(d) < 1e-12) return body;
try {
@@ -389,14 +798,11 @@ function faceColumn(body: Shape3D, F: Face, L: number): Shape3D {
}
return null;
});
let t = F.triangulation();
if (!t || !t.trianglesIndexes.length) {
body.mesh({ tolerance: sizeOf(body) * 1e-3, angularTolerance: 0.3 });
t = F.triangulation();
}
if (!t || !t.trianglesIndexes.length) return extendedRegion(body, F, q0, L);
const t = faceTriangles(F, sizeOf(body));
if (!t) return extendedRegion(body, F, q0, L);
const v = (i: number): Vec3 => [t!.vertices[3 * i], t!.vertices[3 * i + 1], t!.vertices[3 * i + 2]];
const cells = new Map<string, Vec3>();
const parts = new Map<string, Vec3[]>();
for (let k = 0; k < t.trianglesIndexes.length; k += 3) {
const [a, b, c] = [0, 1, 2].map((j) => v(t!.trianglesIndexes[k + j]));
// The middle and near each corner: a triangle may straddle a line where a neighbour's surface crosses the face.
@@ -415,12 +821,13 @@ function faceColumn(body: Shape3D, F: Face, L: number): Shape3D {
if (ds.some((d, i) => sides[i] && Math.abs(d) < tol)) continue;
const key = ds.map((d, i) => (!sides[i] ? "" : d < 0 ? "-" : "+")).join("");
if (!cells.has(key)) cells.set(key, q);
(parts.get(key) ?? parts.set(key, []).get(key)!).push(on);
}
}
if (cells.size <= 1) return extendedRegion(body, F, q0, L);
let E: Shape3D | null = null;
for (const q of cells.values()) {
const c = extendedRegion(body, F, q, L);
for (const [key, q] of cells) {
const c = extendedRegion(body, F, q, L, parts.get(key));
E = E ? fuseCells(E, c) : c;
}
return E!;
@@ -551,112 +958,161 @@ function needsContinuation(body: Shape3D, F: Face): boolean {
* heading there) until it is d further out; the slab between the old and the
* new outline is added (d > 0) or taken away (d < 0).
*/
/** A face pulled past where its sides meet (a cone's end pulled past its point). */
export const SIDES_MEET = "Pulled this far, its sides would meet in a point (they lean in) - pull it less, or draw the shape on the face and extrude that for straight sides";
function offsetByContinuation(body: Shape3D, F: Face, d: number): Shape3D {
const fp = planeOf(F);
const n = fp.normal;
const size = sizeOf(body);
const tol = size * 1e-6;
const nbrs = neighbours(body, F);
// F's outline as a loop of edges, end to end.
const edges = F.clone().outerWire().edges;
const ends = (e: { startPoint: { toTuple(): number[] }; endPoint: { toTuple(): number[] } }): [Vec3, Vec3] => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3];
const order: { k: number; rev: boolean }[] = [{ k: 0, rev: false }];
const used = new Set([0]);
let at = ends(edges[0])[1];
while (used.size < edges.length) {
const k = edges.findIndex((e, i) => !used.has(i) && ends(e).some((q) => dist(q, at) < tol * 10));
if (k < 0) throw new Error("outline not closed");
used.add(k);
const [a, b] = ends(edges[k]);
const rev = dist(b, at) < dist(a, at);
order.push({ k, rev });
at = rev ? a : b;
}
// Where a point on edge k goes: along its neighbour, across the edge, out of F's plane.
// Cutting: the cutter reaches a hair past the walls and above F, so no sliver stays on the coincident surfaces.
const eps = d < 0 ? size * 1e-4 : 0;
const outward = (k: number, t: number): Vec3 => {
const e = edges[k];
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)))!;
const ng = norm(tup(g.normalAt(tup(e.pointAt(t)))));
const flat = sub(ng, scale(n, dot(ng, n)));
return len(flat) < 1e-9 ? [0, 0, 0] : scale(norm(flat), eps);
};
const movedAt = (k: number, t: number): Vec3 => {
const e = edges[k];
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)));
if (!g) throw new Error("no neighbour");
const p = tup(e.pointAt(t));
const dt = 1e-3;
const tangent = norm(sub(tup(e.pointAt(Math.min(1, t + dt))), tup(e.pointAt(Math.max(0, t - dt)))));
// Just inside the edge on g: its normal there (exactly on the edge it can be the other face's).
const ng = norm(tup(g.normalAt(p)));
let dir = norm(cross(ng, tangent));
if (dot(dir, n) < 0) dir = scale(dir, -1);
const rise = dot(dir, n);
if (rise < 0.15) throw new Error("neighbour runs along the face");
return add(add(p, scale(dir, d / rise)), outward(k, t));
};
const liftedAt = (k: number, t: number): Vec3 => add(add(tup(edges[k].pointAt(t)), scale(n, eps)), outward(k, t));
// Corners: shared by two edges. Where the two neighbours meet along an edge
// of the body (a box's corner edge), the corner slides along that edge to
// the new plane - it stays on both neighbours. Each neighbour on its own
// would move it its own way (a wall at 45° and one square to F disagree,
// and halfway between them leaves both: slanted slivers stood up as fins).
// Without such an edge: halfway between their two estimates.
const m = order.length;
const fEdges = F.edges;
const bodyEdges = body.edges.filter((e) => !fEdges.some((fe) => fe.isSame(e)));
const alongEdge = (v: Vec3): Vec3 | null => {
for (const e of bodyEdges) {
const [a, b] = ends(e);
const atStart = dist(a, v) < tol * 10;
if (!atStart && dist(b, v) >= tol * 10) continue;
const dt = 1e-3;
const q = tup(e.pointAt(atStart ? dt : 1 - dt));
const dir = norm(sub(q, v));
const rise = dot(dir, n);
if (Math.abs(rise) < 0.15) continue;
return add(v, scale(dir, d / rise));
// The slab between one of F's outlines (its outer one, or a hole's) and
// where that outline goes: the outline as a loop of edges, end to end.
const column = (edges: Edge[]): Shape3D => {
const ends = (e: { startPoint: { toTuple(): number[] }; endPoint: { toTuple(): number[] } }): [Vec3, Vec3] => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3];
const order: { k: number; rev: boolean }[] = [{ k: 0, rev: false }];
const used = new Set([0]);
let at = ends(edges[0])[1];
while (used.size < edges.length) {
const k = edges.findIndex((e, i) => !used.has(i) && ends(e).some((q) => dist(q, at) < tol * 10));
if (k < 0) throw new Error("outline not closed");
used.add(k);
const [a, b] = ends(edges[k]);
const rev = dist(b, at) < dist(a, at);
order.push({ k, rev });
at = rev ? a : b;
}
return null;
// Where a point on edge k goes: along its neighbour, across the edge, out of F's plane.
// Cutting: the cutter reaches a hair past the walls and above F, so no sliver stays on the coincident surfaces.
const eps = d < 0 ? size * 1e-4 : 0;
const outward = (k: number, t: number): Vec3 => {
const e = edges[k];
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)))!;
const ng = norm(tup(g.normalAt(tup(e.pointAt(t)))));
const flat = sub(ng, scale(n, dot(ng, n)));
return len(flat) < 1e-9 ? [0, 0, 0] : scale(norm(flat), eps);
};
const movedAt = (k: number, t: number): Vec3 => {
const e = edges[k];
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)));
if (!g) throw new Error("no neighbour");
const p = tup(e.pointAt(t));
const dt = 1e-3;
const tangent = norm(sub(tup(e.pointAt(Math.min(1, t + dt))), tup(e.pointAt(Math.max(0, t - dt)))));
// Just inside the edge on g: its normal there (exactly on the edge it can be the other face's).
const ng = norm(tup(g.normalAt(p)));
let dir = norm(cross(ng, tangent));
if (dot(dir, n) < 0) dir = scale(dir, -1);
const rise = dot(dir, n);
if (rise < 0.15) throw new Error("neighbour runs along the face");
return add(add(p, scale(dir, d / rise)), outward(k, t));
};
const liftedAt = (k: number, t: number): Vec3 => add(add(tup(edges[k].pointAt(t)), scale(n, eps)), outward(k, t));
// Corners: shared by two edges. Where the two neighbours meet along an edge
// of the body (a box's corner edge), the corner slides along that edge to
// the new plane - it stays on both neighbours. Each neighbour on its own
// would move it its own way (a wall at 45° and one square to F disagree,
// and halfway between them leaves both: slanted slivers stood up as fins).
// Without such an edge: halfway between their two estimates.
// Do the sides meet on the way (a cone's end pulled past its point)? Each
// point of the outline goes in a straight line, so the area inside it is a
// quadratic in how far it has gone: down to nothing on the way, or turned
// inside out, and what's left is an hourglass (or nothing at all: the
// kernel gave the body back unchanged, without a word).
{
const u = xDirFor(n);
const w = cross(n, u);
const ps: Vec3[] = [];
const vs: Vec3[] = [];
for (const { k, rev } of order) {
for (let j = 0; j < 8; j++) {
const t = rev ? 1 - j / 8 : j / 8;
const p = tup(edges[k].pointAt(t));
ps.push(p);
vs.push(sub(movedAt(k, t), p));
}
}
const areaAt = (s: number) => {
let A = 0;
for (let i = 0; i < ps.length; i++) {
const j = (i + 1) % ps.length;
const a = add(ps[i], scale(vs[i], s));
const b = add(ps[j], scale(vs[j], s));
A += dot(a, u) * dot(b, w) - dot(b, u) * dot(a, w);
}
return A / 2;
};
// (Counted the way round that makes it positive at the start.)
const sg = Math.sign(areaAt(0)) || 1;
const A0 = sg * areaAt(0);
const Ah = sg * areaAt(0.5);
const A1 = sg * areaAt(1);
const qa = 2 * A1 - 4 * Ah + 2 * A0;
const qb = 4 * Ah - A1 - 3 * A0;
const sv = qa > 0 ? -qb / (2 * qa) : -1;
const least = Math.min(A1, sv > 0 && sv < 1 ? qa * sv * sv + qb * sv + A0 : Infinity);
if (A0 > 0 && least < A0 * 1e-3) throw new Error(SIDES_MEET);
}
const m = order.length;
const fEdges = F.edges;
const bodyEdges = body.edges.filter((e) => !fEdges.some((fe) => fe.isSame(e)));
const alongEdge = (v: Vec3): Vec3 | null => {
for (const e of bodyEdges) {
const [a, b] = ends(e);
const atStart = dist(a, v) < tol * 10;
if (!atStart && dist(b, v) >= tol * 10) continue;
const dt = 1e-3;
const q = tup(e.pointAt(atStart ? dt : 1 - dt));
const dir = norm(sub(q, v));
const rise = dot(dir, n);
if (Math.abs(rise) < 0.15) continue;
return add(v, scale(dir, d / rise));
}
return null;
};
const corner: Vec3[] = order.map(({ k, rev }, i) => {
const prev = order[(i - 1 + m) % m];
const a = movedAt(k, rev ? 1 : 0);
const b = movedAt(prev.k, prev.rev ? 0 : 1);
const v = ends(edges[k])[rev ? 1 : 0];
return alongEdge(v) ?? scale(add(a, b), 0.5);
});
const lowerCorner: Vec3[] = order.map(({ k, rev }) => liftedAt(k, rev ? 1 : 0));
const lowerEdges = eps
? order.map(({ k, rev }, i) => {
// Cutting: F's outline nudged up and out (see eps).
const c0 = lowerCorner[i];
const c1 = lowerCorner[(i + 1) % m];
if (edges[k].geomType === "LINE") return makeLine(c0, c1);
const pts: Vec3[] = [];
for (let j = 0; j <= 24; j++) pts.push(liftedAt(k, rev ? 1 - j / 24 : j / 24));
pts[0] = c0;
pts[24] = c1;
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
})
: order.map(({ k }) => edges[k].clone());
const upperEdges = order.map(({ k, rev }, i) => {
const e = edges[k];
const c0 = corner[i];
const c1 = corner[(i + 1) % m];
if (e.geomType === "LINE") return makeLine(c0, c1);
// A curved edge: a smooth curve through its moved points.
const pts: Vec3[] = [];
for (let j = 0; j <= 24; j++) pts.push(movedAt(k, rev ? 1 - j / 24 : j / 24));
pts[0] = c0;
pts[24] = c1;
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
});
const a = assembleWire(lowerEdges);
const b = assembleWire(upperEdges);
return loft(d > 0 ? [a, b] : [b, a], { ruled: true }) as Shape3D;
};
const corner: Vec3[] = order.map(({ k, rev }, i) => {
const prev = order[(i - 1 + m) % m];
const a = movedAt(k, rev ? 1 : 0);
const b = movedAt(prev.k, prev.rev ? 0 : 1);
const v = ends(edges[k])[rev ? 1 : 0];
return alongEdge(v) ?? scale(add(a, b), 0.5);
});
const lowerCorner: Vec3[] = order.map(({ k, rev }) => liftedAt(k, rev ? 1 : 0));
const lowerEdges = eps
? order.map(({ k, rev }, i) => {
// Cutting: F's outline nudged up and out (see eps).
const c0 = lowerCorner[i];
const c1 = lowerCorner[(i + 1) % m];
if (edges[k].geomType === "LINE") return makeLine(c0, c1);
const pts: Vec3[] = [];
for (let j = 0; j <= 24; j++) pts.push(liftedAt(k, rev ? 1 - j / 24 : j / 24));
pts[0] = c0;
pts[24] = c1;
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
})
: order.map(({ k }) => edges[k].clone());
const upperEdges = order.map(({ k, rev }, i) => {
const e = edges[k];
const c0 = corner[i];
const c1 = corner[(i + 1) % m];
if (e.geomType === "LINE") return makeLine(c0, c1);
// A curved edge: a smooth curve through its moved points.
const pts: Vec3[] = [];
for (let j = 0; j <= 24; j++) pts.push(movedAt(k, rev ? 1 - j / 24 : j / 24));
pts[0] = c0;
pts[24] = c1;
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
});
const a = assembleWire(lowerEdges);
const b = assembleWire(upperEdges);
const slab = loft(d > 0 ? [a, b] : [b, a], { ruled: true });
let slab = column(F.clone().outerWire().edges);
// A hole in F (or something standing on it): the slab stops at its walls,
// carried on the same way. (Over the whole outline, a top pulled up closed
// the hole through it with a lid; pushed down, it cut a boss off at its foot.)
for (const hole of F.clone().innerWires()) slab = slab.cut(column(hole.edges)) as Shape3D;
const out = d > 0 ? body.fuse(slab) : body.cut(slab);
return sanity(body, out);
}
@@ -666,13 +1122,32 @@ export function offsetFace(body: Shape3D, F: Face, d: number): Shape3D {
// Curved neighbours, or a face with inward corners (a zigzag, an L): the
// half-space trick would clip it to its convex part, so each edge carries on
// along its own neighbour instead.
if (F.geomType === "PLANE" && (needsContinuation(body, F) || !convexFace(F))) {
// (A face with holes whose neighbours are flat or stand upright: the plane
// trick first - it takes each hole's own walls on as they are, a round one
// staying one true cylinder. Edge by edge is the way for it only if that fails.)
const holed = F.geomType === "PLANE" && F.clone().innerWires().length > 0;
const curved = F.geomType === "PLANE" && needsContinuation(body, F);
if (F.geomType === "PLANE" && (curved || (!holed && !convexFace(F)))) {
try {
return offsetByContinuation(body, F, d);
} catch {
} catch (err) {
// (Sides that meet meet with the plane trick too.)
if (err instanceof Error && err.message === SIDES_MEET) throw err;
// fall through to the plane trick
}
}
if (holed && !curved) {
const { origin, normal } = planeOf(F);
try {
return replaceFacePlane(body, F, { origin: add(origin, scale(normal, d)), normal, xDir: xDirFor(normal) });
} catch (err) {
try {
return offsetByContinuation(body, F, d);
} catch {
throw err;
}
}
}
if (F.geomType === "PLANE") {
const { origin, normal } = planeOf(F);
return replaceFacePlane(body, F, { origin: add(origin, scale(normal, d)), normal, xDir: xDirFor(normal) });
@@ -1141,7 +1616,19 @@ export function unify(body: Shape3D, size?: number): Shape3D {
u.SetLinearTolerance((size ?? sizeOf(body)) * 1e-6);
u.SetAngularTolerance(1e-6);
u.Build();
return cast(u.Shape()) as Shape3D;
// (The kernel's handle to the result is given back once the body has its own: release.ts.)
const made = u.Shape();
let out: Shape3D;
try {
out = cast(made) as Shape3D;
} finally {
made.delete();
}
// Merged into a broken face: the pieces as they were. (A cut across a
// shelled mouse's top was sound; merged again, the two pieces of the
// round either side of its seam came out a face that "didn't meet up".)
if (out.faces.length !== body.faces.length && !shapeValid(out) && shapeValid(body)) return body;
return out;
} catch {
// Merging is tidying only: if OpenCascade can't (a fillet ending on a face split in two), keep the pieces.
return body;
+35 -8
View File
@@ -2,21 +2,24 @@
// bicubic B-spline face interpolating its grid of points; faces are sewn and,
// when the cage is closed, made into a solid.
import { cast, getOC, measureVolume, type Shape3D } from "replicad";
import { cast, getOC, type Shape3D } from "replicad";
import { quickVolume } from "./ocFree";
import { subShapes } from "./health";
import { cubicKnots, interpolateGrid } from "../freeform/bspline";
import { isClosed, limitPoints, subdivide, type Cage } from "../freeform/cage";
import { isClosed, limitPoints, subdivide, type Cage, type Subdivided } from "../freeform/cage";
export interface Thicken {
thickness: number;
side: "up" | "down" | "both";
}
export function cageToShape(cage: Cage, levels = 3, thicken?: Thicken): Shape3D {
/** `ready`: the cage already subdivided, its points on the smooth surface (else done here). */
export function cageToShape(cage: Cage, levels = 3, thicken?: Thicken, ready?: Subdivided): Shape3D {
if (!cage.faces.length) throw new Error("The freeform has no faces");
const oc = getOC();
const s = subdivide(cage, levels);
const s = ready ?? subdivide(cage, levels);
// Fitted through points on the smooth surface itself (see limitPoints).
s.points = limitPoints(s);
if (!ready) s.points = limitPoints(s);
const N = s.n + 1;
const tol = Math.max(1e-4, sizeOf(s.points) * 1e-5);
const sewing = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
@@ -71,15 +74,39 @@ function thickenSheet(sheet: unknown, { thickness: t, side }: Thicken): Shape3D
try {
mk.MakeThickSolidBySimple(sheet as never, d);
const solid = cast(mk.Shape()) as Shape3D;
// Growing along the normals comes out inside-out: turn it the right way.
return measureVolume(solid) < 0 ? (cast(solid.wrapped.Reversed()) as Shape3D) : solid;
// Growing along the normals comes out inside-out, and marking the solid as reversed (as was done) measured
// right but left its faces looking inwards: a rounding of its rim took every edge for a hollow one and came
// out as rubbish - "would turn the body inside out". A solid made anew from its skin has them outwards.
const shells = subShapes(solid, "SHELL");
if (shells.length === 1) {
const fix = new oc.ShapeFix_Solid();
try {
const made = cast(fix.SolidFromShell(oc.TopoDS.Shell(shells[0]))) as Shape3D;
if (quickVolume(made) > 0) return made;
} catch {
// as it was, below
} finally {
fix.delete();
}
}
return quickVolume(solid) < 0 ? (cast(solid.wrapped.Reversed()) as Shape3D) : solid;
} finally {
mk.delete();
}
};
if (side === "up") return thick(t);
if (side === "down") return thick(-t);
return thick(t / 2).fuse(thick(-t / 2));
// Both ways: the sheet moved half the thickness back, then thickened the
// whole way forward - one solid. (Two halves fused leaked ~50 MB of the
// engine's memory on every rebuild: a phone ran out after a few dozen.)
const mk = new oc.BRepOffsetAPI_MakeOffsetShape();
try {
mk.PerformBySimple(sheet as never, -t / 2);
if (!mk.IsDone()) throw new Error("offset");
return thickenSheet(mk.Shape(), { thickness: t, side: "up" });
} finally {
mk.delete();
}
}
function sizeOf(pts: number[][]): number {
+119 -13
View File
@@ -1,6 +1,7 @@
// Health checks for solids, shared by the engine's edit guard and the repair tool.
import { cast, getOC, measureArea, type Edge, type Shape3D } from "replicad";
import { meshFaces, meshOff } from "./meshing";
/** OpenCascade's own check (self-crossing faces, bad edges…). */
const validCache = new WeakMap<Shape3D, boolean>();
@@ -14,43 +15,122 @@ export function shapeValid(shape: Shape3D): boolean {
function checkValid(shape: Shape3D): boolean {
try {
const oc = getOC();
const check = new oc.BRepCheck_Analyzer(shape.wrapped, true, false, false);
const ok = (check as unknown as { IsValid(): boolean }).IsValid();
check.delete();
return ok;
return validNow(shape.wrapped);
} catch {
return true;
}
}
/**
* OpenCascade's check of a shape, made now (nothing remembered). Its checker
* keeps what it found on every face, edge and corner, and deleting it doesn't
* give that back: each check of an everyday body left over half a megabyte
* behind for good. A plate of 35 faces checked 3 000 times took the engine
* from 100 MB to 1.9 GB - and every edit checks its result, so a long session
* ran the engine out of memory. Pointed at nothing before it goes, the checker
* lets go of it all.
*/
export function validNow(wrapped: unknown): boolean {
const oc = getOC();
const check = new oc.BRepCheck_Analyzer(wrapped as never, true, false, false);
try {
return (check as unknown as { IsValid(): boolean }).IsValid();
} finally {
const builder = new oc.TopoDS_Builder();
const nothing = new oc.TopoDS_Compound();
try {
builder.MakeCompound(nothing);
check.Init(nothing, false);
} catch {
// As it is: the check itself is done.
}
builder.delete();
nothing.delete();
check.delete();
}
}
/**
* Edges with a face on one side only (gaps), by index. Worked out once per
* shape, like the checks below: every edit asks it of the body as it was
* before, which is the same body on each move of a drag.
*/
const openCache = new WeakMap<Shape3D, { open: number[]; pinched: number }>();
export function openEdges(shape: Shape3D): number[] {
return edgeUse(shape).open;
}
/**
* Edges with more than two faces round them: two pieces that only meet
* along an edge (a slab stood on a block's edge and "joined"), held
* together by nothing - one body by name, two by any printer or saw.
*/
export function pinchedEdges(shape: Shape3D): number {
return edgeUse(shape).pinched;
}
function edgeUse(shape: Shape3D): { open: number[]; pinched: number } {
let known = openCache.get(shape);
if (!known) openCache.set(shape, (known = findEdgeUse(shape)));
return known;
}
function findEdgeUse(shape: Shape3D): { open: number[]; pinched: number } {
const edges = shape.edges;
const buckets = new Map<number, { e: Edge; i: number; n: number }[]>();
const buckets = new Map<number, { e: Edge; i: number; n: number; faces: Set<number> }[]>();
edges.forEach((e, i) => {
const h = e.hashCode;
buckets.set(h, [...(buckets.get(h) ?? []), { e, i, n: 0 }]);
buckets.set(h, [...(buckets.get(h) ?? []), { e, i, n: 0, faces: new Set<number>() }]);
});
const oc = getOC();
for (const f of shape.faces) {
shape.faces.forEach((f, k) => {
for (const fe of f.edges) {
const m = buckets.get(fe.hashCode)?.find((x) => x.e.isSame(fe));
// A seam (cylinder/torus) belongs to its face twice but is listed once.
if (m) m.n += oc.BRep_Tool.IsClosed(fe.wrapped, f.wrapped) ? 2 : 1;
m?.faces.add(k);
}
}
});
// A pole (where a revolved profile touches the axis) is a point-edge, not a gap.
return [...buckets.values()].flat().filter((x) => x.n < 2 && !oc.BRep_Tool.Degenerated(x.e.wrapped)).map((x) => x.i);
const all = [...buckets.values()].flat();
return { open: all.filter((x) => x.n < 2 && !oc.BRep_Tool.Degenerated(x.e.wrapped)).map((x) => x.i), pinched: all.filter((x) => x.faces.size > 2).length };
}
/**
* A real copy: its own topology and its own curves and surfaces (replicad's
* clone() only wraps the same shape again). Made by "moving" it nowhere with
* copying on.
* clone() only wraps the same shape again), its faces and edges in the same
* order. Written out and read back. The kernel's own copier ("moving" it
* nowhere with copying on) keeps every piece of the shape and of the copy,
* and can't be made to let go of them (release.ts): each edit of a step that
* works on a copy - a fillet's size dragged - lost a whole body for good.
* What is read from a file is held by its handle alone. (The mesh goes out
* and in with it, and is taken off: a copy has none.)
*/
let copies = 0;
export function deepCopy(s: Shape3D): Shape3D {
const oc = getOC();
const name = `/copy-${copies++}.bin`;
const progress = new oc.Message_ProgressRange();
const read = new oc.TopoDS_Shape();
try {
if (oc.BinTools.Write(s.wrapped, name, progress) && oc.BinTools.Read(read, name, progress) && !read.IsNull()) {
oc.BRepTools.Clean(read, true);
return cast(read) as Shape3D;
}
} catch (err) {
// (The engine itself breaking down is not a copy that couldn't be made.)
if (typeof WebAssembly !== "undefined" && err instanceof WebAssembly.RuntimeError) throw err;
} finally {
try {
oc.FS.unlink(name);
} catch {
// never written
}
progress.delete();
read.delete();
}
// The old way, if it can't be written.
const t = new oc.gp_Trsf();
const mk = new oc.BRepBuilderAPI_Transform(s.wrapped, t, true, false);
try {
@@ -65,13 +145,39 @@ export function subShapes(s: Shape3D, kind: "SOLID" | "SHELL"): any[] {
const oc = getOC();
const ex = new oc.TopExp_Explorer(s.wrapped, kind === "SOLID" ? oc.TopAbs_ShapeEnum.TopAbs_SOLID : oc.TopAbs_ShapeEnum.TopAbs_SHELL, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
const out: any[] = [];
for (; ex.More(); ex.Next()) out.push(kind === "SOLID" ? oc.TopoDS.Solid(ex.Current()) : oc.TopoDS.Shell(ex.Current()));
for (; ex.More(); ex.Next()) {
const item = ex.Current();
out.push(kind === "SOLID" ? oc.TopoDS.Solid(item) : oc.TopoDS.Shell(item));
item.delete();
}
ex.delete();
return out;
}
/** How many faces are next to nothing in area (once per shape: every face's area is slow on curved faces). */
const thinCache = new WeakMap<Shape3D, number>();
export function hairThin(s: Shape3D): number {
let known = thinCache.get(s);
if (known === undefined) thinCache.set(s, (known = countHairThin(s)));
return known;
}
function countHairThin(s: Shape3D): number {
const areas = s.faces.map((f) => measureArea(f));
const total = areas.reduce((a, b) => a + b, 0);
return areas.filter((a) => a < total * 1e-7).length;
}
/** A solid's volume counted from a mesh of it (coarse, so the view's own finer mesh still gets made). */
export function meshVolume(s: Shape3D, size: number): number {
const m = meshFaces(s, size * 1e-3, 0.3);
meshOff(s);
const p = m.vertices;
const t = m.triangles;
let v = 0;
for (let k = 0; k < t.length; k += 3) {
const [i, j, l] = [3 * t[k], 3 * t[k + 1], 3 * t[k + 2]];
v += p[i] * (p[j + 1] * p[l + 2] - p[j + 2] * p[l + 1]) - p[i + 1] * (p[j] * p[l + 2] - p[j + 2] * p[l]) + p[i + 2] * (p[j] * p[l + 1] - p[j + 1] * p[l]);
}
return v / 6;
}
+60
View File
@@ -0,0 +1,60 @@
// A loft through sections that are each one closed curve (circles, ellipses,
// a closed spline) whose starts already line up, made as one smooth side.
//
// OpenCascade's loft first makes the sections "compatible": where their start
// points aren't exactly in line it projects each one's start onto the others
// and splits them all there. Six ellipses turned to a propeller's pitch came
// out with six faces down the blade instead of one, the blade's root on the hub
// chopped into pieces 1.3 mm long, and its root fillet failed. When the starts
// are near enough in line already (and the curves all run the same way round),
// the sections are lofted as they are.
import { cast, getOC, isShape3D, type Shape3D, type Wire } from "replicad";
import { add, cross, dot, len, norm, scale, sub } from "../geom";
import type { Vec3 } from "../doc/types";
const centre = (w: Wire): Vec3 => {
const e = w.edges[0];
let c: Vec3 = [0, 0, 0];
const n = 32;
for (let k = 0; k < n; k++) c = add(c, e.pointAt(k / n).toTuple() as Vec3);
return scale(c, 1 / n);
};
/** Single closed curves, starts in line, all one way round: lofted without splitting (else null). */
export function loftInLine(wires: Wire[], ruled: boolean): Shape3D | null {
if (wires.length < 2 || wires.some((w) => w.edges.length !== 1 || !w.isClosed)) return null;
const cs = wires.map(centre);
const axis = norm(sub(cs[cs.length - 1], cs[0]));
if (!(len(sub(cs[cs.length - 1], cs[0])) > 1e-9)) return null;
let prev: Vec3 | null = null;
let sense = 0;
for (const [i, w] of wires.entries()) {
const e = w.edges[0];
const s = sub(e.startPoint.toTuple() as Vec3, cs[i]);
// Seen down the loft's run, its start's direction from its middle...
const flat = sub(s, scale(axis, dot(s, axis)));
if (len(flat) < 1e-9) return null;
const d = norm(flat);
// ...within 45° of the one before's.
if (prev && dot(d, prev) < Math.SQRT1_2) return null;
prev = d;
// And the same way round.
const turn = Math.sign(dot(cross(s, e.tangentAt(0).toTuple() as Vec3), axis));
if (!turn || (sense && turn !== sense)) return null;
sense = turn;
}
const oc = getOC();
const b = new oc.BRepOffsetAPI_ThruSections(true, ruled, 1e-6);
try {
b.CheckCompatibility(false);
for (const w of wires) b.AddWire(w.wrapped);
b.Build();
if (!b.IsDone()) return null;
const shape = cast(b.Shape());
return isShape3D(shape) ? shape : null;
} catch {
return null;
} finally {
b.delete();
}
}
+258
View File
@@ -0,0 +1,258 @@
// A loft held by guide curves (rails) along its sides and by connection
// points (which point of each profile joins which).
//
// OpenCascade's loft takes no rails, so the profiles are resampled here on one
// shared parametrisation: each guide's or connection's point on a profile is at
// the same parameter on every profile, so the loft joins them. Between profiles
// that guides run along, extra sections are added: the two profiles blended,
// then moved so each guide's point lands on its guide - the sides follow the
// guides. Profiles become B-splines (within a ten-thousandth of their size).
import { cast, getOC, isShape3D, type Shape3D, type Wire } from "replicad";
import type { Vec3 } from "../doc/types";
import { add, cross, dot, len, norm, scale, sub } from "../geom";
/** Dense points along a curve, with how far along each is (0…1 of its length). */
interface Curve {
pts: Vec3[];
s: number[];
closed: boolean;
}
function sample(w: Wire, n = 720): Curve {
const oc = getOC();
const ad = new oc.BRepAdaptor_CompCurve(w.wrapped, true);
const pts: Vec3[] = [];
try {
const u0 = ad.FirstParameter();
const u1 = ad.LastParameter();
for (let i = 0; i <= n; i++) {
const p = ad.Value(u0 + ((u1 - u0) * i) / n);
pts.push([p.X(), p.Y(), p.Z()]);
p.delete();
}
} finally {
ad.delete();
}
const s = [0];
for (let i = 1; i < pts.length; i++) s.push(s[i - 1] + len(sub(pts[i], pts[i - 1])));
const L = s[s.length - 1] || 1;
return { pts, s: s.map((x) => x / L), closed: len(sub(pts[0], pts[pts.length - 1])) < 1e-6 * L + 1e-9 };
}
const reversed = (c: Curve): Curve => ({ pts: [...c.pts].reverse(), s: [...c.s].reverse().map((x) => 1 - x), closed: c.closed });
/** The point `f` of the way along (round again past the end of a closed one). */
function at(c: Curve, f: number): Vec3 {
if (c.closed) f = ((f % 1) + 1) % 1;
else f = Math.min(1, Math.max(0, f));
let lo = 0;
let hi = c.s.length - 1;
while (hi - lo > 1) {
const m = (lo + hi) >> 1;
if (c.s[m] <= f) lo = m;
else hi = m;
}
const d = c.s[hi] - c.s[lo];
const t = d > 0 ? (f - c.s[lo]) / d : 0;
return add(c.pts[lo], scale(sub(c.pts[hi], c.pts[lo]), t));
}
/** Where on the curve is nearest p: how far along, and how far off. */
function nearest(c: Curve, p: Vec3): { f: number; d: number } {
let best = { f: 0, d: Infinity };
for (let i = 0; i + 1 < c.pts.length; i++) {
const a = c.pts[i];
const ab = sub(c.pts[i + 1], a);
const l2 = dot(ab, ab);
const t = l2 > 0 ? Math.min(1, Math.max(0, dot(sub(p, a), ab) / l2)) : 0;
const d = len(sub(p, add(a, scale(ab, t))));
if (d < best.d) best = { f: c.s[i] + (c.s[i + 1] - c.s[i]) * t, d };
}
return best;
}
/** Where a guide meets a profile: how far along each. */
function meet(rail: Curve, sec: Curve): { onRail: number; onSec: number; d: number } {
let best = { onRail: 0, onSec: 0, d: Infinity };
// Coarse, then the best few of the guide's points refined.
const step = Math.max(1, Math.floor(rail.pts.length / 240));
const tries: { i: number; d: number }[] = [];
for (let i = 0; i < rail.pts.length; i += step) tries.push({ i, d: nearest(sec, rail.pts[i]).d });
tries.sort((a, b) => a.d - b.d);
for (const { i } of tries.slice(0, 3))
for (let k = Math.max(0, i - step); k <= Math.min(rail.pts.length - 1, i + step); k++) {
const q = nearest(sec, rail.pts[k]);
if (q.d < best.d) best = { onRail: rail.s[k], onSec: q.f, d: q.d };
}
// And back: the profile's point onto the guide.
const back = nearest(rail, at(sec, best.onSec));
return { onRail: back.f, onSec: best.onSec, d: Math.min(best.d, back.d) };
}
const centroidOf = (ps: Vec3[]): Vec3 => scale(ps.reduce((a, p) => add(a, p), [0, 0, 0] as Vec3), 1 / Math.max(1, ps.length));
const centroid = (c: Curve): Vec3 => scale(c.pts.slice(0, -1).reduce((a, p) => add(a, p), [0, 0, 0] as Vec3), 1 / Math.max(1, c.pts.length - 1));
/** Which way round a closed curve runs (Newell's normal, its size the area). */
function winding(c: Curve): Vec3 {
let n: Vec3 = [0, 0, 0];
for (let i = 0; i + 1 < c.pts.length; i++) n = add(n, cross(c.pts[i], c.pts[i + 1]));
return n;
}
interface Anchor {
/** A guide's index, or -1 for connection points. */
rail: number;
/** How far along each profile. */
a: number[];
/** How far along the guide, at each profile. */
r: number[];
}
/** Does a section turn sharply anywhere (more than 20° from one point to the next)? */
function sharp(rows: Vec3[][]): boolean {
const cos20 = Math.cos((20 * Math.PI) / 180);
for (const row of rows)
for (let j = 0; j < row.length; j++) {
const a = sub(row[j], row[(j - 1 + row.length) % row.length]);
const b = sub(row[(j + 1) % row.length], row[j]);
if (len(a) > 0 && len(b) > 0 && dot(norm(a), norm(b)) < cos20) return true;
}
return false;
}
/**
* The loft from its grid of points (a row per section, the same number round
* each): one smooth side through them, the two ends capped flat with the
* side's own end curves, sewn into a solid.
*/
function gridSolid(rows: Vec3[][], size: number): Shape3D {
const oc = getOC();
const nu = rows.length;
const nv = rows[0].length + 1;
const gc: { delete(): void }[] = [];
const keep = <T extends { delete(): void }>(x: T): T => (gc.push(x), x);
try {
const grid = keep(new oc.NCollection_Array2_gp_Pnt(1, nu, 1, nv));
rows.forEach((row, i) => {
for (let j = 0; j < nv; j++) {
const p = keep(new oc.gp_Pnt(...row[j % row.length]));
grid.SetValue(i + 1, j + 1, p);
}
});
// Through the points exactly (fitted within a tolerance, a square's corners came out rounded).
// Smooth profiles: through the points, smooth (C2) all round. Profiles with
// sharp corners (a square): fitted allowing a kink, so the corners stay
// sharp - interpolated, they rippled 0.3 % of the size out past them.
const fit = keep(sharp(rows) ? new oc.GeomAPI_PointsToBSplineSurface(grid, 3, 3, oc.GeomAbs_Shape.GeomAbs_C0, size * 1e-5) : new oc.GeomAPI_PointsToBSplineSurface());
if (!sharp(rows)) fit.Interpolate(grid, false);
const surf = fit.Surface();
const sew = keep(new oc.BRepBuilderAPI_Sewing(size * 1e-6, true, true, true, false));
const side = keep(new oc.BRepBuilderAPI_MakeFace(surf, 1e-6));
sew.Add(side.Face());
for (const [u, row] of [[surf.UKnot(1), rows[0]], [surf.UKnot(surf.NbUKnots()), rows[nu - 1]]] as const) {
const edge = keep(new oc.BRepBuilderAPI_MakeEdge(surf.UIso(u)));
const wire = keep(new oc.BRepBuilderAPI_MakeWire(edge.Edge()));
// On the profile's own plane (from its points).
const c = centroidOf(row);
const n = norm(row.reduce((a, p, j) => add(a, cross(sub(p, c), sub(row[(j + 1) % row.length], c))), [0, 0, 0] as Vec3));
const pln = keep(new oc.gp_Pln(keep(new oc.gp_Pnt(...c)), keep(new oc.gp_Dir(...n))));
const cap = keep(new oc.BRepBuilderAPI_MakeFace(pln, wire.Wire(), true));
if (!cap.IsDone()) throw new Error("A profile isn't flat: the loft's end can't be closed");
sew.Add(cap.Face());
}
const progress = keep(new oc.Message_ProgressRange());
sew.Perform(progress);
const sewed = sew.SewedShape();
if (sewed.ShapeType() !== oc.TopAbs_ShapeEnum.TopAbs_SHELL) throw new Error("These profiles can't be lofted along those guides");
const fix = keep(new oc.ShapeFix_Solid());
const solid = cast(fix.SolidFromShell(oc.TopoDS.Shell(sewed)));
if (!isShape3D(solid)) throw new Error("These profiles can't be lofted along those guides");
return solid;
} finally {
for (const o of gc.reverse()) o.delete();
}
}
/**
* Loft through closed profiles (in order), held by guide curves along its
* sides and by connection points (one point near each profile per connection).
* (Its sides are always smooth: Straight sides doesn't apply.)
*/
export function railLoft(wires: Wire[], rails: Wire[], connections: Vec3[][]): Shape3D {
let secs = wires.map((w) => sample(w));
if (secs.some((c) => !c.closed)) throw new Error("Guide curves and connection points need closed profiles");
const size = Math.max(...secs.map((c) => Math.max(...c.pts.map((p) => len(sub(p, centroid(c)))))), 1e-6);
// All one way round, seen down the loft.
const axis = norm(sub(centroid(secs[secs.length - 1]), centroid(secs[0])));
secs = secs.map((c) => (dot(winding(c), axis) < 0 ? reversed(c) : c));
const anchors: Anchor[] = [];
const railCurves = rails.map((w) => sample(w, 1200));
const tol = Math.max(size * 0.03, 0.05);
railCurves.forEach((rc, k) => {
const m = secs.map((sec) => meet(rc, sec));
const off = m.findIndex((x) => x.d > tol);
if (off >= 0) throw new Error(`Guide curve ${k + 1} doesn't touch profile ${off + 1}: each guide must run through every profile`);
anchors.push({ rail: k, a: m.map((x) => x.onSec), r: m.map((x) => x.onRail) });
});
for (const [k, pts] of connections.entries()) {
if (pts.length !== secs.length) throw new Error(`Connection ${k + 1} needs a point on every profile`);
anchors.push({ rail: -1, a: secs.map((sec, i) => nearest(sec, pts[i]).f), r: [] });
}
if (!anchors.length) throw new Error("Add a guide curve or a connection");
// Round each profile from the first anchor; the anchors must come in the same order on all.
anchors.sort((x, y) => x.a[0] - y.a[0]);
const rel = (i: number, k: number) => (((anchors[k].a[i] - anchors[0].a[i]) % 1) + 1) % 1;
for (let i = 1; i < secs.length; i++)
for (let k = 1; k < anchors.length; k++)
if (rel(i, k) <= rel(i, k - 1)) throw new Error("The guides or connections cross over between profiles: they must go round each profile in the same order");
// The same number of points between each two anchors on every profile.
const N = 160;
const counts = anchors.map((_, k) => Math.max(3, Math.round(N * ((k + 1 < anchors.length ? rel(0, k + 1) : 1) - rel(0, k)))));
const start = counts.map((_, k) => counts.slice(0, k).reduce((a, b) => a + b, 0));
const total = counts.reduce((a, b) => a + b, 0);
const resampled = secs.map((sec, i) => {
const out: Vec3[] = [];
anchors.forEach((an, k) => {
const from = an.a[i];
const to = from + ((k + 1 < anchors.length ? rel(i, k + 1) : 1) - rel(i, k));
for (let m = 0; m < counts[k]; m++) out.push(at(sec, from + ((to - from) * m) / counts[k]));
});
return out;
});
// Between profiles: sections that follow the guides.
const railAnchors = anchors.map((an, k) => ({ an, idx: start[k] })).filter((x) => x.an.rail >= 0);
const sections: Vec3[][] = [resampled[0]];
for (let i = 0; i + 1 < resampled.length; i++) {
{
const M = railAnchors.length ? 6 : 3;
for (let m = 1; m <= M; m++) {
const t = m / (M + 1);
const P = resampled[i].map((p, j) => add(p, scale(sub(resampled[i + 1][j], p), t)));
if (!railAnchors.length) {
sections.push(P);
continue;
}
const moves = railAnchors.map(({ an, idx }) => ({ idx, d: sub(at(railCurves[an.rail], an.r[i] + (an.r[i + 1] - an.r[i]) * t), P[idx]) }));
// Each point moved as the guides either side of it are, by how near it is to each.
sections.push(
P.map((p, j) => {
if (moves.length === 1) return add(p, moves[0].d);
let q = moves.length - 1;
for (let k = 0; k < moves.length; k++) if (moves[k].idx <= j) q = k;
const a = moves[q];
const b = moves[(q + 1) % moves.length];
const span = (b.idx - a.idx + total) % total || total;
const w = ((j - a.idx + total) % total) / span;
return add(p, add(scale(a.d, 1 - w), scale(b.d, w)));
}),
);
}
}
sections.push(resampled[i + 1]);
}
return gridSolid(sections, size);
}
+623
View File
@@ -0,0 +1,623 @@
// A body as triangles and lines: for the view, for a printed file, and for the
// checks that go by a mesh.
import { getOC, type Face, type Shape3D } from "replicad";
import { Earcut } from "three/src/extras/Earcut.js";
/** A body's faces as triangles. `faceGroups[i]` is where face i's corners are in `triangles` (the body's faces in their own order). */
export interface FaceMesh {
vertices: Float32Array;
normals: Float32Array;
triangles: Uint32Array;
faceGroups: { start: number; count: number }[];
}
/** A body's edges as lines. `edgeGroups[i]` is where edge i's points are in `lines` (the body's edges in their own order). */
export interface EdgeLines {
lines: Float32Array;
edgeGroups: { start: number; count: number }[];
}
/**
* Faces meshed in one go. OpenCascade's mesher keeps its working notes on every
* face and edge of what it is given until all of it is done, tens of kilobytes
* each: a body of 4 500 faces took the engine's memory from 100 MB to 1.3 GB
* (and memory once taken is never given back), one of 40 000 - a scanned part
* sewn into a solid - to the 4 GB a browser allows, where the engine breaks.
* The same faces a few hundred at a time are the same triangles in the same
* order, a little sooner, and the memory doesn't move.
*/
const LOT = 300;
/**
* Outlines (the face's own, and one for each hole) from which a flat face is
* cut into triangles here instead of by OpenCascade, whose mesher takes time
* and memory by the square of a face's holes: a plate's two faces with 100
* holes 0.3 s, with 400 holes 5 s and 700 MB - and again for every print file
* and every check that wants a point on such a face. Here: a few milliseconds.
*/
const LOOPS = 30;
/* eslint-disable @typescript-eslint/no-explicit-any */
/** The shapes whose faces are meshed, and how finely (so its edge lines needn't mesh it again). */
const meshedAt = new WeakMap<object, string>();
/** The edge lines of a body some of whose faces were cut into triangles here: worked out with them. */
const linesReady = new WeakMap<object, { key: string; lines: EdgeLines }>();
/** One explorer for each kernel, pointed at shape after shape (each one made stays in the kernel for good: release.ts). */
const explorers = new WeakMap<object, { ex: any; nothing: any }>();
function explorer(): { ex: any; nothing: any } {
const oc = getOC() as any;
let e = explorers.get(oc);
if (!e) explorers.set(oc, (e = { ex: new oc.TopExp_Explorer(), nothing: new oc.TopoDS_Shape() }));
return e;
}
/** How many closed outlines a face has (its own, and one for each hole). */
function loopCount(face: { wrapped: unknown }): number {
const oc = getOC() as any;
const { ex, nothing } = explorer();
const ANY = oc.TopAbs_ShapeEnum.TopAbs_SHAPE;
let n = 0;
for (ex.Init(face.wrapped, oc.TopAbs_ShapeEnum.TopAbs_WIRE, ANY); ex.More(); ex.Next()) n++;
ex.Init(nothing, ANY, ANY);
return n;
}
/** Is this a flat face with so many holes that it is cut into triangles here? */
const manyHoled = (face: Face): boolean => loopCount(face) >= LOOPS && face.geomType === "PLANE";
/** A shape's edges, each once, in the order met - the kernel's own handles: `done()` gives them back. */
function edgesOf(wrapped: unknown): { edges: any[]; at: (edge: any) => number; done: () => void } {
const oc = getOC() as any;
const { ex, nothing } = explorer();
const ANY = oc.TopAbs_ShapeEnum.TopAbs_SHAPE;
const buckets = new Map<number, number[]>();
const edges: any[] = [];
const hash = (x: any): number => oc.ReplicadShapeHasher.HashCode(x, 2147483647);
for (ex.Init(wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE, ANY); ex.More(); ex.Next()) {
const item = ex.Current();
const h = hash(item);
const b = buckets.get(h);
if (b?.some((i) => edges[i].IsSame(item))) {
item.delete();
continue;
}
if (b) b.push(edges.length);
else buckets.set(h, [edges.length]);
edges.push(item);
}
ex.Init(nothing, ANY, ANY);
return {
edges,
at: (edge) => buckets.get(hash(edge))?.find((i) => edges[i].IsSame(edge)) ?? -1,
done: () => edges.forEach((e) => e.delete()),
};
}
/** The lines of a shape's edges as the kernel has them (in the order of the shape's edges). */
function readLines(wrapped: unknown, tolerance: number, angularTolerance: number): EdgeLines {
const raw = (getOC() as any).ReplicadEdgeMeshExtractor.extract(wrapped, tolerance, angularTolerance);
try {
const groups = ints(raw.getEdgeGroupsPtr(), raw.getEdgeGroupsSize());
const edgeGroups: EdgeLines["edgeGroups"] = [];
for (let i = 0; i < groups.length; i += 3) edgeGroups.push({ start: groups[i], count: groups[i + 1] });
return { lines: floats(raw.getLinesPtr(), raw.getLinesSize()), edgeGroups };
} finally {
raw.delete();
}
}
/**
* Edge lines joined end to end into closed outlines (each a run of x, y, z;
* its last point not its first again). Null: they don't close up.
*/
function outlines(lines: Float32Array[], grain: number): Float32Array[] | null {
const key = (l: Float32Array, k: number) => `${Math.round(l[k] / grain)},${Math.round(l[k + 1] / grain)},${Math.round(l[k + 2] / grain)}`;
const out: Float32Array[] = [];
// (A point given twice running - the kernel's lines have some, where a round face's seam is - is one point.)
const add = (pts: ArrayLike<number>) => {
const once: number[] = [];
const apart = (k: number, j: number) => Math.hypot(pts[k] - once[j], pts[k + 1] - once[j + 1], pts[k + 2] - once[j + 2]) > grain;
for (let k = 0; k < pts.length; k += 3) if (!once.length || apart(k, once.length - 3)) once.push(pts[k], pts[k + 1], pts[k + 2]);
const m = once.length;
if (m >= 6 && Math.hypot(once[m - 3] - once[0], once[m - 2] - once[1], once[m - 1] - once[2]) <= grain) once.length = m - 3;
if (once.length >= 9) out.push(Float32Array.from(once));
};
const ends = new Map<string, number[]>();
const open: number[] = [];
lines.forEach((l, i) => {
if (l.length < 6) return;
const [a, b] = [key(l, 0), key(l, l.length - 3)];
if (a === b) {
// (An edge that closes on itself - a circle - is an outline; one that only goes there and back is nothing.)
add(l);
return;
}
open.push(i);
for (const k of [a, b]) ends.set(k, [...(ends.get(k) ?? []), i]);
});
const used = new Set<number>();
for (const first of open) {
if (used.has(first)) continue;
used.add(first);
const pts: number[] = Array.from(lines[first]);
const start = key(lines[first], 0);
let tip = key(lines[first], lines[first].length - 3);
for (let guard = 0; tip !== start; guard++) {
const next = ends.get(tip)?.find((i) => !used.has(i));
if (next === undefined || guard > open.length) return null;
used.add(next);
const l = lines[next];
if (key(l, 0) === tip) {
for (let k = 3; k < l.length; k++) pts.push(l[k]);
tip = key(l, l.length - 3);
} else {
for (let k = l.length - 6; k >= 0; k -= 3) pts.push(l[k], l[k + 1], l[k + 2]);
tip = key(l, 0);
}
}
add(pts);
}
return out;
}
/**
* A flat face as triangles between the points of its outlines (no points of
* its own: it meets its neighbours along the very points they have). Null
* when it doesn't come out as the face's area.
*/
function flatTriangles(loops: Float32Array[], normal: [number, number, number]): FaceMesh | null {
if (!loops.length) return null;
const n = normal;
const l = Math.hypot(n[0], n[1], n[2]);
if (!(l > 0)) return null;
// Two directions across the face (x, then y so that x, y, n turn the usual way).
const a = Math.abs(n[0]) < 0.9 * l ? [1, 0, 0] : [0, 1, 0];
let x = [a[1] * n[2] - a[2] * n[1], a[2] * n[0] - a[0] * n[2], a[0] * n[1] - a[1] * n[0]];
const xl = Math.hypot(x[0], x[1], x[2]);
x = x.map((v) => v / xl);
const y = [(n[1] * x[2] - n[2] * x[1]) / l, (n[2] * x[0] - n[0] * x[2]) / l, (n[0] * x[1] - n[1] * x[0]) / l];
const flat = loops.map((p) => {
const q = new Float64Array((p.length / 3) * 2);
for (let k = 0, j = 0; k < p.length; k += 3, j += 2) {
q[j] = p[k] * x[0] + p[k + 1] * x[1] + p[k + 2] * x[2];
q[j + 1] = p[k] * y[0] + p[k + 1] * y[1] + p[k + 2] * y[2];
}
return q;
});
const area = (q: Float64Array) => {
let s = 0;
for (let j = 0, m = q.length; j < m; j += 2) s += q[j] * q[(j + 3) % m] - q[(j + 2) % m] * q[j + 1];
return s / 2;
};
const areas = flat.map(area);
// The outline itself is the biggest; the others are its holes.
let outer = 0;
areas.forEach((v, i) => Math.abs(v) > Math.abs(areas[outer]) && (outer = i));
const order = [outer, ...loops.map((_, i) => i).filter((i) => i !== outer)];
const count = order.reduce((s, i) => s + flat[i].length / 2, 0);
const data = new Float64Array(count * 2);
const vertices = new Float32Array(count * 3);
const holes: number[] = [];
let at = 0;
for (const i of order) {
if (i !== outer) holes.push(at);
data.set(flat[i], at * 2);
vertices.set(loops[i], at * 3);
at += flat[i].length / 2;
}
// Earcut leaves out a point that lies on the straight line between its
// neighbours (and its neighbours include the cuts it makes from hole to
// hole): a row of square holes lost corners, and the face no longer met the
// holes' walls at them. So no three points are in line for it - each is
// moved a hair (for the cutting only) - and what that makes of points truly
// in line, a triangle with no area, is taken out again below.
let span = 1e-9;
for (let j = 0; j < data.length; j++) span = Math.max(span, Math.abs(data[j]));
const shaken = new Float64Array(data.length);
for (let j = 0; j < data.length; j++) shaken[j] = data[j] + span * 1e-9 * Math.sin(j * 12.9898 + 4.1414) * 0.5;
const cut = Earcut.triangulate(shaken as unknown as number[], holes, 2);
if (cut.length < 3) return null;
const twice = (p: number, q: number, r: number) => (data[2 * q] - data[2 * p]) * (data[2 * r + 1] - data[2 * p + 1]) - (data[2 * r] - data[2 * p]) * (data[2 * q + 1] - data[2 * p + 1]);
const far2 = (p: number, q: number) => (data[2 * q] - data[2 * p]) ** 2 + (data[2 * q + 1] - data[2 * p + 1]) ** 2;
// All turning the way the face looks (they all turn one way: as a whole, not
// one by one - a triangle with next to no area can't say which way it turns).
let tris: number[][] = [];
let turn = 0;
for (let k = 0; k < cut.length; k += 3) {
tris.push([cut[k], cut[k + 1], cut[k + 2]]);
turn += twice(cut[k], cut[k + 1], cut[k + 2]);
}
if (turn < 0) tris = tris.map(([p, q, r]) => [p, r, q]);
// No area: its third corner on its long side, to what a point's seven digits
// can be out by, and well in from both its ends. (Not a long thin needle
// between two holes far apart: that one has an area, small as it is.)
const middle = (t: number[]): [number, number, number] | null => {
let j = 0;
for (let m = 1; m < 3; m++) if (far2(t[m], t[(m + 1) % 3]) > far2(t[j], t[(j + 1) % 3])) j = m;
const [u, v, mid] = [t[j], t[(j + 1) % 3], t[(j + 2) % 3]];
const long2 = far2(u, v);
if (Math.abs(twice(u, v, mid)) > Math.sqrt(long2) * span * 4e-7) return null;
return Math.min(far2(u, mid), far2(v, mid)) > long2 * 1e-6 ? [u, v, mid] : null;
};
// Such a triangle is a point lying on the long side of its neighbour: that
// neighbour is cut in two at the point, and the flat one goes. (Points in a
// row - the tops of a row of round holes - make a fan of flat triangles:
// taken from the outside in, each next to a neighbour that has an area. Each
// is dealt with once: what can't be put right this way stays as it is.)
const dealt = new Set<string>();
for (let pass = 0; pass < 4096; pass++) {
const flatOnes: [number, [number, number, number]][] = [];
tris.forEach((t, i) => {
const m = middle(t);
if (m && !dealt.has([...t].sort((x, y) => x - y).join())) flatOnes.push([i, m]);
});
if (!flatOnes.length) break;
const side = new Map<number, number>();
tris.forEach((t, i) => {
for (let j = 0; j < 3; j++) side.set(t[j] * count + t[(j + 1) % 3], i);
});
const gone = new Set<number>();
const more: number[][] = [];
for (const [i, [u, v, mid]] of flatOnes) {
if (gone.has(i)) continue;
const n = side.get(v * count + u);
if (n === undefined || n === i || gone.has(n)) continue;
const other = tris[n];
if (middle(other)) continue;
const x = other.find((c) => c !== u && c !== v)!;
dealt.add([...tris[i]].sort((p, q) => p - q).join());
gone.add(i);
gone.add(n);
more.push([v, mid, x], [mid, u, x]);
}
if (!gone.size) break;
tris = [...tris.filter((_, i) => !gone.has(i)), ...more];
}
// Along every piece of its outlines there must be a triangle: that is where it meets its neighbours.
const sides = new Set<number>();
for (const t of tris) for (let j = 0; j < 3; j++) sides.add(Math.min(t[j], t[(j + 1) % 3]) * count + Math.max(t[j], t[(j + 1) % 3]));
at = 0;
for (const i of order) {
const m = flat[i].length / 2;
for (let k = 0; k < m; k++) {
const [p, q] = [at + k, at + ((k + 1) % m)];
if (!sides.has(Math.min(p, q) * count + Math.max(p, q))) return null;
}
at += m;
}
const want = Math.abs(areas[outer]) - areas.reduce((sum, v, i) => (i === outer ? sum : sum + Math.abs(v)), 0);
const triangles = new Uint32Array(tris.length * 3);
let got = 0;
tris.forEach((t, i) => {
got += Math.abs(twice(t[0], t[1], t[2])) / 2;
triangles.set(t, i * 3);
});
if (!(want > 0) || Math.abs(got - want) > want * 1e-4) return null;
const normals = new Float32Array(count * 3);
for (let k = 0; k < normals.length; k += 3) normals.set([n[0] / l, n[1] / l, n[2] / l], k);
return { vertices, normals, triangles, faceGroups: [{ start: 0, count: triangles.length }] };
}
/** One edge's points out of a set of edge lines. */
const lineOf = (e: EdgeLines, i: number): Float32Array => e.lines.subarray(e.edgeGroups[i].start * 3, (e.edgeGroups[i].start + e.edgeGroups[i].count) * 3);
function compoundOf(items: { wrapped: unknown }[]): any {
const oc = getOC() as any;
const builder = new oc.TopoDS_Builder();
const compound = new oc.TopoDS_Compound();
builder.MakeCompound(compound);
for (const x of items) builder.Add(compound, x.wrapped);
builder.delete();
return compound;
}
// (Views of the engine's memory are made after each call: when it grows, its buffer is a new one.)
const floats = (ptr: number, size: number) => new Float32Array((getOC() as any).wasmMemory.buffer, ptr >>> 0, size).slice();
const ints = (ptr: number, size: number) => new Int32Array((getOC() as any).wasmMemory.buffer, ptr >>> 0, size).slice();
const indices = (ptr: number, size: number) => new Uint32Array((getOC() as any).wasmMemory.buffer, ptr >>> 0, size).slice();
/** The triangles of a shape handed to the mesher whole. */
function read(wrapped: unknown, tolerance: number, angularTolerance: number): FaceMesh {
const raw = (getOC() as any).ReplicadMeshExtractor.extract(wrapped, tolerance, angularTolerance, false);
try {
const groups = ints(raw.getFaceGroupsPtr(), raw.getFaceGroupsSize());
const faceGroups: FaceMesh["faceGroups"] = [];
for (let i = 0; i < groups.length; i += 3) faceGroups.push({ start: groups[i], count: groups[i + 1] });
return {
vertices: floats(raw.getVerticesPtr(), raw.getVerticesSize()),
normals: floats(raw.getNormalsPtr(), raw.getNormalsSize()),
triangles: indices(raw.getTrianglesPtr(), raw.getTrianglesSize()),
faceGroups,
};
} finally {
raw.delete();
}
}
/** Meshes one after another as one. */
function joined(parts: FaceMesh[]): FaceMesh {
if (parts.length === 1) return parts[0];
const total = (pick: (m: FaceMesh) => { length: number }) => parts.reduce((n, m) => n + pick(m).length, 0);
const out: FaceMesh = {
vertices: new Float32Array(total((m) => m.vertices)),
normals: new Float32Array(total((m) => m.normals)),
triangles: new Uint32Array(total((m) => m.triangles)),
faceGroups: [],
};
let points = 0;
let corners = 0;
for (const m of parts) {
out.vertices.set(m.vertices, points * 3);
out.normals.set(m.normals, points * 3);
for (let k = 0; k < m.triangles.length; k++) out.triangles[corners + k] = m.triangles[k] + points;
for (const g of m.faceGroups) out.faceGroups.push({ start: g.start + corners, count: g.count });
points += m.vertices.length / 3;
corners += m.triangles.length;
}
return out;
}
/**
* A body's faces as triangles, each face's own (none shared across an edge), in
* the order of `shape.faces`.
*/
export function meshFaces(shape: Shape3D, tolerance: number, angularTolerance: number): FaceMesh {
const faces = shape.faces;
meshedAt.set(shape, `${tolerance}/${angularTolerance}`);
linesReady.delete(shape);
const flat = faces.map(manyHoled);
if (flat.some(Boolean)) {
const made = withFlatFaces(shape, faces, flat, tolerance, angularTolerance);
if (made) return made;
}
if (faces.length <= LOT) return read(shape.wrapped, tolerance, angularTolerance);
const parts: FaceMesh[] = [];
for (let i = 0; i < faces.length; i += LOT) {
const lot = faces.slice(i, i + LOT);
const group = compoundOf(lot);
try {
let part = read(group, tolerance, angularTolerance);
// A face that came to nothing left out of the count: each on its own, so the others keep their places.
if (part.faceGroups.length !== lot.length)
part = joined(
lot.map((f) => {
const one = read(f.wrapped, tolerance, angularTolerance);
return one.faceGroups.length === 1 ? one : { ...one, faceGroups: [{ start: 0, count: one.triangles.length }] };
}),
);
parts.push(part);
} finally {
group.delete();
}
}
return joined(parts);
}
/** Faces a few hundred at a time, as triangles (see LOT). */
function inLots(faces: Face[], tolerance: number, angularTolerance: number): FaceMesh[] {
const parts: FaceMesh[] = [];
for (let i = 0; i < faces.length; i += LOT) {
const lot = faces.slice(i, i + LOT);
const group = compoundOf(lot);
try {
const part = read(group, tolerance, angularTolerance);
if (part.faceGroups.length !== lot.length) throw new Error("a face without triangles");
parts.push(part);
} finally {
group.delete();
}
}
return parts;
}
/**
* A body with flat faces of very many holes (`flat`): those cut into triangles
* here, between the points their neighbours' meshes have along their edges;
* the rest by OpenCascade. Its edge lines are worked out with it (kept for
* meshEdgeLines). Null when it can't be done this way (the usual way then).
*/
function withFlatFaces(shape: Shape3D, faces: Face[], flat: boolean[], tolerance: number, angularTolerance: number): FaceMesh | null {
const trash: (() => void)[] = [];
const rest = faces.filter((_, i) => !flat[i]);
const others = rest.length ? compoundOf(rest) : null;
try {
// The other faces first: their meshes say where the points along the shared edges are.
for (let i = 0; i < rest.length; i += LOT) {
const group = compoundOf(rest.slice(i, i + LOT));
try {
(getOC() as any).ReplicadMeshExtractor.mesh(group, tolerance, angularTolerance);
} finally {
group.delete();
}
}
const theirs: EdgeLines = others ? readLines(others, tolerance, angularTolerance) : { lines: new Float32Array(0), edgeGroups: [] };
const known = others ? edgesOf(others) : null;
if (known) trash.push(known.done);
if (known && known.edges.length !== theirs.edgeGroups.length) return null;
// Edges with no neighbour but such faces (the fold between two): their own lines.
const all = edgesOf(shape.wrapped);
trash.push(all.done);
const lone = all.edges.filter((e) => !known || known.at(e) < 0);
let own: EdgeLines | null = null;
let ownAt: ReturnType<typeof edgesOf> | null = null;
if (lone.length) {
const group = compoundOf(lone.map((e) => ({ wrapped: e })));
try {
own = readLines(group, tolerance, angularTolerance);
ownAt = edgesOf(group);
trash.push(ownAt.done);
if (ownAt.edges.length !== own.edgeGroups.length) return null;
} finally {
group.delete();
}
}
const pointsOf = (edge: any): Float32Array | null => {
const i = known ? known.at(edge) : -1;
if (i >= 0) return lineOf(theirs, i);
const j = ownAt ? ownAt.at(edge) : -1;
return j >= 0 && own ? lineOf(own, j) : null;
};
const box = shape.boundingBox;
const grain = (Math.hypot(box.width, box.height, box.depth) || 1) * 2e-6;
// Each face in its place: runs of the others (in lots), the flat ones one by one.
const parts: FaceMesh[] = [];
let run: Face[] = [];
const flush = () => {
if (run.length) parts.push(...inLots(run, tolerance, angularTolerance));
run = [];
};
for (const [i, face] of faces.entries()) {
if (!flat[i]) {
run.push(face);
continue;
}
const mine = edgesOf(face.wrapped);
let part: FaceMesh | null = null;
try {
const lines = mine.edges.map(pointsOf);
const loops = lines.every(Boolean) ? outlines(lines as Float32Array[], grain) : null;
part = loops && flatTriangles(loops, face.normalAt().toTuple() as [number, number, number]);
} finally {
mine.done();
}
if (!part) return null;
flush();
parts.push(part);
}
flush();
// The body's edge lines, in the order of its edges.
const each = all.edges.map(pointsOf);
if (!each.every(Boolean)) return null;
const lines = new Float32Array(each.reduce((n, l) => n + l!.length, 0));
const edgeGroups: EdgeLines["edgeGroups"] = [];
let at = 0;
for (const l of each as Float32Array[]) {
lines.set(l, at * 3);
edgeGroups.push({ start: at, count: l.length / 3 });
at += l.length / 3;
}
linesReady.set(shape, { key: `${tolerance}/${angularTolerance}`, lines: { lines, edgeGroups } });
return joined(parts);
} catch {
return null;
} finally {
for (const done of trash) done();
others?.delete();
}
}
/**
* A body's edges as lines, in the order of `shape.edges` - the lines its faces'
* triangles meet along (so its faces are meshed first, if they aren't yet).
*/
export function meshEdgeLines(shape: Shape3D, tolerance: number, angularTolerance: number): EdgeLines {
const oc = getOC() as any;
const ready = linesReady.get(shape);
if (ready?.key === `${tolerance}/${angularTolerance}`) return ready.lines;
if (meshedAt.get(shape) !== `${tolerance}/${angularTolerance}`) {
// (A body with faces cut into triangles here: its lines come with those.)
const faces = shape.faces;
if (faces.some(manyHoled)) {
meshFaces(shape, tolerance, angularTolerance);
const made = linesReady.get(shape);
if (made) return made.lines;
}
// (In lots, as above: read off the whole body unmeshed, it is meshed whole.)
for (let i = 0; faces.length > LOT && i < faces.length; i += LOT) {
const group = compoundOf(faces.slice(i, i + LOT));
try {
oc.ReplicadMeshExtractor.mesh(group, tolerance, angularTolerance);
} finally {
group.delete();
}
}
meshedAt.set(shape, `${tolerance}/${angularTolerance}`);
}
return readLines(shape.wrapped, tolerance, angularTolerance);
}
/**
* A body's triangles taken off it again, once whoever asked for them has
* them. Left on, they stay for as long as the kernel holds the body - and the
* tool that made a body holds it for good (release.ts): every shape ever
* shown kept its mesh. Nothing reads them later: each edit works on a copy
* of the body, which has none, and a face that wants its own asks for them.
*/
export function meshOff(shape: Shape3D): void {
meshedAt.delete(shape);
linesReady.delete(shape);
try {
(getOC() as any).BRepTools.Clean(shape.wrapped, true);
} catch {
// Left as they are.
}
}
/**
* One face's own triangles, for what wants points on it: its corners (x, y, z
* each) and which three make each triangle. Made for that face alone when it
* has none yet (`size`: its body's, which says how fine) - the whole body used
* to be meshed for the one face, seconds on a big body - and read out in one
* go: asked for corner by corner, each corner cost four small things in the
* kernel that are never given back (release.ts), a megabyte and more with
* each check of a shell's walls.
*/
export function faceTriangles(face: Face, size: number): { vertices: Float32Array; trianglesIndexes: Uint32Array } | null {
// (A flat face of very many holes: cut into triangles here, between points along its own edges - see LOOPS.)
if (manyHoled(face)) {
const mine = edgesOf(face.wrapped);
const group = compoundOf(mine.edges.map((e) => ({ wrapped: e })));
try {
const own = readLines(group, size * 1e-3, 0.3);
if (own.edgeGroups.length === mine.edges.length) {
const loops = outlines(mine.edges.map((_, i) => lineOf(own, i)), size * 2e-6);
const part = loops && flatTriangles(loops, face.normalAt().toTuple() as [number, number, number]);
if (part) return { vertices: part.vertices, trianglesIndexes: part.triangles };
}
} catch {
// The usual way.
} finally {
mine.done();
group.delete();
}
}
const raw = (getOC() as any).ReplicadMeshExtractor.extract(face.wrapped, size * 1e-3, 0.3, true);
try {
const trianglesIndexes = indices(raw.getTrianglesPtr(), raw.getTrianglesSize());
if (!trianglesIndexes.length) return null;
return { vertices: floats(raw.getVerticesPtr(), raw.getVerticesSize()), trianglesIndexes };
} finally {
raw.delete();
}
}
/** Meshes as one binary STL file (each triangle with its own flat normal, as a slicer reads it). */
export function binarySTL(meshes: FaceMesh[]): Uint8Array {
const count = meshes.reduce((n, m) => n + m.triangles.length / 3, 0);
const out = new Uint8Array(84 + count * 50);
const view = new DataView(out.buffer);
// (80 bytes of heading, never starting "solid": readers take that for the text kind.)
out.set(new TextEncoder().encode("binary stl"), 0);
view.setUint32(80, count, true);
let at = 84;
for (const m of meshes) {
const p = m.vertices;
for (let k = 0; k < m.triangles.length; k += 3) {
const [a, b, c] = [m.triangles[k] * 3, m.triangles[k + 1] * 3, m.triangles[k + 2] * 3];
const [ux, uy, uz] = [p[b] - p[a], p[b + 1] - p[a + 1], p[b + 2] - p[a + 2]];
const [vx, vy, vz] = [p[c] - p[a], p[c + 1] - p[a + 1], p[c + 2] - p[a + 2]];
let [nx, ny, nz] = [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx];
const l = Math.hypot(nx, ny, nz);
if (l > 0) [nx, ny, nz] = [nx / l, ny / l, nz / l];
view.setFloat32(at, nx, true);
view.setFloat32(at + 4, ny, true);
view.setFloat32(at + 8, nz, true);
for (const [j, i] of [a, b, c].entries()) for (let x = 0; x < 3; x++) view.setFloat32(at + 12 + j * 12 + x * 4, p[i + x], true);
at += 50;
}
}
return out;
}
+493
View File
@@ -0,0 +1,493 @@
// A face's point and normal at a place on its surface, read straight off it.
//
// face.normalAt(point) finds where the point is on the surface first (a point
// projection), and on a detailed spline surface each projection keeps about
// half a megabyte of the engine's memory for good, freed or not. Tidying a
// gear's outline swept with a twist (362 spline faces, 25 places each) ran
// the engine out of memory (0.2 GB to 3.8 GB) and broke it. Where the place
// on the surface is known, ask there.
import { getOC, type Edge, type Face, type Shape3D } from "replicad";
type Tuple = [number, number, number];
type Vec3 = Tuple;
/** Point and normal (outward, not of unit length) at (s, t), each 0..1 across the face's surface. */
export function surfaceAt(face: Face, s: number, t: number): { p: Tuple; n: Tuple } {
const oc = getOC();
const { uMin, uMax, vMin, vMax } = face.UVBounds;
const p = new oc.gp_Pnt();
const n = new oc.gp_Vec();
const g = new oc.BRepGProp_Face(face.wrapped, false);
try {
g.Normal(uMin + (uMax - uMin) * s, vMin + (vMax - vMin) * t, p, n);
return { p: [p.X(), p.Y(), p.Z()], n: [n.X(), n.Y(), n.Z()] };
} finally {
g.delete();
n.delete();
p.delete();
}
}
/**
* A face's normal (of unit length) where one of its edges is, at `s` (0..1)
* along the edge (as edge.pointAt counts): read through the edge's own curve
* on the face, so nothing is projected. Null if the edge isn't on the face.
*/
export function normalOnEdge(face: Face, edge: Edge, s: number): Tuple | null {
const oc = getOC();
let c: InstanceType<typeof oc.BRepAdaptor_Curve2d> | null = null;
let uv: { X(): number; Y(): number; delete(): void } | null = null;
const p = new oc.gp_Pnt();
const n = new oc.gp_Vec();
const g = new oc.BRepGProp_Face(face.wrapped, false);
try {
c = new oc.BRepAdaptor_Curve2d(edge.wrapped, face.wrapped);
const t0 = c.FirstParameter();
uv = c.Value(t0 + (c.LastParameter() - t0) * s);
g.Normal(uv!.X(), uv!.Y(), p, n);
const l = Math.hypot(n.X(), n.Y(), n.Z());
return l > 0 ? [n.X() / l, n.Y() / l, n.Z() / l] : null;
} catch {
return null;
} finally {
uv?.delete();
c?.delete();
g.delete();
n.delete();
p.delete();
}
}
// Volumes and areas, measured to a millionth.
//
// replicad's measureVolume / measureArea integrate each face at a fixed
// fineness, which on many-patched spline faces is well off: a propeller (lofted
// blades, rounded roots) measured 203 698 mm³ for 201 310 (1.2 % over), its
// centre of mass 0.2 mm off its axis. Asked to a relative accuracy instead,
// OpenCascade keeps refining until it's there (about twice the time).
const EPS = 1e-6;
type Measurable = Shape3D | Face;
function props(s: Measurable, kind: "volume" | "area") {
const oc = getOC();
const p = new oc.GProp_GProps();
let ok = true;
try {
const err = kind === "volume" ? oc.BRepGProp.VolumeProperties(s.wrapped, p, EPS, false, false) : oc.BRepGProp.SurfaceProperties(s.wrapped, p, EPS, false);
ok = Number.isFinite(err) && Number.isFinite(p.Mass());
} catch {
ok = false;
}
if (ok) return p;
// (Where the adaptive measure won't settle, the plain one.)
p.delete();
const q = new oc.GProp_GProps();
if (kind === "volume") oc.BRepGProp.VolumeProperties(s.wrapped, q, false, false, false);
else oc.BRepGProp.SurfaceProperties(s.wrapped, q, false, false);
return q;
}
/** The volume (signed: below 0 for a solid inside out), as replicad's but to a millionth. */
export function measureVolume(s: Measurable): number {
const own = ownSums(s);
if (own) return own.vol;
const p = props(s, "volume");
try {
return p.Mass();
} finally {
p.delete();
}
}
/**
* The volume to a thousandth or so (measured: within 0.15 %), for checks that need no more: which way out a solid
* is, whether it is empty, whether a join or a cut came to about what it should. The measure to a millionth takes
* seconds on curved bodies (a mug: 1.7 s; a jet engine's cowl: 10.6 s) where this takes 0.2 s and 0.06 s - and such
* checks, asked several times a step, were most of what a join, a cut or a thread on such a body took.
* (The exact one where it is known already.)
*/
const quick = new WeakMap<object, number>();
export function quickVolume(s: Measurable): number {
const exact = measured.get(s);
if (exact) return exact.vol;
const had = quick.get(s);
if (had !== undefined) return had;
const oc = getOC();
let v = NaN;
const p = new oc.GProp_GProps();
try {
const err = oc.BRepGProp.VolumeProperties(s.wrapped, p, 1e-3, false, false);
if (Number.isFinite(err)) v = p.Mass();
} catch {
// The plain one, below.
} finally {
p.delete();
}
if (!Number.isFinite(v)) v = roughVolume(s);
quick.set(s, v);
return v;
}
/**
* The volume roughly (OpenCascade's plain measure, a percent or so out on
* curved sweeps): enough to tell a solid's sign, or that it isn't empty. The
* exact measure of a mug handle's sweep took 3.5 s each time, asked twice for
* every way tried.
*/
export function roughVolume(s: Measurable): number {
const oc = getOC();
const q = new oc.GProp_GProps();
try {
oc.BRepGProp.VolumeProperties(s.wrapped, q, false, false, false);
return q.Mass();
} finally {
q.delete();
}
}
// Faces swept from a curve (an extruded or revolved spline, and offsets of
// them) are integrated by OpenCascade over the whole sweep at one fineness,
// blind to the curve's own pieces: the side of an extruded closed spline
// measured 14 049 mm² for 13 820, its solid 316 000 mm³ for 284 800 (11 %).
// (OpenCascade's Gauss-Kronrod measure gets volumes right but took 11 s on a
// shelled mouse; its areas have no such measure.) Bodies and faces with such
// faces are integrated here instead, piece by piece:
// Green's theorem round each face's outline in its own (u, v), so
// ∫∫ f du dv = ∮ (∫ f du) dv, with f = |Su × Sv| for area and the divergence
// theorem's (X - R)·N / 3 for volume.
//
// (Five points a piece: every piece is smooth, cut at the surface's and the
// outline's joints and where the outline crosses the surface's.)
const GAUSS: [number, number][] = [
[-0.906179845938664, 0.2369268850561891],
[-0.5384693101056831, 0.4786286704993665],
[0, 0.5688888888888889],
[0.5384693101056831, 0.4786286704993665],
[0.906179845938664, 0.2369268850561891],
];
function sweptFace(f: Face): boolean {
const oc = getOC();
const T = oc.GeomAbs_SurfaceType;
const a = new oc.BRepAdaptor_Surface(f.wrapped, true);
try {
const t = a.GetType();
return t === T.GeomAbs_SurfaceOfExtrusion || t === T.GeomAbs_SurfaceOfRevolution || t === T.GeomAbs_OffsetSurface || t === T.GeomAbs_OtherSurface;
} finally {
a.delete();
}
}
/** Breaks of [a, b]: its ends and the given joints inside, each piece cut in `k`. */
function pieces(a: number, b: number, joints: number[], k: number): number[] {
const lo = Math.min(a, b);
const hi = Math.max(a, b);
const at = [lo, ...joints.filter((x) => x > lo + 1e-12 * (1 + Math.abs(lo)) && x < hi - 1e-12 * (1 + Math.abs(hi))), hi];
const out: number[] = [];
for (let i = 0; i + 1 < at.length; i++) for (let j = 0; j < k; j++) out.push(at[i] + ((at[i + 1] - at[i]) * j) / k);
out.push(hi);
return a <= b ? out : out.reverse();
}
/** A face's sums: area, ∫ X dA, its share of the volume (taken from R) and of ∫ (X - R) dV. */
type Sums = { area: number; m: Vec3; vol: number; mv: Vec3 };
/** A face's sums, integrated piece by piece, the pieces halved until two finenesses agree to a millionth. */
function faceSums(f: Face, R: Vec3, size: number): Sums {
const oc = getOC();
const S = oc.GeomAbs_Shape.GeomAbs_C2;
const surf = new oc.BRepAdaptor_Surface(f.wrapped, true);
const g = new oc.BRepGProp_Face(f.wrapped, false);
const p = new oc.gp_Pnt();
const n = new oc.gp_Vec();
const q = new oc.gp_Pnt2d();
const d = new oc.gp_Vec2d();
const ex = new oc.TopExp_Explorer(f.wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
const intervals = (count: number, fill: (arr: InstanceType<typeof oc.NCollection_Array1_double>) => void) => {
const arr = new oc.NCollection_Array1_double(1, count + 1);
try {
fill(arr);
const out: number[] = [];
for (let i = 1; i <= count + 1; i++) out.push(arr.Value(i));
return out;
} finally {
arr.delete();
}
};
const edges: { c: InstanceType<typeof oc.BRepAdaptor_Curve2d>; sign: number; t0: number; t1: number; joints: number[] }[] = [];
try {
// The inner sums run the way the surface has fewer pieces (along an
// extrusion's straight side, round a revolve), as each point of the
// outline needs one: the other way, across a spline's every piece, a
// shelled mouse took 5 s to measure (1 s this way). (Which way round
// the outline is then integrated only changes the sign, set below.)
const nu = surf.NbUIntervals(S);
const nv = surf.NbVIntervals(S);
const alongV = nv < nu;
const w0 = alongV ? surf.FirstVParameter() : surf.FirstUParameter();
const joints = alongV ? intervals(nv, (a) => surf.VIntervals(a, S)) : intervals(nu, (a) => surf.UIntervals(a, S));
// The surface's joints the other way: where the outline crosses one, the
// sums bend there, so the outline is cut there too.
const across = (alongV ? intervals(nu, (a) => surf.UIntervals(a, S)) : intervals(nv, (a) => surf.VIntervals(a, S))).slice(1, -1);
for (; ex.More(); ex.Next()) {
const cur = ex.Current();
const e = oc.TopoDS.Edge(cur);
const sign = e.Orientation() === oc.TopAbs_Orientation.TopAbs_REVERSED ? -1 : 1;
const c = new oc.BRepAdaptor_Curve2d(e, f.wrapped);
e.delete();
cur.delete();
const tJoints = intervals(c.NbIntervals(S), (a) => c.Intervals(a, S));
edges.push({ c, sign, t0: c.FirstParameter(), t1: c.LastParameter(), joints: tJoints });
if (!across.length) continue;
const other = (t: number) => {
c.D1(t, q, d);
return alongV ? q.X() : q.Y();
};
const base = [...tJoints];
for (let i = 0; i + 1 < base.length; i++) {
// (Sampled, then each crossing found by false position.)
const N = 4;
let ta = base[i];
let oa = other(ta);
for (let j = 1; j <= N; j++) {
const tb = base[i] + ((base[i + 1] - base[i]) * j) / N;
const ob = other(tb);
for (const J of across) {
if ((oa - J) * (ob - J) >= 0) continue;
let [lo, hi, flo, fhi] = [ta, tb, oa - J, ob - J];
let side = 0;
let t = lo;
for (let it = 0; it < 60; it++) {
t = (lo * fhi - hi * flo) / (fhi - flo);
const ft = other(t) - J;
if (Math.abs(ft) <= 1e-13 * (1 + Math.abs(J)) || hi - lo <= 1e-14 * (1 + Math.abs(hi))) break;
if (ft * flo < 0) {
[hi, fhi] = [t, ft];
if (side === -1) flo /= 2;
side = -1;
} else {
[lo, flo] = [t, ft];
if (side === 1) fhi /= 2;
side = 1;
}
}
tJoints.push(t);
}
ta = tb;
oa = ob;
}
}
tJoints.sort((x, y) => x - y);
}
const r = new Float64Array(8);
const tot = new Float64Array(8);
// Both ways each piece is one Gauss pass, checked against its two
// halves' and halved again only where they differ, to a tenth of the
// millionth (a slow stretch - a blade's trailing edge - doesn't make
// every other piece finer: halving all of them, again and again, the
// jet's sixteen blade faces took 4 s each and still hadn't agreed).
// A first rough pass (five points a piece) sets the scale.
// (Each half held to half the tolerance - but never below a thousandth
// of it, and no more than a budget of points a face: where the sums can't
// settle - rounding, a pole - halving the tolerance on and on split every
// piece to the bottom, 2^24 of them, and a lofted grid never finished.)
let rough = true;
let tolArea = Infinity;
let budget = 100000;
const gauss = (wa: number, wb: number, o: number) => {
budget--;
const out = new Float64Array(8);
const h = (wb - wa) / 2;
const c = (wb + wa) / 2;
for (const [x, wt] of GAUSS) {
if (alongV) g.Normal(o, c + h * x, p, n);
else g.Normal(c + h * x, o, p, n);
const nx = n.X();
const ny = n.Y();
const nz = n.Z();
const X = p.X();
const Y = p.Y();
const Z = p.Z();
const dx = X - R[0];
const dy = Y - R[1];
const dz = Z - R[2];
const wh = wt * h;
const a = Math.hypot(nx, ny, nz) * wh;
out[0] += a;
out[1] += a * X;
out[2] += a * Y;
out[3] += a * Z;
out[4] += ((dx * nx + dy * ny + dz * nz) / 3) * wh;
out[5] += ((dx * dx) / 2) * nx * wh;
out[6] += ((dy * dy) / 2) * ny * wh;
out[7] += ((dz * dz) / 2) * nz * wh;
}
return out;
};
const refine = (whole: Float64Array, wa: number, wb: number, o: number, tolA: number, depth: number) => {
const m = (wa + wb) / 2;
const l = gauss(wa, m, o);
const rr = gauss(m, wb, o);
if ((Math.abs(l[0] + rr[0] - whole[0]) <= tolA && Math.abs(l[4] + rr[4] - whole[4]) <= tolA * size) || depth >= 20 || budget <= 0) {
for (let j = 0; j < 8; j++) r[j] += l[j] + rr[j];
return;
}
const half = Math.max(tolA / 2, floor);
refine(l, wa, m, o, half, depth + 1);
refine(rr, m, wb, o, half, depth + 1);
};
// ∫ from w0 to w, at the other parameter o, of each sum's integrand.
let floor = 0;
const inner = (w: number, o: number) => {
r.fill(0);
const ws = pieces(w0, w, joints, 1);
const parts: Float64Array[] = [];
let scale = 0;
for (let i = 0; i + 1 < ws.length; i++) {
const got = gauss(ws[i], ws[i + 1], o);
parts.push(got);
scale += Math.abs(got[0]);
}
if (rough) {
for (const got of parts) for (let j = 0; j < 8; j++) r[j] += got[j];
return r;
}
const span = Math.abs(w - w0) || 1;
const tol = scale * EPS * 0.1;
floor = tol * 1e-3;
for (let i = 0; i + 1 < ws.length; i++) refine(parts[i], ws[i], ws[i + 1], o, (tol * Math.abs(ws[i + 1] - ws[i])) / span, 0);
return r;
};
type Curve2d = (typeof edges)[number]["c"];
const piece = (c: Curve2d, sign: number, a: number, b: number) => {
const out = new Float64Array(8);
const h = (b - a) / 2;
const m = (b + a) / 2;
for (const [x, wt] of GAUSS) {
c.D1(m + h * x, q, d);
const dOther = alongV ? d.X() : d.Y();
if (dOther === 0) continue;
const got = alongV ? inner(q.Y(), q.X()) : inner(q.X(), q.Y());
const f2 = sign * dOther * wt * h;
for (let j = 0; j < 8; j++) out[j] += got[j] * f2;
}
return out;
};
const add = (whole: Float64Array, c: Curve2d, sign: number, a: number, b: number, tolA: number, depth: number) => {
const m = (a + b) / 2;
const l = piece(c, sign, a, m);
const rr = piece(c, sign, m, b);
if ((Math.abs(l[0] + rr[0] - whole[0]) <= tolA && Math.abs(l[4] + rr[4] - whole[4]) <= tolA * size) || depth >= 24 || budget <= 0) {
for (let j = 0; j < 8; j++) tot[j] += l[j] + rr[j];
return;
}
const half = Math.max(tolA / 2, tolArea * 1e-4);
add(l, c, sign, a, m, half, depth + 1);
add(rr, c, sign, m, b, half, depth + 1);
};
const sums = (): Sums => {
tot.fill(0);
for (const { c, sign, t0, t1, joints: tj } of edges) {
const ts = pieces(t0, t1, tj, 1);
const span = Math.abs(t1 - t0) || 1;
for (let i = 0; i + 1 < ts.length; i++) {
const share = Math.abs(ts[i + 1] - ts[i]) / span / edges.length;
add(piece(c, sign, ts[i], ts[i + 1]), c, sign, ts[i], ts[i + 1], tolArea * share, 0);
}
}
// (Which way round the outline runs depends on the face's own way
// round: the area must come out above 0.)
const s = tot[0] < 0 ? -1 : 1;
return { area: s * tot[0], m: [s * tot[1], s * tot[2], s * tot[3]], vol: s * tot[4], mv: [s * tot[5], s * tot[6], s * tot[7]] };
};
// (A face an offset closed to nothing - 1e-15 mm² - adds nothing: held
// to a tenth of a millionth of its own no area, it never settled, 3 s each
// in a split box's shell.)
const first = sums();
if (Math.abs(first.area) < size * size * 1e-12) return first;
tolArea = Math.max(Math.abs(first.area), size * size * 1e-6) * EPS * 0.1;
rough = false;
return sums();
} finally {
for (const e of edges) e.c.delete();
ex.delete();
d.delete();
q.delete();
n.delete();
p.delete();
g.delete();
surf.delete();
}
}
/** Sums over all its faces, integrated here - or null when none is swept (OpenCascade measures the rest right). */
function ownSums(s: Measurable): (Sums & { R: Vec3 }) | null {
// (Kept per shape: a shell's checks measure the same body several times.)
const known = measured.get(s);
if (known !== undefined) return known;
const got = ownSumsNow(s);
measured.set(s, got);
return got;
}
const measured = new WeakMap<object, (Sums & { R: Vec3 }) | null>();
function ownSumsNow(s: Measurable): (Sums & { R: Vec3 }) | null {
const faces = s.faces;
if (!faces.some(sweptFace)) return null;
const b = s.boundingBox;
const R = [...b.center] as Vec3;
const size = Math.max(1e-9, Math.hypot(b.width, b.height, b.depth));
const out: Sums = { area: 0, m: [0, 0, 0], vol: 0, mv: [0, 0, 0] };
for (const f of faces) {
const r = faceSums(f, R, size);
out.area += r.area;
out.vol += r.vol;
for (let j = 0; j < 3; j++) {
out.m[j] += r.m[j];
out.mv[j] += r.mv[j];
}
}
return { ...out, R };
}
/** The area of all its faces, to a millionth. */
export function measureArea(s: Measurable): number {
const own = ownSums(s);
if (own) return own.area;
const p = props(s, "area");
try {
return p.Mass();
} finally {
p.delete();
}
}
/** A face's area and its middle (centre of area), measured once - at the plain fineness (for showing, not for checks). */
export function areaProperties(f: Face): { area: number; center: Vec3 } {
const own = ownSums(f);
if (own) return { area: own.area, center: own.m.map((x) => x / own.area) as Vec3 };
const oc = getOC();
const p = new oc.GProp_GProps();
oc.BRepGProp.SurfaceProperties(f.wrapped, p, false, false);
const c = p.CentreOfMass();
try {
return { area: p.Mass(), center: [c.X(), c.Y(), c.Z()] };
} finally {
c.delete();
p.delete();
}
}
/** Volume and centre of mass, to a millionth. */
export function volumeProperties(s: Shape3D): { volume: number; centerOfMass: Vec3 } {
const own = ownSums(s);
if (own) return { volume: own.vol, centerOfMass: own.mv.map((x, j) => own.R[j] + x / own.vol) as Vec3 };
const p = props(s, "volume");
const c = p.CentreOfMass();
try {
return { volume: p.Mass(), centerOfMass: [c.X(), c.Y(), c.Z()] };
} finally {
c.delete();
p.delete();
}
}
+108 -2
View File
@@ -13,6 +13,12 @@ export interface FaceInfo {
plane?: PlaneDef;
/** Set for round (cylindrical) faces: the radius, and whether it's a hole (material outside it). */
round?: { r: number; hole: boolean };
/** The step that made it (see provenance.ts). */
step?: string;
/** Which of that step's faces it is (the sketch curve it came from; see FaceRef.curve). */
curve?: string;
/** The step it used to be put down to (a Move its body went through, say): picks saved then name it by that. */
was?: string;
}
export interface EdgeInfo {
@@ -23,11 +29,25 @@ export interface EdgeInfo {
end: Vec3;
/** LINE, CIRCLE, ELLIPSE, BSPLINE_CURVE… */
type: string;
/** The steps that made the faces either side (sorted). */
steps?: string[];
/** Which faces of those steps (see EdgeRef.curves). */
curves?: string[];
/** The steps its faces used to be put down to, where that differs (see FaceInfo.was). */
was?: string[];
/** Where a round face meets itself (one face on both sides): drawn, but nothing to round or chamfer. */
seam?: boolean;
}
export interface BodyMesh {
id: string;
name: string;
/**
* Which mesh this is: the same key, the same geometry (a body the step
* didn't change). The worker sends only the key for a mesh the page already
* has, and the view keeps what it drew for it.
*/
key: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
@@ -63,12 +83,92 @@ export interface RegenResult {
sketchPlanes: Record<string, PlaneDef>;
/** Outline of the face each face-attached sketch sits on (takes part in its regions). */
sketchBoundaries: Record<string, SketchEntity[]>;
/** Sketches whose curves the engine moved (they follow a body's edge that changed): their curves as they are now. */
sketchEntities?: Record<string, SketchEntity[]>;
/** Subtract / Union / Delete steps that don't say yet which patterns they used whole: those, by step (the page keeps them with the step). */
whole?: Record<string, string[]>;
planes: ConstructionInfo[];
axes: ConstructionInfo[];
errors: FeatureError[];
/** Steps that worked but had to give something up (a fillet that no longer fits…). */
notes?: FeatureError[];
ms: number;
/** The engine's memory after it (MB): it never gives any back, so the page starts a fresh engine when it's big. */
memoryMB?: number;
}
/** A body's physical properties, measured on the solid itself (mm, mm², mm³). */
export interface BodyProps {
id: string;
name: string;
volume: number;
area: number;
/** Centre of mass (of the shape, as if all of one material). */
center: Vec3;
/** Its box: lowest corner, highest corner. */
box: [Vec3, Vec3];
}
/**
* A body's health, measured on the solid (for checking a model from the
* console or the command line): valid, closed, how many solids and faces.
*/
export interface BodyHealth {
id: string;
name: string;
valid: boolean;
solids: number;
shells: number;
openEdges: number;
/** Edges more than two faces meet at: pieces that only touch along an edge. */
pinched: number;
/** Hair-thin faces. */
thin: number;
volume: number;
faces: number;
edges: number;
/** Its box: lowest corner, highest corner. */
box: [Vec3, Vec3];
/** Valid, closed, no hair-thin faces, a real volume. */
healthy: boolean;
}
/** A view to draw: the model seen from `dir` (towards the viewer), `xAxis` to the right on the paper. */
export interface ViewSpec {
id: string;
dir: Vec3;
xAxis: Vec3;
/** A section view: a point on the cut plane (square to `dir`); what lies between the eye and it is taken off. */
cut?: Vec3;
}
/** One body in a drawn view: SVG path data (mm on the paper at 1:1, y down). */
export interface ViewBody {
id: string;
/** Edges seen. */
visible: string;
/** Where two faces meet smoothly (drawn thin). */
tangent: string;
/** Edges behind (drawn dashed). */
hidden: string;
/** A point on one of its seen edges, near its middle: where a balloon's leader ends. */
anchor?: [number, number];
/** For a body hidden whole in this view (inside a housing): a spot on its hidden edges. */
under?: [number, number];
/** Its seen straight edges and circles (arcs), to dimension by tapping them. */
edges: ViewEdge[];
/** A section view: the faces the cut made, as closed outlines (to hatch). */
section?: string;
}
/** A seen edge in a view (mm, y down): a line from a to b, or a circle (an arc from a through m to b; whole when a = b). */
export type ViewEdge = { a: [number, number]; b: [number, number] } | { a: [number, number]; m: [number, number]; b: [number, number]; c: [number, number]; r: number };
/** A drawn view: each body, and the box around them all (2D, y down). */
export interface ProjectedView {
id: string;
bodies: ViewBody[];
box: [[number, number], [number, number]] | null;
}
/** "mesh": each body as triangles, as finely as an STL (for a 3MF), JSON: { id, positions, indices }[]. */
@@ -76,13 +176,19 @@ export type ExportFormat = "stl" | "step" | "mesh";
export type Request =
| { type: "init" }
| { type: "regenerate"; features: Feature[] }
| { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] };
| { type: "regenerate"; features: Feature[]; saved?: boolean }
| { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] }
| { type: "properties"; features: Feature[] }
| { type: "health"; features: Feature[] }
| { type: "drawing"; features: Feature[]; views: ViewSpec[]; bodies?: string[] };
export type Response =
| { type: "ready" }
| { type: "regenerated"; result: RegenResult }
| { type: "exported"; blob: Blob }
| { type: "properties"; bodies: BodyProps[] }
| { type: "health"; bodies: BodyHealth[] }
| { type: "drawing"; views: ProjectedView[] }
| { type: "error"; message: string };
export interface Envelope<T> {
+358
View File
@@ -0,0 +1,358 @@
// Which step made each face (and so each edge) of a body.
//
// A step built on a face or edge remembers it by where it is and how big it
// is; when an earlier step changes, the best match is taken. With nothing
// better to go on, "best" could be a face of another kind altogether: the
// screw bosses went onto the top of the box when the shell that made the
// floor they stood on was switched off, and a fillet round the bosses' feet
// rounded other edges once the bosses were gone - with no word.
//
// So every face is tagged with the step that made it: a face a step leaves
// as it was, or only trims (a side face cut shorter by a fillet, a wall with
// a hole cut through it), keeps its tag; a face it makes new gets the step's
// id. A reference then looks only among faces from the same step, and when
// there are none, says so instead of guessing.
import { getOC, type Face, type Shape3D } from "replicad";
interface Tagged {
/** The step that made each face (in the order of shape.faces). */
steps: string[];
/** Each face's surface (plane, cylinder, …) as a key, for faces only trimmed. */
keys: (string | null)[];
/** Faces by hash, for faces a step left as they were. */
byHash: Map<number, { face: Face; i: number }[]>;
/**
* The step a face used to be put down to, where that was another body's
* (see tagBody) or a Move's (see movedTags): what projects saved before
* then name it by.
*/
alias?: (string | undefined)[];
/**
* Where each face is now, against where its step made it: the moves, turns
* and mirrorings its body has been through since (a 3 x 4 matrix, row by
* row; none: where it was made).
*/
moves?: (Moved | undefined)[];
}
/** A 3 x 4 matrix, row by row: where a point is after a move. */
type Moved = number[];
/** First m, then n. */
function then(m: Moved, n: Moved): Moved {
const out: number[] = [];
for (let r = 0; r < 3; r++) {
for (let c = 0; c < 3; c++) out.push(n[r * 4] * m[c] + n[r * 4 + 1] * m[4 + c] + n[r * 4 + 2] * m[8 + c]);
out.push(n[r * 4] * m[3] + n[r * 4 + 1] * m[7] + n[r * 4 + 2] * m[11] + n[r * 4 + 3]);
}
return out;
}
/** A point (or a direction a face looks) taken back to where it was before a move. */
export type Back = (v: [number, number, number], direction?: boolean) => [number, number, number];
function backOf(m: Moved): Back {
const [a, b, c, d, e, f, g, h, i] = [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]];
const det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
// The matrix turned back (its inverse).
const inv = [e * i - f * h, c * h - b * i, b * f - c * e, f * g - d * i, a * i - c * g, c * d - a * f, d * h - e * g, b * g - a * h, a * e - b * d].map((x) => x / det);
return (v, direction) => {
// (The way a face looks goes back by the matrix laid on its side: the same thing for a move, a turn, a mirroring.)
if (direction) return [a * v[0] + d * v[1] + g * v[2], b * v[0] + e * v[1] + h * v[2], c * v[0] + f * v[1] + i * v[2]];
const q = [v[0] - m[3], v[1] - m[7], v[2] - m[11]];
return [inv[0] * q[0] + inv[1] * q[1] + inv[2] * q[2], inv[3] * q[0] + inv[4] * q[1] + inv[5] * q[2], inv[6] * q[0] + inv[7] * q[1] + inv[8] * q[2]];
};
}
const tags = new WeakMap<Shape3D, Tagged>();
const edgeTags = new WeakMap<Shape3D, string[][]>();
const oldEdgeTags = new WeakMap<Shape3D, string[][] | null>();
const r4 = (v: number) => {
const x = Math.round(v * 1e4) / 1e4;
return Object.is(x, -0) ? "0" : String(x);
};
/** A face's surface, the same however much of it the face covers (null: no key for this kind). */
function surfaceKey(face: Face): string | null {
const oc = getOC();
const s = new oc.BRepAdaptor_Surface(face.wrapped, true);
try {
const T = oc.GeomAbs_SurfaceType;
const type = s.GetType();
// A direction either way round (a face's orientation can flip in an edit).
const dir = (d: { X(): number; Y(): number; Z(): number }) => {
let v = [d.X(), d.Y(), d.Z()];
const k = v.findIndex((x) => Math.abs(x) > 1e-9);
if (k >= 0 && v[k] < 0) v = v.map((x) => -x);
return v;
};
// The point of a line through p along d nearest the origin.
const foot = (p: number[], d: number[]) => {
const t = p[0] * d[0] + p[1] * d[1] + p[2] * d[2];
return [p[0] - t * d[0], p[1] - t * d[1], p[2] - t * d[2]];
};
const pt = (p: { X(): number; Y(): number; Z(): number }) => [p.X(), p.Y(), p.Z()];
if (type === T.GeomAbs_Plane) {
const pl = s.Plane();
const n = dir(pl.Axis().Direction());
const p = pt(pl.Location());
return `P ${n.map(r4)} ${r4(n[0] * p[0] + n[1] * p[1] + n[2] * p[2])}`;
}
if (type === T.GeomAbs_Cylinder) {
const cy = s.Cylinder();
const d = dir(cy.Axis().Direction());
return `C ${d.map(r4)} ${foot(pt(cy.Location()), d).map(r4)} ${r4(cy.Radius())}`;
}
if (type === T.GeomAbs_Sphere) {
const sp = s.Sphere();
return `S ${pt(sp.Location()).map(r4)} ${r4(sp.Radius())}`;
}
if (type === T.GeomAbs_Cone) {
const co = s.Cone() as any;
const d = dir(co.Axis().Direction());
return `K ${d.map(r4)} ${pt(co.Apex()).map(r4)} ${r4(Math.abs(co.SemiAngle()))}`;
}
if (type === T.GeomAbs_Torus) {
const to = s.Torus() as any;
const d = dir(to.Axis().Direction());
return `T ${d.map(r4)} ${pt(to.Location()).map(r4)} ${r4(to.MajorRadius())} ${r4(to.MinorRadius())}`;
}
return null;
} catch {
return null;
} finally {
s.delete();
}
}
/**
* Tag the faces of a body a step made or changed. `from`: the bodies it was
* made from (the same body before the step, and those the step worked on).
*
* `others`: bodies that were there but had no part in it. A new face on the
* same plane as a face of one of them (every body standing on the ground, a
* block as tall as the one beside it) used to be put down to that body's
* step: change that body and steps on this one lost their faces. It is this
* step's now; the old answer is kept beside it, for projects saved with it.
*/
export function tagBody(shape: Shape3D, step: string, from: Shape3D[], others: Shape3D[] = []): void {
if (tags.has(shape)) return;
const hashes = new Map<number, { face: Face; step: string; key: string | null; alias?: string; move?: Moved }[]>();
const byKey = new Map<string, { step: string; alias?: string; move?: Moved }>();
for (const s of from) {
const t = tags.get(s);
if (!t || s === shape) continue;
for (const list of t.byHash.values())
for (const { face, i } of list) {
const h = face.hashCode;
hashes.set(h, [...(hashes.get(h) ?? []), { face, step: t.steps[i], key: t.keys[i], alias: t.alias?.[i], move: t.moves?.[i] }]);
}
t.keys.forEach((k, i) => k && !byKey.has(k) && byKey.set(k, { step: t.steps[i], alias: t.alias?.[i], move: t.moves?.[i] }));
}
const oldKey = new Map<string, string>();
for (const s of others) {
const t = tags.get(s);
if (!t || s === shape || from.includes(s)) continue;
t.keys.forEach((k, i) => k && !oldKey.has(k) && oldKey.set(k, t.alias?.[i] ?? t.steps[i]));
}
const faces = shape.faces;
const out: Tagged = { steps: [], keys: [], byHash: new Map() };
const alias: (string | undefined)[] = [];
const moves: (Moved | undefined)[] = [];
faces.forEach((face, i) => {
const h = face.hashCode;
out.byHash.set(h, [...(out.byHash.get(h) ?? []), { face, i }]);
const same = hashes.get(h)?.find((x) => x.face.isSame(face));
if (same) {
out.steps.push(same.step);
out.keys.push(same.key);
alias.push(same.alias);
moves.push(same.move);
return;
}
const key = surfaceKey(face);
out.keys.push(key);
const kept = key ? byKey.get(key) : undefined;
out.steps.push(kept?.step ?? step);
alias.push(kept ? kept.alias : key ? oldKey.get(key) : undefined);
moves.push(kept?.move);
});
if (alias.some((a) => a !== undefined)) out.alias = alias;
if (moves.some((m) => m !== undefined)) out.moves = moves;
tags.set(shape, out);
}
/**
* A body moved, turned or mirrored whole - by a Move, or as a pattern's copy
* (`m`: where each point went; the same faces in the same order). Every face
* is still the step's that made it, and the same one of that step's faces:
* it used to become the Move's, so a pick on a moved body knew no more than
* where its face was - and a Move put in before a step lost the step its
* picks. What was saved then names the faces by the Move (`step`): kept
* beside, as the old answer.
*/
export function movedTags(from: Shape3D, moved: Shape3D, step: string, m: number[]): void {
const t = tags.get(from);
if (!t || tags.has(moved)) return;
const faces = moved.faces;
if (faces.length !== t.steps.length) return;
const byHash = new Map<number, { face: Face; i: number }[]>();
faces.forEach((face, i) => byHash.set(face.hashCode, [...(byHash.get(face.hashCode) ?? []), { face, i }]));
tags.set(moved, {
steps: t.steps,
keys: faces.map(surfaceKey),
byHash,
alias: faces.map(() => step),
moves: faces.map((_, i) => (t.moves?.[i] ? then(t.moves[i]!, m) : m)),
});
}
/** The step each face used to be put down to, where that differs (see tagBody); undefined: none does. */
export function faceAliases(shape: Shape3D): (string | undefined)[] | undefined {
return tags.get(shape)?.alias;
}
/** The step that made each face of a body (undefined: not tagged). */
export function faceSteps(shape: Shape3D): string[] | undefined {
return tags.get(shape)?.steps;
}
/** Edge steps as projects saved before faces were told apart from other bodies' name them (undefined: the same as edgeSteps). */
export function oldEdgeSteps(shape: Shape3D): string[][] | undefined {
const known = oldEdgeTags.get(shape);
if (known !== undefined) return known ?? undefined;
const t = tags.get(shape);
const out = t?.alias ? stepsOfEdges(shape, t.steps.map((s, i) => t.alias![i] ?? s)) : null;
oldEdgeTags.set(shape, out);
return out ?? undefined;
}
/** For each edge of a body, the steps of the faces it lies between (sorted; one for a seam). */
export function edgeSteps(shape: Shape3D): string[][] | undefined {
const known = edgeTags.get(shape);
if (known) return known;
const steps = faceSteps(shape);
if (!steps) return undefined;
const out = stepsOfEdges(shape, steps);
edgeTags.set(shape, out);
return out;
}
function stepsOfEdges(shape: Shape3D, steps: string[]): string[][] {
const edges = shape.edges;
const buckets = new Map<number, { i: number; s: Set<string> }[]>();
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, s: new Set<string>() }]));
shape.faces.forEach((f, fi) => {
for (const fe of f.edges) {
const list = buckets.get(fe.hashCode);
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
m?.s.add(steps[fi]);
}
});
const out: string[][] = new Array(edges.length).fill(null).map(() => []);
for (const list of buckets.values()) for (const { i, s } of list) out[i] = [...s].sort();
return out;
}
/**
* Which of a step's faces a face is: told from the face itself and what the
* step was made from (an extrusion's side by the sketch curve under it). One
* per step that can tell; set by the engine as it replays the steps.
*/
export type OriginOf = (face: Face, back?: Back) => string | null;
let originOf: Map<string, OriginOf> = new Map();
export function setOrigins(of: Map<string, OriginOf>): void {
originOf = of;
}
const originTags = new WeakMap<Shape3D, (string | undefined)[]>();
/** For each face of a body, which of its step's faces it is (undefined: can't be told). */
export function faceOrigins(shape: Shape3D): (string | undefined)[] | undefined {
const known = originTags.get(shape);
if (known) return known;
const steps = faceSteps(shape);
if (!steps) return undefined;
const moves = tags.get(shape)?.moves;
const out = shape.faces.map((face, i) => {
const of = originOf.get(steps[i]);
if (!of) return undefined;
try {
// (Told where its step made it: a face moved since is taken back there.)
return of(face, moves?.[i] ? backOf(moves[i]!) : undefined) ?? undefined;
} catch {
return undefined;
}
});
originTags.set(shape, out);
return out;
}
const edgeOriginTags = new WeakMap<Shape3D, (string[] | undefined)[]>();
/** For each edge, the faces it lies between as "step|origin" (sorted); undefined when one of them can't be told. */
export function edgeOrigins(shape: Shape3D): (string[] | undefined)[] | undefined {
const known = edgeOriginTags.get(shape);
if (known) return known;
const steps = faceSteps(shape);
const origins = faceOrigins(shape);
if (!steps || !origins) return undefined;
const edges = shape.edges;
const buckets = new Map<number, { i: number; s: Set<string>; all: boolean }[]>();
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, s: new Set<string>(), all: true }]));
shape.faces.forEach((f, fi) => {
for (const fe of f.edges) {
const list = buckets.get(fe.hashCode);
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
if (!m) continue;
if (origins[fi] === undefined) m.all = false;
else m.s.add(`${steps[fi]}|${origins[fi]}`);
}
});
const out: (string[] | undefined)[] = new Array(edges.length).fill(undefined);
for (const list of buckets.values()) for (const { i, s, all } of list) out[i] = all && s.size ? [...s].sort() : undefined;
edgeOriginTags.set(shape, out);
return out;
}
const seamTags = new WeakMap<Shape3D, boolean[]>();
/**
* Per edge: it has the same face on both sides (the seam of a cylinder or a
* sphere). Nothing to round there - a fillet's corner that's gone mustn't
* land on one (a lid's 4 corner edges all went to its seam when the lid
* was made round: "radius too big", not "the edges are gone").
*/
export function seamEdges(shape: Shape3D): boolean[] {
const known = seamTags.get(shape);
if (known) return known;
const edges = shape.edges;
const buckets = new Map<number, { i: number; faces: Set<number> }[]>();
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, faces: new Set<number>() }]));
shape.faces.forEach((f, fi) => {
for (const fe of f.edges) {
const list = buckets.get(fe.hashCode);
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
m?.faces.add(fi);
}
});
const out: boolean[] = new Array(edges.length).fill(false);
for (const list of buckets.values()) for (const { i, faces } of list) out[i] = faces.size === 1;
seamTags.set(shape, out);
return out;
}
/** Same steps, as stored in a reference. */
export function sameSteps(a: string[], b: string[]): boolean {
return a.length === b.length && a.every((x, i) => x === b[i]);
}
/** A copy made face for face (same order): the same tags. */
export function inheritTags(from: Shape3D, copy: Shape3D): void {
const t = tags.get(from);
if (!t || tags.has(copy)) return;
const faces = copy.faces;
if (faces.length !== t.steps.length) return;
const byHash = new Map<number, { face: Face; i: number }[]>();
faces.forEach((face, i) => byHash.set(face.hashCode, [...(byHash.get(face.hashCode) ?? []), { face, i }]));
tags.set(copy, { steps: t.steps, keys: t.keys, byHash, alias: t.alias, moves: t.moves });
}
+112
View File
@@ -0,0 +1,112 @@
// Giving memory back to the kernel.
//
// This build of OpenCascade does not let go of most things when they are
// deleted: `delete()` on a shape's handle, an explorer, a boolean, a checker
// marks it deleted on this side and leaves it whole on the other. A deleted
// handle still counted as a user of its shape, so no body the engine ever
// made was freed, and each tool kept all it had worked out: the engine's
// memory only grew - by a megabyte or so with every rebuild of an everyday
// part - until it was replaced with a fresh one (worker.ts), every step built
// again from nothing. (Read off the kernel's memory: five handles to a box
// deleted, the box still had its five users; emptied first, none.)
//
// So each such thing is told to let go just before it is deleted - here, for
// its whole class, which covers the deleting done by replicad as well.
import { BoundingBox, getOC, Solid } from "replicad";
/* eslint-disable @typescript-eslint/no-explicit-any */
/** The kernels (one at a time: a fresh one after a breakdown) whose classes are done. */
const done = new WeakSet<object>();
/** The last handle to its object, not deleted yet? (A handle can be cloned: the object goes with the last.) */
function last(handle: any): boolean {
if (handle.isDeleted()) return false;
const record = handle[Object.getOwnPropertyNames(handle)[0]];
return !record?.count || record.count.value === 1;
}
/**
* A shape's box, worked out once. The kernel's exact box of a body with curved faces takes its time (a mug with its
* handle: 0.95 s; a freeform shoe: 0.7 s) and was worked out again each time it was asked for - by every step that
* touched the body, several times over, and once more to draw it. Kept by the shape's handle: another shape, or
* the same one moved, is another handle. (Each asker gets a box of its own: some delete theirs.)
*/
const boxes = new WeakMap<object, [number, number, number, number, number, number]>();
let boxed = false;
function useBoxes(): void {
if (boxed) return;
boxed = true;
let proto: any = Solid.prototype;
while (proto && !Object.getOwnPropertyDescriptor(proto, "boundingBox")) proto = Object.getPrototypeOf(proto);
const exact = proto && Object.getOwnPropertyDescriptor(proto, "boundingBox")?.get;
if (!exact) return;
Object.defineProperty(proto, "boundingBox", {
configurable: true,
get(this: any) {
const key = this.wrapped as object;
const had = key && boxes.get(key);
if (had) return BoundingBox.fromBounds([had[0], had[1], had[2]], [had[3], had[4], had[5]]);
const box = exact.call(this);
try {
// (An empty shape's box is no box: asked again each time, as it was.)
if (key && !box.wrapped.IsVoid()) {
const [lo, hi] = box.bounds;
if ([...lo, ...hi].every(Number.isFinite)) boxes.set(key, [lo[0], lo[1], lo[2], hi[0], hi[1], hi[2]]);
}
} catch {
// As it came.
}
return box;
},
});
}
export function useReleases(): void {
useBoxes();
const oc = getOC() as any;
if (done.has(oc)) return;
done.add(oc);
const nothing = new oc.TopoDS_Shape();
const ANY = oc.TopAbs_ShapeEnum.TopAbs_SHAPE;
const before = (name: string, release: (handle: any) => void): void => {
const proto = oc[name]?.prototype;
if (!proto || typeof proto.delete !== "function") return;
const remove = proto.delete as (this: unknown) => unknown;
proto.delete = function (this: any) {
if (last(this)) {
try {
release(this);
} catch {
// Deleted as it is.
}
}
return remove.call(this);
};
};
// A shape's handle (a face's, an edge's... are its kinds): emptied, it no longer uses the shape.
before("TopoDS_Shape", (h) => h.Nullify());
// An explorer keeps the shape it went through.
before("TopExp_Explorer", (h) => h.Init(nothing, ANY, ANY));
// A boolean keeps all it worked out about where its shapes meet (165 KB for
// a hole through a block) - cleared - and the bodies it was given and the
// body it made, which it has no way to be told to drop: it is given a last
// job instead, one point less another, and holds those two points from then on.
const [a, b] = [new oc.gp_Pnt(0, 0, 0), new oc.gp_Pnt(1, 0, 0)];
const speck = (p: unknown) => {
const list = new oc.NCollection_List_TopoDS_Shape();
list.Append(new oc.BRepBuilderAPI_MakeVertex(p).Vertex());
return list;
};
const [one, other] = [speck(a), speck(b)];
const progress = new oc.Message_ProgressRange();
for (const name of ["BRepAlgoAPI_Cut", "BRepAlgoAPI_Fuse", "BRepAlgoAPI_Common", "BRepAlgoAPI_Section", "BRepAlgoAPI_Splitter"])
before(name, (h) => {
h.Clear();
h.SetArguments(one);
h.SetTools(other);
h.Build(progress);
h.Clear();
});
}
+134 -7
View File
@@ -6,28 +6,32 @@
// open edges, hair-thin faces dropped and their slot closed, faces split on
// one surface merged, skins made solid, inside-out solids turned round.
import { assembleWire, cast, getOC, makeCompound, makeFace, measureArea, measureVolume, type Shape3D } from "replicad";
import { assembleWire, cast, getOC, makeCompound, makeFace, makeLine, makeThreePointArc, measureArea, type Shape3D, type Wire } from "replicad";
import { measureVolume, quickVolume } from "./ocFree";
import { unify } from "./faceEdit";
import { deepCopy, hairThin, openEdges, shapeValid, subShapes } from "./health";
import { deepCopy, hairThin, meshVolume, openEdges, pinchedEdges, shapeValid, subShapes } from "./health";
export interface Health {
valid: boolean;
solids: number;
shells: number;
openEdges: number;
/** Edges more than two faces meet at (pieces touching only along an edge). */
pinched: number;
thin: number;
volume: number;
faces: number;
}
export function healthOf(s: Shape3D): Health {
const h: Health = { valid: false, solids: 0, shells: 0, openEdges: 0, thin: 0, volume: 0, faces: 0 };
const h: Health = { valid: false, solids: 0, shells: 0, openEdges: 0, pinched: 0, thin: 0, volume: 0, faces: 0 };
try {
h.faces = s.faces.length;
h.valid = shapeValid(s);
h.solids = subShapes(s, "SOLID").length;
h.shells = subShapes(s, "SHELL").length;
h.openEdges = openEdges(s).length;
h.pinched = pinchedEdges(s);
h.thin = hairThin(s);
h.volume = h.solids ? measureVolume(s) : 0;
} catch {
@@ -43,9 +47,9 @@ export interface RepairOptions {
volume?: number;
}
/** A clean solid: valid, closed, no hair-thin faces, real volume. */
/** A clean solid: valid, closed, no pieces meeting only at an edge, no hair-thin faces, real volume. */
export function isHealthy(h: Health, o: RepairOptions = {}): boolean {
return h.valid && h.solids >= 1 && (!o.maxSolids || h.solids <= o.maxSolids) && h.openEdges === 0 && h.thin === 0 && h.volume > 0;
return h.valid && h.solids >= 1 && (!o.maxSolids || h.solids <= o.maxSolids) && h.openEdges === 0 && !h.pinched && h.thin === 0 && h.volume > 0;
}
/** How broken (0: healthy) - to tell whether a fix helped. */
@@ -67,6 +71,83 @@ function sizeOf(s: Shape3D): number {
type Fix = { label: string; run: (s: Shape3D, size: number) => Shape3D | null };
/** Faces → shell(s) by sewing at `tol`; every closed shell → a solid (turned outward). */
/**
* Flat faces with an edge next to nothing in length (the end of a sliver
* that was closed: two roundings that meet, 4 mm each side of an 8 mm
* block) made again without it, their outline's two neighbours brought
* together. Left in, that speck is an edge to pick, and one the engine
* stumbles on in every later cut and fillet there. Null: none to drop.
*/
function withoutSpecks(s: Shape3D, tol: number): Shape3D | null {
type P = [number, number, number];
const far = (p: P, q: P) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
const remade = (w: Wire): Wire => {
const all = w.edges.map((e) => ({ e, a: e.startPoint.toTuple() as P, b: e.endPoint.toTuple() as P, m: e.pointAt(0.5).toTuple() as P, type: e.geomType as string, speck: e.length < tol, moved: false }));
const specks = all.filter((x) => x.speck);
if (!specks.length) return w;
// The ends that were on a speck: both at its middle now.
const snap = (p: P): P | null => {
for (const k of specks) if (far(p, k.a) < tol || far(p, k.b) < tol) return [(k.a[0] + k.b[0]) / 2, (k.a[1] + k.b[1]) / 2, (k.a[2] + k.b[2]) / 2];
return null;
};
const rest = all.filter((x) => !x.speck);
for (const x of rest) {
const [a, b] = [snap(x.a), snap(x.b)];
if (!a && !b) continue;
if (x.type !== "LINE" && x.type !== "CIRCLE") throw new Error("not a line or an arc");
x.a = a ?? x.a;
x.b = b ?? x.b;
x.moved = true;
}
// In order round the outline (each begins where the one before ends).
const chain = [rest.shift()!];
while (rest.length) {
const end = chain[chain.length - 1].b;
let i = rest.findIndex((x) => far(x.a, end) < tol);
if (i < 0) {
i = rest.findIndex((x) => far(x.b, end) < tol);
if (i < 0) throw new Error("the outline doesn't close");
[rest[i].a, rest[i].b] = [rest[i].b, rest[i].a];
}
chain.push(rest.splice(i, 1)[0]);
}
return assembleWire(chain.map((x) => (!x.moved ? x.e : x.type === "LINE" ? makeLine(x.a, x.b) : makeThreePointArc(x.a, x.m, x.b))));
};
let any = false;
const faces = s.faces.map((f) => {
if (f.geomType !== "PLANE" || !f.edges.some((e) => e.length < tol)) return f.wrapped;
try {
const made = makeFace(remade(f.clone().outerWire()), f.clone().innerWires().map(remade));
any = true;
return made.wrapped;
} catch {
return f.wrapped;
}
});
return any ? sewToSolid(faces, tol) : null;
}
/** Faces on the same surface to within `tol` made one (null: it can't be done). */
function merged(s: Shape3D, tol: number): Shape3D | null {
const oc = getOC();
const u = new oc.ShapeUpgrade_UnifySameDomain(s.wrapped, true, true, false);
try {
u.SetLinearTolerance(tol);
u.SetAngularTolerance(1e-5);
u.Build();
const made = u.Shape();
try {
return cast(made) as Shape3D;
} finally {
made.delete();
}
} catch {
return null;
} finally {
u.delete();
}
}
function sewToSolid(faces: unknown[], tol: number): Shape3D | null {
const oc = getOC();
const sw = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
@@ -195,7 +276,26 @@ const FIXES: Fix[] = [
return Math.min(...[b.width, b.height, b.depth].filter((x) => x > 0), size * 1e-3);
}));
const kept = s.faces.filter((_, i) => !thin[i]).map((f) => f.wrapped);
return sewToSolid(kept, Math.min(size * 1e-3, Math.max(size * 1e-6, width * 2)));
const tol = Math.min(size * 1e-3, Math.max(size * 1e-6, width * 2));
const closed = sewToSolid(kept, tol);
if (!closed) return null;
// The sliver's ends are still there, as edges next to nothing in length on the faces it ended at.
try {
const clean = withoutSpecks(closed, tol);
if (clean && !clean.edges.some((e) => e.length < tol)) {
// What the sliver lay between is one surface but for its width (the two
// roundings of a full round: one half cylinder): one face, with no line down it.
const joined = merged(clean, tol);
const one = joined && FIXES[0].run(joined, size);
const v = measureVolume(closed);
const good = (x: Shape3D) => shapeValid(x) && !openEdges(x).length && Math.abs(measureVolume(x) - v) < Math.abs(v) * 1e-4;
if (one && one.faces.length < clean.faces.length && good(one)) return one;
if (good(clean)) return clean;
}
} catch {
// as it is, then
}
return closed;
},
},
{
@@ -216,7 +316,7 @@ const FIXES: Fix[] = [
label: "turned it the right way out",
run: (s) => {
const oc = getOC();
if (!(measureVolume(s) < 0)) return null;
if (!(quickVolume(s) < 0)) return null;
const c = deepCopy(s);
for (const x of subShapes(c, "SOLID")) oc.BRepLib.OrientClosedSolid(x);
return c;
@@ -251,8 +351,35 @@ export function repairShape(input: Shape3D, o: RepairOptions = {}): { shape: Sha
if (isHealthy(h, o)) return { shape: cur, fixes: [] };
const size = sizeOf(input);
const v0 = o.volume ?? (h.volume > 0 && h.valid ? h.volume : undefined);
// Not valid: its measured volume can't be trusted, but one counted from a
// mesh can (when it's closed). Without it, "fixed faces" was free to change
// the shape: a slot cut into a drill's housing came back 764 mm³ bigger,
// and the housing split in half later left pieces inside out.
let m0: number | undefined;
if (v0 === undefined && h.solids && !h.openEdges) {
try {
const m = meshVolume(input, size);
if (m > 0) m0 = m;
} catch {
m0 = undefined;
}
}
const sameShape = (s: Shape3D, hs: Health) => {
if (Math.abs(sizeOf(s) - size) > size * 1e-3) return false;
// A sound solid measuring below nothing or more than its box is a broken
// "fix": said at once. (Meshed to compare, each took 13 s - a cut through a
// shelled mouse's curved top spent three minutes here before it said no.)
if (hs.valid && hs.solids) {
const b = s.boundingBox;
if (!(hs.volume > 0) || hs.volume > b.width * b.height * b.depth * 1.001) return false;
}
if (m0 !== undefined) {
try {
return Math.abs(meshVolume(s, size) - m0) <= m0 * 5e-3;
} catch {
return false;
}
}
if (v0 === undefined || !(hs.volume > 0)) return true;
return Math.abs(hs.volume - v0) <= v0 * 5e-3;
};
+64 -12
View File
@@ -14,6 +14,7 @@ function run(kind: "fuse" | "cut" | "common", a: { wrapped: unknown }, b: { wrap
const algo = kind === "fuse" ? new oc.BRepAlgoAPI_Fuse() : kind === "cut" ? new oc.BRepAlgoAPI_Cut() : new oc.BRepAlgoAPI_Common();
const args = new oc.NCollection_List_TopoDS_Shape();
const tools = new oc.NCollection_List_TopoDS_Shape();
const progress = new oc.Message_ProgressRange();
try {
args.Append(a.wrapped as never);
tools.Append(b.wrapped as never);
@@ -22,18 +23,60 @@ function run(kind: "fuse" | "cut" | "common", a: { wrapped: unknown }, b: { wrap
algo.SetNonDestructive(true);
if (opts.optimisation === "commonFace") algo.SetGlue(oc.BOPAlgo_GlueEnum.BOPAlgo_GlueShift);
if (opts.optimisation === "sameFace") algo.SetGlue(oc.BOPAlgo_GlueEnum.BOPAlgo_GlueFull);
algo.Build(new oc.Message_ProgressRange());
algo.Build(progress);
if (opts.simplify !== false) algo.SimplifyResult(true, true, 0.001);
const out = cast(algo.Shape());
if (!isShape3D(out)) throw new Error(`Could not ${kind} as a 3d shape`);
return out;
// (The kernel's handle to what it made is given back once the body has its own: release.ts.)
const made = algo.Shape();
try {
const out = cast(withoutInternals(made));
if (!isShape3D(out)) throw new Error(`Could not ${kind} as a 3d shape`);
return out;
} finally {
made.delete();
}
} finally {
algo.delete();
args.delete();
tools.delete();
progress.delete();
}
}
/**
* A boolean's result without the edges (and points) it left lying in a face,
* bounding nothing: where an edge of one shape ran along a face of the other
* (a prism's corner standing against a block's wall), the join kept it there
* as a line across the wall - an edge with no face on its other side, taken
* for a gap ("would tear the body open") though the solid was closed.
* (Only faces the boolean made anew hold such edges: the shapes it was given
* stay as they were.)
*/
export function withoutInternals<T>(wrapped: T): T {
const oc = getOC();
const INTERNAL = oc.TopAbs_Orientation.TopAbs_INTERNAL;
const has = (kind: unknown): boolean => {
const ex = new oc.TopExp_Explorer(wrapped as never, kind as never, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
try {
for (; ex.More(); ex.Next()) {
const item = ex.Current();
const inside = item.Orientation() === INTERNAL;
item.delete();
if (inside) return true;
}
return false;
} finally {
ex.delete();
}
};
try {
if ((wrapped as { IsNull?: () => boolean } | null)?.IsNull?.() !== false) return wrapped;
if (has(oc.TopAbs_ShapeEnum.TopAbs_EDGE) || has(oc.TopAbs_ShapeEnum.TopAbs_VERTEX)) oc.BRepTools.RemoveInternals(wrapped as never, false);
} catch {
// As it came: the usual checks speak for it.
}
return wrapped;
}
let done = false;
export function useSafeBooleans(): void {
if (done) return;
@@ -54,32 +97,41 @@ export function useSafeBooleans(): void {
const q = Shape.prototype as unknown as object;
Object.defineProperty(q, "edges", { configurable: true, get(this: { wrapped: unknown }) {
const oc = getOC();
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE).map((x) => new Edge(oc.TopoDS.Edge(x)));
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE, (x) => new Edge(oc.TopoDS.Edge(x as never)));
} });
Object.defineProperty(q, "faces", { configurable: true, get(this: { wrapped: unknown }) {
const oc = getOC();
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_FACE).map((x) => new Face(oc.TopoDS.Face(x)));
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_FACE, (x) => new Face(oc.TopoDS.Face(x as never)));
} });
}
/** The sub-shapes of one kind, each once (the same one met again from another face is skipped). */
function unique(shape: unknown, kind: unknown): any[] {
/**
* The sub-shapes of one kind, each once (the same one met again from another
* face is skipped), as `wrap` makes them. (The explorer's own handles are
* deleted here, each of them: left to lie, every one kept its face or edge
* alive for good - see release.ts.)
*/
function unique<T>(shape: unknown, kind: unknown, wrap: (item: unknown) => T): T[] {
const oc = getOC();
const ex = new oc.TopExp_Explorer(shape as never, kind as never, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
const buckets = new Map<number, any[]>();
const out: any[] = [];
const found: any[] = [];
try {
for (; ex.More(); ex.Next()) {
const item = ex.Current();
const h = oc.ReplicadShapeHasher.HashCode(item, HASH_CODE_MAX);
const b = buckets.get(h);
if (b?.some((x) => x.IsSame(item))) continue;
if (b?.some((x) => x.IsSame(item))) {
item.delete();
continue;
}
if (b) b.push(item);
else buckets.set(h, [item]);
out.push(item);
found.push(item);
}
return found.map(wrap);
} finally {
for (const item of found) item.delete();
ex.delete();
}
return out;
}
+81 -3
View File
@@ -15,9 +15,9 @@ import {
type Face,
type Wire,
} from "replicad";
import type { PlaneDef, SketchEntity, Vec2 } from "../doc/types";
import type { PlaneDef, SketchEntity, Vec2, Vec3 } from "../doc/types";
import { toWorld } from "../geom";
import { entityPrims, evalPrim, isClosedPrim, SPLINE_PER_SPAN, splineSpanAt, splineSpans, type Prim } from "../sketch/curves";
import { entityPolylines, entityPrims, evalPrim, isClosedPrim, SPLINE_PER_SPAN, splineHeightSamples, splineSpanAt, splineSpans, type Prim } from "../sketch/curves";
import { arrangement, resolveRegion, type Arrangement, type Loop, type LoopRef, type Piece, type RegionRef } from "../sketch/regions";
/** Faces for the referenced regions of a sketch (one face per region, holes included). */
@@ -40,12 +40,36 @@ export function regionWire(entities: SketchEntity[], plane: PlaneDef, ref: Regio
return loopWire(arr, r.outer, plane);
}
/** The outlines of a region's holes (for sweeps that make the outer wire's body and cut these out). */
export function regionHoleWires(entities: SketchEntity[], plane: PlaneDef, ref: RegionRef): Wire[] {
const arr = arrangement(entities);
const r = resolveRegion(arr, ref);
if (!r) throw new Error("A profile it used no longer exists in its sketch");
return r.holes.map((h) => loopWire(arr, h, plane));
}
/** A wire along sketch entities (open or closed), used as a sweep path. */
export function entitiesWire(entities: SketchEntity[], ids: string[], plane: PlaneDef): Wire {
const edges: Edge[] = [];
for (const id of ids) {
const e = entities.find((x) => x.id === id);
if (!e) throw new Error("A path curve was deleted");
// A spline with points off the plane: through space, as it is drawn.
const high = splineHeightSamples(e);
if (high) {
const flat = entityPolylines(e)[0] ?? [];
const pts = flat.map((q, i): Vec3 => {
const at = toWorld(plane, q);
const h = high[Math.min(i, high.length - 1)];
return [at[0] + plane.normal[0] * h, at[1] + plane.normal[1] * h, at[2] + plane.normal[2] * h];
});
let run = 0;
for (let i = 1; i < pts.length; i++) run += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1], pts[i][2] - pts[i - 1][2]);
if (pts.length >= 3 && run > 1e-9) {
edges.push(makeBSplineApproximation(pts, { tolerance: Math.max(1e-6, run * 1e-6), degMax: 5, degMin: 3 }));
continue;
}
}
for (const p of entityPrims(e)) {
if (p.t === "line") edges.push(makeLine(toWorld(plane, p.a), toWorld(plane, p.b)));
else if (p.t === "circle" && isClosedPrim(p)) edges.push(makeCircle(p.r, toWorld(plane, p.c), plane.normal));
@@ -53,7 +77,48 @@ export function entitiesWire(entities: SketchEntity[], ids: string[], plane: Pla
else edges.push(exactSpline(p, 0, 1, plane) ?? bspline(Array.from({ length: 65 }, (_, i) => evalPrim(p, i / 64)), plane));
}
}
return assembleWire(edges);
return pathOf(endToEnd(edges));
}
/** A path's curves as one wire - a gap in it said "Failed to build the wire, disconnected wire". */
export function pathOf(edges: Edge[]): Wire {
try {
return assembleWire(edges);
} catch (e) {
if (/disconnected/i.test(String((e as Error)?.message ?? e))) throw new Error(PATH_GAP);
throw e;
}
}
export const PATH_GAP = "The path's curves don't join end to end - tap a curve again to leave it out, or pick ones that meet";
/**
* Path curves in the order they run, whatever order they were picked or drawn
* in: a fillet's arc is added after the two lines it joins, and the wire was
* built in list order - it stopped at the first gap, so a string swept over a
* rounded saddle ended there (10 mm of a 650 mm path), with no error.
*/
function endToEnd(edges: Edge[]): Edge[] {
if (edges.length < 3) return edges;
const ends = edges.map((e) => [e.startPoint.toTuple(), e.endPoint.toTuple()] as Vec3[]);
const size = Math.max(1, ...ends.flat().map((q) => Math.hypot(q[0], q[1], q[2])));
const tol = size * 1e-7;
const same = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) < tol;
const touching = (q: Vec3, skip: number) => ends.some((pair, j) => j !== skip && pair.some((x) => same(x, q)));
// Start at a loose end (an open path), else anywhere (a closed one).
let first = ends.findIndex((pair, i) => pair.some((q) => !touching(q, i)));
if (first < 0) first = 0;
const order = [first];
const used = new Set(order);
let tip = touching(ends[first][1], first) ? ends[first][1] : ends[first][0];
while (order.length < edges.length) {
const next = ends.findIndex((pair, j) => !used.has(j) && pair.some((q) => same(q, tip)));
if (next < 0) return edges; // not one chain: as it was
order.push(next);
used.add(next);
tip = same(ends[next][0], tip) ? ends[next][1] : ends[next][0];
}
return order.map((i) => edges[i]);
}
function loopWire(arr: Arrangement, loop: Loop, plane: PlaneDef): Wire {
@@ -248,6 +313,19 @@ function exactSpline(p: Prim, t0: number, t1: number, plane: PlaneDef, a?: Vec2,
const curve = new oc.Geom_BSplineCurve(arr, knots, mults, 3, false);
const tol = 1e-6 * Math.max(1, ...poles.map((q) => Math.hypot(q[0], q[1])));
for (let i = 2; i <= m; i++) curve.RemoveKnot(i, 2, tol);
// A whole closed spline: one periodic curve, smooth where it starts too.
// Left as an open curve whose ends meet, its start was a seam - a fillet
// round the bottom of a guitar body pulled up from it failed there.
if (ctrl.closed && Math.abs(f1 - f0 - spans) < 1e-9 && Math.hypot(poles[0][0] - poles[poles.length - 1][0], poles[0][1] - poles[poles.length - 1][1]) < tol) {
try {
curve.SetPeriodic();
curve.RemoveKnot(curve.FirstUKnotIndex(), 2, tol);
const k0 = curve.FirstUKnotIndex();
curve.SetOrigin((curve.Knot(k0) + curve.Knot(k0 + 1)) / 2, 1e-9);
} catch {
// (stays as it was)
}
}
const mk = new oc.BRepBuilderAPI_MakeEdge(curve);
const edge = cast(mk.Edge()) as Edge;
mk.delete();
+516
View File
@@ -0,0 +1,516 @@
// Drawing views from the bodies' meshes: hidden line removal by a depth
// buffer, for models OpenCascade's exact one takes too long on (a freeform
// body took it 20 s a view). The edges are the mesh's own edge lines (which lie
// on its triangles), the outlines of curved faces come from the mesh normals.
import type { Shape3D } from "replicad";
import { getOC } from "replicad";
import type { BodyMesh, ViewBody, ViewEdge, ViewSpec } from "./protocol";
import { cylinderOf } from "./faceEdit";
import { normalOnEdge } from "./ocFree";
type V3 = [number, number, number];
type P2 = [number, number];
const r3 = (n: number) => String(Math.round(n * 1000) / 1000);
const rr = (p: P2): P2 => [Math.round(p[0] * 1000) / 1000, Math.round(p[1] * 1000) / 1000];
/** A line, or a circle seen face on (its centre found from three of its points), as a view edge. */
export function viewEdge(kind: "line" | "circle" | "other", pts: P2[]): ViewEdge | undefined {
if (kind === "line") return { a: rr(pts[0]), b: rr(pts[pts.length - 1]) };
if (kind !== "circle" || pts.length < 3) return undefined;
const a = pts[0];
const b = pts[pts.length - 1];
const closed = Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-6;
const p1 = pts[Math.round(pts.length / 3)];
const p2 = pts[Math.min(pts.length - 1, Math.round((2 * pts.length) / 3))];
const m = pts[Math.round(pts.length / 2)];
// The circle through a, p1, p2.
const [ax, ay] = a;
const [bx, by] = p1;
const [cx, cy] = p2;
const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
if (Math.abs(d) < 1e-12) return undefined;
const ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d;
const uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d;
const r = Math.hypot(ax - ux, ay - uy);
return { a: rr(a), m: rr(m), b: closed ? rr(a) : rr(b), c: rr([ux, uy]), r: Math.round(r * 1000) / 1000 };
}
/** On the body's seen edges, the point nearest the middle of them (where a balloon's leader ends). */
export function anchorOf(lines: P2[][]): P2 | undefined {
if (!lines.length) return undefined;
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
for (const l of lines) for (const [x, y] of l) (x0 = Math.min(x0, x)), (x1 = Math.max(x1, x)), (y0 = Math.min(y0, y)), (y1 = Math.max(y1, y));
const c: P2 = [(x0 + x1) / 2, (y0 + y1) / 2];
let best = lines[0][0];
let bd = Infinity;
for (const l of lines)
for (let i = 1; i < l.length; i++) {
const [a, b] = [l[i - 1], l[i]];
const ab = [b[0] - a[0], b[1] - a[1]];
const n = ab[0] * ab[0] + ab[1] * ab[1];
const t = n ? Math.max(0, Math.min(1, ((c[0] - a[0]) * ab[0] + (c[1] - a[1]) * ab[1]) / n)) : 0;
const p: P2 = [a[0] + t * ab[0], a[1] + t * ab[1]];
const d = (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2;
if (d < bd) (bd = d), (best = p);
}
return rr(best);
}
/** How an edge is drawn: where faces meet at an angle, where they meet smoothly (thin), or not (a seam). */
type EdgeKind = "sharp" | "smooth" | "seam";
const kindsOf = new WeakMap<Shape3D, EdgeKind[]>();
function edgeKinds(shape: Shape3D): EdgeKind[] {
const known = kindsOf.get(shape);
if (known) return known;
const oc = getOC();
const edges = shape.edges;
const faces = shape.faces;
const buckets = new Map<number, { i: number; faces: number[] }[]>();
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, faces: [] }]));
faces.forEach((f, fi) => {
for (const fe of f.edges) {
const list = buckets.get(fe.hashCode);
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
m?.faces.push(fi);
}
});
const out: EdgeKind[] = new Array(edges.length).fill("sharp");
for (const list of buckets.values())
for (const { i, faces: fs } of list) {
try {
if (fs.length === 1) {
// One face: the seam of a round one - or the open rim of a sheet.
if (oc.BRep_Tool.IsClosed(edges[i].wrapped as never, faces[fs[0]].wrapped as never)) out[i] = "seam";
} else if (fs.length === 2) {
// Read through the edge's curve on each face (a point projected onto
// a face per edge kept the engine's memory: a gear's ran it out).
const n1 = normalOnEdge(faces[fs[0]], edges[i], 0.5);
const n2 = normalOnEdge(faces[fs[1]], edges[i], 0.5);
if (n1 && n2 && n1[0] * n2[0] + n1[1] * n2[1] + n1[2] * n2[2] > 0.9995) out[i] = "smooth";
}
} catch {
// Kept sharp.
}
}
kindsOf.set(shape, out);
return out;
}
/** Round faces' axes, by face (for outlines put right on them, not on the mesh's chords). */
const cylsOf = new WeakMap<Shape3D, Map<number, ReturnType<typeof cylinderOf>>>();
function cylinderAt(shape: Shape3D, face: number) {
let m = cylsOf.get(shape);
if (!m) cylsOf.set(shape, (m = new Map()));
if (!m.has(face)) {
let c: ReturnType<typeof cylinderOf> = null;
try {
c = cylinderOf(shape.faces[face]);
} catch {
// Left on the mesh.
}
m.set(face, c);
}
return m.get(face) ?? null;
}
/** The faces the exact hidden line removal is slow on (anything but planes, cylinders, cones, spheres and tori). */
export function freeformFaces(mesh: BodyMesh): number {
return mesh.faces.filter((f) => !["PLANE", "CYLINDRE", "CONE", "SPHERE", "TORUS"].includes(f.type)).length;
}
/** The views of the bodies, worked out on their meshes. Each view: its bodies, and the box of what it shows. */
export function meshViews(bodies: { id: string; shape: Shape3D; mesh: BodyMesh }[], views: ViewSpec[]): { id: string; bodies: ViewBody[]; box: [P2, P2] | null }[] {
const kinds = bodies.map((b) => edgeKinds(b.shape));
return views.map((v) => meshView(bodies, kinds, v));
}
function meshView(bodies: { id: string; shape: Shape3D; mesh: BodyMesh }[], kinds: EdgeKind[][], v: ViewSpec): { id: string; bodies: ViewBody[]; box: [P2, P2] | null } {
const unit = (p: V3): V3 => {
const l = Math.hypot(p[0], p[1], p[2]) || 1;
return [p[0] / l, p[1] / l, p[2] / l];
};
const d = unit(v.dir as V3);
const X = unit(v.xAxis as V3);
const Y: V3 = [d[1] * X[2] - d[2] * X[1], d[2] * X[0] - d[0] * X[2], d[0] * X[1] - d[1] * X[0]];
// On the paper: x along X, y down (-Y); depth towards the eye (+d).
const px2 = (x: number, y: number, z: number): [number, number, number] => [x * X[0] + y * X[1] + z * X[2], -(x * Y[0] + y * Y[1] + z * Y[2]), x * d[0] + y * d[1] + z * d[2]];
// ---- The depth buffer.
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity, z0 = Infinity, z1 = -Infinity;
const proj = bodies.map(({ mesh }) => {
const P = mesh.positions;
const out = new Float64Array(P.length);
for (let i = 0; i < P.length; i += 3) {
const [a, b, c] = px2(P[i], P[i + 1], P[i + 2]);
out[i] = a;
out[i + 1] = b;
out[i + 2] = c;
if (a < x0) x0 = a;
if (a > x1) x1 = a;
if (b < y0) y0 = b;
if (b > y1) y1 = b;
if (c < z0) z0 = c;
if (c > z1) z1 = c;
}
return out;
});
if (!(x1 >= x0)) return { id: v.id, bodies: bodies.map((b) => ({ id: b.id, visible: "", tangent: "", hidden: "", edges: [] })), box: null };
const extent = Math.max(x1 - x0, y1 - y0, 1e-6);
const px = extent / 2048;
const gw = Math.ceil((x1 - x0) / px) + 5;
const gh = Math.ceil((y1 - y0) / px) + 5;
const ox = x0 - 2 * px;
const oy = y0 - 2 * px;
const zb = new Float32Array(gw * gh).fill(-Infinity);
bodies.forEach(({ mesh }, bi) => {
const T = mesh.indices;
const Q = proj[bi];
for (let t = 0; t < T.length; t += 3) {
const a = T[t] * 3, b = T[t + 1] * 3, c = T[t + 2] * 3;
const ax = (Q[a] - ox) / px, ay = (Q[a + 1] - oy) / px, az = Q[a + 2];
const bx = (Q[b] - ox) / px, by = (Q[b + 1] - oy) / px, bz = Q[b + 2];
const cx = (Q[c] - ox) / px, cy = (Q[c + 1] - oy) / px, cz = Q[c + 2];
const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
if (Math.abs(area) < 1e-12) continue;
const i0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)));
const i1 = Math.min(gw - 1, Math.ceil(Math.max(ax, bx, cx)));
const j0 = Math.max(0, Math.floor(Math.min(ay, by, cy)));
const j1 = Math.min(gh - 1, Math.ceil(Math.max(ay, by, cy)));
// (The weights are fractions: a pixel's centre on a shared side belongs to both triangles.)
const e = -1e-9;
for (let j = j0; j <= j1; j++) {
const y = j + 0.5;
for (let i = i0; i <= i1; i++) {
const x = i + 0.5;
const w0 = ((bx - x) * (cy - y) - (by - y) * (cx - x)) / area;
const w1 = ((cx - x) * (ay - y) - (cy - y) * (ax - x)) / area;
const w2 = 1 - w0 - w1;
if (w0 < e || w1 < e || w2 < e) continue;
const z = w0 * az + w1 * bz + w2 * cz;
const k = j * gw + i;
if (z > zb[k]) zb[k] = z;
}
}
}
});
const eps = 2 * px + (z1 - z0) * 1e-6;
/** Seen: nothing clearly in front of it (around it, a pixel either way: on an outline, the far side counts). */
const seenAt = (x: number, y: number, z: number) => {
const i = Math.floor((x - ox) / px);
const j = Math.floor((y - oy) / px);
let far = Infinity;
for (let jj = j - 1; jj <= j + 1; jj++)
for (let ii = i - 1; ii <= i + 1; ii++) {
const q = ii >= 0 && jj >= 0 && ii < gw && jj < gh ? zb[jj * gw + ii] : -Infinity;
if (q < far) far = q;
}
return z >= far - eps;
};
const pathOf = (pts: P2[]) => pts.map((p, i) => `${i ? "L" : "M"}${r3(p[0])} ${r3(p[1])}`).join("");
const straight = (pts: P2[]) => {
const [a, b] = [pts[0], pts[pts.length - 1]];
const L = Math.hypot(b[0] - a[0], b[1] - a[1]);
if (L < 1e-6) return false;
const tol = Math.max(px, L * 1e-3);
return pts.every((p) => Math.abs((p[0] - a[0]) * (b[1] - a[1]) - (p[1] - a[1]) * (b[0] - a[0])) / L < tol);
};
// ---- Every line to draw, sampled a pixel apart: the bodies' edges, and the
// outlines of their curved faces (where the surface turns away from the eye).
type Line = { body: number; kind: EdgeKind | "outline"; shape: "line" | "circle" | "other"; xyz: number[]; vert: boolean[]; state: Int8Array };
const lines: Line[] = [];
const addLine = (body: number, kind: Line["kind"], shape: Line["shape"], pts: [number, number, number][]) => {
const xyz: number[] = [];
const vert: boolean[] = [];
pts.forEach((p, k) => {
if (k > 0) {
const q = pts[k - 1];
const n = Math.max(1, Math.ceil(Math.hypot(p[0] - q[0], p[1] - q[1]) / px));
for (let s = 1; s < n; s++) {
const t = s / n;
xyz.push(q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t, q[2] + (p[2] - q[2]) * t);
vert.push(false);
}
}
xyz.push(p[0], p[1], p[2]);
vert.push(true);
});
lines.push({ body, kind, shape, xyz, vert, state: new Int8Array(vert.length) });
};
bodies.forEach(({ mesh }, bi) => {
const E = mesh.edgePositions;
mesh.edgeGroups.forEach((g, ei) => {
const kind = kinds[bi][ei] ?? "sharp";
if (kind === "seam" || g.count < 2) return;
const pts: [number, number, number][] = [];
for (let k = 0; k < g.count; k++) {
const o = (g.start + k) * 3;
const q = px2(E[o], E[o + 1], E[o + 2]);
// (The mesh's edge lines come as pairs of points: each point twice.)
const last = pts[pts.length - 1];
if (!last || Math.abs(q[0] - last[0]) > 1e-9 || Math.abs(q[1] - last[1]) > 1e-9 || Math.abs(q[2] - last[2]) > 1e-9) pts.push(q);
}
if (pts.length < 2) return;
if (pts.every((p) => Math.abs(p[0] - pts[0][0]) < 1e-9 && Math.abs(p[1] - pts[0][1]) < 1e-9 && Math.abs(p[2] - pts[0][2]) < 1e-9)) return;
const info = mesh.edges[ei];
// A circle shows as one only seen face on.
let shape: Line["shape"] = info?.type === "LINE" ? "line" : "other";
if (info?.type === "CIRCLE" && g.count >= 3) {
const o = (i: number) => (g.start + i) * 3;
const [a, b, c] = [o(0), o(Math.floor(g.count / 3)), o(Math.floor((2 * g.count) / 3))];
const u: V3 = [E[b] - E[a], E[b + 1] - E[a + 1], E[b + 2] - E[a + 2]];
const w: V3 = [E[c] - E[a], E[c + 1] - E[a + 1], E[c + 2] - E[a + 2]];
const n = unit([u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]);
if (Math.abs(n[0] * d[0] + n[1] * d[1] + n[2] * d[2]) > 1 - 1e-6) shape = "circle";
}
addLine(bi, kind, shape, pts);
});
const N = mesh.normals;
const T = mesh.indices;
const P = mesh.positions;
mesh.faceGroups.forEach((g) => {
const type = mesh.faces[g.face]?.type;
if (type === "PLANE") return;
// On a round face, the outline lies on the surface, straight along it.
const cyl = type === "CYLINDRE" ? cylinderAt(bodies[bi].shape, g.face) : null;
const across = cyl ? unit([d[1] * cyl.a[2] - d[2] * cyl.a[1], d[2] * cyl.a[0] - d[0] * cyl.a[2], d[0] * cyl.a[1] - d[1] * cyl.a[0]]) : null;
const onto = (p: V3): V3 => {
if (!cyl || !across) return p;
const a = unit(cyl.a as V3);
const q: V3 = [p[0] - cyl.c[0], p[1] - cyl.c[1], p[2] - cyl.c[2]];
const t = q[0] * a[0] + q[1] * a[1] + q[2] * a[2];
const sg = q[0] * across[0] + q[1] * across[1] + q[2] * across[2] >= 0 ? 1 : -1;
return [cyl.c[0] + a[0] * t + across[0] * cyl.r * sg, cyl.c[1] + a[1] * t + across[1] * cyl.r * sg, cyl.c[2] + a[2] * t + across[2] * cyl.r * sg];
};
// Crossing points, by the mesh edge they're on (so the pieces join up).
const at = new Map<string, V3>();
const links = new Map<string, string[]>();
const link = (a: string, b: string) => {
links.set(a, [...(links.get(a) ?? []), b]);
links.set(b, [...(links.get(b) ?? []), a]);
};
const f = (i: number) => N[i * 3] * d[0] + N[i * 3 + 1] * d[1] + N[i * 3 + 2] * d[2];
for (let t = g.start; t < g.start + g.count; t += 3) {
const vs = [T[t], T[t + 1], T[t + 2]];
const fs = vs.map(f);
if (fs.every((x) => Math.abs(x) < 1e-7)) continue;
const pos = fs.map((x) => x >= -1e-7);
if (pos[0] === pos[1] && pos[1] === pos[2]) continue;
const cross: string[] = [];
for (const [i, j] of [
[0, 1],
[1, 2],
[2, 0],
]) {
if (pos[i] === pos[j]) continue;
const [va, vb] = vs[i] < vs[j] ? [vs[i], vs[j]] : [vs[j], vs[i]];
const k = `${va}_${vb}`;
if (!at.has(k)) {
const fa = f(va);
const fb = f(vb);
const s = Math.abs(fa - fb) < 1e-12 ? 0.5 : Math.max(0, Math.min(1, fa / (fa - fb)));
at.set(k, onto([P[va * 3] + (P[vb * 3] - P[va * 3]) * s, P[va * 3 + 1] + (P[vb * 3 + 1] - P[va * 3 + 1]) * s, P[va * 3 + 2] + (P[vb * 3 + 2] - P[va * 3 + 2]) * s]));
}
cross.push(k);
}
if (cross.length === 2) link(cross[0], cross[1]);
}
// Joined into polylines.
const used = new Set<string>();
const ends = [...links.keys()].sort((a, b) => (links.get(a)!.length === 1 ? 0 : 1) - (links.get(b)!.length === 1 ? 0 : 1));
for (const start of ends) {
if (used.has(start)) continue;
const chain = [start];
used.add(start);
let cur = start;
for (;;) {
const next = links.get(cur)!.find((n) => !used.has(n));
if (!next) break;
used.add(next);
chain.push(next);
cur = next;
}
// A closed loop: back to its start.
if (chain.length > 2 && links.get(cur)!.includes(start)) chain.push(start);
if (chain.length < 2) continue;
addLine(
bi,
"outline",
"other",
chain.map((k) => {
const p = at.get(k)!;
return px2(p[0], p[1], p[2]);
}),
);
}
});
});
// ---- Seen or hidden, each sample. Then, nearest lines first: a sample
// lying right under a line already drawn is left out, seen or not (the back
// edge of a box seen straight on, a hole's far rim under its near one).
for (const l of lines) for (let k = 0; k < l.state.length; k++) l.state[k] = seenAt(l.xyz[k * 3], l.xyz[k * 3 + 1], l.xyz[k * 3 + 2]) ? 1 : 0;
const ink = new Float32Array(gw * gh).fill(-Infinity);
// Which line (and which of its samples) put the ink there: a line steep in
// depth must not hide its own next samples.
const inkLine = new Int32Array(gw * gh).fill(-1);
const inkK = new Int32Array(gw * gh);
const pix = (x: number, y: number) => [Math.floor((x - ox) / px), Math.floor((y - oy) / px)];
const underInk = (x: number, y: number, z: number, li = -1, k = 0) => {
const [i, j] = pix(x, y);
for (let jj = j - 1; jj <= j + 1; jj++)
for (let ii = i - 1; ii <= i + 1; ii++) {
if (ii < 0 || jj < 0 || ii >= gw || jj >= gh) continue;
const q = jj * gw + ii;
if (ink[q] > z + eps && (inkLine[q] !== li || Math.abs(inkK[q] - k) > 8)) return true;
}
return false;
};
/** Near a line's ends, where it meets the next one: never left out there. */
const nearEnd = (l: Line, k: number) => {
const n = l.state.length - 1;
const x = l.xyz[k * 3];
const y = l.xyz[k * 3 + 1];
return Math.hypot(x - l.xyz[0], y - l.xyz[1]) < 2.5 * px || Math.hypot(x - l.xyz[n * 3], y - l.xyz[n * 3 + 1]) < 2.5 * px;
};
// Every seen sample, nearest first - the tangent lines after all the others:
// one on a seen edge or outline (a face split in two, seen edge on) gives
// way to it, nearer or not.
const order: [number, number, number][] = [];
lines.forEach((l, li) => {
for (let k = 0; k < l.state.length; k++) if (l.state[k] === 1) order.push([l.xyz[k * 3 + 2], li, k]);
});
const soft = (li: number) => (lines[li].kind === "smooth" ? 1 : 0);
order.sort((a, b) => soft(a[1]) - soft(b[1]) || b[0] - a[0]);
for (const [z, li, k] of order) {
const l = lines[li];
const x = l.xyz[k * 3];
const y = l.xyz[k * 3 + 1];
if (!nearEnd(l, k) && underInk(x, y, l.kind === "smooth" ? -Infinity : z, li, k)) {
l.state[k] = -1;
continue;
}
const [i, j] = pix(x, y);
if (i >= 0 && j >= 0 && i < gw && j < gh && z > ink[j * gw + i]) {
const q = j * gw + i;
ink[q] = z;
inkLine[q] = li;
inkK[q] = k;
}
}
for (const l of lines)
for (let k = 0; k < l.state.length; k++) if (l.state[k] === 0 && (l.kind === "smooth" || underInk(l.xyz[k * 3], l.xyz[k * 3 + 1], l.xyz[k * 3 + 2]))) l.state[k] = -1;
// ---- The runs, as paths and as edges to dimension.
let lo: P2 = [Infinity, Infinity];
let hi: P2 = [-Infinity, -Infinity];
const out: ViewBody[] = bodies.map(({ id }) => ({ id, visible: "", tangent: "", hidden: "", edges: [] }));
const seen = bodies.map(() => [] as P2[][]);
const under = bodies.map(() => [] as P2[][]);
for (const l of lines) {
const b = out[l.body];
let k = 0;
while (k < l.state.length) {
const st = l.state[k];
let e = k;
while (e + 1 < l.state.length && l.state[e + 1] === st) e++;
// The run from the sample before it (no gap between a seen run and a hidden one).
const from = k > 0 && l.state[k - 1] !== -1 ? k - 1 : k;
if (st !== -1 && e > from) {
const pts: P2[] = [];
for (let q = from; q <= e; q++) if (q === from || q === e || (l.shape !== "line" && l.vert[q])) pts.push([l.xyz[q * 3], l.xyz[q * 3 + 1]]);
for (const p of pts) {
lo = [Math.min(lo[0], p[0]), Math.min(lo[1], p[1])];
hi = [Math.max(hi[0], p[0]), Math.max(hi[1], p[1])];
}
const long = Math.hypot(pts[pts.length - 1][0] - pts[0][0], pts[pts.length - 1][1] - pts[0][1]) > 3 * px || pts.length > 3;
if (st === 0) {
b.hidden += pathOf(pts);
under[l.body].push(pts);
} else {
if (l.kind === "smooth") b.tangent += pathOf(pts);
else b.visible += pathOf(pts);
seen[l.body].push(pts);
if (long) {
if (l.kind === "outline") {
if (straight(pts)) b.edges.push({ a: rr(pts[0]), b: rr(pts[pts.length - 1]) });
} else {
const ve = viewEdge(l.shape, pts);
if (ve) b.edges.push(ve);
}
}
}
}
k = e + 1;
}
}
out.forEach((b, i) => {
b.anchor = anchorOf(seen[i]);
if (!b.anchor && under[i].length) b.under = anchorOf(under[i]);
});
return { id: v.id, bodies: out, box: lo[0] <= hi[0] ? exactBox(bodies, X, Y) ?? [lo, hi] : null };
}
/**
* Looking along an axis, the view's box from the solids themselves (the mesh
* lies a little inside round faces: an overall size came out 0.01 short).
*/
function exactBox(bodies: { shape: Shape3D }[], X: V3, Y: V3): [P2, P2] | null {
const axial = (v: V3) => v.filter((c) => Math.abs(c) > 1e-9).length === 1;
if (!axial(X) || !axial(Y)) return null;
const lo3: V3 = [Infinity, Infinity, Infinity];
const hi3: V3 = [-Infinity, -Infinity, -Infinity];
for (const b of bodies) {
const bb = boxOf(b.shape);
if (!bb) return null;
for (let c = 0; c < 3; c++) {
lo3[c] = Math.min(lo3[c], bb[0][c]);
hi3[c] = Math.max(hi3[c], bb[1][c]);
}
}
if (!(lo3[0] <= hi3[0])) return null;
const xs: number[] = [];
const ys: number[] = [];
for (const i of [0, 1])
for (const j of [0, 1])
for (const k of [0, 1]) {
const c: V3 = [i ? hi3[0] : lo3[0], j ? hi3[1] : lo3[1], k ? hi3[2] : lo3[2]];
xs.push(c[0] * X[0] + c[1] * X[1] + c[2] * X[2]);
ys.push(-(c[0] * Y[0] + c[1] * Y[1] + c[2] * Y[2]));
}
return [
[Math.min(...xs), Math.min(...ys)],
[Math.max(...xs), Math.max(...ys)],
];
}
/** A body's exact box, worked out once (it's slow on a big body, and every view wants it). */
const boxes = new WeakMap<Shape3D, [V3, V3] | null>();
function boxOf(shape: Shape3D): [V3, V3] | null {
if (boxes.has(shape)) return boxes.get(shape)!;
const oc = getOC();
const box = new oc.Bnd_Box();
let out: [V3, V3] | null = null;
try {
oc.BRepBndLib.AddOptimal(shape.wrapped as never, box, false, false);
if (!box.IsVoid()) {
const p = box.CornerMin();
const q = box.CornerMax();
out = [
[p.X(), p.Y(), p.Z()],
[q.X(), q.Y(), q.Z()],
];
p.delete();
q.delete();
}
} catch {
out = null;
} finally {
box.delete();
}
boxes.set(shape, out);
return out;
}
+57 -8
View File
@@ -4,27 +4,76 @@
import opencascade from "replicad-opencascadejs";
import wasmUrl from "replicad-opencascadejs/wasm?url";
import { setOC } from "replicad";
import { errorText, exportBodies, regenerate } from "./engine";
import type { Envelope, Request, Response } from "./protocol";
import { bodyHealth, bodyProperties, projectViews, errorText, exportBodies, regenerate, resetKernel, withFreshKernel } from "./engine";
import type { BodyMesh, Envelope, Request, Response } from "./protocol";
self.onmessage = async (e: MessageEvent<Envelope<Request>>) => {
/**
* The meshes the page has (it keeps the last answer's): those go back as their
* key only - a step changes one body, and every body's triangles were copied
* across on each move of a drag.
*/
let sent = new Set<number>();
let oc: { wasmMemory?: WebAssembly.Memory } = {};
/** Past this much memory the engine is replaced before the next rebuild (a phone's tab is killed not far above it). */
const FRESH_ENGINE_MB = 1200;
/** OpenCascade loaded afresh (at the start, and after it broke down: its memory can't be trusted then). */
async function load(): Promise<void> {
oc = await opencascade({ locateFile: () => wasmUrl });
setOC(oc as never);
// Everything is new to the page again.
sent = new Set();
}
/**
* One message at a time: a rebuild waits at points (it awaits), and another
* message taken then (an export, the bodies' properties) ran the same steps
* at once, on the same cache.
*/
let queue: Promise<void> = Promise.resolve();
self.onmessage = (e: MessageEvent<Envelope<Request>>) => {
queue = queue.then(() => handle(e));
};
async function handle(e: MessageEvent<Envelope<Request>>): Promise<void> {
const { id, msg } = e.data;
const reply = (r: Response) => (self as DedicatedWorkerGlobalScope).postMessage({ id, msg: r } satisfies Envelope<Response>);
try {
switch (msg.type) {
case "init":
setOC(await opencascade({ locateFile: () => wasmUrl }));
await load();
reply({ type: "ready" });
break;
case "regenerate":
reply({ type: "regenerated", result: await regenerate(msg.features) });
case "regenerate": {
// The engine's memory only grows (and some steps leak tens of MB a
// rebuild: a long drag of a fillet's size). The page swaps in a spare
// engine when it can; if it didn't get to, a fresh one here, before
// this one runs out mid-step.
if ((oc.wasmMemory?.buffer.byteLength ?? 0) / 2 ** 20 > FRESH_ENGINE_MB) {
await load();
resetKernel();
}
const result = await withFreshKernel(load, () => regenerate(msg.features, msg.saved));
const bodies = result.bodies.map((b) => (sent.has(b.key) ? ({ id: b.id, name: b.name, key: b.key, same: true } as unknown as BodyMesh) : b));
sent = new Set(result.bodies.map((b) => b.key));
reply({ type: "regenerated", result: { ...result, bodies, memoryMB: (oc.wasmMemory?.buffer.byteLength ?? 0) / 2 ** 20 } });
break;
}
case "export":
reply({ type: "exported", blob: await exportBodies(msg.features, msg.format, msg.bodies) });
reply({ type: "exported", blob: await withFreshKernel(load, () => exportBodies(msg.features, msg.format, msg.bodies)) });
break;
case "drawing":
reply({ type: "drawing", views: await withFreshKernel(load, () => projectViews(msg.features, msg.views, msg.bodies)) });
break;
case "properties":
reply({ type: "properties", bodies: await withFreshKernel(load, () => bodyProperties(msg.features)) });
break;
case "health":
reply({ type: "health", bodies: await withFreshKernel(load, () => bodyHealth(msg.features)) });
break;
}
} catch (err) {
console.error(err);
reply({ type: "error", message: errorText(err) });
}
};
}
+279
View File
@@ -0,0 +1,279 @@
// Sketches put onto a body's faces: Project as Edge (the curves drawn onto the
// faces they land on, the faces split along them) and Wrap & Emboss (a sketch's
// shapes wrapped round a round face, raised from it or sunk into it).
import { cast, draw, getOC, makeCompound, makeLine, makeVertex, type Drawing, type Edge, type Face, type Shape3D } from "replicad";
import type { Vec3 } from "../doc/types";
import { add, cross, dist, dot, len, norm, scale, sub } from "../geom";
import { cylinderOf } from "./faceEdit";
import { measureVolume, quickVolume } from "./ocFree";
const tup = (v: { toTuple(): number[] }) => v.toTuple() as Vec3;
type Src = { face: Face; normal: Vec3 }[];
/** A body's size: its bounding box's diagonal, and its middle. */
function sizeOf(body: Shape3D): { d: number; c: Vec3 } {
const bb = body.boundingBox;
const c = bb.center as unknown as number[];
return { d: Math.hypot(bb.width, bb.height, bb.depth), c: [c[0], c[1], c[2]] };
}
/**
* Project as Edge: curves (a sketch's outlines, or edges) drawn onto the body
* along a direction, the faces split along them. Which of the lines found are
* kept is `keep`'s to say (those seen from the sketch, those on one face).
* Nothing else changes: the new edges are there to push, pull, fillet or
* sketch from.
*/
export function imprint(body: Shape3D, curves: Edge[], dir: Vec3, keep: (e: Edge) => boolean): Shape3D {
const oc = getOC();
const { d: D, c: mid } = sizeOf(body);
const n = norm(dir);
const kept: Edge[] = [];
const progress = new oc.Message_ProgressRange();
const sec = new oc.BRepAlgoAPI_Section();
try {
// Each curve swept both ways through the whole body: where those walls cross the body's faces.
const walls = curves.map((e) => {
const far = D + dist(tup(e.pointAt(0.5)), mid) + 1;
const v = new oc.gp_Vec(n[0] * 2 * far, n[1] * 2 * far, n[2] * 2 * far);
const pr = new oc.BRepPrimAPI_MakePrism(e.clone().translate(scale(n, -far)).wrapped, v, false, true);
try {
return cast(pr.Shape());
} finally {
pr.delete();
v.delete();
}
});
sec.Init1(body.wrapped);
sec.Init2(makeCompound(walls as never).wrapped);
sec.Build(progress);
const cut = cast(sec.Shape());
for (const e of "edges" in cut ? (cut.edges as Edge[]) : []) if (keep(e)) kept.push(e);
} finally {
sec.delete();
progress.delete();
}
if (!kept.length) throw new Error("Nothing lands on the body's faces seen from there");
return splitFaces(body, kept);
}
/** The lines seen from a sketch's plane (through o, square to n): not on the far side, nor behind other faces. */
export function seenFrom(body: Shape3D, o: Vec3, n: Vec3): (e: Edge) => boolean {
const eps = Math.max(1e-4, sizeOf(body).d * 1e-5);
return (e) => seen(e, o, norm(n), body, eps);
}
/** The lines on one face. */
export function onFace(body: Shape3D, F: Face): (e: Edge) => boolean {
const oc = getOC();
const eps = Math.max(1e-4, sizeOf(body).d * 1e-5);
return (e) => {
const ds = new oc.BRepExtrema_DistShapeShape(makeVertex(tup(e.pointAt(0.5))).wrapped, F.wrapped);
try {
return ds.IsDone() && ds.Value() < eps;
} finally {
ds.delete();
}
};
}
/**
* Whether an edge is seen from the sketch's plane: nothing of the body between
* them along the normal (a step just off the edge towards the plane is in the
* open, and so is the way on to the plane).
*/
function seen(e: Edge, o: Vec3, n: Vec3, body: Shape3D, eps: number): boolean {
const oc = getOC();
const pm = tup(e.pointAt(0.5));
const h = dot(sub(pm, o), n);
if (Math.abs(h) < 2 * eps) return true;
const sg = Math.sign(h);
const q = sub(pm, scale(n, sg * eps));
const pp = sub(pm, scale(n, h - sg * eps));
const seg = makeLine(q, pp);
const ds = new oc.BRepExtrema_DistShapeShape(seg.wrapped, body.wrapped);
try {
if (!(ds.IsDone() && ds.Value() > eps * 0.05)) return false;
} finally {
ds.delete();
}
// Run all the way inside the body, it's hidden too: the distance measured is
// to the faces round it, not 0 (a circle drawn on a block's top went through
// onto its bottom). Its middle inside, then.
const mid = makeVertex(scale(add(q, pp), 0.5));
const at = new oc.BRepExtrema_DistShapeShape();
try {
at.LoadS1(body.wrapped);
at.LoadS2(mid.wrapped);
at.Perform();
return !(at.IsDone() && at.InnerSolution());
} finally {
at.delete();
mid.delete();
}
}
/** The body's faces split along edges lying on them (one solid still). */
function splitFaces(body: Shape3D, edges: Edge[]): Shape3D {
const oc = getOC();
const sp = new oc.BRepAlgoAPI_Splitter();
const args = new oc.NCollection_List_TopoDS_Shape();
const tools = new oc.NCollection_List_TopoDS_Shape();
const progress = new oc.Message_ProgressRange();
try {
args.Append(body.wrapped);
tools.Append(makeCompound(edges).wrapped);
sp.SetArguments(args);
sp.SetTools(tools);
sp.Build(progress);
if (!sp.IsDone()) throw new Error("The faces couldn't be split along the sketch");
const out = cast(sp.Shape()) as Shape3D;
const solids = out.constructor.name === "Solid" ? [out] : ((out as unknown as { solids?: Shape3D[] }).solids ?? []);
if (solids.length !== 1) throw new Error("The faces couldn't be split along the sketch");
return solids[0];
} finally {
sp.delete();
args.delete();
tools.delete();
progress.delete();
}
}
/**
* Wrap & Emboss: the sketch's shapes wrapped round a round face, lengths kept
* (a line along the sketch goes as far round the face), then raised from it
* (height > 0) or sunk into it (height < 0) square to the face. The sketch is
* on a plane along the face's axis (touching it, or anywhere beside it): where
* the plane is nearest the axis is where the wrap starts from.
*/
export function wrapOnto(body: Shape3D, round: Face, src: Src, height: number): Shape3D {
if (Math.abs(height) < 1e-6) throw new Error("Height is zero");
const cy = cylinderOf(round);
if (!cy) throw new Error("Wrap goes on a round face (a cylinder)");
const oc = getOC();
const ad = new oc.BRepAdaptor_Surface(round.wrapped, true);
const cyl = ad.Cylinder();
const pos = cyl.Position();
const Loc: Vec3 = [pos.Location().X(), pos.Location().Y(), pos.Location().Z()];
const X = norm([pos.XDirection().X(), pos.XDirection().Y(), pos.XDirection().Z()]);
const Z = norm([pos.Direction().X(), pos.Direction().Y(), pos.Direction().Z()]);
const r = cyl.Radius();
ad.delete();
// The way the face's U goes round (replicad turns a left-handed one round).
const Y = cross(Z, X);
const n = norm(src[0].normal);
if (Math.abs(dot(n, Z)) > 1e-6) throw new Error("Draw the sketch on a plane along the round face's axis");
const o = tup(src[0].face.center);
// The plane's nearest point to the axis: where the wrap starts.
let R0 = sub(o, Loc);
R0 = sub(R0, scale(Z, dot(R0, Z)));
// (Straight out from the axis to the plane, along its normal: not towards
// the first shape, or a word centred on a mug's far side came out started
// from its first letter's place, a quarter of the way round.)
const side = dot(R0, n);
if (Math.abs(side) > 1e-9) R0 = scale(n, Math.sign(side));
else if (len(R0) < 1e-9) R0 = n;
R0 = norm(R0);
const T = cross(Z, R0);
const theta0 = (Math.atan2(dot(R0, Y), dot(R0, X)) + 2 * Math.PI) % (2 * Math.PI);
// Seen from outside the face, as it can only be read: a sketch facing in
// towards the axis (drawn on a plane through the far side, looking out from
// inside) is turned round, or its letters came out back to front.
const across = dot(n, R0) < 0 ? -1 : 1;
const map = (p: Vec3): [number, number] => [r * theta0 + across * dot(sub(p, Loc), T), dot(sub(p, Loc), Z)];
const solids: Shape3D[] = [];
for (const { face } of src) {
const loops = [face.clone().outerWire(), ...face.clone().innerWires()].map((w) => chain(w.edges as Edge[]));
const all = loops.flat().flatMap((e) => [0, 0.5, 1].map((t) => map(e.at(t))[0]));
const [lo, hi] = [Math.min(...all), Math.max(...all)];
if (hi - lo > 2 * Math.PI * r - 1e-6) throw new Error("The sketch is longer than the way round the face");
const shift = lo < 0 ? 2 * Math.PI * r : 0;
const m = (p: Vec3): [number, number] => {
const q = map(p);
return [q[0] + shift, q[1]];
};
const drawings = loops.map((loop) => loopDrawing(loop, m));
let dr = drawings[0];
for (const h of drawings.slice(1)) dr = dr.cut(h);
const sk = dr.sketchOnFace(round, "original") as unknown as { faces?: () => Face; face?: () => Face };
const onFace = sk.faces ? sk.faces() : sk.face!();
solids.push(thicken(onFace, height, cy));
}
let out = body;
for (const s of solids) out = (height > 0 ? out.fuse(s) : out.cut(s)) as Shape3D;
return out;
}
type Run = { at: (t: number) => Vec3; kind: string };
/** A wire's edges one after another, each the way the loop goes. */
function chain(edges: Edge[]): Run[] {
const left = edges.map((e) => ({ e, a: tup(e.startPoint), b: tup(e.endPoint) }));
const out: Run[] = [];
let end: Vec3 | null = null;
while (left.length) {
let i = 0;
let flip = false;
if (end) {
let best = Infinity;
left.forEach((x, k) => {
const [da, db] = [dist(x.a, end!), dist(x.b, end!)];
if (da < best) [best, i, flip] = [da, k, false];
if (db < best) [best, i, flip] = [db, k, true];
});
}
const { e, a, b } = left.splice(i, 1)[0];
const at = (t: number) => tup(e.pointAt(flip ? 1 - t : t));
out.push({ at, kind: e.geomType });
end = flip ? a : b;
}
return out;
}
/** A loop in the unrolled face (lengths round it, heights along it): lines stay lines, circles circles. */
function loopDrawing(loop: Run[], m: (p: Vec3) => [number, number]): Drawing {
let pen = draw(m(loop[0].at(0)));
for (const run of loop) {
const closed = dist(run.at(0), run.at(1)) < 1e-9;
if (run.kind === "LINE") pen = pen.lineTo(m(run.at(1)));
else if (run.kind === "CIRCLE") {
if (closed) pen = pen.threePointsArcTo(m(run.at(0.5)), m(run.at(0.25))).threePointsArcTo(m(run.at(1)), m(run.at(0.75)));
else pen = pen.threePointsArcTo(m(run.at(1)), m(run.at(0.5)));
} else for (let k = 1; k <= 32; k++) pen = pen.lineTo(m(run.at(k / 32)));
}
return pen.close();
}
/** A face on the round face made solid: `height` out from it (away from the material) or into it. */
function thicken(face: Face, height: number, cy: { s: number }): Shape3D {
const oc = getOC();
// Away from the axis on a boss raised, or a hole sunk; towards it otherwise.
const want = Math.sign(height) * cy.s;
const make = (k: number): Shape3D | null => {
const th = new oc.BRepOffsetAPI_MakeThickSolid();
try {
th.MakeThickSolidBySimple(face.wrapped, k);
if (!th.IsDone()) return null;
let s = cast(th.Shape()) as Shape3D;
if (quickVolume(s) < 0) s = cast(s.wrapped.Reversed()) as Shape3D;
return s;
} catch {
return null;
} finally {
th.delete();
}
};
// Made both ways: the one away from the axis is the bigger (it lies further out). (Not
// told by its centre of mass: a slab bent round an arc has that nearer the axis than it is.)
const both = [make(Math.abs(height)), make(-Math.abs(height))];
if (both[0] && both[1]) {
const [a, b] = both.map((s) => measureVolume(s!));
const outer = a > b ? both[0] : both[1];
const inner = a > b ? both[1] : both[0];
return want > 0 ? outer! : inner!;
}
throw new Error("The wrapped shape couldn't be made solid");
}
+7
View File
@@ -1,6 +1,8 @@
import "./style.css";
import { App } from "./app";
import { outerScrollbars } from "./ui/scrollbars";
import { installDebug } from "./debug";
import { keepPageSteady } from "./ui/steady";
// Update reloads with ?v=<time> so no stored copy is used; once loaded, the
// address is plain again (it's what people copy to share the app).
@@ -12,9 +14,14 @@ import { outerScrollbars } from "./ui/scrollbars";
}
}
// The page itself never scrolls (a phone pushing it along for a keyboard that does not come).
keepPageSteady();
// Scroll bars outside the windows, only while scrolling.
outerScrollbars();
const app = new App(document.getElementById("view") as HTMLCanvasElement);
// Handy for debugging from the console.
(window as unknown as { supergeometry: App }).supergeometry = app;
// And sg: read and work the app from the console (sg.help()).
installDebug(app);
+146 -1
View File
@@ -23,6 +23,12 @@ export interface Settings {
animateCamera: boolean;
ortho: boolean;
shader: "shaded" | "wireframe" | "xray";
/** Surface analysis on the bodies (Display modes): zebra stripes or a curvature map. */
analysis: "none" | "zebra" | "curvature";
zebraStripes: number;
zebraDirection: "vertical" | "horizontal";
/** Curvature map: a curve this tight (radius, mm) shows fully red (domed) or blue (hollow). */
curvatureRadius: number;
showEdges: boolean;
showHiddenEdges: boolean;
showPinned: boolean;
@@ -30,6 +36,8 @@ export interface Settings {
showConstraints: boolean;
/** Sketch: add Horizontal/Vertical/Coincident automatically while drawing. */
autoConstrain: boolean;
/** Sketch: when a constraint joins two things, the first or the last picked stays put (the anchored one). */
sketchAnchor: "first" | "last";
/** Sketch: draw the constraint badges (H, V, ∥, dimensions…) on the geometry. */
showConstraintGlyphs: boolean;
/** Bumped when defaults change for everyone (see the constructor). */
@@ -40,6 +48,129 @@ export interface Settings {
numpad: boolean;
/** The guide text (what to tap next) - switched in More. */
showHints: boolean;
/** Offline mode: the app's files are kept on this device (More → Offline mode). */
offline: boolean;
/**
* The sentence bar: a line at the bottom that says what is picked and what
* can be done with it. Always on - it is the only way to the tools (kept as a
* setting for the code that asks).
*/
sentence: boolean;
/**
* Direct touch: what is picked is dragged by itself, not only by its arrow
* or dot - a face pulled, a shape pulled up, an edge rounded - and a finger
* pressed and held on one picks it and pulls in the same touch. Always on
* (kept as a setting for the code that asks).
*/
direct: boolean;
/**
* Which mouse drags turn, move and zoom the view (Settings > Mouse): the app's own way, or the way of another
* CAD program, for hands used to it (see MOUSE_PRESETS). In all of them the wheel zooms, Alt + left drag turns,
* and a right drag turns too unless the preset uses it for something else.
*/
mouse: string;
/** The wheel rolled forward zooms out (it zooms in otherwise). */
wheelReverse: boolean;
}
export type MouseNav = "orbit" | "pan" | "zoom";
/**
* A way of working the view with a mouse. `middle` and `right`: what a drag with that button does, by the keys
* held (`plain`, `shift`, `ctrl`, `both` for Ctrl + Shift; one not given falls back to `plain`). `chord`: what
* the middle button's drag becomes while another button is held with it (CATIA, NX, FreeCAD).
*/
export interface MousePreset {
id: string;
/** The programs that work this way (the row in Settings). */
apps: string;
/** What it does, in words. */
text: string;
middle: { plain: MouseNav; shift?: MouseNav; ctrl?: MouseNav; both?: MouseNav };
right?: { shift?: MouseNav; ctrl?: MouseNav };
chord?: { left?: MouseNav; right?: MouseNav };
}
/**
* The presets. Asked for: "it should have controls presets from all major CAD apps". Each as its program's own
* help gives it (2026-11); programs that work the same way share a row. The wheel's way round is its own switch
* (programs differ, and each lets it be turned over).
*/
export const MOUSE_PRESETS: MousePreset[] = [
{
id: "default",
apps: "superGeometry, Onshape, Tinkercad",
text: "Right drag turns the view. Middle drag moves it (also Shift or Ctrl + right drag).",
middle: { plain: "pan" },
right: { shift: "pan", ctrl: "pan" },
},
{
id: "fusion",
apps: "Fusion, Inventor, Revit, AutoCAD",
text: "Shift + middle drag turns the view. Middle drag moves it. Ctrl + Shift + middle drag zooms.",
middle: { plain: "pan", shift: "orbit", both: "zoom" },
right: { shift: "pan" },
},
{
id: "solidworks",
apps: "SolidWorks",
text: "Middle drag turns the view. Ctrl + middle drag moves it. Shift + middle drag zooms.",
middle: { plain: "orbit", ctrl: "pan", shift: "zoom" },
right: { shift: "pan" },
},
{
id: "creo",
apps: "Creo, Solid Edge, Blender, SketchUp",
text: "Middle drag turns the view. Shift + middle drag moves it. Ctrl + middle drag zooms.",
middle: { plain: "orbit", shift: "pan", ctrl: "zoom" },
right: { shift: "pan" },
},
{
id: "nx",
apps: "NX",
text: "Middle drag turns the view. Middle + right drag (or Shift + middle) moves it. Middle + left drag (or Ctrl + middle) zooms.",
middle: { plain: "orbit", shift: "pan", ctrl: "zoom" },
right: { shift: "pan" },
chord: { right: "pan", left: "zoom" },
},
{
id: "catia",
apps: "CATIA, FreeCAD",
text: "Middle drag moves the view. Hold the middle button and press the left or right one too: the drag turns it. Ctrl + middle drag zooms.",
middle: { plain: "pan", ctrl: "zoom" },
right: { shift: "pan" },
chord: { left: "orbit", right: "orbit" },
},
{
id: "rhino",
apps: "Rhino",
text: "Right drag turns the view. Shift + right drag moves it. Ctrl + right drag zooms. Middle drag moves it too.",
middle: { plain: "pan" },
right: { shift: "pan", ctrl: "zoom" },
},
];
/** The preset in use (one not known - an older setting - is the app's own). */
export function mousePreset(id: string): MousePreset {
return MOUSE_PRESETS.find((m) => m.id === id) ?? MOUSE_PRESETS[0];
}
/** What a mouse press on the view does to the view, in a preset: null, nothing (the press is for the tools). */
export function mouseDrag(id: string, button: number, keys: { shift: boolean; ctrl: boolean; alt: boolean }): MouseNav | "right" | null {
const preset = mousePreset(id);
if (button === 0) return keys.alt ? "orbit" : null;
// The right button: a drag turns the view, a click is the right-click (told apart as it moves) - with a key, what the preset says.
if (button === 2) return (keys.ctrl ? preset.right?.ctrl : keys.shift ? preset.right?.shift : undefined) ?? "right";
if (button !== 1) return null;
const m = preset.middle;
return (keys.ctrl && keys.shift ? (m.both ?? m.ctrl ?? m.shift) : keys.ctrl ? m.ctrl : keys.shift ? m.shift : undefined) ?? m.plain;
}
/** A middle drag while other buttons are held with it (`buttons` as a pointer event gives them): what it becomes, or null. */
export function mouseChord(id: string, buttons: number): MouseNav | null {
const chord = mousePreset(id).chord;
if (!chord || !(buttons & 4)) return null;
return (buttons & 1 ? chord.left : undefined) ?? (buttons & 2 ? chord.right : undefined) ?? null;
}
const DEFAULTS: Settings = {
@@ -53,6 +184,10 @@ const DEFAULTS: Settings = {
animateCamera: true,
ortho: true,
shader: "shaded",
analysis: "none",
zebraStripes: 16,
zebraDirection: "vertical",
curvatureRadius: 10,
showEdges: true,
showHiddenEdges: false,
showPinned: true,
@@ -61,11 +196,17 @@ const DEFAULTS: Settings = {
// constraints themselves are in the card of what's selected.
showConstraints: false,
autoConstrain: true,
sketchAnchor: "first",
showConstraintGlyphs: true,
// On by default on touch screens (phones, tablets, headsets).
numpad: isTouchDevice,
showHints: true,
version: 4,
offline: false,
sentence: true,
direct: true,
mouse: "default",
wheelReverse: false,
version: 5,
};
type Listener = (s: Settings) => void;
@@ -89,6 +230,10 @@ class SettingsStore {
if ((saved.version ?? 1) < 3) this.value = { ...this.value, numpad: isTouchDevice, version: 3 };
// v4: the Constraints column starts closed (it got in the way; the Constraints button opens it).
if ((saved.version ?? 1) < 4) this.value = { ...this.value, showConstraints: false, version: 4 };
// The sentence bar is the only way to the tools (its switch in More is gone): on for everyone.
this.value.sentence = true;
// Direct touch is how the app is worked too (it had a switch in More for a while: one saved as off is on again).
this.value.direct = true;
}
set<K extends keyof Settings>(key: K, v: Settings[K]): void {
+318 -20
View File
@@ -4,7 +4,8 @@
// from wandering (so the result is the smallest change that satisfies them).
import type { ConstraintType, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../doc/types";
import { arcFrom3, entityCorners } from "./curves";
import { arcFrom3, entityCorners, entityPolylines } from "./curves";
import { mirrorXf, offsetEntity, transformEntity } from "./edit";
// ------------------------------------------------------------- parameters
@@ -36,18 +37,28 @@ function params(e: SketchEntity): number[] {
}
}
/** Length per unit of each parameter (1 for coordinates, the radius for angles). */
function pullScale(e: SketchEntity, p: number[]): number[] {
/**
* A shape with a size of its own (a rectangle, an ellipse, a polygon) keeps it sooner than its place: asked to bring
* a corner somewhere, it goes there - it is not squashed towards it. (Each counted the same, a rectangle whose corner
* was put on a point 60 away came out 0.00001 tall, and an ellipse flat.)
*/
const STIFF = 4;
/**
* Length per unit of each parameter (1 for coordinates, the radius for angles). `stiff`: how much sooner a shape
* keeps its size and its way round than its place (1 while it is dragged: a corner pulled is the shape pulled about).
*/
function pullScale(e: SketchEntity, p: number[], stiff: number): number[] {
const r = (v: number) => Math.max(Math.abs(v), 1e-9);
switch (e.kind) {
case "arc":
return p.length === 5 ? [1, 1, 1, r(p[2]), r(p[2])] : p.map(() => 1);
return p.length === 5 ? [1, 1, stiff, stiff * r(p[2]), stiff * r(p[2])] : p.map(() => 1);
case "ellipse":
return [1, 1, 1, 1, r(Math.max(e.rx, e.ry))];
return [1, 1, stiff, stiff, r(Math.max(e.rx, e.ry))];
case "rect":
return [1, 1, 1, 1, r(Math.hypot(e.w, e.h) / 2)];
return [1, 1, stiff, stiff, r(Math.hypot(e.w, e.h) / 2)];
case "polygon":
return [1, 1, 1, r(e.radius)];
return [1, 1, stiff, r(e.radius)];
default:
return p.map(() => 1);
}
@@ -90,12 +101,25 @@ export function pointsOf(e: SketchEntity): { p: string; at: Vec2 }[] {
return [{ p: "a", at: e.a }, { p: "b", at: e.b }, ...(c ? [{ p: "c", at: c.c }] : [])];
}
case "circle":
case "ellipse":
return [{ p: "c", at: e.center }];
case "ellipse": {
if (e.sweep === undefined) return [{ p: "c", at: e.center }];
// Part of an ellipse: its two ends too.
const at = (t: number): Vec2 => {
const x = e.rx * Math.cos(t);
const y = e.ry * Math.sin(t);
return [e.center[0] + x * Math.cos(e.rotation) - y * Math.sin(e.rotation), e.center[1] + x * Math.sin(e.rotation) + y * Math.cos(e.rotation)];
};
return [{ p: "a", at: at(e.a0 ?? 0) }, { p: "b", at: at((e.a0 ?? 0) + e.sweep) }, { p: "c", at: e.center }];
}
case "rect":
case "polygon":
return [{ p: "c", at: e.center }, ...entityCorners(e).map((at, i) => ({ p: `k${i}`, at }))];
case "spline":
// A curve that follows a body's edge (Project): its two ends, as the edge has - the points between are the
// edge's shape, made again whenever the body changes, and not there to pick, snap to or drag.
if (e.id.startsWith(LINKED) && !e.closed && e.points.length > 2) return [{ p: "k0", at: e.points[0] }, { p: `k${e.points.length - 1}`, at: e.points[e.points.length - 1] }];
return e.points.map((at, i) => ({ p: `k${i}`, at }));
case "polyline":
return e.points.map((at, i) => ({ p: `k${i}`, at }));
}
@@ -172,7 +196,7 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
if (a && b) return [a[0] - b[0], a[1] - b[1]];
// Point on a curve.
const e = E(0);
if (a && e) return [distToEntity(a, e)];
if (a && e) return distToEntity(a, e);
return [];
}
case "horizontal":
@@ -210,8 +234,21 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
if (line && round) return [distPointLine(round.c, line.a, line.b) - round.r];
if (r1 && r2) {
const d = Math.hypot(r1.c[0] - r2.c[0], r1.c[1] - r2.c[1]);
// External tangency unless one contains the other.
return [Math.min(Math.abs(d - (r1.r + r2.r)), Math.abs(d - Math.abs(r1.r - r2.r)))];
// Touching from outside, or one inside the other: whichever is nearer. (With its sign: the smaller of the two
// sizes has a kink right at the answer, and the last of the way there was crept.)
const out = d - (r1.r + r2.r);
const ins = d - Math.abs(r1.r - r2.r);
return [Math.abs(out) < Math.abs(ins) ? out : ins];
}
// A line and an ellipse: the line is as far from the centre as the ellipse reaches that way.
const ell = e1.kind === "ellipse" ? e1 : e2.kind === "ellipse" ? e2 : null;
if (line && ell) {
const l = Math.hypot(line.b[0] - line.a[0], line.b[1] - line.a[1]) || 1;
const n: Vec2 = [(line.b[1] - line.a[1]) / l, -(line.b[0] - line.a[0]) / l];
const cs = Math.cos(ell.rotation);
const sn = Math.sin(ell.rotation);
const reach = Math.hypot(ell.rx * (n[0] * cs + n[1] * sn), ell.ry * (-n[0] * sn + n[1] * cs));
return [distPointLine(ell.center, line.a, line.b) - reach];
}
return [];
}
@@ -239,6 +276,57 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
const a = c.pts?.[0] && P(c.pts[0]);
return a && c.at ? [a[0] - c.at[0], a[1] - c.at[1]] : [];
}
case "pattern": {
// A copy in a sketch pattern: each of its points is the original's,
// moved by `at` (or turned round `at` by `value` degrees); sizes the same.
const o = E(0);
const k = E(1);
if (!o || !k || o.kind !== k.kind || !c.at) return [];
const t = ((c.value ?? 0) * Math.PI) / 180;
const [cx, cy] = c.at;
const map = (p: Vec2): Vec2 => (c.turn ? [cx + (p[0] - cx) * Math.cos(t) - (p[1] - cy) * Math.sin(t), cy + (p[0] - cx) * Math.sin(t) + (p[1] - cy) * Math.cos(t)] : [p[0] + cx, p[1] + cy]);
const out: number[] = [];
for (const q of pointsOf(o)) {
const w = pointOf(k, q.p);
if (!w) return [];
const m = map(q.at);
out.push(w[0] - m[0], w[1] - m[1]);
}
if ((o.kind === "circle" || o.kind === "polygon") && (k.kind === "circle" || k.kind === "polygon")) out.push(k.radius - o.radius);
if (o.kind === "ellipse" && k.kind === "ellipse") out.push(k.rx - o.rx, k.ry - o.ry);
return out;
}
case "follow": {
// A copy made from another curve - its offset, its mirror image: it is that, of the original as it is now.
// (An offset or a mirrored copy was a curve of its own from the moment it was made: the original given
// another size - a dimension typed, a variable changed - the copy stayed as it had been.)
const o = E(0);
const k = E(1);
const how = c.how;
if (!o || !k || !how) return [];
const want = how.mirror ? transformEntity(o, mirrorXf(how.mirror[0], how.mirror[1])) : how.offset !== undefined ? offsetEntity(o, how.offset) : null;
if (!want) return [];
if (how.loose) {
// A piece of an offset outline: on the original's offset (its ends are its neighbours' business).
if (want.kind === "line" && k.kind === "line") return [distPointLineSigned(k.a, want.a, want.b), distPointLineSigned(k.b, want.a, want.b)];
if (want.kind === "arc" && k.kind === "arc") {
const w = arcFrom3(want.a, want.m, want.b);
return w ? [k.a, k.m, k.b].map((p) => Math.hypot(p[0] - w.c[0], p[1] - w.c[1]) - w.r) : [];
}
return [];
}
if (want.kind !== k.kind) return [];
const out: number[] = [];
for (const q of pointsOf(want)) {
const w = pointOf(k, q.p);
if (!w) return [];
out.push(w[0] - q.at[0], w[1] - q.at[1]);
}
if (want.kind === "arc" && k.kind === "arc") out.push(k.m[0] - want.m[0], k.m[1] - want.m[1]);
if ((want.kind === "circle" || want.kind === "polygon") && (k.kind === "circle" || k.kind === "polygon")) out.push(k.radius - want.radius);
if (want.kind === "ellipse" && k.kind === "ellipse") out.push(k.rx - want.rx, k.ry - want.ry, wrap(k.rotation - want.rotation) * Math.max(want.rx, want.ry));
return out;
}
case "distance": {
if (c.value === undefined) return [];
// Point to line: perpendicular distance.
@@ -247,6 +335,17 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
const l = E(0);
return p && l?.kind === "line" ? [distPointLine(p, l.a, l.b) - c.value] : [];
}
// Line to line: they run the same way, that far apart (the second's middle from the first).
if (!c.pts?.length && c.curves?.length === 2) {
const [l, m] = [E(0), E(1)];
if (l?.kind !== "line" || m?.kind !== "line") return [];
const [d1, d2] = [dirOf(l), dirOf(m)];
if (!d1 || !d2) return [];
const mid: Vec2 = [(m.a[0] + m.b[0]) / 2, (m.a[1] + m.b[1]) / 2];
const len = Math.hypot(m.b[0] - m.a[0], m.b[1] - m.a[1]) || 1;
// (The turn as a length - the second line's end off the first's way - so it weighs as the distance does.)
return [distPointLine(mid, l.a, l.b) - c.value, (d1[0] * d2[1] - d1[1] * d2[0]) * len];
}
const [a, b] = (c.pts ?? []).map(P);
return a && b ? [Math.hypot(a[0] - b[0], a[1] - b[1]) - c.value] : [];
}
@@ -289,15 +388,55 @@ function distPointLineSigned(p: Vec2, a: Vec2, b: Vec2): number {
return ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / l;
}
function distToEntity(p: Vec2, e: SketchEntity): number {
if (e.kind === "line") return distPointLineSigned(p, e.a, e.b);
function distToEntity(p: Vec2, e: SketchEntity): number[] {
if (e.kind === "line") return [distPointLineSigned(p, e.a, e.b)];
const r = roundOf(e);
if (r) return Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r;
return 0;
if (r) return [Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r];
if (e.kind === "ellipse") {
// In the ellipse's own frame, how far out the point is as a share of the way to it (1: on it).
const dx = p[0] - e.center[0];
const dy = p[1] - e.center[1];
const cs = Math.cos(e.rotation);
const sn = Math.sin(e.rotation);
const k = Math.hypot((dx * cs + dy * sn) / Math.max(e.rx, 1e-12), (-dx * sn + dy * cs) / Math.max(e.ry, 1e-12));
return [(k - 1) * Math.min(e.rx, e.ry)];
}
// A rectangle, a polygon, a polyline, a spline: from the nearest place on it (a spline: as it is drawn) to the
// point, across and up. Two numbers that change evenly as the point goes round a corner, so it gets there from
// anywhere and the last of the way is not crept. (It was 0 for all of these: a point "put on" a rectangle's edge
// was taken and stayed where it was.)
const runs: Vec2[][] = e.kind === "rect" || e.kind === "polygon" ? [closedRun(entityCorners(e))] : e.kind === "polyline" ? [e.closed ? closedRun(e.points) : e.points] : entityPolylines(e);
let best = Infinity;
let out = [0, 0];
for (const run of runs)
for (let i = 0; i + 1 < run.length; i++) {
const a = run[i];
const b = run[i + 1];
const ux = b[0] - a[0];
const uy = b[1] - a[1];
const l2 = ux * ux + uy * uy;
if (l2 < 1e-24) continue;
const s = ((p[0] - a[0]) * ux + (p[1] - a[1]) * uy) / l2;
const c = Math.max(0, Math.min(1, s));
const vx = p[0] - a[0] - c * ux;
const vy = p[1] - a[1] - c * uy;
const d = Math.hypot(vx, vy);
if (d >= best) continue;
best = d;
out = [vx, vy];
}
return out;
}
function closedRun(pts: Vec2[]): Vec2[] {
return pts.length ? [...pts, pts[0]] : pts;
}
// ------------------------------------------------------------------ solver
/** How the id of a curve that follows a body's edge begins: it is where that edge is, and nothing in the sketch moves it. */
export const LINKED = "ref-";
export interface SolveOptions {
/** Points to pull towards a target (dragging), with a strong weight. */
drag?: { ref: PointRef; to: Vec2 }[];
@@ -321,6 +460,8 @@ export interface SolveResult {
* whose constraints are already met, with nothing dragged in it, isn't touched.
*/
export function solve(entities: SketchEntity[], constraints: SketchConstraint[], opts: SolveOptions = {}): SolveResult {
const held = entities.filter((e) => e.id.startsWith(LINKED));
if (held.length) opts = { ...opts, fixed: new Set([...(opts.fixed ?? []), ...held.map((e) => e.id)]) };
const ids = new Set(entities.map((e) => e.id));
const live = constraints.filter((c) => refsOf(c).every((id) => ids.has(id)));
const drags = opts.drag ?? [];
@@ -392,9 +533,44 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
const p = params(e);
offsets.push(x0.length);
counts.push(p.length);
per.push(...pullScale(e, p));
per.push(...pullScale(e, p, opts.drag?.length ? 1 : STIFF));
x0.push(...p);
}
// A line asked to lie a way it is far from (Vertical on one nearly level; an angle 130 degrees off): turned there
// about its middle first, its length kept. Left to the steps alone it got there by shrinking - shorter is the
// shortest way to "upright" - and a line given a far angle ended a speck.
if (!opts.drag?.length) {
const at = new Map(movers.map((e, i) => [e.id, i]));
for (const c of live) {
const pair = (c.type === "parallel" || c.type === "perpendicular") && c.curves?.length === 2;
// (Parallel, Perpendicular: the second line is the one turned - the first if only that one may move.)
const which = pair ? (at.has(c.curves![1]) ? 1 : 0) : 0;
const i = (pair || c.curves?.length === 1) && !c.pts?.length ? at.get(c.curves![which]) : undefined;
const e = i === undefined ? undefined : movers[i];
if (i === undefined || e?.kind !== "line") continue;
const now = Math.atan2(e.b[1] - e.a[1], e.b[0] - e.a[0]);
let want: number | null = null;
if (pair) {
const o = entities.find((x) => x.id === c.curves![1 - which]);
if (o?.kind !== "line") continue;
const base = Math.atan2(o.b[1] - o.a[1], o.b[0] - o.a[0]) + (c.type === "perpendicular" ? Math.PI / 2 : 0);
// (Either way along it will do: the nearer.)
want = Math.abs(wrap(base - now)) <= Math.PI / 2 ? base : base + Math.PI;
}
if (c.type === "dim" && c.prop === "angle" && c.value !== undefined) want = (c.value * Math.PI) / 180;
else if (c.type === "horizontal") want = Math.abs(wrap(now)) < Math.PI / 2 ? 0 : Math.PI;
else if (c.type === "vertical") want = wrap(now) > 0 ? Math.PI / 2 : -Math.PI / 2;
if (want === null || Math.abs(wrap(want - now)) < Math.PI / 6) continue;
const o = offsets[i];
const mx = (e.a[0] + e.b[0]) / 2;
const my = (e.a[1] + e.b[1]) / 2;
const h = Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1]) / 2;
x0[o] = mx - h * Math.cos(want);
x0[o + 1] = my - h * Math.sin(want);
x0[o + 2] = mx + h * Math.cos(want);
x0[o + 3] = my + h * Math.sin(want);
}
}
const byId = new Map(entities.map((e) => [e.id, e]));
const build = (x: number[]) => {
const m = new Map(byId);
@@ -471,7 +647,7 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
// (The pull pass only has to get near: once a step gains next to nothing
// it stops - it used to run all 30 steps every frame, as the pull never
// reaches zero; the exact pass stops once the constraints are met.)
xs = lm(xs, 1e-3, true, t, Math.min(30, it), 1e-6, false, 1e-7);
xs = lm(xs, 1e-7, true, t, Math.min(30, it), 1e-6, false, 1e-7);
xs = lm(xs, 1e-8, false, t, it, 1e-10, true, 1e-9);
} else {
// A noticeable pull first (smallest change), then almost none (exact constraints).
@@ -516,6 +692,16 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
const xg = gradually(1 / 16, 60);
if (xg && errorAt(xg) <= Math.max(errorAt(xs), tol)) xs = xg;
}
// Float noise off the answer (a height typed as 93 solved to 92.999999999999,
// then shown, saved and built so): each value a hair off a clean one is put
// on it, when that keeps the constraints as well met.
if (!drags.length) {
const clean = xs.map((v) => {
const r = Math.round(v * 1e9) / 1e9;
return r !== v && Math.abs(r - v) < 1e-10 * Math.max(1, Math.abs(v)) ? r : v;
});
if (clean.some((v, i) => v !== xs[i]) && errorAt(clean) <= Math.max(errorAt(xs), tol)) xs = clean;
}
const m = build(xs);
const error = errorAt(xs);
return { entities: entities.map((e) => m.get(e.id) ?? e), error, ok: error < 1e-6 * Math.max(1, scale) };
@@ -617,8 +803,15 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) A[b][a] = A[a][b];
let improved = false;
let gain = 0;
// Damped the same in every direction (each parameter in its own length): the step is then the shortest one
// that does it. Damped by each parameter's own share (Marquardt's way), a sketch with room to spare - most
// are - stepped furthest in the direction that helped least: a line given a length drew its ends together
// sideways until it stood upright, and stopped there, the length not met.
let mean = 0;
for (let i = 0; i < n; i++) mean += A[i][i] / (per[i] * per[i]);
mean = mean / Math.max(1, n) || 1;
for (let tries = 0; tries < 8; tries++) {
const diag = A.map((rowA, i) => rowA[i] * (1 + lambda) + 1e-12);
const diag = A.map((rowA, i) => rowA[i] + lambda * mean * per[i] * per[i] + 1e-12);
let dx = solveSPD(A, diag, g);
if (!dx) {
const M = A.map((rowA, i) => rowA.map((v, j) => (i === j ? diag[i] : v)));
@@ -705,6 +898,107 @@ function sameTurns(a: Map<string, number>, b: Map<string, number>): boolean {
}
/** Entity ids a constraint refers to. */
/**
* Which curves the constraints hold completely - nothing about them can
* change without breaking one (a sketch drawn green there) - and whether that's
* all of them. From the rank of the constraints' Jacobian: a parameter is held
* when no free direction of the system moves it. Null for a sketch too big
* to work it out quickly.
*/
export function definedCurves(entities: SketchEntity[], constraints: SketchConstraint[]): { defined: Set<string>; all: boolean } | null {
const ids = new Set(entities.map((e) => e.id));
const live = constraints.filter((c) => refsOf(c).every((id) => ids.has(id)));
// Curves that follow a body's edge are where the edge is: held already.
const movers = entities.filter((e) => !e.id.startsWith(LINKED));
const offsets: number[] = [];
const counts: number[] = [];
const x0: number[] = [];
for (const e of movers) {
const p = params(e);
offsets.push(x0.length);
counts.push(p.length);
x0.push(...p);
}
const n = x0.length;
const linked = new Set(entities.filter((e) => e.id.startsWith(LINKED)).map((e) => e.id));
if (!n) return { defined: linked, all: true };
if (n > 300) return null;
const byId = new Map(entities.map((e) => [e.id, e]));
const at = (id: string) => byId.get(id);
const rowStart: number[] = [];
let m = 0;
for (const c of live) {
rowStart.push(m);
m += residuals(c, at).length;
}
const J: Float64Array[] = Array.from({ length: m }, () => new Float64Array(n));
const moverOf = new Map(movers.map((e, i) => [e.id, i]));
const usedBy: number[][] = movers.map(() => []);
live.forEach((c, ci) => {
for (const id of new Set(refsOf(c))) {
const i = moverOf.get(id);
if (i !== undefined) usedBy[i].push(ci);
}
});
let big = 0;
movers.forEach((e, i) => {
const xs = x0.slice(offsets[i], offsets[i] + counts[i]);
for (let k = 0; k < counts[i]; k++) {
const j = offsets[i] + k;
const h = 1e-6 * Math.max(1, Math.abs(xs[k]));
const up = xs.slice();
const down = xs.slice();
up[k] += h;
down[k] -= h;
const ep = withParams(e, up);
const em = withParams(e, down);
for (const ci of usedBy[i]) {
const rp = residuals(live[ci], (id) => (id === e.id ? ep : byId.get(id)));
const rm = residuals(live[ci], (id) => (id === e.id ? em : byId.get(id)));
for (let r = 0; r < rp.length; r++) {
const v = (rp[r] - rm[r]) / (2 * h);
if (Number.isFinite(v)) {
J[rowStart[ci] + r][j] = v;
big = Math.max(big, Math.abs(v));
}
}
}
}
});
// Reduced row echelon form; the columns without a pivot are free directions.
const tol = 1e-7 * Math.max(1, big);
const pivotRow = new Int32Array(n).fill(-1);
let row = 0;
for (let col = 0; col < n && row < m; col++) {
let p = row;
for (let r = row + 1; r < m; r++) if (Math.abs(J[r][col]) > Math.abs(J[p][col])) p = r;
if (Math.abs(J[p][col]) < tol) continue;
[J[row], J[p]] = [J[p], J[row]];
const R = J[row];
const d = R[col];
for (let c = col; c < n; c++) R[c] /= d;
for (let r = 0; r < m; r++) {
if (r === row) continue;
const f = J[r][col];
if (Math.abs(f) < 1e-15) continue;
const Rr = J[r];
for (let c = col; c < n; c++) Rr[c] -= f * R[c];
}
pivotRow[col] = row++;
}
const free: number[] = [];
for (let j = 0; j < n; j++) if (pivotRow[j] < 0) free.push(j);
// A pivot parameter is held when no free direction moves it.
const held = (j: number) => pivotRow[j] >= 0 && free.every((f) => Math.abs(J[pivotRow[j]][f]) < 1e-6);
const defined = new Set(linked);
movers.forEach((e, i) => {
let ok = true;
for (let k = 0; k < counts[i] && ok; k++) ok = held(offsets[i] + k);
if (ok) defined.add(e.id);
});
return { defined, all: defined.size === entities.length };
}
export function refsOf(c: SketchConstraint): string[] {
return [...(c.pts ?? []).map((p) => p.e), ...(c.curves ?? [])];
}
@@ -805,7 +1099,9 @@ export function applicable(type: ConstraintType, pts: PointRef[], curves: Sketch
case "equal":
return curves.length === 2 && (lines.length === 2 || rounds.length === 2);
case "tangent":
return curves.length === 2 && rounds.length >= 1;
// A circle or an arc with a line or another of them; a line with an ellipse. (It was offered for a circle with
// anything - a rectangle, a spline, an ellipse - and taken, and did nothing.)
return curves.length === 2 && (rounds.length === 2 || (rounds.length === 1 && lines.length === 1) || (lines.length === 1 && curves.some((e) => e.kind === "ellipse")));
case "concentric":
return curves.length === 2 && curves.every((e) => e.kind !== "line" && e.kind !== "spline" && e.kind !== "polyline");
case "midpoint":
@@ -813,7 +1109,7 @@ export function applicable(type: ConstraintType, pts: PointRef[], curves: Sketch
case "symmetric":
return pts.length === 2 && lines.length === 1 && curves.length === 1;
case "distance":
return (pts.length === 2 && !curves.length) || (pts.length === 1 && lines.length === 1 && curves.length === 1);
return (pts.length === 2 && !curves.length) || (pts.length === 1 && lines.length === 1 && curves.length === 1) || (!pts.length && lines.length === 2 && curves.length === 2);
case "fix":
// Points, or whole curves (all their points).
return pts.length >= 1 || curves.length >= 1;
@@ -1017,6 +1313,8 @@ export function addForUser(
export function constraintName(c: SketchConstraint): string {
if (c.type === "dim") return `${c.prop === "angle" ? "angle" : (c.prop ?? "size")} dimension`;
if (c.type === "fix") return "lock";
if (c.type === "pattern") return "pattern link";
if (c.type === "follow") return c.how?.mirror ? "mirror link" : "offset link";
return c.type;
}
+36 -2
View File
@@ -2,7 +2,8 @@
// Every sketch entity is broken into primitives (line / circular arc /
// elliptical arc / spline) that can be evaluated at a parameter t ∈ [0, 1].
import type { SketchEntity, Vec2 } from "../doc/types";
import type { PlaneDef, SketchEntity, Vec2, Vec3 } from "../doc/types";
import { toWorld } from "../geom";
export type Prim =
| { t: "line"; a: Vec2; b: Vec2; src: string }
@@ -82,7 +83,7 @@ export function entityPrims(e: SketchEntity): Prim[] {
case "circle":
return [{ t: "circle", c: e.center, r: e.radius, a0: 0, sweep: TAU, src }];
case "ellipse":
return [{ t: "ellipse", c: e.center, rx: e.rx, ry: e.ry, rot: e.rotation, a0: 0, sweep: TAU, src }];
return [{ t: "ellipse", c: e.center, rx: e.rx, ry: e.ry, rot: e.rotation, a0: e.sweep === undefined ? 0 : (e.a0 ?? 0), sweep: e.sweep ?? TAU, src }];
case "spline":
return [{ t: "spline", pts: splinePoints(e.points, e.closed, e.mode), closed: e.closed && e.points.length > 2, src, ...(e.points.length > 2 ? { ctrl: { points: e.points, closed: e.closed, mode: e.mode } } : {}) }];
case "rect":
@@ -120,6 +121,39 @@ export function entityCorners(e: Extract<SketchEntity, { kind: "rect" | "polygon
] as Vec2[]).map(([x, y]) => [e.center[0] + x * c - y * s, e.center[1] + x * s + y * c] as Vec2);
}
/** A spline's heights off its sketch's plane, one for each of its points - null when it is flat (or they don't fit its points). */
export function splineHeights(e: SketchEntity): number[] | null {
if (e.kind !== "spline" || !e.z || e.z.length !== e.points.length || !e.z.some((v) => Math.abs(v) > 1e-12)) return null;
return e.z;
}
/**
* The height at each point of the spline's drawn polyline (entityPolylines' own points, in step with them): the
* heights of its points run through the same curve as their places. Null for a flat one.
*/
export function splineHeightSamples(e: SketchEntity): number[] | null {
const z = splineHeights(e);
if (!z || e.kind !== "spline") return null;
return splinePoints(z.map((v): Vec2 => [v, 0]), e.closed && e.points.length > 2, e.mode).map((p) => p[0]);
}
/**
* An entity's drawn polylines where they are in space: on the sketch's plane - and a spline with points off the
* plane up where it runs. (What picks a place on a curve - a plane on it, a preview along it - goes by this, not by
* the curve's shadow on the plane.)
*/
export function entityWorldPolylines(e: SketchEntity, plane: PlaneDef): Vec3[][] {
const high = splineHeightSamples(e);
const n = plane.normal;
return entityPolylines(e).map((poly) =>
poly.map((q, i) => {
const at = toWorld(plane, q);
const h = high ? (high[Math.min(i, high.length - 1)] ?? 0) : 0;
return h ? ([at[0] + n[0] * h, at[1] + n[1] * h, at[2] + n[2] * h] as Vec3) : at;
}),
);
}
/** Dense polyline for drawing an entity. */
export function entityPolylines(e: SketchEntity): Vec2[][] {
return entityPrims(e).map((p) => samplePrim(p, 0, 1));
+322 -19
View File
@@ -1,10 +1,12 @@
// Pure sketch-editing operations (no UI): trim, extend, offset, fillet,
// transforms, projection of 3D edges, and text outlines.
import type { PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec3 } from "../doc/types";
import { roundSig, toPlane } from "../geom";
import type { OutlineOffset, PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec3 } from "../doc/types";
import { roundSig, toPlane, toWorld } from "../geom";
import type { Arrangement, Region } from "./regions";
import { constraintError, pointOf, pointsOf, refsOf, solve } from "./constraints";
import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, type Prim } from "./curves";
import { fitSpline } from "./freehand";
import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, splineHeights, splineHeightSamples, type Prim } from "./curves";
export function uid(): string {
return Math.random().toString(36).slice(2, 10);
@@ -51,9 +53,11 @@ export function transformEntity(e: SketchEntity, xf: Xf, newId = false): SketchE
case "circle":
return { ...base, kind: "circle", center: xf(e.center), radius: e.radius * k };
case "ellipse":
return { ...base, kind: "ellipse", center: xf(e.center), rx: e.rx * k, ry: e.ry * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot };
// (Part of an ellipse, mirrored: it runs the other way round from the other side of its axis.)
return { ...base, kind: "ellipse", center: xf(e.center), rx: e.rx * k, ry: e.ry * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot, ...(e.sweep === undefined ? {} : { a0: mirrored ? -(e.a0 ?? 0) : (e.a0 ?? 0), sweep: mirrored ? -e.sweep : e.sweep }) };
case "spline":
return { ...base, kind: "spline", points: e.points.map(xf), closed: e.closed, mode: e.mode };
// (Moved, turned or mirrored in the plane, its points stay as far off it; scaled, that much nearer or further.)
return { ...base, kind: "spline", points: e.points.map(xf), closed: e.closed, mode: e.mode, ...(e.z ? { z: e.z.map((v) => v * k) } : {}) };
case "rect":
return { ...base, kind: "rect", center: xf(e.center), w: e.w * k, h: e.h * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot };
case "polygon": {
@@ -82,7 +86,8 @@ export function guidePoints(e: SketchEntity): { p: Vec2; kind: "end" | "mid" | "
case "circle":
case "ellipse":
out.push({ p: e.center, kind: "center" });
for (const p of entityPrims(e)) for (const t of [0, 0.25, 0.5, 0.75]) out.push({ p: evalPrim(p, t), kind: "end" });
// (Part of an ellipse: its two ends and its middle.)
for (const p of entityPrims(e)) for (const t of e.kind === "ellipse" && e.sweep !== undefined ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75]) out.push({ p: evalPrim(p, t), kind: "end" });
break;
case "spline":
e.points.forEach((p) => out.push({ p, kind: "end" }));
@@ -165,7 +170,7 @@ export function explodeJoined(
}
/** Parameters where other entities cross primitive `p`. */
function crossings(p: Prim, others: Prim[]): number[] {
export function crossings(p: Prim, others: Prim[]): number[] {
const ts: number[] = [];
const n = Math.max(primSegments(p), 1) * 4;
const A = Array.from({ length: n + 1 }, (_, i) => evalPrim(p, i / n));
@@ -306,7 +311,7 @@ export function trim(entities: SketchEntity[], id: string, at: Vec2): SketchEnti
}
/** Entity for part [t0, t1] of a primitive (t may exceed 1 for closed curves). */
function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity {
export function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity {
const at = (t: number) => evalPrim(p, isClosedPrim(p) && p.t !== "spline" ? t : Math.min(1, t > 1 ? t - 1 : t));
if (p.t === "line") return { id: uid(), kind: "line", a: at(t0), b: at(t1), construction };
if (p.t === "circle") return { id: uid(), kind: "arc", a: at(t0), m: at((t0 + t1) / 2), b: at(t1), construction };
@@ -379,7 +384,7 @@ export function splineEnds(e: SketchEntity): [Vec2, Vec2] | null {
function reverseIf(e: SketchEntity, rev: boolean): SketchEntity {
if (!rev) return e;
if (e.kind === "line" || e.kind === "arc") return { ...e, a: e.b, b: e.a } as SketchEntity;
if (e.kind === "spline") return { ...e, points: [...e.points].reverse() };
if (e.kind === "spline") return { ...e, points: [...e.points].reverse(), ...(e.z ? { z: [...e.z].reverse() } : {}) };
return e;
}
@@ -449,6 +454,7 @@ function moveEnd(e: SketchEntity, end: "a" | "b", to: Vec2): SketchEntity {
// The end fit point moves there.
const pts = [...e.points];
pts[end === "a" ? 0 : pts.length - 1] = to;
// (Its heights stay with its points: the spread above keeps them.)
return { ...e, points: pts };
}
if (e.kind !== "arc") return e;
@@ -654,6 +660,10 @@ export function splitAny(entities: SketchEntity[], id: string, at: Vec2, step: n
pts = e.points;
closed = e.closed;
mode = e.mode;
} else if (e.sweep !== undefined) {
// Part of an ellipse: an open spline through 13 of its points.
pts = Array.from({ length: 13 }, (_, i) => evalPrim(prim, i / 12));
closed = false;
} else {
pts = Array.from({ length: 12 }, (_, i) => evalPrim(prim, i / 12));
closed = true;
@@ -662,15 +672,21 @@ export function splitAny(entities: SketchEntity[], id: string, at: Vec2, step: n
const T = closestOnPrim(prim, P).t;
const spans = closed ? pts.length : pts.length - 1;
const s = Math.max(0, Math.min(spans - 1, Math.floor(T * spans + 1e-9)));
// A spline with points off the plane: each piece keeps its points' heights, and the new end is as high as the
// curve is there. (The pieces came out flat on the plane.)
const z = splineHeights(e);
const high = z ? splineHeightSamples(e) : null;
const zP = high ? (high[Math.max(0, Math.min(high.length - 1, Math.round(T * (high.length - 1))))] ?? 0) : 0;
const up = (list: number[]) => (z ? { z: list } : {});
if (closed) {
// A closed loop opens up at that point (one piece, both ends there).
const ring = [...pts.slice(s + 1), ...pts.slice(0, s + 1)];
const open: SketchEntity = { id, kind: "spline", points: [P, ...ring, P], closed: false, mode, construction: e.construction };
const open: SketchEntity = { id, kind: "spline", points: [P, ...ring, P], closed: false, mode, construction: e.construction, ...up(z ? [zP, ...z.slice(s + 1), ...z.slice(0, s + 1), zP] : []) };
return { entities: entities.map((x) => (x.id === id ? open : x)), parts: [id], exploded: true };
}
const n = newId();
const first: SketchEntity = { id, kind: "spline", points: [...pts.slice(0, s + 1), P], closed: false, mode, construction: e.construction };
const second: SketchEntity = { id: n, kind: "spline", points: [P, ...pts.slice(s + 1)], closed: false, mode, construction: e.construction };
const first: SketchEntity = { id, kind: "spline", points: [...pts.slice(0, s + 1), P], closed: false, mode, construction: e.construction, ...up(z ? [...z.slice(0, s + 1), zP] : []) };
const second: SketchEntity = { id: n, kind: "spline", points: [P, ...pts.slice(s + 1)], closed: false, mode, construction: e.construction, ...up(z ? [zP, ...z.slice(s + 1)] : []) };
return { entities: entities.flatMap((x) => (x.id === id ? [first, second] : [x])), parts: [id, n], exploded: false };
}
return null;
@@ -1035,7 +1051,7 @@ export function offsetEntity(e: SketchEntity, d: number): SketchEntity | null {
case "circle":
return e.radius + d > 0 ? { ...base, kind: "circle", center: e.center, radius: e.radius + d } : null;
case "ellipse":
return e.rx + d > 0 && e.ry + d > 0 ? { ...base, kind: "ellipse", center: e.center, rx: e.rx + d, ry: e.ry + d, rotation: e.rotation } : null;
return e.rx + d > 0 && e.ry + d > 0 ? { ...base, kind: "ellipse", center: e.center, rx: e.rx + d, ry: e.ry + d, rotation: e.rotation, ...(e.sweep === undefined ? {} : { a0: e.a0 ?? 0, sweep: e.sweep }) } : null;
case "rect":
return e.w + 2 * d > 0 && e.h + 2 * d > 0 ? { ...base, kind: "rect", center: e.center, w: e.w + 2 * d, h: e.h + 2 * d, rotation: e.rotation } : null;
case "polygon": {
@@ -1072,9 +1088,13 @@ export function offsetEntity(e: SketchEntity, d: number): SketchEntity | null {
// Outward for CCW closed curves = to the right of travel.
return [p[0] + (ty / L) * d * sign * (closed ? 1 : -1), p[1] - (tx / L) * d * sign * (closed ? 1 : -1)] as Vec2;
});
// Enough fit points to follow the curve closely (four per original span).
const n = Math.max(24, (e.kind === "spline" ? e.points.length : 6) * 4 + 1);
return e.kind === "spline" ? { ...base, kind: "spline", points: thin(closed ? out.slice(0, -1) : out, n), closed, mode: "fit" } : { ...base, kind: "polyline", points: out, closed };
if (e.kind !== "spline") return { ...base, kind: "polyline", points: out, closed };
// As few fit points as follow the curve closely (within a five-thousandth of its size): it was four per span of
// the original, so the offset of a curve projected from an edge - 24 points, out of sight - came out a row of 97 dots.
const xs = out.map((q) => q[0]);
const ys = out.map((q) => q[1]);
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
return { ...base, kind: "spline", points: fitSpline(closed ? out.slice(0, -1) : out, closed, Math.max(size * 2e-4, 1e-9)), closed, mode: "fit" };
}
}
}
@@ -1227,7 +1247,18 @@ const unit = (a: Vec2): Vec2 => {
* A 3D polyline (e.g. a body edge) flattened onto the sketch plane, as the
* simplest matching entity: line, circle, arc or spline.
*/
export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string): SketchEntity | null {
/**
* (A curved edge that is no circle is a spline through 24 of its points: as
* close to the edge as that gets. A curve that follows its edge keeps that -
* only its two ends show (`pointsOf`). `lean`: a free copy, which is the
* user's to shape - a whole ellipse as an ellipse, anything else with as few
* points as hold it within a two-thousandth of its size, not a row of 24 dots
* to drag one by one. And a round edge seen at a slant - part of a circle or
* of an ellipse - is part of an ellipse, exactly, with its two ends: `conic`
* false keeps the spline, for a curve of an older project made as one, which
* may have sizes tied to its points.)
*/
export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string, lean = false, conic = true): SketchEntity | null {
const pts = dedupe(pts3.map((p) => toPlane(plane, p)));
if (pts.length < 2) return null;
const a = pts[0];
@@ -1244,8 +1275,207 @@ export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string): Sk
if (ok) return closed ? { id: uid(), kind: "circle", center: c.c, radius: c.r } : { id: uid(), kind: "arc", a, m, b };
}
}
const fit = thin(closed ? pts.slice(0, -1) : pts, 24);
return { id: uid(), kind: "spline", points: fit, closed, mode: "fit" };
const run = closed ? pts.slice(0, -1) : pts;
if (conic && !closed && (type === "CIRCLE" || type === "ELLIPSE") && run.length >= 7) {
const xs = pts.map((p) => p[0]);
const ys = pts.map((p) => p[1]);
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
const el = fitEllipse(run);
// (Only when every point is on it: a short, nearly straight piece can be fitted by ellipses that are nothing like it.)
if (el && run.every((p) => offEllipse(p, el) < size * 1e-6) && Math.max(el.rx, el.ry) < size * 50) {
const at = (p: Vec2) => {
const dx = p[0] - el.c[0];
const dy = p[1] - el.c[1];
return Math.atan2((-dx * Math.sin(el.rot) + dy * Math.cos(el.rot)) / el.ry, (dx * Math.cos(el.rot) + dy * Math.sin(el.rot)) / el.rx);
};
// Which way round it goes: the way that passes its middle point.
const turn = (from: number, to: number) => ((((to - from) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI));
const a0 = at(a);
const toMid = turn(a0, at(run[Math.floor(run.length / 2)]));
const toEnd = turn(a0, at(b));
const sweep = toMid <= toEnd ? toEnd : toEnd - 2 * Math.PI;
if (Math.abs(sweep) > 1e-6) return { id: uid(), kind: "ellipse", center: el.c, rx: el.rx, ry: el.ry, rotation: el.rot, a0, sweep };
}
}
if (lean) {
const xs = pts.map((p) => p[0]);
const ys = pts.map((p) => p[1]);
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
// A circle seen at a slant, an ellipse: the ellipse itself.
if (closed && run.length >= 6) {
const el = fitEllipse(run);
if (el && run.every((p) => offEllipse(p, el) < size * 1e-5)) return { id: uid(), kind: "ellipse", center: el.c, rx: el.rx, ry: el.ry, rotation: el.rot };
}
// Within a two-thousandth of its size of the edge (0.025 on a curve 50 long).
const tol = Math.max(size * 5e-4, 1e-9);
const ctrl = closed ? null : fitControl(run, tol);
if (ctrl) return { id: uid(), kind: "spline", points: ctrl, closed: false, mode: "control" };
return { id: uid(), kind: "spline", points: fitSpline(run, closed, tol), closed, mode: "fit" };
}
return { id: uid(), kind: "spline", points: thin(run, 24), closed, mode: "fit" };
}
/** A spline with only the points it needs (one that followed an edge and was unlinked: its 24 become the user's to shape). */
export function leanSpline<E extends SketchEntity>(e: E): E {
if (e.kind !== "spline" || e.mode !== "fit" || e.points.length < 7) return e;
const xs = e.points.map((p) => p[0]);
const ys = e.points.map((p) => p[1]);
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
return { ...e, points: fitSpline(e.points, e.closed, Math.max(size * 5e-4, 1e-9)) };
}
/** Solve m (n rows of n + 1: the last column the right side) in place; null when it has no one answer. */
function solveRows(m: number[][]): number[] | null {
const n = m.length;
for (let i = 0; i < n; i++) {
let best = i;
for (let r = i + 1; r < n; r++) if (Math.abs(m[r][i]) > Math.abs(m[best][i])) best = r;
if (Math.abs(m[best][i]) < 1e-12) return null;
[m[i], m[best]] = [m[best], m[i]];
for (let r = 0; r < n; r++) {
if (r === i) continue;
const f = m[r][i] / m[i][i];
for (let j = i; j <= n; j++) m[r][j] -= f * m[i][j];
}
}
return m.map((row, i) => row[n] / row[i]);
}
/**
* The fewest control points of an open spline (the sketch's own kind: a
* uniform cubic B-spline that starts and ends on its first and last point)
* that keep it within `tol` of the points: its two ends where the curve's
* are, the handles between fitted (least squares, each point's place along
* the curve put right and fitted again). Null when even twelve don't hold it.
*/
function fitControl(run: Vec2[], tol: number): Vec2[] | null {
const n = run.length;
if (n < 4) return null;
const A = run[0];
const Z = run[n - 1];
// Where each point is along the curve, 0 to 1, by the way gone.
const way = [0];
for (let i = 1; i < n; i++) way.push(way[i - 1] + Math.hypot(run[i][0] - run[i - 1][0], run[i][1] - run[i - 1][1]));
if (!(way[n - 1] > 0)) return null;
const start = way.map((w) => w / way[n - 1]);
/** How much of each control point a place along the curve is made of (the mirrored ones past the ends folded in). */
const weights = (m: number, at: number): number[] => {
const spans = m - 1;
const s = Math.min(spans - 1e-12, Math.max(0, at * spans));
const k = Math.min(spans - 1, Math.floor(s));
const u = s - k;
const u2 = u * u;
const u3 = u2 * u;
const b = [(1 - 3 * u + 3 * u2 - u3) / 6, (4 - 6 * u2 + 3 * u3) / 6, (1 + 3 * u + 3 * u2 - 3 * u3) / 6, u3 / 6];
const w = new Array<number>(m).fill(0);
for (let j = 0; j < 4; j++) {
const i = k - 1 + j;
if (i < 0) (w[0] += 2 * b[j]), (w[1] -= b[j]);
else if (i > m - 1) (w[m - 1] += 2 * b[j]), (w[m - 2] -= b[j]);
else w[i] += b[j];
}
return w;
};
const at = (P: Vec2[], x: number): Vec2 => {
const w = weights(P.length, x);
return [w.reduce((s, c, i) => s + c * P[i][0], 0), w.reduce((s, c, i) => s + c * P[i][1], 0)];
};
for (let m = 3; m <= 12 && m < n; m++) {
let ts = start.slice();
let P: Vec2[] | null = null;
for (let round = 0; round < 4; round++) {
// The handles (all but the two ends), least squares.
const q = m - 2;
const mx = Array.from({ length: q }, () => new Array<number>(q + 1).fill(0));
const my = Array.from({ length: q }, () => new Array<number>(q + 1).fill(0));
for (let j = 0; j < n; j++) {
const w = weights(m, ts[j]);
const rx = run[j][0] - w[0] * A[0] - w[m - 1] * Z[0];
const ry = run[j][1] - w[0] * A[1] - w[m - 1] * Z[1];
for (let a = 0; a < q; a++) {
for (let b = 0; b < q; b++) {
mx[a][b] += w[a + 1] * w[b + 1];
my[a][b] += w[a + 1] * w[b + 1];
}
mx[a][q] += w[a + 1] * rx;
my[a][q] += w[a + 1] * ry;
}
}
const xs = solveRows(mx);
const ys = solveRows(my);
if (!xs || !ys) break;
P = [A, ...xs.map((x, i): Vec2 => [x, ys[i]]), Z];
// Each point's place along this curve, put right: the nearest of a fine walk along it, near where it was.
const fine = 24 * (m - 1);
const walk = Array.from({ length: fine + 1 }, (_, i) => at(P!, i / fine));
let worst = 0;
const next = ts.slice();
for (let j = 1; j < n - 1; j++) {
const mid = Math.round(ts[j] * fine);
let best = Infinity;
let where = ts[j];
for (let i = Math.max(1, mid - 24); i <= Math.min(fine, mid + 24); i++) {
// (To the piece of the walk, not just its corners.)
const a = walk[i - 1];
const b = walk[i];
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const f = Math.max(0, Math.min(1, ((run[j][0] - a[0]) * dx + (run[j][1] - a[1]) * dy) / (dx * dx + dy * dy || 1)));
const d = Math.hypot(run[j][0] - a[0] - f * dx, run[j][1] - a[1] - f * dy);
if (d < best) (best = d), (where = (i - 1 + f) / fine);
}
next[j] = where;
worst = Math.max(worst, best);
}
if (worst <= tol) return P;
ts = next;
}
}
return null;
}
/** The ellipse through these points (a conic fitted to them, least squares), or null when they are not on one. */
function fitEllipse(pts: Vec2[]): { c: Vec2; rx: number; ry: number; rot: number } | null {
const n = pts.length;
const mx = pts.reduce((s, p) => s + p[0], 0) / n;
const my = pts.reduce((s, p) => s + p[1], 0) / n;
const k = Math.max(...pts.map((p) => Math.hypot(p[0] - mx, p[1] - my))) || 1;
// A x² + B xy + C y² + D x + E y = 1, about their middle and at their own size (so the numbers stay tame).
const m = Array.from({ length: 5 }, () => new Array<number>(6).fill(0));
for (const p of pts) {
const x = (p[0] - mx) / k;
const y = (p[1] - my) / k;
const row = [x * x, x * y, y * y, x, y];
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) m[i][j] += row[i] * row[j];
m[i][5] += row[i];
}
}
const sol = solveRows(m);
if (!sol) return null;
const [A, B, C, D, E] = sol;
const det = 4 * A * C - B * B;
if (!(det > 1e-12)) return null;
const cx = (B * E - 2 * C * D) / det;
const cy = (B * D - 2 * A * E) / det;
const f = A * cx * cx + B * cx * cy + C * cy * cy + D * cx + E * cy - 1;
const rot = 0.5 * Math.atan2(B, A - C);
const cos = Math.cos(rot);
const sin = Math.sin(rot);
const along = A * cos * cos + B * cos * sin + C * sin * sin;
const across = A * sin * sin - B * cos * sin + C * cos * cos;
if (!(-f / along > 0) || !(-f / across > 0)) return null;
return { c: [mx + cx * k, my + cy * k], rx: Math.sqrt(-f / along) * k, ry: Math.sqrt(-f / across) * k, rot };
}
/** About how far a point is from an ellipse (exact on it, near enough close by). */
function offEllipse(p: Vec2, el: { c: Vec2; rx: number; ry: number; rot: number }): number {
const dx = p[0] - el.c[0];
const dy = p[1] - el.c[1];
const x = dx * Math.cos(el.rot) + dy * Math.sin(el.rot);
const y = -dx * Math.sin(el.rot) + dy * Math.cos(el.rot);
const r = Math.hypot(x / el.rx, y / el.ry);
return Math.abs(r - 1) * Math.min(el.rx, el.ry);
}
function dedupe(pts: Vec2[]): Vec2[] {
@@ -1456,6 +1686,9 @@ export function carryConstraints(before: SketchEntity[], after: SketchEntity[],
};
const out: SketchConstraint[] = [];
for (const c of cs) {
// A copy that follows its original (an offset, a mirror image), one of the two cut or reshaped here: it is its
// own curve from now on - held to being the copy, a trimmed offset would be pulled back to its whole length.
if (c.type === "follow" && (c.curves ?? []).some((id) => old.get(id) !== now.get(id))) continue;
let ok = true;
const pts = c.pts?.map((r) => {
const was = old.get(r.e);
@@ -1573,3 +1806,73 @@ export function chamferConstraints(entities: SketchEntity[], constraints: Sketch
export function lineMeet(p: LineE, q: LineE): Vec2 | null {
return meetLines(p.a, [p.b[0] - p.a[0], p.b[1] - p.a[1]], q.a, q.b);
}
/**
* The curves of a sketch's linked offsets of its face outline (see
* SketchFeature.outlineOffsets), made from the outline as it is now. Each
* offsets the loop of the outline nearest where it was tapped.
*/
export function outlineOffsetCurves(boundary: SketchEntity[], links: OutlineOffset[] | undefined): SketchEntity[] {
const out: SketchEntity[] = [];
for (const o of links ?? []) {
let seed: SketchEntity | null = null;
let best = Infinity;
for (const e of boundary) {
for (const p of entityPrims(e)) {
const d = closestOnPrim(p, o.at).d;
if (d < best) [best, seed] = [d, e];
}
}
if (!seed) continue;
let made: SketchEntity[] = [];
if (!o.single && (seed.kind === "line" || seed.kind === "arc" || (seed.kind === "spline" && !seed.closed))) made = offsetChain(boundary, seed.id, o.distance)?.slice(boundary.length) ?? [];
else {
const one = offsetEntity(seed, o.distance);
if (one) made = [one];
}
made.forEach((e, k) => out.push({ ...e, id: `lnk-${o.id}-${k}` }));
}
return out;
}
/**
* A sketch's shapes onto another plane, square to it: each outline (and hole)
* of the regions, a run of one curve at a time (a whole circle stays a circle,
* one squashed by the slant becomes a spline).
*/
export function projectRegions(arr: Arrangement, regions: Region[], from: PlaneDef, to: PlaneDef): SketchEntity[] {
const kind = (prim: number) => ({ line: "LINE", circle: "CIRCLE" })[arr.prims[prim].t as "line" | "circle"] ?? "SPLINE";
const out: SketchEntity[] = [];
const seen = new Set<number>();
for (const r of regions)
for (const loop of [r.outer, ...r.holes]) {
// Runs of pieces of one curve, the run started where the curve changes.
const ps = loop.pieces;
let start = ps.findIndex((x, i) => arr.pieces[x.piece].prim !== arr.pieces[ps[(i + ps.length - 1) % ps.length].piece].prim);
if (start < 0) start = 0;
let run: { prim: number; pts: Vec2[]; pieces: number[] } | null = null;
const flush = () => {
// A piece two regions share (a line between them) is drawn once.
if (run && !run.pieces.every((k) => seen.has(k))) {
run.pieces.forEach((k) => seen.add(k));
const e = projectPolyline(run.pts.map((q) => toWorld(from, q)), to, kind(run.prim));
if (e) out.push(e);
}
run = null;
};
for (let i = 0; i < ps.length; i++) {
const ref = ps[(start + i) % ps.length];
const pc = arr.pieces[ref.piece];
const poly = ref.reversed ? pc.poly.slice().reverse() : pc.poly;
if (run && (run as { prim: number }).prim === pc.prim && kind(pc.prim) !== "LINE") {
(run as { pts: Vec2[] }).pts.push(...poly.slice(1));
(run as { pieces: number[] }).pieces.push(ref.piece);
} else {
flush();
run = { prim: pc.prim, pts: poly.slice(), pieces: [ref.piece] };
}
}
flush();
}
return out;
}
+171
View File
@@ -0,0 +1,171 @@
// Fill Pattern: a closed shape of a sketch filled with a pattern of curves - lines from edge to edge (straight,
// crossed, zigzag, waves) or small shapes inside it (dots, a honeycomb, squares, diamonds). The pattern's curves
// are curves of the sketch like any other, so the strips and cells they make can be extruded or cut: a texture on
// a model. (Asked for: "a new tool in sketch mode named fill pattern ... different line patterns that you can only
// put in closed shapes that go from edges to edges ... very useful when I want different textures on my models.
// Also I should be able to change the space between lines, or distance between shapes".)
import type { SketchEntity, SketchFill, Vec2 } from "../doc/types";
import { arcFrom3, entityCorners, entityPrims, evalPrim, pointInPoly, type Prim } from "./curves";
import { crossings, pieceEntity } from "./edit";
import { arrangement, type Region } from "./regions";
/** The patterns, in the order they are offered. `lines`: whether it runs edge to edge (else: shapes inside). */
export const FILL_KINDS: { id: SketchFill["kind"]; label: string; lines: boolean; sized: boolean }[] = [
{ id: "lines", label: "Lines", lines: true, sized: false },
{ id: "cross", label: "Crossed lines", lines: true, sized: false },
{ id: "zigzag", label: "Zigzag", lines: true, sized: true },
{ id: "waves", label: "Waves", lines: true, sized: true },
{ id: "dots", label: "Dots", lines: false, sized: true },
{ id: "hex", label: "Honeycomb", lines: false, sized: true },
{ id: "squares", label: "Squares", lines: false, sized: true },
{ id: "diamonds", label: "Diamonds", lines: false, sized: true },
];
/** A fill's curves are named for it: "fp-<fill>-<n>". */
export const FILL_PREFIX = "fp-";
export const fillOf = (entityId: string): string | null => (entityId.startsWith(FILL_PREFIX) ? entityId.slice(FILL_PREFIX.length, entityId.lastIndexOf("-")) : null);
/** The sketch's own curves: all but the ones fills made. */
export const withoutFills = (entities: SketchEntity[]): SketchEntity[] => entities.filter((e) => !e.id.startsWith(FILL_PREFIX));
/** No more curves than this in one fill (a spacing typed a hundred times too small). */
export const FILL_MOST = 2500;
const inRegion = (r: Region, q: Vec2): boolean => pointInPoly(q, r.outer.poly) && !r.holes.some((h) => pointInPoly(q, h.poly));
/** The closed shape a point is in (the smallest, where shapes are one in another): null on none. */
export function fillRegion(entities: SketchEntity[], at: Vec2): Region | null {
const regions = arrangement(withoutFills(entities)).regions.filter((r) => inRegion(r, at));
return regions.sort((a, b) => a.area - b.area)[0] ?? null;
}
/**
* The curves of one fill, for the sketch as it is (its own curves; other fills' are left out). Null: no closed
* shape there. `tooMany`: the spacing gives more curves than a sketch should hold - none made.
*/
export function fillCurves(entities: SketchEntity[], fill: SketchFill): { curves: SketchEntity[]; tooMany?: boolean } | null {
const own = withoutFills(entities);
const region = fillRegion(own, fill.at);
if (!region) return null;
const around = new Set(region.curves);
const edge: Prim[] = own.filter((e) => around.has(e.id) && !e.construction).flatMap(entityPrims);
const kind = FILL_KINDS.find((k) => k.id === fill.kind) ?? FILL_KINDS[0];
const out: SketchEntity[] = [];
const name = () => `${FILL_PREFIX}${fill.id}-${out.length}`;
const th = (fill.angle * Math.PI) / 180;
const d: Vec2 = [Math.cos(th), Math.sin(th)];
const n: Vec2 = [-d[1], d[0]];
// The shape's reach along the pattern's own two ways, and its middle there.
const along = region.outer.poly.map((p) => p[0] * d[0] + p[1] * d[1]);
const across = region.outer.poly.map((p) => p[0] * n[0] + p[1] * n[1]);
const [a0, a1, c0, c1] = [Math.min(...along), Math.max(...along), Math.min(...across), Math.max(...across)];
const mid: Vec2 = [(a0 + a1) / 2, (c0 + c1) / 2];
const at = (u: number, v: number): Vec2 => [d[0] * u + n[0] * v, d[1] * u + n[1] * v];
const reach = Math.hypot(a1 - a0, c1 - c0);
const step = Math.max(1e-6, Math.abs(fill.spacing));
const size = Math.max(1e-6, Math.abs(fill.size));
/** The parts of a curve that are inside the shape, each from edge to edge. */
const clipped = (p: Prim): boolean => {
const ts = [0, ...crossings(p, edge), 1].filter((t, i, all) => i === 0 || t - all[i - 1] > 1e-7);
for (let i = 0; i + 1 < ts.length; i++) {
if (!inRegion(region, evalPrim(p, (ts[i] + ts[i + 1]) / 2))) continue;
if (out.length >= FILL_MOST) return false;
out.push({ ...pieceEntity(p, ts[i], ts[i + 1]), id: name() } as SketchEntity);
}
return true;
};
if (kind.lines) {
// Rows `step` apart, the middle one through the shape's middle; cross: the same again, square to them.
for (const turn of fill.kind === "cross" ? [0, 1] : [0]) {
const [u0, u1, v0, v1, um, vm] = turn ? [c0, c1, -a1, -a0, mid[1], -mid[0]] : [a0, a1, c0, c1, mid[0], mid[1]];
const P = (u: number, v: number): Vec2 => (turn ? at(-v, u) : at(u, v));
const pad = reach * 0.01 + 1e-3;
const rows = Math.ceil((v1 - v0) / step / 2) + 1;
if (rows * 2 > FILL_MOST) return { curves: [], tooMany: true };
for (let k = -rows; k <= rows; k++) {
const v = vm + k * step;
// (Zigzag and waves swing `size` either side of their row.)
const swing = fill.kind === "zigzag" || fill.kind === "waves" ? size / 2 : 0;
if (v + swing <= v0 || v - swing >= v1) continue;
if (fill.kind === "lines" || fill.kind === "cross") {
if (!clipped({ t: "line", a: P(u0 - pad, v), b: P(u1 + pad, v), src: "" })) return { curves: [], tooMany: true };
continue;
}
// A tooth or a wave every `size` along the row, up then down, starting a whole number of them from the middle.
const first = um - Math.ceil((um - u0 + pad) / size) * size;
const teeth = Math.ceil((u1 + pad - first) / size);
if (teeth * rows > FILL_MOST * 4) return { curves: [], tooMany: true };
for (let j = 0; j < teeth; j++) {
const up = (Math.round((first - um) / size) + j) % 2 === 0 ? 1 : -1;
const [x0, x1] = [first + j * size, first + (j + 1) * size];
let prim: Prim;
if (fill.kind === "zigzag") prim = { t: "line", a: P(x0, v - (up * size) / 2), b: P(x1, v + (up * size) / 2), src: "" };
else {
const arc = arcFrom3(P(x0, v), P((x0 + x1) / 2, v + up * size * 0.3), P(x1, v));
if (!arc) continue;
prim = { t: "circle", c: arc.c, r: arc.r, a0: arc.a0, sweep: arc.sweep, src: "" };
}
if (!clipped(prim)) return { curves: [], tooMany: true };
}
}
}
return { curves: out };
}
// Shapes: `size` across, `step` between one and the next, in rows - every other row half a step along for dots,
// the honeycomb and diamonds. Only those wholly inside the shape.
const pitch = size + step;
const stagger = fill.kind !== "squares";
const rowGap = fill.kind === "squares" ? pitch : fill.kind === "diamonds" ? pitch / 2 : (pitch * Math.sqrt(3)) / 2;
const rows = Math.ceil((c1 - c0) / rowGap / 2) + 1;
const cols = Math.ceil((a1 - a0) / pitch / 2) + 1;
if ((2 * rows + 1) * (2 * cols + 1) > FILL_MOST * 6) return { curves: [], tooMany: true };
for (let r = -rows; r <= rows; r++) {
for (let c = -cols; c <= cols; c++) {
const u = mid[0] + c * pitch + (stagger && r % 2 !== 0 ? pitch / 2 : 0);
const v = mid[1] + r * rowGap;
const centre = at(u, v);
let e: SketchEntity;
let rim: Vec2[];
if (fill.kind === "dots") {
e = { id: "", kind: "circle", center: centre, radius: size / 2 } as SketchEntity;
rim = Array.from({ length: 16 }, (_, i) => [centre[0] + (size / 2) * Math.cos((i * Math.PI) / 8), centre[1] + (size / 2) * Math.sin((i * Math.PI) / 8)] as Vec2);
} else {
// (Honeycomb: `size` across its flats, a flat towards its neighbours in the row. Squares: `size` a side.
// Diamonds: `size` from point to point.)
const [sides, radius, turn] = fill.kind === "hex" ? [6, size / Math.sqrt(3), th] : fill.kind === "squares" ? [4, size / Math.SQRT2, th + Math.PI / 4] : [4, size / 2, th];
const poly = { id: "", kind: "polygon" as const, center: centre, radius, sides, angle: turn };
e = poly as SketchEntity;
const corners = entityCorners(poly as Extract<SketchEntity, { kind: "polygon" }>);
rim = corners.flatMap((p, i) => {
const q = corners[(i + 1) % corners.length];
return [p, [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2] as Vec2];
});
}
if (!rim.every((p) => inRegion(region, p))) continue;
// (All its points inside, and its outline crossing nothing: not across a thin neck of the shape.)
if (entityPrims(e).some((p) => crossings(p, edge).length)) continue;
if (out.length >= FILL_MOST) return { curves: [], tooMany: true };
out.push({ ...e, id: name() });
}
}
return { curves: out };
}
/**
* The sketch's curves with every fill's made again for the shapes as they are now (a shape changed size: its
* pattern follows). A fill whose shape is gone keeps the curves it had; curves of a fill that is no more go.
*/
export function refill(entities: SketchEntity[], fills: SketchFill[] | undefined): SketchEntity[] {
const own = withoutFills(entities);
if (!fills?.length) return own.length === entities.length ? entities : own;
const made: SketchEntity[] = [];
for (const f of fills) {
const got = fillCurves(own, f);
if (got && !got.tooMany) made.push(...got.curves);
else made.push(...entities.filter((e) => fillOf(e.id) === f.id));
}
return [...own, ...made];
}
+103
View File
@@ -0,0 +1,103 @@
// Curves of a sketch that follow a body's edge have moved (the body changed):
// what is dimensioned to them is carried along before the sketch is solved
// again. A distance says how far, not which side: a pin 8 mm from a wall that
// moved 40 mm was left on the wall's other side, 8 mm from it there.
import type { SketchConstraint, SketchEntity, Vec2 } from "../doc/types";
import { refsOf } from "./constraints";
import { transformEntity } from "./edit";
/** Where a curve is, as one point (a line's middle, a circle's centre, the mean of a curve's points). */
function middle(e: SketchEntity): Vec2 {
switch (e.kind) {
case "line":
return [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2];
case "arc":
return [(e.a[0] + e.m[0] + e.b[0]) / 3, (e.a[1] + e.m[1] + e.b[1]) / 3];
case "spline":
case "polyline": {
const n = Math.max(1, e.points.length);
return [e.points.reduce((s, p) => s + p[0], 0) / n, e.points.reduce((s, p) => s + p[1], 0) / n];
}
default:
return e.center;
}
}
/**
* `now` (the sketch with its edge-following curves where the edges are now)
* with the other curves moved along: each group of curves tied together by
* constraints is shifted by what the followed curves it is tied to moved.
* A line that moved along itself (the edge got longer) shifts nothing.
*/
export function carried(old: SketchEntity[], now: SketchEntity[], constraints: SketchConstraint[], held: Set<string>): SketchEntity[] {
const was = new Map(old.map((e) => [e.id, e]));
// What each followed curve asks of what is tied to it: a shift along a direction (a line: square to it), or a shift outright.
const asks = new Map<string, { n?: Vec2; v: Vec2 }>();
for (const e of now) {
const o = was.get(e.id);
if (!held.has(e.id) || !o || o === e) continue;
const [m0, m1] = [middle(o), middle(e)];
if (o.kind === "line" && e.kind === "line") {
const L = Math.hypot(o.b[0] - o.a[0], o.b[1] - o.a[1]) || 1;
const n: Vec2 = [-(o.b[1] - o.a[1]) / L, (o.b[0] - o.a[0]) / L];
const d = n[0] * (m1[0] - o.a[0]) + n[1] * (m1[1] - o.a[1]);
asks.set(e.id, { n, v: [n[0] * d, n[1] * d] });
} else asks.set(e.id, { v: [m1[0] - m0[0], m1[1] - m0[1]] });
}
if (!asks.size) return now;
// Groups of free curves tied to each other.
const parent = new Map<string, string>();
const find = (a: string): string => {
let r = a;
while (parent.has(r) && parent.get(r) !== r) r = parent.get(r)!;
parent.set(a, r);
return r;
};
const ids = new Set(now.map((e) => e.id));
for (const c of constraints) {
const free = refsOf(c).filter((id) => ids.has(id) && !held.has(id));
for (const id of free) find(id);
for (let i = 1; i < free.length; i++) parent.set(find(free[0]), find(free[i]));
}
// The shift that best gives each group what its followed curves ask (least squares, the smallest such shift).
const sums = new Map<string, { a: number; b: number; c: number; x: number; y: number; seen: Set<string> }>();
for (const c of constraints) {
const refs = refsOf(c);
const free = refs.find((id) => ids.has(id) && !held.has(id));
if (!free) continue;
const root = find(free);
let s = sums.get(root);
if (!s) sums.set(root, (s = { a: 0, b: 0, c: 0, x: 0, y: 0, seen: new Set() }));
for (const id of refs) {
const ask = asks.get(id);
if (!ask || s.seen.has(id)) continue;
s.seen.add(id);
// (n n^T) t = n d for a line; t = v otherwise.
const [nx, ny] = ask.n ?? [1, 0];
if (ask.n) {
s.a += nx * nx;
s.b += nx * ny;
s.c += ny * ny;
} else {
s.a += 1;
s.c += 1;
}
s.x += ask.v[0];
s.y += ask.v[1];
}
}
const shift = new Map<string, Vec2>();
for (const [root, s] of sums) {
if (!s.seen.size) continue;
const k = 1e-9;
const [a, b, c] = [s.a + k, s.b, s.c + k];
const det = a * c - b * b;
const t: Vec2 = [(c * s.x - b * s.y) / det, (a * s.y - b * s.x) / det];
if (Math.hypot(t[0], t[1]) > 1e-9) shift.set(root, t);
}
if (!shift.size) return now;
return now.map((e) => {
const t = !held.has(e.id) && parent.has(e.id) ? shift.get(find(e.id)) : undefined;
return t ? transformEntity(e, (p) => [p[0] + t[0], p[1] + t[1]]) : e;
});
}
-3
View File
@@ -305,9 +305,6 @@ export function simplifyStroke(raw: Vec2[], tol: number, closeTol = tol * 6): Fr
return { pieces, closed: closed && pieces.length > 0 };
}
export function startOf(e: FreehandPiece): Vec2 {
return e.kind === "spline" ? e.points[0] : e.kind === "circle" ? e.center : e.a;
}
export function endOf(e: FreehandPiece): Vec2 {
return e.kind === "spline" ? e.points[e.points.length - 1] : e.kind === "circle" ? e.center : e.b;
}
+54 -9
View File
@@ -148,7 +148,15 @@ function compute(entities: SketchEntity[]): Arrangement {
for (let j = i + 1; j < segs.length && segs[j].x0 <= A.x1; j++) {
const B = segs[j];
if (B.y0 > A.y1 || B.y1 < A.y0) continue;
if (A.p === B.p) continue; // self-intersections are ignored
if (A.p === B.p) {
// A spline crossing itself (a loop drawn by hand that runs past its
// start, a figure 8) is split there like two curves crossing: it had
// no region at all. Neighbouring pieces of it always touch, so skip those.
if (prims[A.p].t !== "spline") continue;
const n = samples[A.p].pts.length - 1;
const gap = Math.abs(A.i - B.i);
if (gap <= 1 || (isClosedPrim(prims[A.p]) && gap >= n - 1)) continue;
}
// Lines lying on each other (e.g. drawn over a face's edge): each is split
// where the other one ends, and the doubled pieces merge below.
const lap = overlap(A.a, A.b, B.a, B.b, eps);
@@ -169,10 +177,23 @@ function compute(entities: SketchEntity[]): Arrangement {
// ---- pieces
const nodes: Vec2[] = [];
// (Looked up by the cell they're in, and the cells around it: a sketch of
// hundreds of curves compared every end with every node.)
const cells = new Map<string, number[]>();
const nodeOf = (pt: Vec2): number => {
const tol = eps * 50;
for (let k = 0; k < nodes.length; k++) if (Math.abs(nodes[k][0] - pt[0]) < tol && Math.abs(nodes[k][1] - pt[1]) < tol) return k;
const cx = Math.floor(pt[0] / tol);
const cy = Math.floor(pt[1] / tol);
let best = -1;
for (let dx = -1; dx <= 1; dx++)
for (let dy = -1; dy <= 1; dy++)
for (const k of cells.get(`${cx + dx},${cy + dy}`) ?? []) if (Math.abs(nodes[k][0] - pt[0]) < tol && Math.abs(nodes[k][1] - pt[1]) < tol && (best < 0 || k < best)) best = k;
if (best >= 0) return best;
nodes.push(pt);
const key = `${cx},${cy}`;
const list = cells.get(key);
if (list) list.push(nodes.length - 1);
else cells.set(key, [nodes.length - 1]);
return nodes.length - 1;
};
let pieces: Piece[] = [];
@@ -206,13 +227,16 @@ function compute(entities: SketchEntity[]): Arrangement {
// ---- the same stretch drawn twice counts once
{
const seen = new Map<string, Vec2>();
// (Kept by their two ends: only pieces between the same two nodes are compared.)
const seen = new Map<string, Vec2[]>();
pieces = pieces.filter((pc) => {
const key = pc.n0 < pc.n1 ? `${pc.n0}:${pc.n1}` : `${pc.n1}:${pc.n0}`;
const mid = pc.poly[Math.floor(pc.poly.length / 2)];
const m = pc.poly.length > 2 ? mid : [(pc.poly[0][0] + pc.poly[1][0]) / 2, (pc.poly[0][1] + pc.poly[1][1]) / 2] as Vec2;
for (const [k, q] of seen) if (k.split("#")[0] === key && Math.hypot(q[0] - m[0], q[1] - m[1]) < eps * 1e3) return false;
seen.set(`${key}#${seen.size}`, m);
const had = seen.get(key);
if (had?.some((q) => Math.hypot(q[0] - m[0], q[1] - m[1]) < eps * 1e3)) return false;
if (had) had.push(m);
else seen.set(key, [m]);
return true;
});
}
@@ -282,15 +306,36 @@ function compute(entities: SketchEntity[]): Arrangement {
const faces = cycles.filter((c) => c.area > minArea);
const outers = cycles.filter((c) => c.area <= minArea);
const holes = new Map<(typeof faces)[number], typeof outers>();
// (Each face's box first: a plate with hundreds of holes tested every hole's
// outline against every other hole's, point by point.)
const boxes = faces.map((f) => {
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
for (const [x, y] of f.poly) {
if (x < x0) x0 = x;
if (x > x1) x1 = x;
if (y < y0) y0 = y;
if (y > y1) y1 = y;
}
return [x0, y0, x1, y1];
});
const compOf = faces.map(comp);
for (const o of outers) {
const p = o.poly[0];
const co = comp(o);
let best: (typeof faces)[number] | null = null;
for (const f of faces) {
if (comp(f) === comp(o)) continue;
for (let k = 0; k < faces.length; k++) {
const f = faces[k];
const b = boxes[k];
if (p[0] < b[0] || p[0] > b[2] || p[1] < b[1] || p[1] > b[3]) continue;
if (best && f.area >= best.area) continue;
if (compOf[k] === co) continue;
if (!pointInPoly(p, f.poly)) continue;
if (!best || f.area < best.area) best = f;
best = f;
}
if (best) holes.set(best, [...(holes.get(best) ?? []), o]);
if (!best) continue;
const list = holes.get(best);
if (list) list.push(o);
else holes.set(best, [o]);
}
const toLoop = (c: { hs: number[]; poly: Vec2[] }): Loop => ({
+64
View File
@@ -0,0 +1,64 @@
// A sketch pattern whose count is a variable (or a formula): kept with the sketch, so its copies are made again
// when the count comes to another number - six holes round a circle become eight when "n" does. (A sketch pattern
// was its copies and nothing more: the count could be typed once, and never follow anything.)
//
// The copies are curves of the sketch, each tied to its original by the same "pattern" link a plain pattern's
// copies have - named for their pattern, "rp-<pattern>-<copy>-<curve>", their links "rpc-...".
import type { SketchConstraint, SketchEntity, SketchRepeat } from "../doc/types";
import { rotateXf, transformEntity, translateXf } from "./edit";
export const REPEAT_PREFIX = "rp-";
const LINK_PREFIX = "rpc-";
/** No more copies than this from one pattern (a count that came to thousands by a slip). */
export const REPEAT_MOST = 500;
const mine = (id: string, r: SketchRepeat) => id.startsWith(`${REPEAT_PREFIX}${r.id}-`) || id.startsWith(`${LINK_PREFIX}${r.id}-`);
/** How many times the pattern's curves are there now, the originals counted (1: no copies). */
export function repeatCountNow(entities: SketchEntity[], r: SketchRepeat): number {
const copies = new Set(entities.filter((e) => mine(e.id, r)).map((e) => e.id.slice(`${REPEAT_PREFIX}${r.id}-`.length).split("-")[0]));
return copies.size + 1;
}
/** The pattern's copies and their links, for its originals as they are now. */
export function repeatCurves(entities: SketchEntity[], r: SketchRepeat): { curves: SketchEntity[]; links: SketchConstraint[] } {
const src = r.src.map((id) => entities.find((e) => e.id === id)).filter((e): e is SketchEntity => !!e);
const n = Math.max(1, Math.min(REPEAT_MOST, Math.round(r.count)));
const curves: SketchEntity[] = [];
const links: SketchConstraint[] = [];
const full = Math.abs(Math.abs(r.angle ?? 0) - 360) < 1e-6;
const turn = (r.angle ?? 0) / (full ? n : Math.max(1, n - 1));
for (let k = 1; k < n; k++) {
src.forEach((e, i) => {
const id = `${REPEAT_PREFIX}${r.id}-${k}-${i}`;
const xf = r.kind === "linear" ? translateXf(r.step![0] * k, r.step![1] * k) : rotateXf(r.at!, (turn * k * Math.PI) / 180);
curves.push({ ...transformEntity(e, xf, true), id });
const base = { id: `${LINK_PREFIX}${r.id}-${k}-${i}`, type: "pattern" as const, curves: [e.id, id] };
links.push(r.kind === "linear" ? { ...base, at: [r.step![0] * k, r.step![1] * k] } : { ...base, turn: true, at: r.at!, value: turn * k });
});
}
return { curves, links };
}
/**
* The sketch's curves and constraints with each pattern's copies as many as its count says. A pattern whose copies
* are that many already is left as it is (its copies follow their originals by their links); one whose originals
* are all gone goes, its copies staying as plain curves. Null: nothing to change.
*/
export function applyRepeats(entities: SketchEntity[], constraints: SketchConstraint[], repeats: SketchRepeat[] | undefined, force = false): { entities: SketchEntity[]; constraints: SketchConstraint[] } | null {
if (!repeats?.length) return null;
let changed = false;
for (const r of repeats) {
const want = Math.max(1, Math.min(REPEAT_MOST, Math.round(r.count)));
if (!force && repeatCountNow(entities, r) === want) continue;
if (!r.src.some((id) => entities.some((e) => e.id === id))) continue;
const base = entities.filter((e) => !mine(e.id, r));
const made = repeatCurves(base, r);
entities = [...base, ...made.curves];
const gone = (c: SketchConstraint) => mine(c.id, r) || [...(c.curves ?? []), ...(c.pts ?? []).map((q) => q.e)].some((id) => mine(id, r) && !made.curves.some((e) => e.id === id));
constraints = [...constraints.filter((c) => !gone(c)), ...made.links];
changed = true;
}
return changed ? { entities, constraints } : null;
}
+3398 -20
View File
File diff suppressed because it is too large Load Diff
+46 -9
View File
@@ -5,7 +5,7 @@ import { BufferGeometry, ConeGeometry, Group, Line, LineBasicMaterial, LineDashe
import { mergingCommits } from "../doc/store";
import type { PinDef, Vec3 } from "../doc/types";
import { el } from "../ui/ui";
import { numpadInput, openNumpad } from "../ui/numpad";
import { numpadInput, openNumpad, typingInto } from "../ui/numpad";
import { settings } from "../settings";
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
import type { Viewport } from "../view/viewport";
@@ -90,8 +90,11 @@ export interface DimWidgetOptions {
/**
* Keep the value box off the geometry: "side" puts it beside the middle of
* the dimension, "beyond" past its end b (e.g. outside a fillet arc).
* "clear": beside the middle where the line is long enough on screen for
* the box to sit there, else back past its start a (a line just drawn:
* the way it came from, not over its end, where the next point is tapped).
*/
boxAt?: "middle" | "side" | "beyond";
boxAt?: "middle" | "side" | "beyond" | "clear";
/** Extra screen distance past the end for "beyond" (e.g. to clear a drag arrow there). */
boxGap?: number;
/** Which way "beyond" goes when the dimension has no length yet (e.g. the arrow's direction). */
@@ -100,6 +103,13 @@ export interface DimWidgetOptions {
angle?: boolean;
/** No dimension line (just the box, e.g. at the corner between two lines). */
noLine?: boolean;
/**
* The face the value belongs to, by its outward normal: seen from behind,
* the box steps aside (the value is in the tool's card then). It sat over
* whatever is in front of that face: a funnel's spout end, tapped from
* below to open it too, went to Shell's thickness box on the top face.
*/
facing?: Vec3;
/** Variables to choose from (a ƒx menu before the pin): the value becomes that variable. */
variables?: string[];
onVariable?(name: string): void;
@@ -115,9 +125,10 @@ export class DimWidget {
private input = document.createElement("input");
private mid = new Vector3();
private ends: [Vector3, Vector3] = [new Vector3(), new Vector3()];
private boxAt: "middle" | "side" | "beyond";
private boxAt: "middle" | "side" | "beyond" | "clear";
private boxGap: number;
private dir?: Vec3;
private facing?: Vec3;
private hook = () => this.layout();
constructor(
@@ -128,6 +139,7 @@ export class DimWidget {
this.boxAt = opts.boxAt ?? "middle";
this.boxGap = opts.boxGap ?? 0;
this.dir = opts.dir;
this.facing = opts.facing;
view.overlay.add(this.line.group);
if (opts.modes) {
const sel = document.createElement("select");
@@ -232,7 +244,7 @@ export class DimWidget {
}
setValue(v: number): void {
if (document.activeElement !== this.input) this.input.value = this.show(v);
if (!typingInto(this.input)) this.input.value = this.show(v);
this.box.classList.remove("typing", "invalid");
}
@@ -272,7 +284,12 @@ export class DimWidget {
}
const l = Math.hypot(dx, dy) || 1;
const half = { w: this.box.offsetWidth / 2 + 10, h: this.box.offsetHeight / 2 + 10 };
if (this.boxAt === "beyond") {
// Too short for the box beside it (it would cover both ends): behind the start.
const behind = this.boxAt === "clear" && l < 2 * Math.hypot(half.w, half.h) + 24;
if (behind) {
const k = Math.abs((dx / l) * half.w) + Math.abs((dy / l) * half.h) + 6;
s = [sa[0] - (dx / l) * k, sa[1] - (dy / l) * k];
} else if (this.boxAt === "beyond") {
// Past the end, far enough that the box's own size clears it.
const k = Math.abs((dx / l) * half.w) + Math.abs((dy / l) * half.h) + this.boxGap;
s = [sb[0] + (dx / l) * k, sb[1] + (dy / l) * k];
@@ -284,6 +301,16 @@ export class DimWidget {
s = [s[0] + n[0] * k, s[1] + n[1] * k];
}
}
// Its face turned away (seen from behind): out of the way - and out of
// the numpad's hands (on a phone it has it from the start), the value
// then typed in the tool's card.
if (s && this.facing) {
const v = this.view.cam.viewDir();
if (v.x * this.facing[0] + v.y * this.facing[1] + v.z * this.facing[2] > 0.05) {
s = null;
if (this.input === document.activeElement) this.input.blur();
}
}
this.box.hidden = !s;
// The dimension on screen (the tool's options card keeps off it).
if (sa && sb) this.box.dataset.seg = `${Math.round(sa[0])},${Math.round(sa[1])},${Math.round(sb[0])},${Math.round(sb[1])}`;
@@ -312,8 +339,8 @@ export class DimWidget {
/** A screen point moved (if needed) so a box of these half sizes is on screen and off the open side panels. */
/** The side panels' and the tool card's places, measured at most every 120 ms (not per box per frame). */
let freeCache: { t: number; sides: DOMRect[]; panel: DOMRect | null } | null = null;
function freeAreas(): { sides: DOMRect[]; panel: DOMRect | null } {
let freeCache: { t: number; sides: DOMRect[]; panel: DOMRect | null; low: DOMRect[] } | null = null;
function freeAreas(): { sides: DOMRect[]; panel: DOMRect | null; low: DOMRect[] } {
const now = performance.now();
if (freeCache && now - freeCache.t < 120) return freeCache;
const sides: DOMRect[] = [];
@@ -323,11 +350,20 @@ function freeAreas(): { sides: DOMRect[]; panel: DOMRect | null } {
}
const p = document.getElementById("panel");
const panel = document.documentElement.dataset.screen === "phone" && p && !p.hidden && p.offsetHeight ? p.getBoundingClientRect() : null;
freeCache = { t: now, sides, panel };
// What sits along the bottom - the line with its tools, and on a phone undo and the guide text over it: a value
// box stays above them (pulled down into a cut on a phone, the box sat on the guide text).
const low: DOMRect[] = [];
for (const id of ["sentence", "undo-dock", "hint"]) {
const e = document.getElementById(id);
const r = e && !e.hidden && e.offsetHeight && getComputedStyle(e).visibility !== "hidden" ? e.getBoundingClientRect() : null;
if (r && r.top > window.innerHeight * 0.5) low.push(r);
}
low.sort((a, b) => b.top - a.top);
freeCache = { t: now, sides, panel, low };
return freeCache;
}
function clampToFree(s: [number, number], hw: number, hh: number): [number, number] {
export function clampToFree(s: [number, number], hw: number, hh: number): [number, number] {
let left = 8;
let right = window.innerWidth - 8;
const free = freeAreas();
@@ -344,6 +380,7 @@ function clampToFree(s: [number, number], hw: number, hh: number): [number, numb
const r = free.panel;
if (x + hw > r.left - 6 && x - hw < r.right + 6 && y + hh > r.top - 6) y = Math.max(52 + hh, r.top - 8 - hh);
}
for (const r of free.low) if (x + hw > r.left - 6 && x - hw < r.right + 6 && y + hh > r.top - 6 && y - hh < r.bottom + 6) y = Math.max(52 + hh, r.top - 8 - hh);
return [x, y];
}
+150
View File
@@ -0,0 +1,150 @@
// More ways to make a construction axis, each from what it says:
// Point to Point – through two points of the model.
// Intersection of 2 Planes – where two planes or flat faces cross.
// (Square to a face, along an edge and the middle of a cylinder or cone are
// one tap each: started from the wheel with the pick, see app.ts.)
// The axis is worked out from the picks and kept, like the planes.
import type { AxisFeature, AxisKind, PlaneDef, Vec3 } from "../doc/types";
import { add, cross, dot, len, norm, scale, sub } from "../geom";
import type { PanelItem } from "../ui/ui";
import { FeatureOp } from "./featureOp";
import { roundAxis } from "./select";
import { planeSlot, pointSlot } from "./slots";
import type { AppContext } from "./tool";
abstract class AxisFromPicks extends FeatureOp<AxisFeature> {
readonly id = "axis";
constructor(app: AppContext, label: string, kind: AxisKind) {
super(app, { ...app.store.newIdentity("axis", label), type: "axis", origin: [0, 0, 0], dir: [0, 0, 1], kind });
}
/** The axis the picks make (null: not yet / they don't make one). */
protected abstract make(): { origin: Vec3; dir: Vec3 } | null;
protected sync(): void {
const a = this.make();
if (a) (this.feature.origin = a.origin), (this.feature.dir = a.dir);
}
protected ready(): boolean {
return super.ready() && !!this.make();
}
protected items(): PanelItem[] {
return [];
}
}
export class TwoPointAxisOp extends AxisFromPicks {
private pts: (Vec3 | null)[] = [null, null];
constructor(app: AppContext) {
super(app, "Axis Point to Point", "2pt");
this.slots = ["First point", "Second point"].map((l, i) => pointSlot(app, l, () => this.pts[i], (p) => ((this.pts[i] = p), this.sync())));
this.finishWhenPicked = true;
}
protected make(): { origin: Vec3; dir: Vec3 } | null {
const [a, b] = this.pts;
if (!a || !b || len(sub(b, a)) < 1e-9) return null;
return { origin: a, dir: norm(sub(b, a)) };
}
protected hint(): string {
const [a, b] = this.pts;
return a && b && !this.make() ? "⚠ The two points are the same - pick another" : "Tap two points (corners, points on edges or in sketches): the axis goes through both.";
}
}
export class PlanesAxisOp extends AxisFromPicks {
private a: PlaneDef | null = null;
private b: PlaneDef | null = null;
constructor(app: AppContext) {
super(app, "Axis 2 Planes", "planes");
this.slots = [
planeSlot(app, "First plane", () => this.a, (p) => ((this.a = p), this.sync())),
planeSlot(app, "Second plane", () => this.b, (p) => ((this.b = p), this.sync())),
];
this.finishWhenPicked = true;
}
protected make(): { origin: Vec3; dir: Vec3 } | null {
return this.a && this.b ? planesMeet(this.a, this.b) : null;
}
protected hint(): string {
return this.a && this.b && !this.make() ? "⚠ The two planes are parallel - they never cross. Pick another" : "Tap two planes or flat faces: the axis goes where they cross.";
}
}
/** Where two planes cross: the line, through the point of it nearest the middle of their origins. */
export function planesMeet(a: PlaneDef, b: PlaneDef): { origin: Vec3; dir: Vec3 } | null {
const n1 = norm(a.normal);
const n2 = norm(b.normal);
const d = cross(n1, n2);
if (len(d) < 1e-6) return null;
const dir = norm(d);
// A point on both: x = q + s n1 + t n2, with n1·x = n1·a.origin and n2·x = n2·b.origin, q the middle.
const q = scale(add(a.origin, b.origin), 0.5);
const r1 = dot(n1, sub(a.origin, q));
const r2 = dot(n2, sub(b.origin, q));
const c = dot(n1, n2);
const det = 1 - c * c;
const s = (r1 - c * r2) / det;
const t = (r2 - c * r1) / det;
return { origin: add(q, add(scale(n1, s), scale(n2, t))), dir };
}
/**
* The middle line of a round face - a cylinder (or a hole), a cone (a
* countersink, a taper) - from its mesh: every normal on it is at the same
* angle to the axis, and every normal line goes through the axis.
*/
export function surfaceAxis(app: AppContext, body: string, face: number): { origin: Vec3; dir: Vec3 } | null {
const round = roundAxis(app, body, face);
if (round) return round;
const b = app.view.body(body);
const info = b?.faces[face];
const g = b?.faceGroups.find((x) => x.face === face);
if (!b || !info || !g || g.count < 3 || !["CONE", "CYLINDRE", "REVOLUTION_SURFACE", "TORUS", "SPHERE"].includes(info.type)) return null;
const at = (A: ArrayLike<number>, i: number): Vec3 => [A[3 * i], A[3 * i + 1], A[3 * i + 2]];
const idx = [...new Set(Array.from(b.indices.subarray(g.start, g.start + g.count)))];
const ns = idx.map((i) => norm(at(b.normals, i)));
const ps = idx.map((i) => at(b.positions, i));
// The axis: the way the normals don't spread (their spread's least direction).
const m = scale(ns.reduce(add, [0, 0, 0] as Vec3), 1 / ns.length);
const C = [0, 0, 0, 0, 0, 0, 0, 0, 0];
for (const n of ns) {
const v = sub(n, m);
for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) C[r * 3 + c] += v[r] * v[c];
}
const tr = C[0] + C[4] + C[8];
if (tr < 1e-6 * ns.length) return null; // all the normals one way: a sliver, nothing to go by
// Power steps on (tr·I − C): its biggest is C's least.
let d: Vec3 = norm(cross(ns[0], ns[ns.length >> 1]));
if (len(d) < 0.5) d = [0.577, 0.577, 0.577];
for (let k = 0; k < 60; k++) {
const nd: Vec3 = [0, 1, 2].map((r) => tr * d[r] - (C[r * 3] * d[0] + C[r * 3 + 1] * d[1] + C[r * 3 + 2] * d[2])) as Vec3;
if (len(nd) < 1e-12) return null;
d = norm(nd);
}
// The point on the axis: nearest every normal line, across the axis.
const A = [0, 0, 0, 0, 0, 0, 0, 0, 0];
const rhs: Vec3 = [0, 0, 0];
for (let i = 0; i < ns.length; i++) {
const u0 = sub(ns[i], scale(d, dot(ns[i], d)));
if (len(u0) < 1e-6) continue;
const u = norm(u0);
for (let r = 0; r < 3; r++)
for (let c = 0; c < 3; c++) {
const M = (r === c ? 1 : 0) - u[r] * u[c] - d[r] * d[c];
A[r * 3 + c] += M;
rhs[r] += M * ps[i][c];
}
}
// (Along the axis it is free: held at the face's middle.)
for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) A[r * 3 + c] += d[r] * d[c] * ns.length;
for (let r = 0; r < 3; r++) rhs[r] += d[r] * dot(d, info.center) * ns.length;
const o = solve3(A, rhs);
return o && { origin: o, dir: d };
}
function solve3(A: number[], b: Vec3): Vec3 | null {
const det = (m: number[]) => m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
const D = det(A);
if (Math.abs(D) < 1e-12) return null;
const col = (k: number) => A.map((v, i) => (i % 3 === k ? b[Math.floor(i / 3)] : v));
return [det(col(0)) / D, det(col(1)) / D, det(col(2)) / D];
}
+152 -7
View File
@@ -2,7 +2,9 @@
// change it with (−), picked in turn; keep either side if wanted.
import type { BooleanFeature, Vec3 } from "../doc/types";
import { add, scale } from "../geom";
import type { PanelItem } from "../ui/ui";
import { DimWidget } from "./annotate";
import { FeatureOp, type Slot } from "./featureOp";
import { bodyCenter } from "./ops";
import type { AppContext } from "./tool";
@@ -18,7 +20,13 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
constructor(app: AppContext, op: "subtract" | "intersect", target = "", tools: string[] = [], existing?: BooleanFeature) {
super(app, { ...app.store.newIdentity("boolean", cap(op)), type: "boolean", op, target, tools: tools.filter((t) => t !== target) }, existing);
const sub = this.feature.op === "subtract";
const bodyOf = (hit: { kind: string; body?: string }) => (hit.kind === "body" || hit.kind === "face" || hit.kind === "edge" || hit.kind === "vertex" ? hit.body ?? null : null);
// Not this subtract's own result: with "Keep modified body" on, its preview
// shows beside the original, and a tap on it made it one of its own tools.
const own = (b: string) => b === this.feature.id || b.startsWith(`${this.feature.id}:`);
const bodyOf = (hit: { kind: string; body?: string }) => {
const b = hit.kind === "body" || hit.kind === "face" || hit.kind === "edge" || hit.kind === "vertex" ? hit.body ?? null : null;
return b && !own(b) ? b : null;
};
const targetSlot: Slot = {
label: sub ? "Remove from" : "Body",
describe: () => (this.feature.target ? this.nameOf(this.feature.target) : "Tap a body"),
@@ -30,6 +38,8 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
if (!b) return false;
this.feature.target = b;
this.feature.tools = this.feature.tools.filter((t) => t !== b);
// (Worked out again for the bodies as now picked.)
this.feature.whole = undefined;
return true;
},
};
@@ -45,26 +55,65 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
if (!b || b === this.feature.target) return false;
const t = this.feature.tools;
this.feature.tools = t.includes(b) ? t.filter((x) => x !== b) : [...t, b];
this.feature.whole = undefined;
return true;
},
};
this.slots = [targetSlot, toolsSlot];
}
/** Names seen (while its preview is being made, a body can be missing from the list). */
private names = new Map<string, string>();
private nameOf(id: string): string {
return this.app.store.doc.names?.[id] ?? this.app.view.bodyList.find((b) => b.id === id)?.name ?? "Body";
const name = this.app.store.doc.names?.[id] ?? this.app.view.bodyList.find((b) => b.id === id)?.name ?? this.names.get(id);
if (name) this.names.set(id, name);
return name ?? "Body";
}
protected hint(): string {
return this.feature.op === "subtract"
? "Select a body to remove from, then a body to subtract from it."
: "Select a body, then the bodies to intersect it with (what they share is kept).";
? "Tap the body to cut, then the bodies to cut away from it."
: "Tap a body, then the bodies it overlaps. Only the part they share is kept.";
}
/** Which bodies give way to the clearance, named after the bodies picked. */
private sides(): { id: string; label: string }[] {
const t = this.feature.tools;
return [
{ id: "body", label: this.feature.target ? this.nameOf(this.feature.target) : "Body" },
{ id: "tools", label: t.length === 1 ? this.nameOf(t[0]) : "The others" },
{ id: "all", label: t.length > 1 ? "All" : "Both" },
];
}
private setSide(id: string): void {
this.feature.cutFrom = id === "body" ? undefined : (id as "tools" | "all");
this.render();
this.update();
}
private setClearance(v: number): void {
if (!(v >= 0)) return;
this.feature.clearance = v || undefined;
this.app.ui.updatePanelValues([v]);
this.dim?.setValue(v);
this.update();
}
protected items(): PanelItem[] {
const f = this.feature;
const sub = f.op === "subtract";
const gap: PanelItem[] = sub
? [
{ ...this.num("Clearance", "clearance", "length", { min: 0, onInput: (v) => this.setClearance(v), inBox: true }), value: f.clearance ?? 0 } as PanelItem,
{ type: "choice", label: "Cut from", options: this.sides(), value: f.cutFrom ?? "body", onChange: (id) => this.setSide(id) },
]
: [];
// The others give way (or all do): every body stays, changed.
if (sub && f.cutFrom) return gap;
return [
...gap,
{ type: "toggle", label: "Keep modified body", value: !!f.keepTarget, onChange: (v) => ((f.keepTarget = v || undefined), this.render(), this.update()) },
{ type: "toggle", label: sub ? "Keep subtracted bodies" : "Keep intersecting bodies", value: !!f.keepTools, onChange: (v) => ((f.keepTools = v || undefined), this.render(), this.update()) },
];
@@ -77,39 +126,135 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
}
exit(): void {
this.dim?.dispose();
this.dim = null;
this.app.view.frameHooks.delete(this.hook);
for (const m of this.marks) m.remove();
this.marks = [];
super.exit();
}
/** The clearance, typed between the body and the first body it's subtracted with. */
private dim: DimWidget | null = null;
/** The names in its drop-down (made again when the bodies picked change). */
private dimSides = "";
protected onDraftChanged(): void {
this.placeMarks();
const f = this.feature;
const a = this.centers.get(f.target), b = f.tools[0] ? this.centers.get(f.tools[0]) : undefined;
const sides = this.sides();
const key = JSON.stringify(sides);
if (f.op !== "subtract" || !a || !b || key !== this.dimSides) {
this.dim?.dispose();
this.dim = null;
}
if (f.op !== "subtract" || !a || !b) return;
this.dimSides = key;
this.dim ??= new DimWidget(this.app.view, {
noLine: true,
value: f.clearance ?? 0,
modes: sides,
mode: f.cutFrom ?? "body",
onMode: (id) => this.setSide(id),
onInput: (v, text) => {
if (!(v >= 0)) return;
this.typedInto("clearance", text);
this.setClearance(v);
},
onCommit: () => this.done(),
});
const [p, q] = this.boxAt(scale(add(a, b), 0.5));
this.boxPoint = p;
this.dim.set(p, q);
this.dim.setMode(f.cutFrom ?? "body");
this.dim.setValue(f.clearance ?? 0);
// (The signs again, clear of the box just made.)
this.placeMarks();
}
/**
* The sign on `body` turned the other way: a "−" body becomes the one
* changed, the one that was takes its place among the others; the "+" body
* swaps with the first of the others.
*/
private swap(body: string): void {
const f = this.feature;
if (!f.target || !f.tools.length) return;
const other = body === f.target ? f.tools[0] : body;
if (!f.tools.includes(other)) return;
f.tools = f.tools.map((t) => (t === other ? f.target : t));
f.target = other;
f.whole = undefined;
this.render();
this.update();
this.placeMarks();
}
/** "+" on the body that's changed, "−" on each body it's changed with. */
/**
* Where the clearance box goes: between the two bodies, or - when that's
* over a body (a tray's middle, its pockets still to be tapped) - further
* down the screen, clear of them. (It sat on the pockets; its number pad,
* opened by a tap meant for one, covered half the tray.)
*/
private boxPoint: Vec3 | null = null;
private boxAt(mid: Vec3): [Vec3, Vec3] {
const view = this.app.view;
const s = view.toScreen(mid);
if (!s) return [mid, mid];
const over = (y: number) => [-90, 0, 90].some((dx) => view.pick(s[0] + dx, y, { edgeTolPx: 24, planes: false }));
if (!over(s[1])) return [mid, mid];
let y = s[1];
while (y < view.height - 160 && over(y)) y += 20;
if (over(y)) return [mid, mid];
const w = view.worldUnder(s[0], y).toArray() as Vec3;
return [w, w];
}
private placeMarks(): void {
const want: [string, string][] = [];
if (this.feature.target) want.push([this.feature.target, "+"]);
for (const t of this.feature.tools) want.push([t, "−"]);
// Many taken away (eight pockets out of a tray): only the first keeps its
// sign - the rest, pushed aside to clear each other, landed on bodies still
// to be tapped, and a tap meant for a pocket swapped the tray out instead.
for (const t of this.feature.tools.length > 2 ? this.feature.tools.slice(0, 1) : this.feature.tools) want.push([t, "−"]);
while (this.marks.length > want.length) this.marks.pop()!.remove();
while (this.marks.length < want.length) {
const m = document.createElement("div");
m.className = "bool-mark";
// A tap on a sign turns it the other way round: picked in the wrong order, fixed in one tap.
m.addEventListener("pointerdown", (e) => e.stopPropagation());
m.addEventListener("click", (e) => {
e.stopPropagation();
if (m.dataset.body) this.swap(m.dataset.body);
});
document.body.append(m);
this.marks.push(m);
}
const r = this.app.view.canvas.getBoundingClientRect();
// (Bodies sharing a middle - a peg through a plate - get their signs side by side, each one tappable.)
const placed: [number, number][] = [];
// (And clear of the clearance's box, which sits between the first two bodies.)
const a = this.centers.get(this.feature.target), b = this.feature.tools[0] ? this.centers.get(this.feature.tools[0]) : undefined;
const box = this.dim && a && b ? this.app.view.toScreen(this.boxPoint ?? scale(add(a, b), 0.5)) : null;
want.forEach(([body, sign], i) => {
const m = this.marks[i];
m.title = sign === "+" ? "Changed" : "Changed with";
m.dataset.body = body;
m.title = sign === "+" ? "Changed - tap to change it with this one instead" : "Changed with - tap to change this one instead";
m.classList.toggle("minus", sign !== "+");
// (Where the body was: in the preview a subtracted body is used up.)
if (this.app.view.bodyList.some((b) => b.id === body)) this.centers.set(body, bodyCenter(this.app, [body]));
const at = this.centers.get(body);
const c = at ? this.app.view.toScreen(at) : null;
m.hidden = !c;
if (c) m.style.transform = `translate(${Math.round(r.left + c[0] - 14)}px, ${Math.round(r.top + c[1] - 14)}px)`;
if (!c) return;
let x = c[0], y = c[1];
if (box && Math.abs(box[0] - x) < 100 && Math.abs(box[1] - y) < 36) y = box[1] - 36;
while (placed.some(([px, py]) => Math.abs(px - x) < 30 && Math.abs(py - y) < 30)) x += 32;
placed.push([x, y]);
m.style.transform = `translate(${Math.round(r.left + x - 14)}px, ${Math.round(r.top + y - 14)}px)`;
});
}
}
+14 -2
View File
@@ -83,9 +83,21 @@ export class DragTyping {
(this.boxEl.querySelector(".dim-unit") as HTMLElement).textContent = unit;
if (document.activeElement !== this.boxInput) this.boxInput!.value = value.replace(/\s*(mm|cm|m|in|ft|°|")$/, "").replace(/^×/, "");
const r = this.app.view.canvas.getBoundingClientRect();
this.boxEl.style.left = `${Math.round(r.left + p.x + 22)}px`;
this.boxEl.style.top = `${Math.round(r.top + p.y + 16)}px`;
this.boxEl.hidden = false;
// Below right of the finger - or left of it / above it where that runs off
// the screen (a face pushed out at a phone's right edge had its box at
// x 387 on a 375 screen: there, but not to be tapped).
const w = this.boxEl.offsetWidth;
const h = this.boxEl.offsetHeight;
const M = 8;
let x = r.left + p.x + 22;
let y = r.top + p.y + 16;
if (x + w > innerWidth - M) x = r.left + p.x - 22 - w;
if (y + h > innerHeight - M) y = r.top + p.y - 16 - h;
x = Math.max(M, Math.min(x, innerWidth - M - w));
y = Math.max(M, Math.min(y, innerHeight - M - h));
this.boxEl.style.left = `${Math.round(x)}px`;
this.boxEl.style.top = `${Math.round(y)}px`;
this.app.ui.setLabel(0, 0, null);
}
+135
View File
@@ -0,0 +1,135 @@
// Freeform Face: a flat face of a body made a smooth surface. A cage is laid
// over the face - a grid whose border runs round the face's edge - and shaped
// in the Freeform tool: tap its points, edges or faces and move them with the
// gimbal (along the face, or out of it). The border stays put, so the face's
// edges, and the rest of the body, don't move.
import type { FaceFreeformFeature, FaceRef, Vec3 } from "../doc/types";
import { editedStep } from "../doc/freeformEdits";
import { facesNormal } from "../freeform/faceGrid";
import { faceStepNormal, FreeformTool, layFaceCage, type EditKeep } from "./freeform";
import { faceRefOf, type AppContext, type Sel, type Tool } from "./tool";
/** The triangles of face `i` of a body as shown (the cage goes only where the face is). */
function faceTriangles(app: AppContext, body: string, i: number): [Vec3, Vec3, Vec3][] {
const b = app.view.body(body);
const g = b?.faceGroups.find((x) => x.face === i);
if (!b || !g) return [];
const P = (k: number): Vec3 => [b.positions[3 * k], b.positions[3 * k + 1], b.positions[3 * k + 2]];
const out: [Vec3, Vec3, Vec3][] = [];
for (let t = g.start; t < g.start + g.count; t += 3) out.push([P(b.indices[t]), P(b.indices[t + 1]), P(b.indices[t + 2])]);
return out;
}
/** Do the faces (each as its triangles) all hang together, each sharing an edge with another? */
function joined(faces: [Vec3, Vec3, Vec3][][]): boolean {
const key = (p: Vec3) => p.map((x) => Math.round(x * 1e4)).join(",");
const edgesOf = (tris: [Vec3, Vec3, Vec3][]) => {
const s = new Set<string>();
for (const t of tris)
for (let k = 0; k < 3; k++) {
const a = key(t[k]);
const b = key(t[(k + 1) % 3]);
s.add(a < b ? `${a}|${b}` : `${b}|${a}`);
}
return s;
};
const sets = faces.map(edgesOf);
const reached = new Set([0]);
for (let grew = true; grew; ) {
grew = false;
for (let i = 0; i < sets.length; i++) {
if (reached.has(i)) continue;
if ([...reached].some((j) => [...sets[i]].some((e) => sets[j].has(e)))) (reached.add(i), (grew = true));
}
}
return reached.size === sets.length;
}
/**
* A Freeform Face step (as its edits leave it) whose surface on the picked
* faces' body shares an edge with them, and that surface's triangles.
*/
function touchedStep(app: AppContext, picked: Extract<Sel, { kind: "face" }>[]): { step: FaceFreeformFeature; tris: [Vec3, Vec3, Vec3][] } | null {
const body = picked[0].body;
if (picked.some((p) => p.body !== body)) return null;
const faces = app.view.body(body)?.faces ?? [];
const mine = new Set(picked.map((p) => p.face));
const steps = [...new Set(faces.flatMap((f, k) => (f.step && !mine.has(k) ? [f.step] : [])))];
const pickedTris = picked.map((p) => faceTriangles(app, body, p.face));
for (const id of steps) {
const s = editedStep<FaceFreeformFeature>(app.store.features, id);
if (s?.type !== "faceFreeform" || s.face.body !== body) continue;
const tris = faces.flatMap((f, k) => (f.step === id && !mine.has(k) ? faceTriangles(app, body, k) : []));
if (tris.length && joined([tris, ...pickedTris])) return { step: s, tris };
}
return null;
}
/** The face most like a saved one (facing the same way, its middle nearest), or -1. */
function nearestFace(faces: { center: Vec3; normal: Vec3 }[], ref: FaceRef): number {
let best = -1;
let d = Infinity;
faces.forEach((f, k) => {
if (f.normal[0] * ref.normal[0] + f.normal[1] * ref.normal[1] + f.normal[2] * ref.normal[2] < 0.999) return;
const e = Math.hypot(f.center[0] - ref.center[0], f.center[1] - ref.center[1], f.center[2] - ref.center[2]);
if (e < d) ((d = e), (best = k));
});
return best;
}
/**
* The Freeform tool on a face: `face`, a flat face to shape (a new step), or
* `existing`, a Freeform Face step to change (its face found on the body by
* the step that made it). Null (after saying why) when no cage fits the face.
*/
export function faceFreeformTool(app: AppContext, face: Extract<Sel, { kind: "face" }> | Extract<Sel, { kind: "face" }>[] | null, existing?: FaceFreeformFeature, keep?: EditKeep): Tool | null {
if (existing) {
const faces = app.view.body(existing.face.body)?.faces ?? [];
// (Several faces made one: the surface may be in pieces, all made by the step.)
let at = faces.flatMap((f, k) => (f.step === existing.id ? [k] : []));
if (!existing.more?.length) at = at.slice(0, 1);
// The step didn't work (so its face isn't there): the flat faces it was made on.
if (!at.length) at = [existing.face, ...(existing.more ?? [])].map((r) => nearestFace(faces, r)).filter((k) => k >= 0);
// (Over a face already shaped the cage is laid on its outline, which is the flat face's.)
const tris = at.flatMap((k) => faceTriangles(app, existing.face.body, k));
const feature = structuredClone(existing);
if (!feature.cage?.verts?.length) {
// Made before faces had cages: a fresh one over it.
const laid = layFaceCage(tris, feature.face.center, faceStepNormal(feature), 5, !!feature.more?.length);
if (!laid) return (app.ui.toast("This face's outline won't take a grid - pick it again with Freeform Face"), null);
feature.cage = laid.cage;
feature.grid = laid.n;
}
return new FreeformTool(app, { face: { feature, existing: true, tris, keep } });
}
const picked = !face ? [] : Array.isArray(face) ? face : [face];
const refs = picked.map((s) => faceRefOf(app, s) as FaceRef | null);
if (!picked.length || refs.some((r) => !r)) return null;
const [ref, ...more] = refs as FaceRef[];
const tris = picked.flatMap((s) => faceTriangles(app, s.body, s.face));
// Several faces: they must touch, one after another (a grid can't jump a gap).
if (more.length && !joined(picked.map((s) => faceTriangles(app, s.body, s.face)))) return (app.ui.toast("Pick faces that touch each other - side by side, sharing an edge"), null);
// Touching a surface a Freeform Face step made on the same body: that step
// grows to take these faces in - one surface, no edge where they meet (an
// Edit Freeform step in History: delete it and they are apart again).
const grow = touchedStep(app, picked);
if (grow) {
const s = grow.step;
const all: FaceRef[] = [...(s.more ?? []), ...(refs as FaceRef[])];
const feature: FaceFreeformFeature = { ...structuredClone(s), more: all };
const both = [...grow.tris, ...tris];
// (Laid over the surface as it is shaped now and the new faces: what was shaped stays so, near enough.)
const laid = layFaceCage(both, s.face.center, faceStepNormal(feature), Math.max(5, s.grid ?? 5), true);
if (!laid) return (app.ui.toast("These faces won't take one grid with the freeform beside them (seen together they fold back over each other)"), null);
feature.cage = laid.cage;
feature.grid = laid.n;
app.ui.toast(`Joined to ${s.name}: one smooth surface`);
return new FreeformTool(app, { face: { feature, existing: true, tris: both } });
}
const normal = more.length ? facesNormal([ref.normal, ...more.map((m) => m.normal)]) : ref.normal;
const laid = layFaceCage(tris, ref.center, normal, 5, more.length > 0);
if (!laid) return (app.ui.toast(more.length ? "These faces won't take one grid (seen together they fold back over each other) - pick fewer" : "This face's outline won't take a grid (too small, or too odd a shape)"), null);
const feature: FaceFreeformFeature = { ...app.store.newIdentity("faceFreeform"), type: "faceFreeform", face: ref, ...(more.length ? { more } : {}), cage: laid.cage, grid: laid.n };
return new FreeformTool(app, { face: { feature, existing: false, tris } });
}
+216 -18
View File
@@ -1,10 +1,11 @@
import { getPath, setPath } from "../doc/params";
import { BETA_TYPES } from "../doc/store";
import type { ExtrudeSource, Feature, SketchFeature, Vec2 } from "../doc/types";
import type { FieldKind, PanelItem, ToolItem } from "../ui/ui";
import { isExpression } from "../ui/ui";
import type { ToolPointer } from "../view/input";
import type { PickHit, PickOptions } from "../view/viewport";
import { hitToSel, sourcesOf, type AppContext, type Sel, type Tool } from "./tool";
import { hitToSel, sourcesOf, viewMenu, type AppContext, type Sel, type Tool } from "./tool";
import { DragTyping } from "./dragTyping";
import { screenClass } from "../device";
import { arrangement, materialRegions, pointInRegion, resolveRegion, type Region } from "../sketch/regions";
@@ -82,12 +83,105 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
this.app.ui.setTools(screenClass() === "phone" ? [{ id: "cancel", label: "Cancel", icon: "close", shortcut: "Esc", run: () => this.cancel() }] : []);
this.app.ui.setBottom([]);
this.active = this.slots.findIndex((s) => !s.filled());
// A step opened again with everything picked: taps add to (or take from) its
// list of picks, as they did when it was made. (They did nothing: the four
// bolts left out of a Subtract couldn't be added without tapping its slot first.)
if (this.active < 0) this.active = this.slots.reduce((last, s, i) => (s.multi ? i : last), -1);
this.render();
this.update();
this.app.ui.focusPanel();
this.steps = [JSON.stringify(this.feature)];
this.redos = [];
window.addEventListener("pointerdown", this.onDown, true);
window.addEventListener("pointerup", this.onUp, true);
window.addEventListener("pointercancel", this.onUp, true);
}
// ---- Undo inside the tool
// Each change made while the tool is open - a drag of its handle, a value typed, an option chosen, something more
// picked - is a step of its own that Undo takes back, one at a time, and Redo puts back (asked for: "when I ...
// select a vertex and I move it around, and I hit undo, that undo should change the last modification, not go back
// to the extruding action or the one before entirely ... I want full history control"). Undo used to close the tool,
// throwing all of it away, and then take back the step before it as well. With nothing left to take back in the
// tool, Undo closes it (nothing made); the next Undo is the project's.
private steps: string[] = [];
private redos: string[] = [];
private held = false;
private settle = 0;
private restoring = false;
private onDown = (): void => void (this.held = true);
private onUp = (): void => {
this.held = false;
// (After the tool's own handlers for this lift have run.)
window.setTimeout(() => this.record(), 0);
};
/** What the draft is now, as a step - if it differs from the last one. */
private record(): void {
if (this.restoring || !this.steps.length) return;
const now = JSON.stringify(this.feature);
if (now === this.steps[this.steps.length - 1]) return;
this.steps.push(now);
if (this.steps.length > 100) this.steps.shift();
this.redos = [];
(this.app as AppContext & { refreshUndo?(): void }).refreshUndo?.();
}
/** The draft changed: a step once the drag ends, or once typing stops for a moment (digit by digit is one step). */
private noteChange(): void {
if (this.restoring || this.held) return;
clearTimeout(this.settle);
this.settle = window.setTimeout(() => this.record(), 450);
}
/** The draft put back to a step (in place: the window's parts and the handles hold on to it). */
private restore(step: string): void {
this.restoring = true;
try {
const f = this.feature as unknown as Record<string, unknown>;
for (const k of Object.keys(f)) delete f[k];
Object.assign(f, JSON.parse(step));
this.restored();
this.render();
this.update();
} finally {
this.restoring = false;
}
}
/** After Undo / Redo put the draft back: for a tool that keeps something beside the draft in step with it. */
protected restored(): void {}
get canUndo(): boolean {
return true;
}
get canRedo(): boolean {
return this.redos.length > 0;
}
undo(): boolean {
clearTimeout(this.settle);
this.record();
if (this.steps.length < 2) {
this.cancel();
return true;
}
this.redos.push(this.steps.pop()!);
this.restore(this.steps[this.steps.length - 1]);
return true;
}
redo(): boolean {
const next = this.redos.pop();
if (!next) return false;
this.steps.push(next);
this.restore(next);
return true;
}
exit(): void {
clearTimeout(this.settle);
window.removeEventListener("pointerdown", this.onDown, true);
window.removeEventListener("pointerup", this.onUp, true);
window.removeEventListener("pointercancel", this.onUp, true);
this.app.view.setOriginPlanesVisible(false);
this.app.ui.showPanel(null);
this.app.ui.setHint(null);
@@ -142,13 +236,23 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
return true;
}
/** A tap on a body the step waiting can't use (a mirror's plane, a ball tapped): true if the tool took it some other way. */
protected otherBody(_body: string): boolean {
return false;
}
/** After regionTap changed the profile (e.g. Extrude moves its arrow). */
protected regionsChanged(): void {}
tap(p: ToolPointer): void {
const slot = this.slots[this.active];
const h = this.lastHover;
const hit = h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6 ? h.hit : this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}) });
let hit = h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6 ? h.hit : this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}) });
// Not what this step is making (its preview): what's under it. (A Fill's
// last boundary curve, tapped once the loop closed, took the edge of the
// surface just made on it instead.)
const mine = (b: string) => b === this.feature.id || b.startsWith(`${this.feature.id}:`);
if (hit && "body" in hit && hit.body && mine(hit.body)) hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}), bodies: false });
if (this.moreRegions && (!slot || !hit || hit.kind === "plane" || hit.kind === "profile") && this.regionTap(p)) return;
// Tapping empty space ends the tool: keep the result if it's complete.
if (!hit) {
@@ -157,8 +261,12 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
return;
}
if (!slot) return;
if (!slot.accept(hit)) {
// Not this one - but another body's face in the same place is (the bolts
// flush with the flange they're to cut: the flange came first every time).
const body = "body" in hit ? hit.body : null;
if (!slot.accept(hit) && !(body && this.app.view.facesAt(p.x, p.y).some((f) => f.kind === "face" && f.body !== body && slot.accept(f)))) {
if (this.moreRegions && this.regionTap(p)) return;
if (body && !mine(body) && this.otherBody(body)) return;
if (slot.rejectHint) this.app.ui.toast(slot.rejectHint);
return;
}
@@ -168,6 +276,24 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
this.update();
}
/**
* A body tapped in Items: the slot waiting takes it, as a tap on it in the
* view would. (Six pegs inside a pulley's web, to subtract, can't be tapped
* there - and the tap in Items put Subtract away and selected the body.)
*/
pickBody(id: string): boolean {
const slot = this.slots[this.active];
if (!slot || !slot.accept({ kind: "body", body: id, point: [0, 0, 0] } as unknown as PickHit)) return false;
if (!slot.multi) this.active = this.slots.findIndex((s, i) => i > this.active && !s.filled());
this.render();
if (this.finishWhenPicked && this.ready()) {
void this.finishIfOk();
return true;
}
this.update();
return true;
}
/** Nothing left to set once the picks are made (e.g. Replace Face): the last pick finishes. */
protected finishWhenPicked = false;
@@ -184,9 +310,15 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
this.done();
}
/** Right-click: back out of the tool (like Esc). */
context(): void {
this.cancel();
/**
* Right-click: Done and Cancel (and the view's switches) by the pointer -
* a stray right-click no longer throws the tool's work away.
*/
context(p: ToolPointer): void {
viewMenu(this.app, p.x, p.y, [
{ label: "Done", shortcut: "Enter", disabled: !this.ready() || !!this.error, run: () => this.done() },
{ label: "Cancel", shortcut: "Esc", run: () => this.cancel() },
]);
}
key(e: KeyboardEvent): boolean {
@@ -206,6 +338,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
]);
this.app.ui.showPanel({
title: this.feature.name,
beta: BETA_TYPES.has(this.feature.type),
items: [...slotItems, ...this.items()],
actions: this.actions(),
onDone: () => this.done(),
@@ -225,25 +358,60 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
this.app.setSelection(this.slots.flatMap((s) => s.shows?.() ?? []));
}
private setHint(): void {
protected setHint(): void {
const slot = this.slots[this.active];
const text = this.error ? `⚠ ${this.error}` : slot && !slot.filled() ? `${slot.label}: ${slot.describe()}` : this.hint();
this.app.ui.setHint(text);
this.app.ui.setPanelWarning(this.error);
}
/**
* What the last preview asked for was: a drag snaps its value to steps and
* asks again on every pointer move - the same draft on the same project is
* on screen already (or on its way), not rebuilt and shown again.
*/
private asked: { key: string; base: readonly Feature[]; pending: boolean; result: unknown } | null = null;
/** Re-run the preview with the current draft. */
protected update(): void {
this.onDraftChanged();
if (!this.ready()) {
this.app.preview([...this.app.store.features]);
this.noteChange();
const ready = this.ready();
const base = this.app.store.features;
// (The steps that aren't the project's own: the draft, or what a tool puts in its place.)
const list = ready ? this.featuresWith() : null;
const own = new Set(base);
const key = list ? JSON.stringify(list.filter((f) => !own.has(f))) : "";
const was = this.asked;
if (was && was.key === key && was.base === base && (was.pending || was.result === this.app.result)) return;
const mine = { key, base, pending: true, result: null as unknown };
this.asked = mine;
const shown = (r: unknown) => {
mine.pending = false;
mine.result = r;
// Overtaken by something else's rebuild: asked again next time.
if (!r && this.asked === mine) this.asked = null;
};
if (!ready) {
void this.app.preview([...base]).then(shown);
return;
}
this.app.preview(this.featuresWith()).then((r) => {
this.app.preview(list!).then((r) => {
shown(r);
this.error = r?.errors.find((e) => e.featureId === this.feature.id)?.message ?? null;
this.setHint();
// What the step notes about itself (it cut where Add may have been
// meant, a piece left off): said while it's being made, not only on
// its History row, out of sight on a phone. Once per new note.
const note = r ? (r.notes?.find((n) => n.featureId === this.feature.id)?.message ?? null) : this.noted;
if (note && note !== this.noted && !this.error) this.app.ui.toast(note);
this.noted = note;
});
}
/** The note the last preview had for this step (said once). */
private noted: string | null = null;
/** Hook for handles etc. */
protected onDraftChanged(): void {}
@@ -261,12 +429,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
min: opts.min,
expr: f.exprs?.[path],
inBox: opts.inBox,
onExpr: (expr) => {
const exprs = { ...(f.exprs ?? {}) };
if (expr) exprs[path] = expr;
else delete exprs[path];
f.exprs = Object.keys(exprs).length ? exprs : undefined;
},
onExpr: (expr) => this.setExpr(path, expr),
onInput: (v) => {
setPath(f, path, v);
if (opts.onInput) opts.onInput(v);
@@ -279,6 +442,15 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
* Text typed into a value box at the model: a formula with variables keeps
* the value linked to them (as the panel's field does); a plain number unlinks it.
*/
/** The value at `path` follows this formula (null: just a number). */
protected setExpr(path: string, expr: string | null): void {
const f = this.feature as Feature;
const exprs = { ...(f.exprs ?? {}) };
if (expr) exprs[path] = expr;
else delete exprs[path];
f.exprs = Object.keys(exprs).length ? exprs : undefined;
}
protected typedInto(path: string, text: string, wrap: (t: string) => string = (t) => t): void {
const f = this.feature as Feature;
const exprs = { ...(f.exprs ?? {}) };
@@ -335,9 +507,31 @@ function allRegionsUsed(app: AppContext, sketch: string, features: Feature[]): b
if (r) used.push(r);
}
};
// A full turn's axis in the sketch: what's drawn across it (a whole circle
// for a ball, its lower half never picked) is in the solid too.
const mirrors: ((q: Vec2) => Vec2)[] = [];
const pl = app.sketchPlane(sketch);
for (const g of features) {
if (g.type === "extrude" || g.type === "revolve" || g.type === "sweep") add(g.source);
else if (g.type === "loft") g.sections.forEach(add);
if (g.type === "revolve" && pl && Math.abs(g.angle) >= 360 - 1e-9 && g.source.kind === "profile" && g.source.sketch === sketch) {
const n = pl.normal;
const y: [number, number, number] = [n[1] * pl.xDir[2] - n[2] * pl.xDir[1], n[2] * pl.xDir[0] - n[0] * pl.xDir[2], n[0] * pl.xDir[1] - n[1] * pl.xDir[0]];
const d3 = g.axis.dir;
const dl = Math.hypot(d3[0], d3[1], d3[2]) || 1;
const off = (d3[0] * n[0] + d3[1] * n[1] + d3[2] * n[2]) / dl;
const rel = [g.axis.origin[0] - pl.origin[0], g.axis.origin[1] - pl.origin[1], g.axis.origin[2] - pl.origin[2]];
if (Math.abs(off) > 1e-9 || Math.abs(rel[0] * n[0] + rel[1] * n[1] + rel[2] * n[2]) > 1e-6) continue;
const dot2 = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const o: Vec2 = [dot2(rel, pl.xDir), dot2(rel, y)];
const du = dot2(d3, pl.xDir) / dl;
const dv = dot2(d3, y) / dl;
mirrors.push((q) => {
const t = (q[0] - o[0]) * du + (q[1] - o[1]) * dv;
const f: Vec2 = [o[0] + t * du, o[1] + t * dv];
return [2 * f[0] - q[0], 2 * f[1] - q[1]];
});
}
}
// Every shape drawn has been made into something. (Matched shape by shape,
// not piece by piece: where the drawing meets an edge in its plane - the
@@ -346,14 +540,16 @@ function allRegionsUsed(app: AppContext, sketch: string, features: Feature[]): b
// use; the sketch stayed in view and its face-wide region took every later
// tap on that face.)
const inside = (m: Region, q: Vec2) => pointInPoly(q, m.outer.poly) && !m.holes.some((h) => pointInPoly(q, h.poly));
return drawn.every((m) => used.some((r) => inside(m, pointInRegion(r))));
const covered = (m: Region) => used.some((r) => inside(m, pointInRegion(r)));
const turnedIn = (m: Region) => mirrors.some((mir) => used.some((r) => inside(r, mir(pointInRegion(m)))));
return drawn.every((m) => covered(m) || turnedIn(m));
} catch {
return true;
}
}
/** The sketches an extrude / revolve / sweep / loft was made from. */
function sketchesUsed(f: Feature): string[] {
export function sketchesUsed(f: Feature): string[] {
const of = (s: ExtrudeSource) => (s.kind === "profile" ? [s.sketch] : []);
switch (f.type) {
case "extrude":
@@ -363,6 +559,8 @@ function sketchesUsed(f: Feature): string[] {
return [...of(f.source), ...(f.path.kind === "sketch" ? [f.path.sketch] : [])];
case "loft":
return f.sections.flatMap(of);
case "fill":
return [...f.boundary, ...(f.guides ?? [])].flatMap((p) => (p.kind === "sketch" ? [p.sketch] : []));
default:
return [];
}
+576 -77
View File
File diff suppressed because it is too large Load Diff
+202
View File
@@ -0,0 +1,202 @@
// A look ahead, drawn on the model in dashed yellow: what a tool would do to
// what is picked, shown while the pointer is over the tool (before anything
// is started) - a face's outline lifted for Extrude, the lines a round would
// run between for Fillet, a row of boxes for a pattern. Nothing is computed
// by the kernel for it: it is a sketch of the change, from what the view
// already has, so it comes up at once.
import { BufferGeometry, Float32BufferAttribute, LineDashedMaterial, LineSegments } from "three";
import type { Vec3 } from "../doc/types";
import { add, cross, dot, len, norm, scale, sub, toWorld } from "../geom";
import { entityPolylines } from "../sketch/curves";
import type { Viewport } from "../view/viewport";
import { edgesOfFace, sourceFrame, sourcesOf, type AppContext, type Sel } from "./tool";
const YELLOW = 0xffd23a;
/** Line segments (pairs of points, flat) in dashed yellow, over everything. Dashes keep their size on screen. */
export class Ghost {
private mat = new LineDashedMaterial({ color: YELLOW, depthTest: false, transparent: true, opacity: 0.95, dashSize: 1, gapSize: 1 });
private line = new LineSegments(new BufferGeometry(), this.mat);
private wpp = 0;
private onFrame = () => this.dashes();
constructor(private view: Viewport, segs: number[]) {
this.line.renderOrder = 48;
this.line.frustumCulled = false;
this.line.geometry.setAttribute("position", new Float32BufferAttribute(segs, 3));
this.line.computeLineDistances();
this.dashes();
view.overlay.add(this.line);
view.frameHooks.add(this.onFrame);
view.helpers.add(this);
view.requestRender();
}
private dashes(): void {
const w = this.view.cam.worldPerPixel(this.view.height);
if (Math.abs(w - this.wpp) < this.wpp * 0.02) return;
this.wpp = w;
this.mat.dashSize = w * 7;
this.mat.gapSize = w * 5;
}
dispose(): void {
this.view.helpers.delete(this);
this.view.frameHooks.delete(this.onFrame);
this.view.overlay.remove(this.line);
this.line.geometry.dispose();
this.mat.dispose();
this.view.requestRender();
}
}
type Segs = number[];
const seg = (out: Segs, a: Vec3, b: Vec3) => void out.push(a[0], a[1], a[2], b[0], b[1], b[2]);
const moved = (segs: Segs, v: Vec3): Segs => segs.map((x, i) => x + v[i % 3]);
/** The outline of a body's face, as the view drew its edges. */
function faceOutline(app: AppContext, body: string, face: number): Segs {
const m = app.view.body(body);
if (!m) return [];
const out: Segs = [];
const of = new Set(edgesOfFace(app, body, face));
for (const g of m.edgeGroups) if (of.has(g.edge)) for (let j = g.start * 3; j < (g.start + g.count) * 3; j++) out.push(m.edgePositions[j]);
return out;
}
/** The box round some bodies: its twelve edges, and its middle. */
export function bodiesBox(app: AppContext, ids: string[]): { lo: Vec3; hi: Vec3; mid: Vec3; segs: Segs } | null {
const lo: Vec3 = [Infinity, Infinity, Infinity];
const hi: Vec3 = [-Infinity, -Infinity, -Infinity];
for (const id of ids) {
const p = app.view.body(id)?.positions;
if (!p) continue;
for (let i = 0; i < p.length; i++) {
const k = i % 3;
if (p[i] < lo[k]) lo[k] = p[i];
if (p[i] > hi[k]) hi[k] = p[i];
}
}
if (!Number.isFinite(lo[0])) return null;
const c = (i: number): Vec3 => [i & 1 ? hi[0] : lo[0], i & 2 ? hi[1] : lo[1], i & 4 ? hi[2] : lo[2]];
const segs: Segs = [];
for (const [a, b] of [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]]) seg(segs, c(a), c(b));
return { lo, hi, mid: scale(add(lo, hi), 0.5), segs };
}
/** A row of copies: the bodies' box again and again along `dir`, and the line they go along. */
export function rowGhost(app: AppContext, ids: string[], dir: Vec3, spacing: number, count: number): Segs {
const box = bodiesBox(app, ids);
if (!box) return [];
const d = norm(dir);
const out: Segs = [];
for (let k = 1; k < count; k++) out.push(...moved(box.segs, scale(d, spacing * k)));
seg(out, box.mid, add(box.mid, scale(d, spacing * (count - 1))));
return out;
}
/** A ring of copies: the bodies' box turned about the axis, and the circle its middle goes round. */
export function ringGhost(app: AppContext, ids: string[], axis: { origin: Vec3; dir: Vec3 }, angle: number, count: number): Segs {
const box = bodiesBox(app, ids);
if (!box) return [];
const d = norm(axis.dir);
const turn = (p: Vec3, deg: number): Vec3 => {
const a = (deg * Math.PI) / 180;
const v = sub(p, axis.origin);
const along = scale(d, dot(v, d));
const flat = sub(v, along);
return add(axis.origin, add(along, add(scale(flat, Math.cos(a)), scale(cross(d, flat), Math.sin(a)))));
};
const full = Math.abs(Math.abs(angle) - 360) < 1e-6;
const step = angle / (full ? count : Math.max(1, count - 1));
const out: Segs = [];
for (let k = 1; k < count; k++) for (let i = 0; i < box.segs.length; i += 3) out.push(...turn([box.segs[i], box.segs[i + 1], box.segs[i + 2]], step * k));
// (The circle: only where the bodies are off the axis.)
if (len(sub(box.mid, turn(box.mid, 180))) > 1e-6) for (let k = 0; k < 48; k++) seg(out, turn(box.mid, (angle * k) / 48), turn(box.mid, (angle * (k + 1)) / 48));
return out;
}
/**
* What the tool `id` would do to what is picked, as dashed lines - or nothing,
* where there is no telling picture of it (most tools: those say what they do
* by name).
*/
export function peekSegs(app: AppContext, id: string, sel: Sel[]): Segs {
const s = sel[0];
if (!s) return [];
const out: Segs = [];
if (s.kind === "face" && (id === "extrude" || id === "offsetFace" || id === "offset" || id === "shell" || id === "thicken")) {
const f = app.view.body(s.body)?.faces[s.face];
if (!f) return [];
const outline = faceOutline(app, s.body, s.face);
// (Out by about a third of the face's size; Shell: in, by a wall.)
const d = Math.sqrt(f.area) * (id === "shell" ? -0.12 : 0.35);
const v = scale(f.normal, d);
out.push(...moved(outline, v));
// (Up from the outline's corners - every few points of a round one.)
const stride = Math.max(1, Math.floor(outline.length / 6 / 12));
for (let i = 0; i < outline.length; i += 6 * stride) seg(out, [outline[i], outline[i + 1], outline[i + 2]], add([outline[i], outline[i + 1], outline[i + 2]], v));
return out;
}
if (s.kind === "profile" && (id === "extrude" || id === "revolve")) {
if (id !== "extrude") return [];
const src = sourcesOf(app, sel)[0];
const plane = app.sketchPlane(s.sketch);
if (!src || !plane) return [];
const fr = sourceFrame(app, src);
const flat: Segs = [];
for (const e of app.sketchCurves(s.sketch)) {
if (e.construction) continue;
for (const poly of entityPolylines(e)) for (let i = 0; i + 1 < poly.length; i++) seg(flat, toWorld(plane, poly[i]), toWorld(plane, poly[i + 1]));
}
let size = 0;
for (let i = 0; i < flat.length; i += 3) size = Math.max(size, len(sub([flat[i], flat[i + 1], flat[i + 2]], fr.base)));
const v = scale(fr.normal, Math.max(size * 0.6, 1e-3));
out.push(...moved(flat, v));
const stride = Math.max(1, Math.floor(flat.length / 6 / 12));
for (let i = 0; i < flat.length; i += 6 * stride) seg(out, [flat[i], flat[i + 1], flat[i + 2]], add([flat[i], flat[i + 1], flat[i + 2]], v));
return out;
}
if (s.kind === "edge" && (id === "fillet" || id === "chamfer")) {
const m = app.view.body(s.body);
if (!m || m.faces.length > 400) return [];
for (const one of sel) {
if (one.kind !== "edge" || one.body !== s.body) continue;
const e = m.edges[one.edge];
if (!e || e.type !== "LINE") continue;
// The two flat faces the edge is between, and the way into each from the edge.
const into: Vec3[] = [];
for (let f = 0; f < m.faces.length && into.length < 2; f++) {
const face = m.faces[f];
if (!face.plane || Math.abs(dot(face.normal, e.dir)) > 1e-3 || Math.abs(dot(sub(e.mid, face.center), face.normal)) > 1e-4) continue;
if (!edgesOfFace(app, s.body, f).includes(one.edge)) continue;
const side = norm(cross(face.normal, e.dir));
into.push(dot(side, sub(face.center, e.mid)) < 0 ? scale(side, -1) : side);
}
if (into.length < 2) continue;
const r = Math.min(e.length * 0.25, Math.sqrt(Math.min(...m.faces.map((x) => x.area))) * 0.5);
const a = (p: Vec3) => add(p, scale(into[0], r));
const b = (p: Vec3) => add(p, scale(into[1], r));
seg(out, a(e.start), a(e.end));
seg(out, b(e.start), b(e.end));
for (const p of [e.start, e.end]) {
if (id === "chamfer") seg(out, a(p), b(p));
else {
// (The round's end: from one line to the other, bowed towards the edge.)
const q = (t: number): Vec3 => add(add(scale(a(p), (1 - t) * (1 - t)), scale(p, 2 * t * (1 - t) * 0.83 + 0)), add(scale(add(a(p), b(p)), t * (1 - t) * 0.17), scale(b(p), t * t)));
for (let k = 0; k < 8; k++) seg(out, q(k / 8), q((k + 1) / 8));
}
}
}
return out;
}
if (s.kind === "body" && (id === "patl" || id === "patc")) {
const ids = sel.flatMap((x) => (x.kind === "body" ? [x.body] : []));
const box = bodiesBox(app, ids);
if (!box) return [];
if (id === "patl") return rowGhost(app, ids, [1, 0, 0], (box.hi[0] - box.lo[0]) * 1.5 || 10, 3);
return ringGhost(app, ids, { origin: [0, 0, 0], dir: [0, 0, 1] }, 360, 6);
}
return out;
}
+39 -9
View File
@@ -8,7 +8,11 @@ import type { ToolPointer } from "../view/input";
// Amber, so a handle never disappears against the blue of a selection.
const COLOR = 0xffa31a;
const HOT = 0xffd27a;
const ARROW_PX = 84;
// (Slim and short: a line with a dark edge under it, so it reads over a lit face and over the grid alike, and a
// head sized for a finger whatever the arrow's length.)
const ARROW_PX = 64;
const HEAD_PX = 70;
const EDGE = 0x15171b;
/**
* A drag handle drawn at constant screen size: an arrow along a direction, or a
@@ -23,16 +27,26 @@ export class Handle {
private mat = new MeshBasicMaterial({ color: COLOR, depthTest: false, transparent: true });
private head: Mesh;
private shaft: LineSegments2 | null = null;
/** The dark edge under the shaft. */
private under: LineSegments2 | null = null;
private underMat: ReturnType<Viewport["lineMaterial"]> | null = null;
private lineMat;
private onFrame = () => this.layout();
constructor(private view: Viewport, readonly shape: "arrow" | "dot") {
this.lineMat = view.lineMaterial(COLOR, 4);
/** `px`: how long an arrow is on screen (a pair back to back - a double arrow - is drawn shorter). */
constructor(private view: Viewport, readonly shape: "arrow" | "dot", private px = ARROW_PX) {
this.lineMat = view.lineMaterial(COLOR, 3);
this.lineMat.transparent = true;
this.head = new Mesh(shape === "arrow" ? new ConeGeometry(0.11, 0.3, 20) : new SphereGeometry(0.12, 20, 12), this.mat);
this.head = new Mesh(shape === "arrow" ? new ConeGeometry(0.095, 0.3, 24) : new SphereGeometry(0.1, 20, 12), this.mat);
this.head.renderOrder = 50;
this.group.add(this.head);
if (shape === "arrow") {
this.underMat = view.lineMaterial(EDGE, 6);
this.underMat.transparent = true;
this.underMat.opacity = 0.55;
this.under = new LineSegments2(new LineSegmentsGeometry(), this.underMat);
this.under.renderOrder = 49;
this.group.add(this.under);
this.shaft = new LineSegments2(new LineSegmentsGeometry(), this.lineMat);
this.shaft.renderOrder = 50;
this.group.add(this.shaft);
@@ -51,7 +65,7 @@ export class Handle {
this.mat.color.setHex(on ? HOT : COLOR);
if (this.shaft) {
this.view.releaseLineMaterial(this.lineMat);
this.lineMat = this.view.lineMaterial(on ? HOT : COLOR, on ? 6 : 4);
this.lineMat = this.view.lineMaterial(on ? HOT : COLOR, on ? 4.5 : 3);
this.lineMat.transparent = true;
this.shaft.material = this.lineMat;
}
@@ -71,7 +85,15 @@ export class Handle {
return this.view.toScreen(this.tip());
}
/** Shown or not (a hidden one can't be grabbed). */
setVisible(on: boolean): void {
if (this.group.visible === on) return;
this.group.visible = on;
this.view.requestRender();
}
hit(p: ToolPointer): boolean {
if (!this.group.visible) return false;
const s = this.grabPoint();
return !!s && Math.hypot(s[0] - p.x, s[1] - p.y) < Math.max(30, p.tol * 1.8);
}
@@ -82,16 +104,18 @@ export class Handle {
this.view.overlay.remove(this.group);
this.head.geometry.dispose();
this.shaft?.geometry.dispose();
this.under?.geometry.dispose();
if (this.underMat) this.view.releaseLineMaterial(this.underMat);
this.view.releaseLineMaterial(this.lineMat);
this.view.requestRender();
}
private size(): number {
return this.view.cam.worldPerPixel(this.view.height) * ARROW_PX;
return this.view.cam.worldPerPixel(this.view.height) * this.px;
}
private headScale(): number {
return this.size() * (this.hot ? 1.45 : 1);
return this.view.cam.worldPerPixel(this.view.height) * HEAD_PX * (this.hot ? 1.3 : 1);
}
private tip(): Vector3 {
@@ -105,8 +129,14 @@ export class Handle {
const tip = this.tip();
this.head.position.copy(tip);
this.head.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), this.dir);
const start = this.base.clone().addScaledVector(this.dir, s * 0.12);
(this.shaft!.geometry as LineSegmentsGeometry).setPositions([...start.toArray(), ...tip.toArray()]);
// (From a little off its foot to the head's base; the head's point is the arrow's tip.)
const h = this.headScale() * 0.3;
this.head.position.copy(tip).addScaledVector(this.dir, -h / 2);
const start = this.base.clone().addScaledVector(this.dir, Math.min(s * 0.12, Math.max(0, s - h)));
const end = this.base.clone().addScaledVector(this.dir, Math.max(0, s - h));
const at = [...start.toArray(), ...end.toArray()];
(this.shaft!.geometry as LineSegmentsGeometry).setPositions(at);
(this.under!.geometry as LineSegmentsGeometry).setPositions(at);
} else {
this.head.position.copy(this.base);
}
+48 -3
View File
@@ -36,7 +36,7 @@ export class MeasureTool implements Tool {
this.app.ui.setTools([{ id: "exit", label: "Exit Measure", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) }]);
// The view tools stay, this one lit and pulsing (tap it again to close it).
this.app.ui.setBottom(this.app.bottomTools());
this.app.ui.setHint("Select objects to see their measurements. Double-tap for a whole body.");
this.app.ui.setHint("Tap faces, edges or points to see their sizes. Double-tap for a whole body.");
this.card = el("div", "measure-card");
document.body.append(this.card);
this.render();
@@ -154,7 +154,14 @@ export class MeasureTool implements Tool {
if (s.kind === "face") {
const f = b.faces[s.face];
const pts = facePoints(b, s.face);
const rows = [{ name: `Surface area · ${niceType(f.type)}`, value: fmtArea(f.area), at: f.center }];
const rows: Row[] = [{ name: `Surface area · ${niceType(f.type)}`, value: fmtArea(f.area), at: f.center }];
// A round face (a shaft, a hole): its diameter, pinned as a line straight across it.
if (f.round) {
const r = f.round.r;
const across = acrossCylinder(b, s.face, r, f.round.hole, f.center);
rows.push({ name: f.round.hole ? "Diameter · hole" : "Diameter", value: `Ø ${fmtLen(2 * r)}`, at: across?.mid ?? f.center, ...(across ? { a: across.a, b: across.b } : {}) });
rows.push({ name: "Radius", value: `R ${fmtLen(r)}`, at: across?.b ?? f.center, ...(across ? { a: across.mid, b: across.b } : {}) });
}
return { rows, anchor: f.center, points: pts, dir: f.plane ? f.normal : undefined };
}
if (s.kind === "edge") {
@@ -211,6 +218,44 @@ function edgePoints(b: BodyMesh, edge: number): Vec3[] {
return out;
}
/**
* A line straight across a round face, through its axis, level with the
* middle of the face: its ends on the surface (null where the face's own
* normals can't tell the axis).
*/
function acrossCylinder(b: BodyMesh, face: number, r: number, hole: boolean, center: Vec3): { a: Vec3; b: Vec3; mid: Vec3 } | null {
const g = b.faceGroups.find((x) => x.face === face);
if (!g || !g.count) return null;
const at = (i: number): { p: Vec3; n: Vec3 } => {
const v = b.indices[i] * 3;
return { p: [b.positions[v], b.positions[v + 1], b.positions[v + 2]], n: [b.normals[v], b.normals[v + 1], b.normals[v + 2]] };
};
const first = at(g.start);
// The surface's normals all stand square to the axis: two far apart give it.
let axis: Vec3 | null = null;
let best = 0.2;
for (let i = g.start; i < g.start + g.count; i++) {
const c = cross(first.n, at(i).n);
const l = len(c);
if (l > best) {
best = l;
axis = [c[0] / l, c[1] / l, c[2] / l];
}
}
if (!axis) return null;
// (A hole's surface faces its axis, a shaft's away from it.)
const k = hole ? r : -r;
const onAxis: Vec3 = [first.p[0] + first.n[0] * k, first.p[1] + first.n[1] * k, first.p[2] + first.n[2] * k];
const t = dot(sub(center, onAxis), axis);
const mid: Vec3 = [onAxis[0] + axis[0] * t, onAxis[1] + axis[1] * t, onAxis[2] + axis[2] * t];
const side = dot(first.n, axis);
const u0: Vec3 = [first.n[0] - axis[0] * side, first.n[1] - axis[1] * side, first.n[2] - axis[2] * side];
const ul = len(u0);
if (ul < 1e-9) return null;
const u: Vec3 = [u0[0] / ul, u0[1] / ul, u0[2] / ul];
return { a: [mid[0] - u[0] * r, mid[1] - u[1] * r, mid[2] - u[2] * r], b: [mid[0] + u[0] * r, mid[1] + u[1] * r, mid[2] + u[2] * r], mid };
}
function closestPair(a: Vec3[], b: Vec3[]): { d: number; p: Vec3; q: Vec3 } {
let best = { d: Infinity, p: a[0], q: b[0] };
const step = (n: number) => Math.max(1, Math.floor(n / 600));
@@ -255,5 +300,5 @@ function fmtVolume(mm3: number): string {
}
function niceType(t: string): string {
return t.toLowerCase().replace(/_/g, " ").replace("bspline", "free-form");
return t.toLowerCase().replace(/_/g, " ").replace("bspline", "free-form").replace("cylindre", "cylinder");
}
+117 -2
View File
@@ -7,9 +7,14 @@
import type { PlaneDef, SketchFeature, Vec3 } from "../doc/types";
import type { BodyMesh } from "../kernel/protocol";
import { len, roundSig, sub } from "../geom";
import { add, dot, len, niceStep, norm, roundSig, scale, sub } from "../geom";
import type { PanelItem } from "../ui/ui";
import { fmtLen } from "../units";
import type { ToolPointer } from "../view/input";
import { DimWidget } from "./annotate";
import { DragTyping } from "./dragTyping";
import { FeatureOp, type Slot } from "./featureOp";
import { axisDrag, Handle } from "./handles";
import { offsetLineOnFace } from "./offsetEdgeGeom";
import { faceRefOf, type AppContext, type Sel } from "./tool";
@@ -36,6 +41,13 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
private typed = false;
/** Why there's no line (the edge across the face, the line off it). */
private problem: string | null = null;
/** The line as it is now, in the world (the arrow sits on its middle). */
private line: { a: Vec3; b: Vec3 } | null = null;
/** A double arrow on the line, dragged to set how far from the edge it runs; the distance in a box beside it. */
private arrows: [Handle, Handle] | null = null;
private dim: DimWidget | null = null;
private dragging: { from: ToolPointer; d0: number; foot: Vec3; out: Vec3 } | null = null;
private typing = new DragTyping(this.app);
/** Started from an edge (Offset Edge) or from the face (Offset from Edge): the other is tapped next. */
constructor(app: AppContext, start?: { body: string; edge: number }, onFace?: { body: string; face: number }) {
@@ -95,6 +107,7 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
/** The line from the picks and the distance, into the sketch. */
private sync(): void {
this.problem = null;
this.line = null;
if (!this.edge || !this.face) return;
const l = offsetLineOnFace(this.face.body, this.face.face, this.face.plane, this.edge.start, this.edge.end, this.distance);
if (typeof l === "string") {
@@ -103,6 +116,107 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
return;
}
this.feature.entities = [{ id: "offset", kind: "line", a: l.a2, b: l.b2 }];
this.line = { a: l.a, b: l.b };
}
/**
* Where the line's middle is measured from on the edge, and the way a
* bigger distance goes (across the face, away from the edge).
*/
private frame(): { foot: Vec3; out: Vec3 } | null {
if (!this.edge || !this.face || !this.line) return null;
const n = norm(this.face.plane.normal);
const flat = (p: Vec3): Vec3 => sub(p, scale(n, dot(sub(p, this.face!.plane.origin), n)));
const e0 = flat(this.edge.start);
const along = norm(sub(flat(this.edge.end), e0));
const mid = scale(add(this.line.a, this.line.b), 0.5);
const foot = add(e0, scale(along, dot(sub(mid, e0), along)));
const w = sub(mid, foot);
if (len(w) < 1e-9 || !this.distance) return null;
return { foot, out: scale(norm(w), Math.sign(this.distance)) };
}
private setDistance(v: number): void {
this.typed = true;
this.distance = v;
this.sync();
this.app.ui.updatePanelValues([v]);
this.dim?.setValue(v);
this.update();
}
/** The double arrow and the value box come up once there is a line. */
protected onDraftChanged(): void {
const fr = this.dragging ?? this.frame();
if (!fr || !this.line) {
// (Dragged off the face: they stay where they were, to drag back.)
if (!this.dragging) this.dropGrip();
return;
}
if (!this.arrows) {
this.arrows = [new Handle(this.app.view, "arrow", 34), new Handle(this.app.view, "arrow", 34)];
this.dim = new DimWidget(this.app.view, { boxAt: "beyond", boxGap: 96, dir: fr.out, value: this.distance, onInput: (v) => this.setDistance(v), onCommit: () => this.done() });
}
const mid = scale(add(this.line.a, this.line.b), 0.5);
this.arrows[0].set(mid, fr.out);
this.arrows[1].set(mid, scale(fr.out, -1));
this.dim!.set(fr.foot, mid);
this.dim!.setValue(this.distance);
}
private dropGrip(): void {
this.arrows?.forEach((h) => h.dispose());
this.arrows = null;
this.dim?.dispose();
this.dim = null;
}
exit(): void {
this.dropGrip();
super.exit();
}
hover(p: ToolPointer | null): void {
const on = !!p && !!this.arrows && (!!this.dragging || this.arrows.some((h) => h.hit(p)));
this.arrows?.forEach((h) => h.setHot(on));
if (!on) super.hover(p);
}
down(p: ToolPointer): boolean {
const fr = this.frame();
if (!fr || !this.arrows?.some((h) => h.hit(p))) return false;
this.dragging = { from: p, d0: this.distance, ...fr };
return true;
}
drag(p: ToolPointer): void {
const dr = this.dragging;
if (!dr) return;
this.typing.track(p);
if (this.typing.active) return;
const raw = dr.d0 + axisDrag(this.app.view, add(dr.foot, scale(dr.out, dr.d0)), dr.out, dr.from, p);
const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4);
this.setDistance(Math.round(raw / step) * step);
this.app.ui.setLabel(p.x, p.y, `${fmtLen(this.distance)} · type a value`);
}
up(): void {
this.dragging = null;
this.typing.reset();
this.app.ui.setLabel(0, 0, null);
this.arrows?.forEach((h) => h.setHot(false));
this.onDraftChanged();
}
dragKey(e: KeyboardEvent): boolean {
const dr = this.dragging;
if (!dr) return false;
return this.typing.key(e, {
kind: "length",
apply: (v) => this.setDistance(v),
commit: () => ((this.dragging = null), this.done()),
cancel: () => this.setDistance(dr.d0),
});
}
protected ready(): boolean {
@@ -120,6 +234,7 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
this.typed = true;
this.distance = v;
this.sync();
this.dim?.setValue(v);
this.update();
},
},
@@ -130,6 +245,6 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
if (this.problem) return `⚠ ${this.problem}`;
if (!this.edge) return this.face ? "Tap a straight edge: the line on this face runs alongside it." : "Tap a straight edge: the line runs alongside it.";
if (!this.face) return "Tap the flat face to draw the line on.";
return "The line runs across the face, edge to edge. Type the distance (below 0: the other side of the edge).";
return "The line runs across the face beside the edge. Drag the double arrow, or type, to set how far from the edge (negative: the other side).";
}
}
+1327 -80
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -5,6 +5,7 @@ import { Vector3 } from "three";
import type { Vec3 } from "../doc/types";
import { el } from "../ui/ui";
import { numpadInput } from "../ui/numpad";
import { selectAll } from "../ui/textField";
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
import type { Viewport } from "../view/viewport";
@@ -65,7 +66,7 @@ export class PatternBox {
document.body.append(this.box);
view.frameHooks.add(this.hook);
view.helpers.add(this);
setTimeout(() => (this.count.focus(), this.count.select()), 0);
setTimeout(() => (this.count.focus(), selectAll(this.count)), 0);
}
/** Where the box sits (a world point, e.g. the arrow's tip). */
+14 -9
View File
@@ -9,8 +9,7 @@
import { Vector3 } from "three";
import type { PlaneDef, PlaneFeature, PlaneKind, Vec3 } from "../doc/types";
import { add, cross, dot, len, norm, scale, sub, xDirFor } from "../geom";
import { entityPolylines } from "../sketch/curves";
import { sketchToWorld } from "../view/viewport";
import { entityWorldPolylines } from "../sketch/curves";
import type { PanelItem } from "../ui/ui";
import type { PickHit } from "../view/viewport";
import { FeatureOp, type Slot } from "./featureOp";
@@ -80,8 +79,9 @@ function curvePick(app: AppContext, hit: PickHit): CurvePick | null {
const plane = app.sketchPlane(hit.sketch);
const e = app.sketchCurves(hit.sketch).find((x) => x.id === hit.entity);
if (!plane || !e) return null;
for (const poly of entityPolylines(e)) {
const pts = poly.map((q) => sketchToWorld(plane, q).toArray() as Vec3);
// (Where the curve is in space: a spline with points off its plane is picked up there, and the plane put on it
// is square to it there - it was put on the curve's shadow, off the curve and askew to it.)
for (const pts of entityWorldPolylines(e, plane)) {
const near = nearestOnPolyline(pts, hit.point);
if (near) return { ...near, line: e.kind === "line" ? [pts[0], pts[pts.length - 1]] : undefined, sel: { kind: "curve", sketch: hit.sketch, entity: hit.entity } };
}
@@ -141,7 +141,7 @@ export class ThreePointPlaneOp extends PlaneFromPicks {
return { origin: a, normal: norm(n), xDir: norm(sub(b, a)) };
}
protected hint(): string {
return this.pts.every(Boolean) && !this.make() ? "⚠ The three points are on one line - pick another" : "Tap three points (corners, edge points, sketch points): the plane goes through all of them.";
return this.pts.every(Boolean) && !this.make() ? "⚠ The three points are on one line - pick another" : "Tap three points (corners, points on edges or in sketches): the plane goes through all three.";
}
}
@@ -157,7 +157,7 @@ export class CurvePointPlaneOp extends PlaneFromPicks {
return this.c && { origin: this.c.at, normal: this.c.tangent, xDir: xDirFor(this.c.tangent) };
}
protected hint(): string {
return this.edgesOnly ? "Tap an edge at the point where the plane should cross it (at right angles)." : "Tap a curve or edge where the plane should cross it: it stands across the curve there.";
return this.edgesOnly ? "Tap an edge where the plane should cross it, square to it." : "Tap a line or edge where the plane should cross it, square to it.";
}
}
@@ -166,12 +166,17 @@ export class EdgeAnglePlaneOp extends PlaneFromPicks {
private c: CurvePick | null = null;
private ref: PlaneDef | null = null;
private angle = 45;
constructor(app: AppContext) {
/** `edge`: the straight edge picked before (Plane – Through Edge on an edge). */
constructor(app: AppContext, edge?: { body: string; edge: number; point: Vec3 }) {
super(app, "Plane at Angle", "angle");
this.slots = [
curveSlot(app, "Edge (the plane turns about it)", () => this.c, (c) => ((this.c = c), this.sync()), true),
planeSlot(app, "From face or plane (0°)", () => this.ref, (p) => ((this.ref = p), this.sync())),
];
if (edge) {
const c = curvePick(app, { kind: "edge", ...edge });
if (c?.line) (this.c = c), this.sync();
}
}
protected make(): PlaneDef | null {
if (!this.c?.line) return null;
@@ -191,7 +196,7 @@ export class EdgeAnglePlaneOp extends PlaneFromPicks {
return [{ type: "number", label: "Angle", value: this.angle, kind: "angle", onInput: (v) => ((this.angle = v), this.sync(), this.update()) }];
}
protected hint(): string {
return "Tap a straight edge, then the face (or plane) the angle is measured from, and type the angle.";
return "Tap a straight edge, then the face to measure the angle from, then type the angle.";
}
}
@@ -208,6 +213,6 @@ export class FacePointPlaneOp extends PlaneFromPicks {
return this.ref && this.at ? { ...this.ref, origin: this.at } : null;
}
protected hint(): string {
return "Tap a face or plane, then the point the new plane goes through.";
return "Tap a face or plane to copy its direction, then the point the new plane goes through.";
}
}
+212
View File
@@ -0,0 +1,212 @@
// Quick actions: a short row of round buttons right beside whatever is
// picked - on the model a face, an edge, a point, a body, a sketch's shape, a
// plane, an axis, an image; in a sketch its curves and points - with the two
// tools most likely next for it (a flat face: Sketch, Move; a round one:
// Thread, Fillet; an edge: Chamfer, Move; a body: Fillet, Mirror; a sketch's
// curves: Construction, Delete). The most likely of all already has its handle
// on it (a face's arrow, an edge's fillet dot, a gimbal): these are the next
// ones. On the model the row ends with Delete and More, which opens every
// other tool the pick has (Shell among them); they are the very tools the line
// at the bottom offers for the pick (the same ToolItems).
import type { Vec3 } from "../doc/types";
import { icons } from "../ui/icons";
import type { ToolItem } from "../ui/ui";
import type { Viewport } from "../view/viewport";
import { clampToFree } from "./annotate";
/** By kind of pick: the tools to offer, best first (the first two there are and can be used now). */
export const QUICK = {
// (A freeform surface's face: Edit Freeform first - shaping it again is what it is for.)
face: ["editFreeform", "thread", "sketch", "move", "fillet", "thicken"],
// (Fillet first, before Chamfer - asked for: "when I select an edge, I also want the fillet tool icon ... before
// chamfer". Its dot is on the edge to drag as well.)
edge: ["fillet", "chamfer", "move", "thread", "connect"],
vertex: ["moveVertex", "delete"],
// (A body that is, or began as, a freeform: Edit Freeform first - asked for: "when I double click a freeform body,
// I want the edit freeform button there".)
body: ["editFreeform", "fillet", "mirror"],
profile: ["extrude", "revolve"],
plane: ["sketch", "plane"],
axis: ["delete"],
image: ["scale", "delete"],
// In a sketch: its picked curves and points (the sketch tool's own buttons).
curve: ["construction", "delete"],
point: ["delete"],
} satisfies Record<string, string[]>;
export type QuickKind = keyof typeof QUICK;
export interface QuickPlace {
/** The pick's outward normal (a face's, a shape's): they go the other way from its arrow on the screen. */
facing?: Vec3;
/** Turned away (seen from behind): hidden (a body's face; a sketch's shape is seen from both sides). */
hideBack?: boolean;
/** How far from the point (px): further for a gimbal round it. */
gap?: number;
}
/** At most this many: only the important things (the rest is under More at the row's end). */
const MOST = 2;
/**
* An edge has three: Fillet, Chamfer and Move/Rotate Edge (asked for: "if I select an edge I want the move and
* rotate edge icon there"). Move/Rotate Edge is for one straight edge: with a curved one, or several, it is not
* offered and the row is the two.
*/
const MOST_OF: Partial<Record<QuickKind, number>> = { edge: 3 };
export class QuickActions {
private readonly box = document.createElement("div");
private readonly hook = () => this.layout();
/** `items`: what the pick offers (the wheel's own list, its kinds' items too); `at`: the point it is shown beside. */
static show(view: Viewport, kind: QuickKind, items: ToolItem[], at: Vec3, place: QuickPlace = {}, all = false): QuickActions | null {
const byId = new Map<string, ToolItem>();
const walk = (its: ToolItem[]) => {
for (const it of its) {
if (!byId.has(it.id)) byId.set(it.id, it);
if (it.children?.length) walk(it.children);
}
};
walk(items);
const picked = (QUICK[kind] as readonly string[]).map((id) => byId.get(id)).filter((it): it is ToolItem => !!it && !it.disabled && !!it.run && (!it.beta || it.id === "editFreeform")).slice(0, MOST_OF[kind] ?? MOST);
if (!all) return picked.length ? new QuickActions(view, picked, at, place) : null;
// On the model: Delete beside them, and a last button that opens every other tool the pick has (asked for: "I
// also want to have other tools there that could be used on that element. And also delete"). The few most likely
// stay the row; the rest come up under it only when asked for, so nothing is crowded.
const usable = (it: ToolItem | undefined): it is ToolItem => !!it && !it.disabled && !!it.run;
const del = [byId.get("delete"), byId.get("deleteBody")].find(usable);
const row = del && !picked.includes(del) ? [...picked, del] : picked;
const rest: ToolItem[] = [];
// (Beside a corner, not Move/Rotate Body: it moves the whole body, which is not what a corner was picked for -
// asked for: "it doesn't make sense to be there". It is still under Transform on the line.)
const skip = new Set(["deselect", "reveal", "color", "opacity", "material", "wholePattern", ...(kind === "vertex" ? ["move"] : [])]);
const gather = (its: ToolItem[]) => {
for (const it of its) {
if (!it.label || it.id.startsWith("---") || skip.has(it.id) || it.disabled) continue;
// (A tool that starts by itself is one button, its kinds a tap further inside it; a bare group is its tools.)
if (it.run) {
if (!row.includes(it) && !rest.some((r) => r.label === it.label) && !row.some((r) => r.label === it.label)) rest.push(it);
} else if (it.children?.length) gather(it.children);
}
};
gather(items);
// (Just one more: it is a button of the row, before Delete - a More that opens a single button is a tap wasted.)
if (rest.length === 1) {
const one = rest.pop()!;
row.splice(del && row.includes(del) ? row.indexOf(del) : row.length, 0, one);
}
return row.length || rest.length ? new QuickActions(view, row, at, place, rest) : null;
}
/** These very buttons (a tool's own choices, the one in use lit), beside `at`. */
static of(view: Viewport, items: ToolItem[], at: Vec3, place: QuickPlace = {}): QuickActions {
return new QuickActions(view, items, at, place);
}
private readonly facing?: Vec3;
private constructor(
private readonly view: Viewport,
items: ToolItem[],
private readonly at: Vec3,
private readonly place: QuickPlace,
rest: ToolItem[] = [],
) {
this.facing = place.facing;
this.box.className = "quick-actions";
const button = (it: ToolItem) => {
const b = document.createElement("button");
b.className = `quick-action${it.active ? " on" : ""}${it.id === "delete" || it.id === "deleteBody" ? " danger" : ""}`;
b.title = it.shortcut ? `${it.label} (${it.shortcut})` : it.label;
b.setAttribute("aria-label", it.label);
const icon = icons[it.icon as keyof typeof icons];
b.innerHTML = `${icon ?? ""}<span>${shortName(it.label)}</span>`;
b.addEventListener("click", (e) => {
e.stopPropagation();
it.run?.();
});
return b;
};
const row = document.createElement("div");
row.className = "quick-row";
for (const it of items) row.append(button(it));
this.box.append(row);
if (rest.length) {
// The rest of what the pick offers: under the row, opened by its last button (and shut by it again).
const more = document.createElement("button");
more.className = "quick-action quick-more";
more.title = "Every other tool for this";
more.setAttribute("aria-label", "More tools for this");
more.innerHTML = `${icons.more ?? ""}<span>More</span>`;
const grid = document.createElement("div");
grid.className = "quick-rest";
grid.hidden = true;
for (const it of rest) grid.append(button(it));
more.addEventListener("click", (e) => {
e.stopPropagation();
grid.hidden = !grid.hidden;
more.classList.toggle("on", !grid.hidden);
this.layout();
});
row.append(more);
this.box.append(grid);
}
// A press on them is theirs: never a pick on the model behind, nor the view turning.
this.box.addEventListener("pointerdown", (e) => e.stopPropagation());
document.body.append(this.box);
view.frameHooks.add(this.hook);
this.layout();
}
/** Below the point, clear of the handle on it (moved on with the view: only when the view is drawn again). */
private layout(): void {
const s = this.view.toScreen(this.at);
let shown = !!s;
if (s && this.facing && this.place.hideBack !== false) {
const v = this.view.cam.viewDir();
if (v.x * this.facing[0] + v.y * this.facing[1] + v.z * this.facing[2] > 0.05) shown = false;
}
this.box.hidden = !shown;
if (!s || !shown) return;
const hw = this.box.offsetWidth / 2;
const hh = this.box.offsetHeight / 2;
// (A face's arrow points out along its normal: they go the other way on the screen, not under it.)
const first: [number, number][] = [];
if (this.facing) {
const k = this.view.cam.worldPerPixel(this.view.height) * 60;
const tip = this.view.toScreen([this.at[0] + this.facing[0] * k, this.at[1] + this.facing[1] * k, this.at[2] + this.facing[2] * k]);
const dx = tip ? s[0] - tip[0] : 0;
const dy = tip ? s[1] - tip[1] : 0;
const l = Math.hypot(dx, dy);
if (l > 8) {
const d = Math.abs((dx / l) * hw) + Math.abs((dy / l) * hh) + (this.place.gap ?? 34);
first.push([s[0] + (dx / l) * d, s[1] + (dy / l) * d]);
}
}
const g = this.place.gap ?? 46;
const spots: [number, number][] = [
...first,
[s[0], s[1] + g + hh],
[s[0], s[1] - g - hh],
[s[0] - g - hw, s[1]],
[s[0] + g + hw, s[1]],
].map((p) => clampToFree(p as [number, number], hw, hh));
// (Nor under a value box on the model - an extrude's distance, beside its arrow.)
const boxes = [...document.querySelectorAll<HTMLElement>(".dim-widget")].map((b) => b.getBoundingClientRect()).filter((r) => r.width > 0);
const clear = ([x, y]: [number, number]) => !boxes.some((r) => x + hw + 6 > r.left && x - hw - 6 < r.right && y + hh + 6 > r.top && y - hh - 6 < r.bottom);
const [x, y] = spots.find(clear) ?? spots[0];
this.box.style.transform = `translate(${Math.round(x - hw)}px, ${Math.round(y - hh)}px)`;
}
dispose(): void {
this.view.frameHooks.delete(this.hook);
this.box.remove();
}
}
/** A short name under the icon ("Move/Rotate Edge" → "Move"). */
function shortName(label: string): string {
const s = label.replace(/…$/, "").split(/[/ –]/)[0];
return s.length > 12 ? s.slice(0, 11) + "…" : s;
}
+34 -3
View File
@@ -12,6 +12,10 @@ export interface SectionState {
flipped: boolean;
/** Cut from a face: how far inside it the cut starts (a hair, so the face shows the cut); a plane placed there goes on the face. */
inset?: number;
/** Only the cut faces shown, the rest of the model gone. */
only?: boolean;
/** 2D: seen straight on, flat like a drawing, the edges beyond the cut drawn. */
flat?: boolean;
}
export interface SectionHost extends AppContext {
@@ -53,7 +57,7 @@ export class SectionTool implements Tool {
private askForPlane(): void {
this.app.view.setOriginPlanesVisible(true);
this.app.ui.showPanel(null);
this.app.ui.setHint("Select a plane or a flat face to cut the view with.");
this.app.ui.setHint("Tap a plane or a flat face to cut the view there, so you can see inside.");
}
hover(p: ToolPointer | null): void {
@@ -86,19 +90,46 @@ export class SectionTool implements Tool {
const s = this.app.section!;
this.handle ??= new Handle(this.app.view, "arrow");
this.placeHandle();
this.app.ui.setHint("Drag the arrow to move the cut. Section View stays on until you delete it.");
this.app.ui.setHint("Drag the arrow to move the cut. It stays until you delete it in History.");
this.app.ui.showPanel({
title: "Section View",
items: [
{ type: "number", label: "Offset", value: s.offset, kind: "length", onInput: (v) => this.setOffset(v) },
{ type: "button", label: "Flip", icon: "flip", onClick: () => (this.app.setSection({ ...s, flipped: !this.app.section!.flipped }), this.showControls()) },
{ type: "button", label: "Place Plane", icon: "plane", onClick: () => this.placePlane() },
{ type: "toggle", label: "Section only", value: !!s.only, onChange: (v) => this.restyle({ only: v || undefined, flat: v ? undefined : s.flat }) },
{
type: "toggle",
label: "2D section",
value: !!s.flat,
onChange: (v) => {
this.restyle({ flat: v || undefined, only: v ? undefined : s.only });
if (v) this.lookAtCut();
},
},
{ type: "button", label: "Normal to Section", icon: "normal", onClick: () => this.lookAtCut() },
{ type: "button", label: "Add Plane", icon: "plane", onClick: () => this.placePlane() },
],
actions: [{ id: "delete", label: "Delete Section", icon: "trash", run: () => (this.app.setSection(null), this.handle?.dispose(), (this.handle = null), this.askForPlane()) }],
onDone: () => this.app.setTool(null),
});
}
private restyle(patch: Partial<SectionState>): void {
const s = this.app.section;
if (!s) return;
this.app.setSection({ ...s, ...patch });
this.showControls();
}
/** Look straight at the cut, from the side that's cut away. */
private lookAtCut(): void {
const s = this.app.section;
if (!s) return;
const p = sectionPlane(s);
this.app.view.cam.lookAlong(p.normal, p.xDir);
this.app.view.fitAll();
}
/** A construction plane where the cut is now (to sketch on, split with...). */
private placePlane(): void {
const s = this.app.section;
+717 -122
View File
File diff suppressed because it is too large Load Diff
+1592 -156
View File
File diff suppressed because it is too large Load Diff
+34 -6
View File
@@ -40,13 +40,22 @@ const GLYPH: Partial<Record<ConstraintType, string>> = {
};
/** Constraints for a button press, from the current selection (empty if it doesn't fit). */
export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): SketchConstraint[] {
export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[], all?: SketchEntity[]): SketchConstraint[] {
if (type === "hv") {
if (curves.length === 1 && curves[0].kind === "line" && !pts.length) {
const l = curves[0];
const horiz = Math.abs(l.b[0] - l.a[0]) >= Math.abs(l.b[1] - l.a[1]);
return [{ id: uid(), type: horiz ? "horizontal" : "vertical", curves: [l.id] }];
}
// Two points (a circle's centre and a corner, two ends): level with each other, or one above the other -
// whichever they are nearer to. (The solver had it; no button gave it.)
if (pts.length === 2 && !curves.length && all) {
const [a, b] = pts.map((r) => {
const e = all.find((x) => x.id === r.e);
return e ? pointOf(e, r.p) : null;
});
if (a && b && Math.hypot(a[0] - b[0], a[1] - b[1]) > 1e-9) return [{ id: uid(), type: Math.abs(b[0] - a[0]) >= Math.abs(b[1] - a[1]) ? "horizontal" : "vertical", pts }];
}
return [];
}
if (!applicable(type, pts, curves)) return [];
@@ -64,7 +73,7 @@ export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], c
case "fix": {
// Locking a curve holds all of its points (and a circle's size).
const all = [...pts, ...curves.flatMap((e) => pointsOf(e).map((q) => ({ e: e.id, p: q.p })))];
const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius }] : []));
const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius, held: true }] : []));
return [...all.map((p) => ({ id: uid(), type, pts: [p] })), ...sizes];
}
default:
@@ -89,6 +98,16 @@ export function distanceOf(pts: PointRef[], curves: SketchEntity[], all: SketchE
const dy = l.b[1] - l.a[1];
return Math.abs((p[0] - l.a[0]) * dy - (p[1] - l.a[1]) * dx) / (Math.hypot(dx, dy) || 1);
}
// Two lines that run the same way (within a degree): how far apart they are - the second's middle from the first.
// (Asked for: a distance between two lines. Two lines that cross have an angle between them, not a distance.)
const m = curves[1];
if (!pts.length && curves.length === 2 && l.kind === "line" && m.kind === "line") {
const [dx, dy, ex, ey] = [l.b[0] - l.a[0], l.b[1] - l.a[1], m.b[0] - m.a[0], m.b[1] - m.a[1]];
const [L, M] = [Math.hypot(dx, dy), Math.hypot(ex, ey)];
if (!(L > 1e-12) || !(M > 1e-12) || Math.abs(dx * ey - dy * ex) / (L * M) > Math.sin(Math.PI / 180)) return null;
const mid = [(m.a[0] + m.b[0]) / 2, (m.a[1] + m.b[1]) / 2];
return Math.abs((mid[0] - l.a[0]) * dy - (mid[1] - l.a[1]) * dx) / L;
}
return null;
}
@@ -103,6 +122,8 @@ export function existingConstraints(type: ConstraintType | "hv", constraints: Sk
// A point counts as selected when it is, or when its curve is.
const ptIn = (p: PointRef) => ptKeys.has(`${p.e}:${p.p}`) || ids.has(p.e);
return constraints.filter((c) => {
// (The size Lock put on a circle goes with its lock; it was left behind, and the circle unlocked kept its size.)
if (type === "fix" && c.type === "dim" && c.held && c.curves?.length === 1 && ids.has(c.curves[0])) return true;
if (!types.includes(c.type)) return false;
const cv = c.curves ?? [];
const cp = c.pts ?? [];
@@ -113,10 +134,6 @@ export function existingConstraints(type: ConstraintType | "hv", constraints: Sk
});
}
export function buttonEnabled(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): boolean {
return buildConstraints(type, pts, curves).length > 0;
}
/** Upsert a driving dimension on one entity (length / radius / w / h / …). */
export function setDim(list: SketchConstraint[], entity: string, prop: string, value: number, expr?: string | null): SketchConstraint[] {
const i = list.findIndex((c) => c.type === "dim" && c.curves?.[0] === entity && c.curves.length === 1 && c.prop === prop);
@@ -171,6 +188,8 @@ export class ConstraintGlyphs {
// Several badges at one spot are fanned out (further out) so they stay readable.
const counts = new Map<string, number>();
for (const c of constraints) {
// (A pattern's copies have no badge each: there'd be one on every copy.)
if (c.type === "pattern" || c.type === "follow") continue;
// A mark only while everything it ties together is still drawn.
if (![...(c.pts ?? []).map((p) => p.e), ...(c.curves ?? [])].every((id) => get(id))) continue;
let at: Vec2 | null = null;
@@ -269,6 +288,15 @@ export class ConstraintGlyphs {
this.host.hidden = !on;
}
/**
* Tapped to select (in the Select tool), or let through to the drawing under
* them: a rectangle's width label under its edge took Mirror's tap on the
* circle there, and the shapes picked so far were let go.
*/
setTappable(on: boolean): void {
this.host.classList.toggle("passive", !on);
}
private layout(): void {
if (!this.plane) return;
for (const it of this.items) {
+1 -1
View File
@@ -47,7 +47,7 @@ export class SketchMoveOp extends FeatureOp<SketchFeature> {
}
protected hint(): string {
return "Drag the blue arrow to a parallel plane (red / green slide it in its plane), or type the distance. Tap empty space when done.";
return "Drag the blue arrow to move the sketch forward or back, or red and green to slide it. Tap empty space when done.";
}
protected items(): PanelItem[] {
+81 -6
View File
@@ -33,6 +33,22 @@ export function axisSlot(app: AppContext, label: string, get: () => AxisRef | nu
],
shows: () => (shown ? [shown] : []),
accept(hit) {
// A point of a sketch (a short axis line is mostly its ends, and the
// circle it halves has its own points on it): the sketch line through it.
// (Tapped, it was taken for nothing - the Axis waited on.)
if (hit.kind === "point") {
const s = app.store.find<SketchFeature>(hit.sketch);
const plane = app.sketchPlane(hit.sketch);
if (!s || !plane) return false;
const at = toPlane(plane, hit.point);
const on = s.entities.find((e) => e.kind === "line" && closestOnPrim(entityPrims(e)[0], at).d < 1e-6 * Math.max(1, len(sub(toWorld(plane, e.b), toWorld(plane, e.a)))));
if (!on || on.kind !== "line") return false;
const a = toWorld(plane, on.a);
set({ origin: a, dir: norm(sub(toWorld(plane, on.b), a)), ref: { kind: "sketchLine", sketch: s.id, entity: on.id } });
name = "Sketch line";
shown = { kind: "curve", sketch: s.id, entity: on.id } as Sel;
return true;
}
if (hit.kind === "curve") {
const s = app.store.find<SketchFeature>(hit.sketch);
const e = s?.entities.find((x) => x.id === hit.entity);
@@ -80,9 +96,18 @@ export function axisSlot(app: AppContext, label: string, get: () => AxisRef | nu
};
}
export function planeSlot(app: AppContext, label: string, get: () => PlaneDef | null, set: (p: PlaneDef, face?: FaceRef) => void): Slot {
export function planeSlot(
app: AppContext,
label: string,
get: () => PlaneDef | null,
set: (p: PlaneDef, face?: FaceRef) => void,
// `named`: what's in it already, by name (a plane being edited: "XZ plane",
// not "Plane"). `skip`: construction planes it can't be (a plane can't be
// made from itself, nor from one made after it).
opts: { named?: string; skip?: (planeId: string) => boolean } = {},
): Slot {
let shown: Sel | null = null;
let name = "";
let name = opts.named ?? "";
return {
label,
describe: () => (get() ? name || "Plane" : "Tap a plane, flat face or sketched shape"),
@@ -95,15 +120,15 @@ export function planeSlot(app: AppContext, label: string, get: () => PlaneDef |
// a thin sheet among the bodies, easy to miss with a finger).
presets: [
...["XY", "XZ", "YZ"].map((id) => ({ label: id, apply: () => ((name = `${id} plane`), (shown = null), set(app.view.planeOf(id)!)) })),
...app.view.construction.planes.map((c) => ({ label: c.name, apply: () => ((name = c.name), (shown = null), set(c.plane)) })),
...app.view.construction.planes.filter((c) => !opts.skip?.(c.id)).map((c) => ({ label: c.name, apply: () => ((name = c.name), (shown = null), set(c.plane)) })),
],
shows: () => (shown ? [shown] : []),
accept(hit) {
if (hit.kind === "plane") {
const p = app.view.planeOf(hit.id);
if (!p) return false;
if (!p || opts.skip?.(hit.id)) return false;
set(p);
name = ["XY", "XZ", "YZ"].includes(hit.id) ? `${hit.id} plane` : "Plane";
name = ["XY", "XZ", "YZ"].includes(hit.id) ? `${hit.id} plane` : (app.view.construction.planes.find((c) => c.id === hit.id)?.name ?? "Plane");
shown = { kind: "plane", id: hit.id };
return true;
}
@@ -111,7 +136,7 @@ export function planeSlot(app: AppContext, label: string, get: () => PlaneDef |
const info = app.view.body(hit.body)?.faces[hit.face];
if (!info?.plane) return false;
set(info.plane, faceRefOf(app, hit) ?? undefined);
name = "Face";
name = faceOfName(app, hit.body);
shown = { kind: "face", body: hit.body, face: hit.face };
return true;
}
@@ -130,6 +155,12 @@ export function planeSlot(app: AppContext, label: string, get: () => PlaneDef |
};
}
/** "Face of Body 3": which body a face is on, by the name it has in Items. */
export function faceOfName(app: AppContext, body: string): string {
const n = app.store.doc.names?.[body] ?? app.result?.bodies.find((b) => b.id === body)?.name;
return n ? `Face of ${n}` : "Face";
}
/** A direction: an edge, an axis, a face normal, or X/Y/Z. */
export function directionSlot(app: AppContext, label: string, get: () => Vec3 | null, set: (d: Vec3) => void): Slot {
let shown: Sel | null = null;
@@ -213,6 +244,50 @@ export function pathSlot(app: AppContext, get: () => PathRef | null, set: (p: Pa
};
}
/**
* Curves from any sketches and edges of any bodies, as a list of paths (one
* per sketch, one for the edges): Fill's boundary and guides. Tapping one
* again leaves it out.
*/
export function curvesSlot(app: AppContext, label: string, get: () => PathRef[], set: (p: PathRef[]) => void, optional = false): Slot {
const count = () => get().reduce((n, p) => n + (p.kind === "sketch" ? p.entities.length : p.edges.length), 0);
return {
label,
multi: true,
describe: () => (count() ? `${count()} curve${count() > 1 ? "s" : ""}` : optional ? "None" : "Tap curves or edges"),
filled: () => optional || count() > 0,
pick: { profiles: false, curves: true, planes: false, axes: false },
shows: () => get().flatMap((p) => (p.kind === "sketch" ? p.entities.map((entity) => ({ kind: "curve", sketch: p.sketch, entity }) as Sel) : [])),
get presets() {
return count() ? [{ label: "Clear", apply: () => set([]) }] : [];
},
accept(hit) {
const paths = get();
if (hit.kind === "curve") {
const i = paths.findIndex((p) => p.kind === "sketch" && p.sketch === hit.sketch);
if (i < 0) return set([...paths, { kind: "sketch", sketch: hit.sketch, entities: [hit.entity] }]), true;
const p = paths[i] as Extract<PathRef, { kind: "sketch" }>;
const entities = p.entities.includes(hit.entity) ? p.entities.filter((e) => e !== hit.entity) : [...p.entities, hit.entity];
set(entities.length ? paths.map((x, k) => (k === i ? { ...p, entities } : x)) : paths.filter((_, k) => k !== i));
return true;
}
if (hit.kind === "edge") {
const ref = edgeRefOf(app, hit);
if (!ref) return false;
// One path per body (its face is found from its own body).
const i = paths.findIndex((p) => p.kind === "edges" && p.edges[0]?.body === ref.body);
if (i < 0) return set([...paths, { kind: "edges", edges: [ref] }]), true;
const p = paths[i] as Extract<PathRef, { kind: "edges" }>;
const same = (e: EdgeRef) => JSON.stringify(e) === JSON.stringify(ref);
const edges = p.edges.some(same) ? p.edges.filter((e) => !same(e)) : [...p.edges, ref];
set(edges.length ? paths.map((x, k) => (k === i ? { ...p, edges } : x)) : paths.filter((_, k) => k !== i));
return true;
}
return false;
},
};
}
/** Faces of one body (e.g. faces to open in Shell). */
export function facesSlot(app: AppContext, label: string, get: () => FaceRef[], set: (f: FaceRef[]) => void, optional = false): Slot {
const picked: Sel[] = [];

Some files were not shown because too many files have changed in this diff Show More