@margoengine/road 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,201 +1,201 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2026 Scott Campbell
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE CHANGED
@@ -1,4 +1,4 @@
1
- Margo Engine
2
- Copyright 2026 Scott Campbell
3
-
4
- This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,206 +1,206 @@
1
- # @margoengine/road
2
-
3
- Import `margoengine/road` from the `margoengine` package, or `@margoengine/road` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Arc-length spline sweeps generate a road surface, raised curbs, hard cross-section normals and tiled UV coordinates.
6
-
7
- ```ts
8
- import {road} from 'margoengine/road';
9
- import {Spline} from 'margoengine/splines';
10
- import {Engine} from 'margoengine/core';
11
- const engine = await Engine.create(document.querySelector('canvas')!);
12
- const curve = new Spline([[0, 0, 0], [40, 2, 30], [90, 0, 20]]);
13
- const {geometry, uvs} = road(curve, {width: 6, curbWidth: 0.2, curbHeight: 0.15, uvMeters: 5});
14
- engine.createMesh().setGeometry(geometry);
15
- ```
16
-
17
- `roadPath(curve, {width, curbWidth, crossSection, segments, margin})` gives the ground the road covers as
18
- `{points, width}`: the centreline as XZ points sampled by arc length like `road`, and the full width of the road,
19
- both curbs and `margin` (default 0.5 m) each side; an asymmetric `crossSection` keeps its wider side clear on both.
20
- It is the shape `Scatter`'s `paths` option and `clearPlacements` take, so grass, trees and rocks keep off the road:
21
-
22
- ```ts
23
- import {road, roadPath} from 'margoengine/road';
24
- import {Scatter} from 'margoengine/scatter';
25
- import {Spline} from 'margoengine/splines';
26
- import {Engine} from 'margoengine/core';
27
- import {icosahedronGeometry, toGeometry} from 'margoengine/geometry';
28
- const engine = await Engine.create(document.querySelector('canvas')!);
29
- const curve = new Spline([[0, 0, 0], [40, 0, 30], [90, 0, 20]]);
30
- engine.createMesh().setGeometry(road(curve, {width: 6}).geometry);
31
- Scatter.attach(engine, toGeometry(icosahedronGeometry(0.3, 1, true)), {count: 2000, area: [200, 200], paths: [roadPath(curve, {width: 6})]});
32
- ```
33
-
34
- Closed splines use periodic tangent frames: corresponding first and last section vertices and normals meet exactly, while UV V keeps the full travelled distance.
35
-
36
- Custom crossSection entries are [lateralOffset, height]. UV V follows distance / uvMeters and U follows cross-section distance. The core is frozen and has no UV channel: uvs is separate data for a textured optional renderer/exporter. Sweeps are Y-up and reject vertical or zero tangents; banking is available in the optional entry below; self-intersection repair is available in its own optional entry below.
37
-
38
- ## Junctions
39
-
40
- `@margoengine/road/junctions` stitches crossings and T junctions by uniting the entire road footprint before triangulation. Draw this returned surface instead of overlapping road sweeps. It also preserves courtyard holes. Geometry's existing polygon and triangulation entries load only when the function is called; the road root does not load them.
41
-
42
- ```ts
43
- import {junctions} from 'margoengine/road/junctions';
44
- import {Engine} from 'margoengine/core';
45
- const engine = await Engine.create(document.querySelector('canvas')!);
46
- const {geometry, area} = await junctions([
47
- {points: [[-10, 0], [10, 0]], width: 4},
48
- {points: [[0, -10], [0, 10]], width: 4},
49
- ]);
50
- engine.createMesh().setGeometry(geometry);
51
- console.log(area); // 144 square metres, not 160 with the crossing counted twice
52
- ```
53
-
54
- Points are horizontal `[x, z]` metres. Each line has `width` (default 6). Options are `elevation` (default 0), `uvMeters` (default 1), and `signal` (default none). The signal is checked before and after lazy loading; synchronous geometry work cannot be interrupted. Inputs are snapshotted before loading. The result owns `geometry` and `uvs`, with world-space `[x, -z] / uvMeters`, and needs no disposal; dispose meshes and engines when finished.
55
-
56
- Limits: 1..64 roads, 2..4096 points per line and 4096 total, no equal neighbours, coordinates/elevation within +/-1,000,000 m, widths in (0,1000], UV scale in (0,1,000,000]. Bevel joins and butt ends, a shared constant elevation, no curbs, turn-radius design or bridge separation. The polygon grid has about 2^26 steps across the footprint; features below two steps may vanish. Result geometry uses float32 coordinates, so place small roads near their local origin. Collapsed or reversed float32 triangles and overflowing UVs reject with coded help-linked errors. Both WebGPU and the WebGL2 compatibility layer render the same CPU-generated geometry. The GPU test checks road and clear pixels, exact restoration after device reboot, and mesh/engine disposal on both.
57
-
58
- GPU tests from the repository root: `node scripts/run-with-timeout.mjs --max=8 -- npm run test:gpu --workspace @margoengine/road`.
59
-
60
- Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
61
-
62
- Build and unit tests: npm test --workspace @margoengine/road
63
-
64
-
65
- ## Banking
66
-
67
- ```ts
68
- import {bankedRoad} from "margoengine/road/banking";
69
- import {Spline} from "margoengine/splines";
70
- const surface = await bankedRoad(new Spline([[0,0,0],[20,2,20],[50,0,25]]), {bank:[0,0.12,0]});
71
- console.log(surface.geometry.indices.length);
72
- ```
73
-
74
- `bankedRoad` accepts all root road options and `bank` (default 0): radians about the forward tangent, bounded to +/-pi/4. Positive bank raises the positive lateral edge. A list of 2..4097 angles interpolates linearly at equal arc distances. The entire cross section, including curbs, rotates; normals are rebuilt with the existing geometry utility after deformation. Closed splines require equal first and last bank angles; a mismatched list rejects with a coded `failed` error. Corresponding terminal vertices share all incident triangle corner angles when rebuilding normals, preserving hard edges between curb strips and the separate UV end row. `signal` (default none) checks before and after lazy normal-kernel loading. Data is snapshotted before the first await and caller-owned, with no CPU resource to dispose. Dispose rendered meshes and engines. Input and output positions must stay within +/-1,000,000 m; float32 collapsed triangles and UV overflow reject. Nonvertical tangents and the root road limits apply. Banking does not repair tight bends or design civil-engineering transitions. Both native WebGPU and real WebGL2 compatibility render the banked mesh, including exact device reboot and double disposal tests.
75
-
76
- ## Terrain fit
77
-
78
- ```ts
79
- import {road} from 'margoengine/road';
80
- import {Spline} from 'margoengine/splines';
81
- import {fitTerrain} from 'margoengine/road/terrain';
82
- import {heightfieldGeometry} from 'margoengine/terrain';
83
- const surface = road(new Spline([[0,2,-10],[0,4,10]]));
84
- const height = await fitTerrain(surface.geometry, {base:()=>1, shoulder:3, depth:0.1});
85
- const ground = heightfieldGeometry(height, {size:[30,30], resolution:64});
86
- console.log(ground.indices.length);
87
- ```
88
-
89
- `fitTerrain` returns a height function compatible with terrain heightfields and biome field sources. It cuts ground above the road and fills ground below it. Pass world-space geometry; root curbs, banked grades and junction surfaces work. `base` defaults to flat zero, `shoulder` to 2 m and `depth` below the road to 0 m. The bed follows the lowest barycentric triangle height at each XZ location, so tilted curb walls cannot raise terrain through the driving surface. Footprint containment uses vertical BVH ray hits and their barycentric coordinates; `shoulder:0` keeps interior points on the bed even on oblique roads and leaves points outside the footprint at base. Outside the footprint it fades from the bed at the nearest projected point to base with cubic smoothstep over the shoulder. Faces with zero XZ area are omitted; banked curb faces with nonzero projected area participate in the lower envelope. Input positions and sampled base/query coordinates stay within +/-1,000,000 m, up to one million vertices/faces. No bridge/tunnel or overlapping-layer classification; use one at-grade surface. The input mesh snapshots before lazy BVH loading. `signal` (default none) checks around loading; synchronous queries/builds finish without interruption. Returned CPU data is garbage collected; dispose rendered meshes and engines. WebGPU and WebGL2 compatibility both have fitted-heightfield pixel, value, reboot and disposal proof. Sampling resolution controls the final terrain mesh fidelity.
90
-
91
- ## Self intersection repair
92
-
93
- ```ts
94
- import {repairRoad} from 'margoengine/road/repair';
95
- import {Spline} from 'margoengine/splines';
96
- const surface = await repairRoad(new Spline([[-2,0,-8],[-2,0,8],[0,0,9],[2,0,8],[2,0,-8]]), {width:8});
97
- console.log(surface.area); // one footprint rather than overlapping strips
98
- ```
99
-
100
- `repairRoad` samples equal arc-distance chords and unions their full footprint before triangulation. It replaces the root sweep when a tight planar bend folds or overlaps. `width` defaults to 6 m, `segments` to 128 (1..4095), and `uvMeters` to 1. All junction bounds apply. Elevation comes from the curve; a grade rejects with coded help-linked `unsupported`. Every cubic span is checked at four distinct raw-parameter values before tessellation, independently of `segments` and the spline arc lookup. Equal-height chord endpoints never authorise flattening a hill or an interior Hermite/Bezier excursion. This is a flat driving surface without curbs or banking; it does not trim a 3D banked mesh. The sampled chord approximation and the polygon snap grid set geometric fidelity. Boundaries round to renderer float32 precision before triangulation; collapsed boundaries and invalid final faces still reject. Inputs snapshot before lazy loading; `signal` (default none) checks around loading. CPU output is caller-owned and needs no disposal. Rendered meshes/engines require disposal and survive device reboot on WebGPU and WebGL2 compatibility, as the pixel tests prove.
101
-
102
- ## Lane markings
103
-
104
- ```ts
105
- import {Engine, PbrMaterial} from 'margoengine/core';
106
- import {road} from 'margoengine/road';
107
- import {Spline} from 'margoengine/splines';
108
- import {markings} from 'margoengine/road/markings';
109
- import {Decals} from 'margoengine/post/decals';
110
- import {Tonemap} from 'margoengine/tonemap';
111
- const engine = await Engine.create(document.querySelector('canvas')!);
112
- engine.createMesh().setGeometry(road(new Spline([[0,0,-10],[0,0,10]])).geometry).setMaterial(new PbrMaterial({color:'#202020'}));
113
- Tonemap.attach(engine); // supplies scene depth
114
- const paint = Decals.attach(engine);
115
- paint.setDecals(markings([
116
- {kind:'line',position:[-1,0,0],length:18,dash:[3,1]},
117
- {kind:'arrow',position:[1,0,0],length:4,width:1.5},
118
- ]));
119
- console.log(paint.count);
120
- ```
121
-
122
- Render the engine as usual. `markings` is synchronous and returns independently owned `Decal[]`; no image, loading or GPU allocation occurs. Pass the list to the existing decal renderer, with a scene-depth capture attached. The default white texel paints strokes in unlit `over` mode. Shared settings: `color` linear RGB in 0..1 (default white), `opacity` 0..1 (default 1), `depth` positive through 1000 m (default 2). Individual `angle` (radians about +Y, counterclockwise seen from above: 0 along +Z, pi/2 along +X) defaults 0, `length` to 4 m (positive through 10000), `width` to 0.15 m for lines or 1.5 m for arrows (positive through 1000). `dash` is line-only [paint,gap], both positive through 10000 m; default solid. Its last painted segment trims to the authored end. Up to 4096 resulting projectors; empty input clears the list. Positions stay within +/-1,000,000 m. Arrows are stylized three-stroke glyphs; this is not a traffic-standard artwork library. Downward box projection can paint any upward-facing object inside it, so set its centre/depth around the road. Subpixel or imprecise world placement can disappear; use a local origin. CPU descriptions need no disposal; dispose Decals, meshes and engines. Device reboot, disposal, actual white line/arrow pixels and WebGL2 compatibility are tested.
123
-
124
- Every projector half-extent must be a normal float32 number (at least 2^-126); dimensions of 1e-30 m remain accepted. This excludes values the GPU may flush to zero.
125
-
126
- ## Road network graph
127
-
128
- ```ts
129
- import {roadGraph} from 'margoengine/road/graph';
130
- import {Spline} from 'margoengine/splines';
131
- import {createCompute} from 'margoengine/compute';
132
- import {shortestPaths} from 'margoengine/compute/graph';
133
- using gpu = await createCompute();
134
- using network = roadGraph(gpu, {vertices:3, roads:[
135
- {from:0,to:1,curve:new Spline([[0,0,0],[100,0,0]]),speed:10,direction:'forward'},
136
- {from:1,to:2,curve:new Spline([[100,0,0],[160,0,0]]),speed:10,traffic:2,delay:3},
137
- ]});
138
- const result = await shortestPaths(network, 0);
139
- using distances = result.distances;
140
- using predecessors = result.predecessors;
141
- console.log(await distances.read()); // Float32Array [0, 10, 25] seconds
142
- console.log(await predecessors.read()); // Int32Array [-1, 0, 1]
143
- ```
144
-
145
- `roadGraph` synchronously returns a caller-owned `CsrMatrix` for existing `compute/graph` shortest paths, BFS and components. Junctions are integer IDs in `0..vertices-1`, explicitly shared by the roads you want connected. Split roads at intended intersections; crossings and bridge overlaps never connect automatically. No road geometry or mesh is required. Each link's `curve.length` is snapshotted as arc metres. Weight seconds are `length / speed * traffic + delay`, rounded to float32. Defaults: `roads:[]`, `speed:50/3.6` m/s (50 km/h), `direction:'both'`, `traffic:1`, `delay:0`, `signal` none. Direction can also be `'forward'` (from -> to) or `'reverse'`; use separate links for asymmetric costs. Speed and length are positive finite, traffic finite and at least 1, delay finite and nonnegative. Closed roads are omitted. Rebuild for changed traffic; this graph is a snapshot, without a traffic simulator or lane/turn restrictions.
146
-
147
- Up to 65536 vertices and 65536 input roads; zero vertices/roads, isolated vertices and positive self loops are supported. Parallel arcs keep only the minimum cost, without road identities. Edge seconds must be normal float32 values at least 2^-126 and at most 2^127/max(1,vertices), keeping simple-path sums finite. Solvers use f32 sums, so rounding affects costs; compute/graph's predecessor limitations apply. This adapter does not reconstruct road itineraries. The signal checks before reading and before upload; a synchronous build cannot yield mid-loop. Solvers and reads accept their own signal.
148
-
149
- Native WebGPU and real WebGL2 compatibility both run the existing device-backed compute route, proved by distance/predecessor and lifecycle assertions. For a CPU fallback, use `createCompute({backend:'cpu'})`; the same graph API works in Node. When sharing a render engine, pass `createCompute({engine})`; dispose graph/output arrays/context before engine disposal. Those objects do not own the engine device. After device loss/reboot, create a fresh context and rebuild the graph from your retained road descriptions. Graphs do not restore themselves. The GPU test proves the rebuilt graph has the same answers on both backends.
150
-
151
- Tessellated root-road frames use adjacent chord bisectors, joined periodically
152
- on closed curves. On tight bends the inside lateral offsets (curbs included)
153
- compress proportionally before their focal fold. Both projected triangle areas
154
- stay positive, retaining 5% of the available signed span area at the narrowest
155
- limit; the outside width stays unchanged. Cross-section heights and UV distances
156
- remain authored. This can narrow the inside driving surface, so choose a wider
157
- bend when the full lane width matters. Nonlocal footprint overlaps at crossings
158
- or adjacent return legs still use `/repair` or `/junctions` for a planar surface;
159
- local fold prevention does not classify bridges or trim global intersections.
160
- Vertical tangents reject with linked code `unsupported`; arbitrarily steep
161
- nonvertical ramps work. A sampled cusp/reversal rejects with linked code `failed`:
162
- refine the spline or increase segments. Core Geometry/PbrMaterial have no texture
163
- channel by design; use the separate `uvs` with an optional textured renderer or
164
- exporter, as documented above.
165
-
166
- ## Wet roads and lane driving
167
-
168
- `@margoengine/road/driving` turns rendered `road` and `bankedRoad` triangles into fixed colliders with measured dry and wet tyre limits. `RoadSurfaces.register()` applies the same material model to an existing deck or soil collider. An optional pressure–sinkage curve makes suspension compress less as the tyres press into soft soil. Use `groundReaction: true` on a vehicle that exchanges wheel forces with a moving deck.
169
-
170
- `RoadDriver` follows a lane made from the road spline. It watches the rigid body's pose at 60 Hz, steers toward a geometric look-ahead point, and brakes before a curve or the end of an open path. Its speed bound depends on bank and available grip. Supply `SurfaceEnergySolver.wetnessField` to use the same ATMO-09 moisture in planning and in `RoadSurfaces` through its wetness callback. Bind the existing `Vehicle` once and unbind it at disposal. The world snapshot includes its drive controls, engine and wheel spin.
171
-
172
- ```ts
173
- import { Physics } from '@margoengine/physics';
174
- import { PhysicsWorld, RigidSolver, worldMemory } from '@margoengine/physics/world';
175
- import { road } from '@margoengine/road';
176
- import { addRoadVehicle, roadDrivePath, RoadDriver, RoadSurfaces } from '@margoengine/road/driving';
177
- import { Spline } from '@margoengine/splines';
178
-
179
- await Physics.load();
180
- const gravity = [0, -9.81, 0] as const;
181
- const world = new PhysicsWorld({ rate: { num: 60, den: 1 }, gravity, memory: worldMemory(false) });
182
- using physics = new Physics(null, { arena: world.arena, gravity });
183
- const spline = new Spline([[0, 0, -8], [0, 0, 0], [0, 0, 16]]);
184
- const traction = { dry: 0.8, wet: 0.25 };
185
- const surfaces = new RoadSurfaces();
186
- surfaces.add(physics, road(spline), { traction, wetness: 0.5 });
187
- const wheels = [-1, 1].flatMap((end) => [-1, 1].map((side) => ({
188
- position: [0.65 * side, -0.15, end] as const, radius: 0.3, steer: end > 0, suspensionStiffness: 18,
189
- })));
190
- const { body, vehicle } = await addRoadVehicle(physics, null, {
191
- mass: 1200, size: [1.3, 0.36, 2.4], position: [0, 0.614, 0], groundMaterial: surfaces.sample, wheels,
192
- });
193
- const lane = await RoadDriver.create();
194
- world.add(new RigidSolver(), { physics });
195
- world.add(lane, { vehicles: [{ body: body.row, path: roadDrivePath(spline), traction, wheelbase: 2, maxSpeed: 4, attachment: vehicle }] });
196
- world.couple([lane.id, 'rigid'], 'staggered');
197
- const unbind = lane.bindVehicle(world, physics, 0);
198
- try {
199
- world.advance(90);
200
- if (body.position[2] < 1) throw new Error('Expected the lane-driven car to move at least 1 m');
201
- } finally {
202
- unbind();
203
- }
204
- ```
205
-
206
- `commandsField` uses layout 1 with f64 words for steer, throttle, brake, target speed, measured speed, route progress, relative wetness and segment index. The first three words are normalized `VehicleInput` values. `RoadDriver.read()` returns a copy. `addRoadVehicle()` uses the visual asset's actual dimensions and a supplied measured mass. Provide the asset's local forward direction when it differs from +Z. For wind, pass a `Wind` field such as Weather's `BoundaryLayerWind` and add the existing `AirSolver` to drive the optional attachment on the world clock.
1
+ # @margoengine/road
2
+
3
+ Import `margoengine/road` from the `margoengine` package, or `@margoengine/road` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Arc-length spline sweeps generate a road surface, raised curbs, hard cross-section normals and tiled UV coordinates.
6
+
7
+ ```ts
8
+ import {road} from 'margoengine/road';
9
+ import {Spline} from 'margoengine/splines';
10
+ import {Engine} from 'margoengine/core';
11
+ const engine = await Engine.create(document.querySelector('canvas')!);
12
+ const curve = new Spline([[0, 0, 0], [40, 2, 30], [90, 0, 20]]);
13
+ const {geometry, uvs} = road(curve, {width: 6, curbWidth: 0.2, curbHeight: 0.15, uvMeters: 5});
14
+ engine.createMesh().setGeometry(geometry);
15
+ ```
16
+
17
+ `roadPath(curve, {width, curbWidth, crossSection, segments, margin})` gives the ground the road covers as
18
+ `{points, width}`: the centreline as XZ points sampled by arc length like `road`, and the full width of the road,
19
+ both curbs and `margin` (default 0.5 m) each side; an asymmetric `crossSection` keeps its wider side clear on both.
20
+ It is the shape `Scatter`'s `paths` option and `clearPlacements` take, so grass, trees and rocks keep off the road:
21
+
22
+ ```ts
23
+ import {road, roadPath} from 'margoengine/road';
24
+ import {Scatter} from 'margoengine/scatter';
25
+ import {Spline} from 'margoengine/splines';
26
+ import {Engine} from 'margoengine/core';
27
+ import {icosahedronGeometry, toGeometry} from 'margoengine/geometry';
28
+ const engine = await Engine.create(document.querySelector('canvas')!);
29
+ const curve = new Spline([[0, 0, 0], [40, 0, 30], [90, 0, 20]]);
30
+ engine.createMesh().setGeometry(road(curve, {width: 6}).geometry);
31
+ Scatter.attach(engine, toGeometry(icosahedronGeometry(0.3, 1, true)), {count: 2000, area: [200, 200], paths: [roadPath(curve, {width: 6})]});
32
+ ```
33
+
34
+ Closed splines use periodic tangent frames: corresponding first and last section vertices and normals meet exactly, while UV V keeps the full travelled distance.
35
+
36
+ Custom crossSection entries are [lateralOffset, height]. UV V follows distance / uvMeters and U follows cross-section distance. The core is frozen and has no UV channel: uvs is separate data for a textured optional renderer/exporter. Sweeps are Y-up and reject vertical or zero tangents; banking is available in the optional entry below; self-intersection repair is available in its own optional entry below.
37
+
38
+ ## Junctions
39
+
40
+ `@margoengine/road/junctions` stitches crossings and T junctions by uniting the entire road footprint before triangulation. Draw this returned surface instead of overlapping road sweeps. It also preserves courtyard holes. Geometry's existing polygon and triangulation entries load only when the function is called; the road root does not load them.
41
+
42
+ ```ts
43
+ import {junctions} from 'margoengine/road/junctions';
44
+ import {Engine} from 'margoengine/core';
45
+ const engine = await Engine.create(document.querySelector('canvas')!);
46
+ const {geometry, area} = await junctions([
47
+ {points: [[-10, 0], [10, 0]], width: 4},
48
+ {points: [[0, -10], [0, 10]], width: 4},
49
+ ]);
50
+ engine.createMesh().setGeometry(geometry);
51
+ console.log(area); // 144 square metres, not 160 with the crossing counted twice
52
+ ```
53
+
54
+ Points are horizontal `[x, z]` metres. Each line has `width` (default 6). Options are `elevation` (default 0), `uvMeters` (default 1), and `signal` (default none). The signal is checked before and after lazy loading; synchronous geometry work cannot be interrupted. Inputs are snapshotted before loading. The result owns `geometry` and `uvs`, with world-space `[x, -z] / uvMeters`, and needs no disposal; dispose meshes and engines when finished.
55
+
56
+ Limits: 1..64 roads, 2..4096 points per line and 4096 total, no equal neighbours, coordinates/elevation within +/-1,000,000 m, widths in (0,1000], UV scale in (0,1,000,000]. Bevel joins and butt ends, a shared constant elevation, no curbs, turn-radius design or bridge separation. The polygon grid has about 2^26 steps across the footprint; features below two steps may vanish. Result geometry uses float32 coordinates, so place small roads near their local origin. Collapsed or reversed float32 triangles and overflowing UVs reject with coded help-linked errors. Both WebGPU and the WebGL2 compatibility layer render the same CPU-generated geometry. The GPU test checks road and clear pixels, exact restoration after device reboot, and mesh/engine disposal on both.
57
+
58
+ GPU tests from the repository root: `node scripts/run-with-timeout.mjs --max=8 -- npm run test:gpu --workspace @margoengine/road`.
59
+
60
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
61
+
62
+ Build and unit tests: npm test --workspace @margoengine/road
63
+
64
+
65
+ ## Banking
66
+
67
+ ```ts
68
+ import {bankedRoad} from "margoengine/road/banking";
69
+ import {Spline} from "margoengine/splines";
70
+ const surface = await bankedRoad(new Spline([[0,0,0],[20,2,20],[50,0,25]]), {bank:[0,0.12,0]});
71
+ console.log(surface.geometry.indices.length);
72
+ ```
73
+
74
+ `bankedRoad` accepts all root road options and `bank` (default 0): radians about the forward tangent, bounded to +/-pi/4. Positive bank raises the positive lateral edge. A list of 2..4097 angles interpolates linearly at equal arc distances. The entire cross section, including curbs, rotates; normals are rebuilt with the existing geometry utility after deformation. Closed splines require equal first and last bank angles; a mismatched list rejects with a coded `failed` error. Corresponding terminal vertices share all incident triangle corner angles when rebuilding normals, preserving hard edges between curb strips and the separate UV end row. `signal` (default none) checks before and after lazy normal-kernel loading. Data is snapshotted before the first await and caller-owned, with no CPU resource to dispose. Dispose rendered meshes and engines. Input and output positions must stay within +/-1,000,000 m; float32 collapsed triangles and UV overflow reject. Nonvertical tangents and the root road limits apply. Banking does not repair tight bends or design civil-engineering transitions. Both native WebGPU and real WebGL2 compatibility render the banked mesh, including exact device reboot and double disposal tests.
75
+
76
+ ## Terrain fit
77
+
78
+ ```ts
79
+ import {road} from 'margoengine/road';
80
+ import {Spline} from 'margoengine/splines';
81
+ import {fitTerrain} from 'margoengine/road/terrain';
82
+ import {heightfieldGeometry} from 'margoengine/terrain';
83
+ const surface = road(new Spline([[0,2,-10],[0,4,10]]));
84
+ const height = await fitTerrain(surface.geometry, {base:()=>1, shoulder:3, depth:0.1});
85
+ const ground = heightfieldGeometry(height, {size:[30,30], resolution:64});
86
+ console.log(ground.indices.length);
87
+ ```
88
+
89
+ `fitTerrain` returns a height function compatible with terrain heightfields and biome field sources. It cuts ground above the road and fills ground below it. Pass world-space geometry; root curbs, banked grades and junction surfaces work. `base` defaults to flat zero, `shoulder` to 2 m and `depth` below the road to 0 m. The bed follows the lowest barycentric triangle height at each XZ location, so tilted curb walls cannot raise terrain through the driving surface. Footprint containment uses vertical BVH ray hits and their barycentric coordinates; `shoulder:0` keeps interior points on the bed even on oblique roads and leaves points outside the footprint at base. Outside the footprint it fades from the bed at the nearest projected point to base with cubic smoothstep over the shoulder. Faces with zero XZ area are omitted; banked curb faces with nonzero projected area participate in the lower envelope. Input positions and sampled base/query coordinates stay within +/-1,000,000 m, up to one million vertices/faces. No bridge/tunnel or overlapping-layer classification; use one at-grade surface. The input mesh snapshots before lazy BVH loading. `signal` (default none) checks around loading; synchronous queries/builds finish without interruption. Returned CPU data is garbage collected; dispose rendered meshes and engines. WebGPU and WebGL2 compatibility both have fitted-heightfield pixel, value, reboot and disposal proof. Sampling resolution controls the final terrain mesh fidelity.
90
+
91
+ ## Self intersection repair
92
+
93
+ ```ts
94
+ import {repairRoad} from 'margoengine/road/repair';
95
+ import {Spline} from 'margoengine/splines';
96
+ const surface = await repairRoad(new Spline([[-2,0,-8],[-2,0,8],[0,0,9],[2,0,8],[2,0,-8]]), {width:8});
97
+ console.log(surface.area); // one footprint rather than overlapping strips
98
+ ```
99
+
100
+ `repairRoad` samples equal arc-distance chords and unions their full footprint before triangulation. It replaces the root sweep when a tight planar bend folds or overlaps. `width` defaults to 6 m, `segments` to 128 (1..4095), and `uvMeters` to 1. All junction bounds apply. Elevation comes from the curve; a grade rejects with coded help-linked `unsupported`. Every cubic span is checked at four distinct raw-parameter values before tessellation, independently of `segments` and the spline arc lookup. Equal-height chord endpoints never authorise flattening a hill or an interior Hermite/Bezier excursion. This is a flat driving surface without curbs or banking; it does not trim a 3D banked mesh. The sampled chord approximation and the polygon snap grid set geometric fidelity. Boundaries round to renderer float32 precision before triangulation; collapsed boundaries and invalid final faces still reject. Inputs snapshot before lazy loading; `signal` (default none) checks around loading. CPU output is caller-owned and needs no disposal. Rendered meshes/engines require disposal and survive device reboot on WebGPU and WebGL2 compatibility, as the pixel tests prove.
101
+
102
+ ## Lane markings
103
+
104
+ ```ts
105
+ import {Engine, PbrMaterial} from 'margoengine/core';
106
+ import {road} from 'margoengine/road';
107
+ import {Spline} from 'margoengine/splines';
108
+ import {markings} from 'margoengine/road/markings';
109
+ import {Decals} from 'margoengine/post/decals';
110
+ import {Tonemap} from 'margoengine/tonemap';
111
+ const engine = await Engine.create(document.querySelector('canvas')!);
112
+ engine.createMesh().setGeometry(road(new Spline([[0,0,-10],[0,0,10]])).geometry).setMaterial(new PbrMaterial({color:'#202020'}));
113
+ Tonemap.attach(engine); // supplies scene depth
114
+ const paint = Decals.attach(engine);
115
+ paint.setDecals(markings([
116
+ {kind:'line',position:[-1,0,0],length:18,dash:[3,1]},
117
+ {kind:'arrow',position:[1,0,0],length:4,width:1.5},
118
+ ]));
119
+ console.log(paint.count);
120
+ ```
121
+
122
+ Render the engine as usual. `markings` is synchronous and returns independently owned `Decal[]`; no image, loading or GPU allocation occurs. Pass the list to the existing decal renderer, with a scene-depth capture attached. The default white texel paints strokes in unlit `over` mode. Shared settings: `color` linear RGB in 0..1 (default white), `opacity` 0..1 (default 1), `depth` positive through 1000 m (default 2). Individual `angle` (radians about +Y, counterclockwise seen from above: 0 along +Z, pi/2 along +X) defaults 0, `length` to 4 m (positive through 10000), `width` to 0.15 m for lines or 1.5 m for arrows (positive through 1000). `dash` is line-only [paint,gap], both positive through 10000 m; default solid. Its last painted segment trims to the authored end. Up to 4096 resulting projectors; empty input clears the list. Positions stay within +/-1,000,000 m. Arrows are stylized three-stroke glyphs; this is not a traffic-standard artwork library. Downward box projection can paint any upward-facing object inside it, so set its centre/depth around the road. Subpixel or imprecise world placement can disappear; use a local origin. CPU descriptions need no disposal; dispose Decals, meshes and engines. Device reboot, disposal, actual white line/arrow pixels and WebGL2 compatibility are tested.
123
+
124
+ Every projector half-extent must be a normal float32 number (at least 2^-126); dimensions of 1e-30 m remain accepted. This excludes values the GPU may flush to zero.
125
+
126
+ ## Road network graph
127
+
128
+ ```ts
129
+ import {roadGraph} from 'margoengine/road/graph';
130
+ import {Spline} from 'margoengine/splines';
131
+ import {createCompute} from 'margoengine/compute';
132
+ import {shortestPaths} from 'margoengine/compute/graph';
133
+ using gpu = await createCompute();
134
+ using network = roadGraph(gpu, {vertices:3, roads:[
135
+ {from:0,to:1,curve:new Spline([[0,0,0],[100,0,0]]),speed:10,direction:'forward'},
136
+ {from:1,to:2,curve:new Spline([[100,0,0],[160,0,0]]),speed:10,traffic:2,delay:3},
137
+ ]});
138
+ const result = await shortestPaths(network, 0);
139
+ using distances = result.distances;
140
+ using predecessors = result.predecessors;
141
+ console.log(await distances.read()); // Float32Array [0, 10, 25] seconds
142
+ console.log(await predecessors.read()); // Int32Array [-1, 0, 1]
143
+ ```
144
+
145
+ `roadGraph` synchronously returns a caller-owned `CsrMatrix` for existing `compute/graph` shortest paths, BFS and components. Junctions are integer IDs in `0..vertices-1`, explicitly shared by the roads you want connected. Split roads at intended intersections; crossings and bridge overlaps never connect automatically. No road geometry or mesh is required. Each link's `curve.length` is snapshotted as arc metres. Weight seconds are `length / speed * traffic + delay`, rounded to float32. Defaults: `roads:[]`, `speed:50/3.6` m/s (50 km/h), `direction:'both'`, `traffic:1`, `delay:0`, `signal` none. Direction can also be `'forward'` (from -> to) or `'reverse'`; use separate links for asymmetric costs. Speed and length are positive finite, traffic finite and at least 1, delay finite and nonnegative. Closed roads are omitted. Rebuild for changed traffic; this graph is a snapshot, without a traffic simulator or lane/turn restrictions.
146
+
147
+ Up to 65536 vertices and 65536 input roads; zero vertices/roads, isolated vertices and positive self loops are supported. Parallel arcs keep only the minimum cost, without road identities. Edge seconds must be normal float32 values at least 2^-126 and at most 2^127/max(1,vertices), keeping simple-path sums finite. Solvers use f32 sums, so rounding affects costs; compute/graph's predecessor limitations apply. This adapter does not reconstruct road itineraries. The signal checks before reading and before upload; a synchronous build cannot yield mid-loop. Solvers and reads accept their own signal.
148
+
149
+ Native WebGPU and real WebGL2 compatibility both run the existing device-backed compute route, proved by distance/predecessor and lifecycle assertions. For a CPU fallback, use `createCompute({backend:'cpu'})`; the same graph API works in Node. When sharing a render engine, pass `createCompute({engine})`; dispose graph/output arrays/context before engine disposal. Those objects do not own the engine device. After device loss/reboot, create a fresh context and rebuild the graph from your retained road descriptions. Graphs do not restore themselves. The GPU test proves the rebuilt graph has the same answers on both backends.
150
+
151
+ Tessellated root-road frames use adjacent chord bisectors, joined periodically
152
+ on closed curves. On tight bends the inside lateral offsets (curbs included)
153
+ compress proportionally before their focal fold. Both projected triangle areas
154
+ stay positive, retaining 5% of the available signed span area at the narrowest
155
+ limit; the outside width stays unchanged. Cross-section heights and UV distances
156
+ remain authored. This can narrow the inside driving surface, so choose a wider
157
+ bend when the full lane width matters. Nonlocal footprint overlaps at crossings
158
+ or adjacent return legs still use `/repair` or `/junctions` for a planar surface;
159
+ local fold prevention does not classify bridges or trim global intersections.
160
+ Vertical tangents reject with linked code `unsupported`; arbitrarily steep
161
+ nonvertical ramps work. A sampled cusp/reversal rejects with linked code `failed`:
162
+ refine the spline or increase segments. Core Geometry/PbrMaterial have no texture
163
+ channel by design; use the separate `uvs` with an optional textured renderer or
164
+ exporter, as documented above.
165
+
166
+ ## Wet roads and lane driving
167
+
168
+ `@margoengine/road/driving` turns rendered `road` and `bankedRoad` triangles into fixed colliders with measured dry and wet tyre limits. `RoadSurfaces.register()` applies the same material model to an existing deck or soil collider. An optional pressure–sinkage curve makes suspension compress less as the tyres press into soft soil. Use `groundReaction: true` on a vehicle that exchanges wheel forces with a moving deck.
169
+
170
+ `RoadDriver` follows a lane made from the road spline. It watches the rigid body's pose at 60 Hz, steers toward a geometric look-ahead point, and brakes before a curve or the end of an open path. Its speed bound depends on bank and available grip. Supply `SurfaceEnergySolver.wetnessField` to use the same ATMO-09 moisture in planning and in `RoadSurfaces` through its wetness callback. Bind the existing `Vehicle` once and unbind it at disposal. The world snapshot includes its drive controls, engine and wheel spin.
171
+
172
+ ```ts
173
+ import { Physics } from '@margoengine/physics';
174
+ import { PhysicsWorld, RigidSolver, worldMemory } from '@margoengine/physics/world';
175
+ import { road } from '@margoengine/road';
176
+ import { addRoadVehicle, roadDrivePath, RoadDriver, RoadSurfaces } from '@margoengine/road/driving';
177
+ import { Spline } from '@margoengine/splines';
178
+
179
+ await Physics.load();
180
+ const gravity = [0, -9.81, 0] as const;
181
+ const world = new PhysicsWorld({ rate: { num: 60, den: 1 }, gravity, memory: worldMemory(false) });
182
+ using physics = new Physics(null, { arena: world.arena, gravity });
183
+ const spline = new Spline([[0, 0, -8], [0, 0, 0], [0, 0, 16]]);
184
+ const traction = { dry: 0.8, wet: 0.25 };
185
+ const surfaces = new RoadSurfaces();
186
+ surfaces.add(physics, road(spline), { traction, wetness: 0.5 });
187
+ const wheels = [-1, 1].flatMap((end) => [-1, 1].map((side) => ({
188
+ position: [0.65 * side, -0.15, end] as const, radius: 0.3, steer: end > 0, suspensionStiffness: 18,
189
+ })));
190
+ const { body, vehicle } = await addRoadVehicle(physics, null, {
191
+ mass: 1200, size: [1.3, 0.36, 2.4], position: [0, 0.614, 0], groundMaterial: surfaces.sample, wheels,
192
+ });
193
+ const lane = await RoadDriver.create();
194
+ world.add(new RigidSolver(), { physics });
195
+ world.add(lane, { vehicles: [{ body: body.row, path: roadDrivePath(spline), traction, wheelbase: 2, maxSpeed: 4, attachment: vehicle }] });
196
+ world.couple([lane.id, 'rigid'], 'staggered');
197
+ const unbind = lane.bindVehicle(world, physics, 0);
198
+ try {
199
+ world.advance(90);
200
+ if (body.position[2] < 1) throw new Error('Expected the lane-driven car to move at least 1 m');
201
+ } finally {
202
+ unbind();
203
+ }
204
+ ```
205
+
206
+ `commandsField` uses layout 1 with f64 words for steer, throttle, brake, target speed, measured speed, route progress, relative wetness and segment index. The first three words are normalized `VehicleInput` values. `RoadDriver.read()` returns a copy. `addRoadVehicle()` uses the visual asset's actual dimensions and a supplied measured mass. Provide the asset's local forward direction when it differs from +Z. For wind, pass a `Wind` field such as Weather's `BoundaryLayerWind` and add the existing `AirSolver` to drive the optional attachment on the world clock.
@@ -46,6 +46,10 @@ export interface RoadDriverParams {
46
46
  /** Required if rigid body positions and this lane are in different world cells. */
47
47
  readonly cellSize?: number;
48
48
  }
49
+ /**
50
+ * Options for the road driver: its registry prefix (default 'road-driver') and an optional relative wetness
51
+ * field.
52
+ */
49
53
  export interface RoadDriverOptions {
50
54
  /** Registry prefix. Default 'road-driver'. */
51
55
  readonly id?: string;
@@ -19,6 +19,10 @@ export interface RoadColliderOptions extends RoadSurfaceOptions {
19
19
  /** Offset from the physics world origin, m. Default [0, 0, 0]. */
20
20
  readonly position?: WheelGroundContact['point'];
21
21
  }
22
+ /**
23
+ * Returns the grip coefficient for a road given its dry and wet traction and a relative wetness from 0 to 1
24
+ * (default 0). Throws when the coefficients or the wetness are out of range.
25
+ */
22
26
  export declare function roadGrip(traction: RoadTraction, wetness?: number): number;
23
27
  /** Per-collider measured tyre grip and soil response. Pass `sample` as a Vehicle's `groundMaterial`. */
24
28
  export declare class RoadSurfaces {
@@ -16,6 +16,7 @@ export interface RoadVehicleOptions extends VehicleOptions {
16
16
  /** Optional air field. Add an AirSolver when stepping the attachment on a PhysicsWorld clock. */
17
17
  readonly wind?: Wind;
18
18
  }
19
+ /** A road vehicle ready to step: its physics body, its vehicle and the optional wind force. */
19
20
  export interface RoadVehicleAssembly {
20
21
  readonly body: PhysicsBody;
21
22
  readonly vehicle: Vehicle;
@@ -1,16 +1,16 @@
1
- /** `@margoengine/math`'s MargoErrorCode, repeated here because shared code cannot import the package. */
2
- export type MargoErrorCode = 'disposed' | 'attached' | 'state' | 'unsupported' | 'failed' | 'timeout' | 'version';
3
- /** An Error named `MargoError` with `code`: what `new MargoError(code, message)` builds, without the class. */
4
- export function margoError(code: MargoErrorCode, message: string): Error & { code: MargoErrorCode };
5
- /** `margoError` whose message links to `anchor` (default the code) on margoengine.com/errors. */
6
- export function fault(code: MargoErrorCode, message: string, anchor?: string): Error & { code: MargoErrorCode };
7
- /** TypeError whose message links to `anchor` on margoengine.com/errors. */
8
- export function typeError(message: string, anchor: string): TypeError;
9
- /** RangeError whose message links to `anchor` on margoengine.com/errors. */
10
- export function rangeError(message: string, anchor: string): RangeError;
11
-
12
- /** Throws a TypeError with code `transform` and the retained-vector help message. */
13
- export function vectorAssignment(): never;
14
-
15
- /** Coded error with CSP help for policy-blocked Wasm initialization; other errors pass through. */
16
- export function wasmError(error: unknown): unknown;
1
+ /** `@margoengine/math`'s MargoErrorCode, repeated here because shared code cannot import the package. */
2
+ export type MargoErrorCode = 'disposed' | 'attached' | 'state' | 'unsupported' | 'failed' | 'timeout' | 'version';
3
+ /** An Error named `MargoError` with `code`: what `new MargoError(code, message)` builds, without the class. */
4
+ export function margoError(code: MargoErrorCode, message: string): Error & { code: MargoErrorCode };
5
+ /** `margoError` whose message links to `anchor` (default the code) on margoengine.com/errors. */
6
+ export function fault(code: MargoErrorCode, message: string, anchor?: string): Error & { code: MargoErrorCode };
7
+ /** TypeError whose message links to `anchor` on margoengine.com/errors. */
8
+ export function typeError(message: string, anchor: string): TypeError;
9
+ /** RangeError whose message links to `anchor` on margoengine.com/errors. */
10
+ export function rangeError(message: string, anchor: string): RangeError;
11
+
12
+ /** Throws a TypeError with code `transform` and the retained-vector help message. */
13
+ export function vectorAssignment(): never;
14
+
15
+ /** Coded error with CSP help for policy-blocked Wasm initialization; other errors pass through. */
16
+ export function wasmError(error: unknown): unknown;
package/package.json CHANGED
@@ -1,106 +1,106 @@
1
- {
2
- "name": "@margoengine/road",
3
- "version": "0.1.0",
4
- "description": "Arc-length spline road surfaces, raised curbs and tiled UVs.",
5
- "keywords": [
6
- "margoengine",
7
- "webgpu",
8
- "3d",
9
- "road"
10
- ],
11
- "homepage": "https://margoengine.com",
12
- "bugs": {
13
- "url": "https://github.com/scottcampbelldata/margoengine/issues"
14
- },
15
- "repository": {
16
- "type": "git",
17
- "url": "git+https://github.com/scottcampbelldata/margoengine.git",
18
- "directory": "packages/road"
19
- },
20
- "license": "Apache-2.0",
21
- "author": "Scott Campbell",
22
- "type": "module",
23
- "sideEffects": false,
24
- "exports": {
25
- ".": {
26
- "types": "./dist/index.d.ts",
27
- "import": "./dist/index.js"
28
- },
29
- "./junctions": {
30
- "types": "./dist/junctions.d.ts",
31
- "import": "./dist/junctions.js"
32
- },
33
- "./driving": {
34
- "types": "./dist/driving.d.ts",
35
- "import": "./dist/driving.js"
36
- },
37
- "./banking": {
38
- "types": "./dist/banking.d.ts",
39
- "import": "./dist/banking.js"
40
- },
41
- "./terrain": {
42
- "types": "./dist/terrain.d.ts",
43
- "import": "./dist/terrain.js"
44
- },
45
- "./repair": {
46
- "types": "./dist/repair.d.ts",
47
- "import": "./dist/repair.js"
48
- },
49
- "./markings": {
50
- "types": "./dist/markings.d.ts",
51
- "import": "./dist/markings.js"
52
- },
53
- "./graph": {
54
- "types": "./dist/graph.d.ts",
55
- "import": "./dist/graph.js"
56
- },
57
- "./intersections": {
58
- "types": "./dist/intersections.d.ts",
59
- "import": "./dist/intersections.js"
60
- },
61
- "./lanes": {
62
- "types": "./dist/lanes.d.ts",
63
- "import": "./dist/lanes.js"
64
- },
65
- "./geojson": {
66
- "types": "./dist/geojson.d.ts",
67
- "import": "./dist/geojson.js"
68
- },
69
- "./structures": {
70
- "types": "./dist/structures.d.ts",
71
- "import": "./dist/structures.js"
72
- }
73
- },
74
- "files": [
75
- "dist",
76
- "LICENSE",
77
- "NOTICE"
78
- ],
79
- "publishConfig": {
80
- "access": "public"
81
- },
82
- "dependencies": {
83
- "@margoengine/math": "^0.1.0",
84
- "@margoengine/splines": "^0.1.0",
85
- "@margoengine/geometry": "^0.1.0",
86
- "@margoengine/bvh": "^0.1.0",
87
- "@margoengine/post": "^0.1.0",
88
- "@margoengine/compute": "^0.1.0"
89
- },
90
- "peerDependencies": {
91
- "@margoengine/core": "^0.1.0",
92
- "@margoengine/physics": "^0.1.0"
93
- },
94
- "peerDependenciesMeta": {
95
- "@margoengine/physics": {
96
- "optional": true
97
- }
98
- },
99
- "scripts": {
100
- "build": "node ../../scripts/build-optional.js road",
101
- "test": "npm run build && node --test test/*.test.js tests/coupling/*.test.js",
102
- "prepack": "npm run build",
103
- "test:gpu": "node test/browser-check.mjs",
104
- "test:browser:driving": "node test/driving-browser.mjs"
105
- }
106
- }
1
+ {
2
+ "name": "@margoengine/road",
3
+ "version": "1.0.0",
4
+ "description": "Arc-length spline road surfaces, raised curbs and tiled UVs.",
5
+ "keywords": [
6
+ "margoengine",
7
+ "webgpu",
8
+ "3d",
9
+ "road"
10
+ ],
11
+ "homepage": "https://margoengine.com",
12
+ "bugs": {
13
+ "url": "https://github.com/scottcampbelldata/margoengine/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/scottcampbelldata/margoengine.git",
18
+ "directory": "packages/road"
19
+ },
20
+ "license": "Apache-2.0",
21
+ "author": "Scott Campbell",
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.js"
28
+ },
29
+ "./junctions": {
30
+ "types": "./dist/junctions.d.ts",
31
+ "import": "./dist/junctions.js"
32
+ },
33
+ "./driving": {
34
+ "types": "./dist/driving.d.ts",
35
+ "import": "./dist/driving.js"
36
+ },
37
+ "./banking": {
38
+ "types": "./dist/banking.d.ts",
39
+ "import": "./dist/banking.js"
40
+ },
41
+ "./terrain": {
42
+ "types": "./dist/terrain.d.ts",
43
+ "import": "./dist/terrain.js"
44
+ },
45
+ "./repair": {
46
+ "types": "./dist/repair.d.ts",
47
+ "import": "./dist/repair.js"
48
+ },
49
+ "./markings": {
50
+ "types": "./dist/markings.d.ts",
51
+ "import": "./dist/markings.js"
52
+ },
53
+ "./graph": {
54
+ "types": "./dist/graph.d.ts",
55
+ "import": "./dist/graph.js"
56
+ },
57
+ "./intersections": {
58
+ "types": "./dist/intersections.d.ts",
59
+ "import": "./dist/intersections.js"
60
+ },
61
+ "./lanes": {
62
+ "types": "./dist/lanes.d.ts",
63
+ "import": "./dist/lanes.js"
64
+ },
65
+ "./geojson": {
66
+ "types": "./dist/geojson.d.ts",
67
+ "import": "./dist/geojson.js"
68
+ },
69
+ "./structures": {
70
+ "types": "./dist/structures.d.ts",
71
+ "import": "./dist/structures.js"
72
+ }
73
+ },
74
+ "files": [
75
+ "dist",
76
+ "LICENSE",
77
+ "NOTICE"
78
+ ],
79
+ "publishConfig": {
80
+ "access": "public"
81
+ },
82
+ "dependencies": {
83
+ "@margoengine/math": "^1.0.0",
84
+ "@margoengine/splines": "^1.0.0",
85
+ "@margoengine/geometry": "^1.0.0",
86
+ "@margoengine/bvh": "^1.0.0",
87
+ "@margoengine/post": "^1.0.0",
88
+ "@margoengine/compute": "^1.0.0"
89
+ },
90
+ "peerDependencies": {
91
+ "@margoengine/core": "^1.0.0",
92
+ "@margoengine/physics": "^1.0.0"
93
+ },
94
+ "peerDependenciesMeta": {
95
+ "@margoengine/physics": {
96
+ "optional": true
97
+ }
98
+ },
99
+ "scripts": {
100
+ "build": "node ../../scripts/build-optional.js road",
101
+ "test": "npm run build && node --test test/*.test.js tests/coupling/*.test.js",
102
+ "prepack": "npm run build",
103
+ "test:gpu": "node test/browser-check.mjs",
104
+ "test:browser:driving": "node test/driving-browser.mjs"
105
+ }
106
+ }