@thi.ng/geom-axidraw 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
1
+ # Change Log
2
+
3
+ - **Last updated**: 2022-12-10T14:04:38Z
4
+ - **Generator**: [thi.ng/monopub](https://thi.ng/monopub)
5
+
6
+ All notable changes to this project will be documented in this file.
7
+ See [Conventional Commits](https://conventionalcommits.org/) for commit guidelines.
8
+
9
+ **Note:** Unlisted _patch_ versions only involve non-code or otherwise excluded changes
10
+ and/or version bumps of transitive dependencies.
11
+
12
+ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/geom-axidraw@0.1.0) (2022-12-10)
13
+
14
+ #### 🚀 Features
15
+
16
+ - import as new pkg ([87e4945](https://github.com/thi-ng/umbrella/commit/87e4945))
17
+ - add shape/point ordering support ([58b3b5d](https://github.com/thi-ng/umbrella/commit/58b3b5d))
18
+ - add Point/ShapeOrdering types
19
+ - add pointsByProximity()/shapesByProximity() HOF ordering fns
20
+ - add AxiDrawAttribs.sort attrib
21
+ - add/update doc strings
22
+ - update deps
23
+ - add/update AsAxiDrawOpts ([24f8abe](https://github.com/thi-ng/umbrella/commit/24f8abe))
24
+ - update points & polyline handling
25
+ - add pointsByNearestNeighbor() ordering ([d1ebd21](https://github.com/thi-ng/umbrella/commit/d1ebd21))
26
+ - use pointsByNearestNeighbor() as default for point clouds
27
+ - new method is 25%-30% faster than pointsByProximity()
28
+ - update PointOrdering/ShapeOrdering return types
29
+ - update doc strings
30
+ - update deps
31
+
32
+ #### ♻️ Refactoring
33
+
34
+ - internal restructure, add docs ([443c12c](https://github.com/thi-ng/umbrella/commit/443c12c))
package/LICENSE ADDED
@@ -0,0 +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 {yyyy} {name of copyright owner}
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/README.md ADDED
@@ -0,0 +1,257 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+
3
+ # ![geom-axidraw](https://media.thi.ng/umbrella/banners-20220914/thing-geom-axidraw.svg?97576ad9)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/geom-axidraw.svg)](https://www.npmjs.com/package/@thi.ng/geom-axidraw)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/geom-axidraw.svg)
7
+ [![Twitter Follow](https://img.shields.io/twitter/follow/thing_umbrella.svg?style=flat-square&label=twitter)](https://twitter.com/thing_umbrella)
8
+
9
+ This project is part of the
10
+ [@thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo.
11
+
12
+ - [About](#about)
13
+ - [Supported shape types](#supported-shape-types)
14
+ - [AxiDraw specific shape attributes](#axidraw-specific-shape-attributes)
15
+ - [Shape interpolation/resampling](#shape-interpolationresampling)
16
+ - [Draw order](#draw-order)
17
+ - [Basic usage & examples](#basic-usage--examples)
18
+ - [Interpolated polygons](#interpolated-polygons)
19
+ - [Clipping](#clipping)
20
+ - [Status](#status)
21
+ - [Related packages](#related-packages)
22
+ - [Installation](#installation)
23
+ - [Dependencies](#dependencies)
24
+ - [API](#api)
25
+ - [Authors](#authors)
26
+ - [License](#license)
27
+
28
+ ## About
29
+
30
+ Conversion and preparation of thi.ng/geom shapes & shape groups to AxiDraw pen plotter draw commands. This is a support package for [@thi.ng/geom](https://github.com/thi-ng/umbrella/tree/develop/packages/geom).
31
+
32
+ This package only deals with the conversion aspects. The
33
+ [@thi.ng/axidraw](https://github.com/thi-ng/umbrella/blob/develop/packages/axidraw)
34
+ is responsible for the actual plotter output...
35
+
36
+ ### Supported shape types
37
+
38
+ | Shape type | Remarks |
39
+ |------------|-------------------------------------------------|
40
+ | arc | elliptic arc<sup>(1)</sup> |
41
+ | circle | circle<sup>(1)</sup> |
42
+ | cubic | cubic bezier segment<sup>(1)</sup> |
43
+ | ellipse | ellipse<sup>(1)</sup> |
44
+ | group | shape group (possibly nested) |
45
+ | line | line segment<sup>(2)</sup> |
46
+ | path | single outline only, no holes |
47
+ | points | point cloud (stippling) |
48
+ | polyline | polyline (any number of vertices)<sup>(2)</sup> |
49
+ | polygon | simple polygon, no holes<sup>(2)</sup> |
50
+ | quad | arbitrary 4-gon<sup>(2)</sup> |
51
+ | quadratic | quadratic bezier segment<sup>(1)</sup> |
52
+ | rect | axis aligned rectangle<sup>(2)</sup> |
53
+ | triangle | triangle<sup>(2)</sup> |
54
+
55
+ - <sup>(1)</sup> always interpolated/sampled
56
+ - <sup>(2)</sup> only interpolated if forced via attrib
57
+
58
+ ### AxiDraw specific shape attributes
59
+
60
+ All
61
+ [thi.ng/geom](https://github.com/thi-ng/umbrella/blob/develop/packages/geom/)
62
+ shape types have support for arbitrary attributes. Different support packages
63
+ can then utilize these attribs to customize usage or behaviors. In this case,
64
+ any package-specific attribs must be stored under the `__axi` key:
65
+
66
+ - `clip`: Optional clip polygon vertices (if given only the parts of strokes
67
+ inside that polygon will be plotted)
68
+ - `delayDown`: Shape specific delay (in ms), i.e. initial hold time for the
69
+ stroke or when stippling...
70
+ - `delayUp`: Delay for pen up command at the end this particular
71
+ shape/polyline/point.
72
+ - `down`: Pen down position (in \%) for this particular shape/polyline. Will be
73
+ reset to globally configured default at the end of the shape.
74
+ - `speed`: Speed factor (multiple of globally configured draw speed). Depending
75
+ on pen used, slower speeds might result in thicker strokes.
76
+ - `sort`: Ordering function (in lieu of full path planning/optimization, which
77
+ is planned for a later stage). For shapes other than `points()`, order of
78
+ appearance is used by default.
79
+
80
+ ```ts
81
+ // a circle which will be plotted at only 10% of the normal speed
82
+ circle(100, { __axi: { speed: 0.1 } })
83
+ ```
84
+
85
+ #### Shape interpolation/resampling
86
+
87
+ Since many of the supported shapes are not inherently vertex-based, their
88
+ boundaries/outlines need to be sampled when they are being converted to
89
+ polylines. Therefore, in addition to the above attributes, the thi.ng/geom
90
+ package itself also makes use of the `__samples` attribute to control the
91
+ re-sampling of individual shapes. Please see the following links for more
92
+ details and supported options:
93
+
94
+ - [`SamplingOpts`](https://docs.thi.ng/umbrella/geom-api/interfaces/SamplingOpts.html)
95
+ - [`vertices()`](https://docs.thi.ng/umbrella/geom/functions/vertices.html)
96
+
97
+ ### Draw order
98
+
99
+ As mentioned above, the default draw order for shapes within a group is order of
100
+ appearance. For point clouds, the {@link pointsByNearestNeighbor} ordering
101
+ function is used by default, which attempts to minimize travel distance between
102
+ points.
103
+
104
+ Currently, the following ordering functions are available, but custom
105
+ implementations can be provided too...
106
+
107
+ - [`pointsByNearestNeighbor()`](https://docs.thi.ng/umbrella/geom-axidraw/functions/pointsByNearestNeighbor.html)
108
+ - [`pointsByProximity()`](https://docs.thi.ng/umbrella/geom-axidraw/functions/pointsByProximity.html)
109
+ - [`shapesByProximity()`](https://docs.thi.ng/umbrella/geom-axidraw/functions/shapesByProximity.html)
110
+
111
+ ### Basic usage & examples
112
+
113
+ The main function of this package is the polymorphic function
114
+ [`asAxiDraw()`](https://docs.thi.ng/umbrella/geom-axidraw/functions/asAxiDraw.html),
115
+ which converts any of the supported shape types into an iterable of
116
+ [thi.ng/axidraw](https://github.com/thi-ng/umbrella/blob/develop/packages/axidraw)
117
+ drawing commands. This conversion happens **semi-lazily** (via generator
118
+ functions) to minimize memory usage and spread out the computational load of the
119
+ conversions.
120
+
121
+ The below example can be directly launched via `node cubics.js` (obviously
122
+ provided you have an AxiDraw connected and all listed packages installed):
123
+
124
+ #### Interpolated polygons
125
+
126
+ (Result: https://mastodon.thi.ng/@toxi/109473655772673067)
127
+
128
+ ```ts tangle:export/readme-cubics.ts
129
+ import { AxiDraw } from "@thi.ng/axidraw";
130
+ import { asCubic, group, pathFromCubics, star } from "@thi.ng/geom";
131
+ import { asAxiDraw } from "@thi.ng/geom-axidraw";
132
+ import { map, range } from "@thi.ng/transducers";
133
+
134
+ (async () => {
135
+ // create group of bezier-interpolated star polygons,
136
+ // with each path using a slightly different configuration
137
+ const geo = group({ translate: [100, 100] }, [
138
+ ...map(
139
+ (t) =>
140
+ pathFromCubics(
141
+ asCubic(star(90, 6, [t, 1]), {
142
+ breakPoints: true,
143
+ scale: 0.66,
144
+ })
145
+ ),
146
+ range(0.3, 1.01, 0.05)
147
+ ),
148
+ ]);
149
+
150
+ // connect to plotter
151
+ const axi = new AxiDraw();
152
+ await axi.connect();
153
+ // convert geometry to drawing commands & send to plotter
154
+ await axi.draw(asAxiDraw(geo, { samples: 40 }));
155
+ })();
156
+ ```
157
+
158
+ ### Clipping
159
+
160
+ (Result: https://mastodon.thi.ng/@toxi/109483553358349473)
161
+
162
+ ```ts tangle:export/readme-clipping.ts
163
+ import { AxiDraw, complete } from "@thi.ng/axidraw";
164
+ import { circle, group, starWithCentroid, vertices } from "@thi.ng/geom";
165
+ import { asAxiDraw } from "@thi.ng/geom-axidraw";
166
+ import { map, range } from "@thi.ng/transducers";
167
+
168
+ (async () => {
169
+ const origin = [100, 100];
170
+ const radius = 50;
171
+ const boundary = starWithCentroid(origin, radius, 5, [1, 0.45], { __axi: { speed: 0.25 } });
172
+ // group of concentric circles using boundary as clip polygon
173
+ const geo = group({}, [
174
+ boundary,
175
+ group({ __samples: 40, __axi: { clip: vertices(boundary) } }, [
176
+ ...map((r) => circle(origin, r), range(2, radius, 2)),
177
+ ]),
178
+ ]);
179
+ const axi = new AxiDraw();
180
+ await axi.connect();
181
+ await axi.draw(asAxiDraw(geo));
182
+ })();
183
+ ```
184
+
185
+ ## Status
186
+
187
+ **ALPHA** - bleeding edge / work-in-progress
188
+
189
+ [Search or submit any issues for this package](https://github.com/thi-ng/umbrella/issues?q=%5Bgeom-axidraw%5D+in%3Atitle)
190
+
191
+ ## Related packages
192
+
193
+ - [@thi.ng/axidraw](https://github.com/thi-ng/umbrella/tree/develop/packages/axidraw) - Minimal AxiDraw plotter/drawing machine controller for Node.js
194
+
195
+ ## Installation
196
+
197
+ ```bash
198
+ yarn add @thi.ng/geom-axidraw
199
+ ```
200
+
201
+ ES module import:
202
+
203
+ ```html
204
+ <script type="module" src="https://cdn.skypack.dev/@thi.ng/geom-axidraw"></script>
205
+ ```
206
+
207
+ [Skypack documentation](https://docs.skypack.dev/)
208
+
209
+ For Node.js REPL:
210
+
211
+ ```text
212
+ # with flag only for < v16
213
+ node --experimental-repl-await
214
+
215
+ > const geomAxidraw = await import("@thi.ng/geom-axidraw");
216
+ ```
217
+
218
+ Package sizes (brotli'd, pre-treeshake): ESM: 856 bytes
219
+
220
+ ## Dependencies
221
+
222
+ - [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
223
+ - [@thi.ng/arrays](https://github.com/thi-ng/umbrella/tree/develop/packages/arrays)
224
+ - [@thi.ng/axidraw](https://github.com/thi-ng/umbrella/tree/develop/packages/axidraw)
225
+ - [@thi.ng/compare](https://github.com/thi-ng/umbrella/tree/develop/packages/compare)
226
+ - [@thi.ng/defmulti](https://github.com/thi-ng/umbrella/tree/develop/packages/defmulti)
227
+ - [@thi.ng/geom](https://github.com/thi-ng/umbrella/tree/develop/packages/geom)
228
+ - [@thi.ng/geom-accel](https://github.com/thi-ng/umbrella/tree/develop/packages/geom-accel)
229
+ - [@thi.ng/geom-api](https://github.com/thi-ng/umbrella/tree/develop/packages/geom-api)
230
+ - [@thi.ng/geom-clip-line](https://github.com/thi-ng/umbrella/tree/develop/packages/geom-clip-line)
231
+ - [@thi.ng/geom-isec](https://github.com/thi-ng/umbrella/tree/develop/packages/geom-isec)
232
+ - [@thi.ng/vectors](https://github.com/thi-ng/umbrella/tree/develop/packages/vectors)
233
+
234
+ ## API
235
+
236
+ [Generated API docs](https://docs.thi.ng/umbrella/geom-axidraw/)
237
+
238
+ TODO
239
+
240
+ ## Authors
241
+
242
+ Karsten Schmidt
243
+
244
+ If this project contributes to an academic publication, please cite it as:
245
+
246
+ ```bibtex
247
+ @misc{thing-geom-axidraw,
248
+ title = "@thi.ng/geom-axidraw",
249
+ author = "Karsten Schmidt",
250
+ note = "https://thi.ng/geom-axidraw",
251
+ year = 2022
252
+ }
253
+ ```
254
+
255
+ ## License
256
+
257
+ &copy; 2022 Karsten Schmidt // Apache Software License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { Fn } from "@thi.ng/api";
2
+ import type { IShape, SamplingOpts } from "@thi.ng/geom-api";
3
+ import type { ReadonlyVec } from "@thi.ng/vectors";
4
+ /**
5
+ * Package-specific shape attributes used to control conversion behavior. MUST
6
+ * be stored under the `__axi` attribute name.
7
+ *
8
+ * @remark
9
+ * Important: TODO keep this in sync with
10
+ * [PolylineOpts](https://docs.thi.ng/umbrella/axidraw/interfaces/PolylineOpts.html)
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * // a circle which will be drawn at 25% speed
15
+ * circle(100, { __axi: { speed: 0.25 } });
16
+ * ```
17
+ */
18
+ export interface AxiDrawAttribs {
19
+ /**
20
+ * Clip polygon vertices. See {@link AsAxiDrawOpts.clip}.
21
+ */
22
+ clip: ReadonlyVec[];
23
+ /**
24
+ * Optional speed factor (multiple of globally configured draw speed).
25
+ * Depending on pen used, slower speeds might result in thicker strokes.
26
+ */
27
+ speed: number;
28
+ /**
29
+ * Optional shape specific delay (in ms), i.e. initial hold time for the
30
+ * stroke or when stippling...
31
+ */
32
+ delayDown: number;
33
+ /**
34
+ * Delay for pen up command at the end this particular shape/polyline/point.
35
+ */
36
+ delayUp: number;
37
+ /**
38
+ * Pen down position (%) for this particular shape/polyline. Will be reset
39
+ * to globally configured default at the end of the shape.
40
+ */
41
+ down: number;
42
+ /**
43
+ * Ordering function (in lieu of full path planning/optimization, which is
44
+ * planned for a later stage). For shapes other than `points()`, order of
45
+ * appearance is used by default.
46
+ *
47
+ * @remarks
48
+ * Currently available implementations:
49
+ *
50
+ * - {@link pointsByNearestNeighbor} (for `points()`, default)
51
+ * - {@link pointsByProximity} (for `points()`)
52
+ * - {@link shapesByProximity} (for `group()`)
53
+ */
54
+ sort: PointOrdering | ShapeOrdering;
55
+ }
56
+ export interface AsAxiDrawOpts {
57
+ /**
58
+ * Global options for sampling non-polygonal shape. Shapes can also provide
59
+ * a `__samples` attribute to override these global options.
60
+ *
61
+ * @remarks
62
+ * References:
63
+ * - https://docs.thi.ng/umbrella/geom-api/interfaces/SamplingOpts.html
64
+ * - https://docs.thi.ng/umbrella/geom/functions/vertices.html
65
+ */
66
+ samples: number | Partial<SamplingOpts>;
67
+ /**
68
+ * Clip polygon vertices. Can also be provided per-shape as
69
+ * {@link AxiDrawAttribs.clip} (i.e. as part of a shape's `__axi` attrib).
70
+ */
71
+ clip: ReadonlyVec[];
72
+ }
73
+ export declare type PointOrdering = Fn<ReadonlyVec[], Iterable<ReadonlyVec>>;
74
+ export declare type ShapeOrdering = Fn<IShape[], Iterable<IShape>>;
75
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,45 @@
1
+ import { DrawCommand } from "@thi.ng/axidraw/api";
2
+ import type { MultiFn1O } from "@thi.ng/defmulti";
3
+ import type { IShape } from "@thi.ng/geom-api";
4
+ import type { AsAxiDrawOpts } from "./api.js";
5
+ /**
6
+ * Lazily converts given shape (or group) into an iterable of thi.ng/axidraw
7
+ * drawing commands, using optionally provided config options.
8
+ *
9
+ * @remarks
10
+ * The provided conversion options can (and will) be overridden by a shape's
11
+ * `__axi` attribute. See {@link AxiDrawAttribs} for details.
12
+ *
13
+ * Currently supported shape types (at least all types which are supported by
14
+ * the
15
+ * [`asPolyline()`](https://docs.thi.ng/umbrella/geom/functions/asPolyline.html)
16
+ * function):
17
+ *
18
+ * - arc
19
+ * - circle
20
+ * - cubic
21
+ * - ellipse
22
+ * - group
23
+ * - line
24
+ * - path
25
+ * - points
26
+ * - polygon
27
+ * - polyline
28
+ * - quad
29
+ * - quadratic
30
+ * - rect
31
+ * - triangle
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * [...asAxiDraw(circle(100), { samples: 100 })]
36
+ * [
37
+ * [ 'm', [ 10, 0 ] ],
38
+ * [ 'd' ],
39
+ * [ 'm', [ 9.980267284282716, 0.6279051952931337 ], undefined ],
40
+ * ...
41
+ * ]
42
+ * ```
43
+ */
44
+ export declare const asAxiDraw: MultiFn1O<IShape, Partial<AsAxiDrawOpts>, Iterable<DrawCommand>>;
45
+ //# sourceMappingURL=as-axidraw.d.ts.map
package/as-axidraw.js ADDED
@@ -0,0 +1,120 @@
1
+ import { UP } from "@thi.ng/axidraw/api";
2
+ import { polyline } from "@thi.ng/axidraw/polyline";
3
+ import { defmulti } from "@thi.ng/defmulti/defmulti";
4
+ import { clipPolylinePoly } from "@thi.ng/geom-clip-line/clip-poly";
5
+ import { pointInPolygon2 } from "@thi.ng/geom-isec/point";
6
+ import { applyTransforms } from "@thi.ng/geom/apply-transforms";
7
+ import { asPolyline } from "@thi.ng/geom/as-polyline";
8
+ import { __dispatch } from "@thi.ng/geom/internal/dispatch";
9
+ import { pointsByNearestNeighbor } from "./sort.js";
10
+ /**
11
+ * Lazily converts given shape (or group) into an iterable of thi.ng/axidraw
12
+ * drawing commands, using optionally provided config options.
13
+ *
14
+ * @remarks
15
+ * The provided conversion options can (and will) be overridden by a shape's
16
+ * `__axi` attribute. See {@link AxiDrawAttribs} for details.
17
+ *
18
+ * Currently supported shape types (at least all types which are supported by
19
+ * the
20
+ * [`asPolyline()`](https://docs.thi.ng/umbrella/geom/functions/asPolyline.html)
21
+ * function):
22
+ *
23
+ * - arc
24
+ * - circle
25
+ * - cubic
26
+ * - ellipse
27
+ * - group
28
+ * - line
29
+ * - path
30
+ * - points
31
+ * - polygon
32
+ * - polyline
33
+ * - quad
34
+ * - quadratic
35
+ * - rect
36
+ * - triangle
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * [...asAxiDraw(circle(100), { samples: 100 })]
41
+ * [
42
+ * [ 'm', [ 10, 0 ] ],
43
+ * [ 'd' ],
44
+ * [ 'm', [ 9.980267284282716, 0.6279051952931337 ], undefined ],
45
+ * ...
46
+ * ]
47
+ * ```
48
+ */
49
+ export const asAxiDraw = defmulti(__dispatch, {
50
+ arc: "circle",
51
+ cubic: "circle",
52
+ ellipse: "circle",
53
+ line: "polyline",
54
+ path: "circle",
55
+ poly: "polyline",
56
+ quad: "polyline",
57
+ quadratic: "circle",
58
+ rect: "polyline",
59
+ tri: "polyline",
60
+ }, {
61
+ points: ($, opts) => __points(applyTransforms($).points, $.attribs, opts),
62
+ // used for all shapes which need to be sampled
63
+ circle: ($, opts) => __polyline(asPolyline(applyTransforms($), opts?.samples).points, $.attribs, opts),
64
+ // ignore sample opts for polyline & other polygonal shapes
65
+ // i.e. use points verbatim
66
+ polyline: ($, opts) => __polyline(asPolyline(applyTransforms($)).points, $.attribs, opts),
67
+ group: ($, opts) => __group($, opts),
68
+ });
69
+ function* __group($, opts) {
70
+ const { sort } = __axiAttribs($.attribs);
71
+ const children = sort ? sort($.children) : $.children;
72
+ for (let child of children) {
73
+ const shape = applyTransforms(child);
74
+ shape.attribs = {
75
+ ...shape.attribs,
76
+ ...$.attribs,
77
+ };
78
+ yield* asAxiDraw(shape, opts);
79
+ }
80
+ }
81
+ function* __points(pts, attribs, opts) {
82
+ if (!pts.length)
83
+ return;
84
+ const { clip, delayDown, delayUp, down, speed, sort } = {
85
+ sort: pointsByNearestNeighbor(),
86
+ ...__axiAttribs(attribs),
87
+ };
88
+ const clipPts = clip || opts?.clip;
89
+ if (clipPts) {
90
+ pts = pts.filter((p) => !!pointInPolygon2(p, clipPts));
91
+ if (!pts.length)
92
+ return;
93
+ }
94
+ yield UP;
95
+ if (down != undefined)
96
+ yield ["pen", down];
97
+ for (let p of sort ? sort(pts) : pts) {
98
+ yield* [
99
+ ["m", p, speed],
100
+ ["d", delayDown],
101
+ ["u", delayUp],
102
+ ];
103
+ }
104
+ if (down != undefined)
105
+ yield ["pen"];
106
+ }
107
+ function* __polyline(pts, attribs, opts) {
108
+ if (!pts.length)
109
+ return;
110
+ const { clip, down, delayDown, delayUp, speed } = __axiAttribs(attribs);
111
+ const clipPts = clip || opts?.clip;
112
+ const chunks = clipPts ? clipPolylinePoly(pts, clipPts) : [pts];
113
+ if (!chunks.length)
114
+ return;
115
+ for (let chunk of chunks) {
116
+ yield* polyline(chunk, { down, delayDown, delayUp, speed });
117
+ }
118
+ }
119
+ /** @internal */
120
+ const __axiAttribs = (attribs) => attribs ? attribs.__axi || {} : {};
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./api.js";
2
+ export * from "./as-axidraw.js";
3
+ export * from "./sort.js";
4
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./api.js";
2
+ export * from "./as-axidraw.js";
3
+ export * from "./sort.js";
package/package.json ADDED
@@ -0,0 +1,121 @@
1
+ {
2
+ "name": "@thi.ng/geom-axidraw",
3
+ "version": "0.1.0",
4
+ "description": "Conversion and preparation of thi.ng/geom shapes & shape groups to AxiDraw pen plotter draw commands",
5
+ "type": "module",
6
+ "module": "./index.js",
7
+ "typings": "./index.d.ts",
8
+ "sideEffects": false,
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/thi-ng/umbrella.git"
12
+ },
13
+ "homepage": "https://github.com/thi-ng/umbrella/tree/master/packages/geom-axidraw#readme",
14
+ "funding": [
15
+ {
16
+ "type": "github",
17
+ "url": "https://github.com/sponsors/postspectacular"
18
+ },
19
+ {
20
+ "type": "patreon",
21
+ "url": "https://patreon.com/thing_umbrella"
22
+ }
23
+ ],
24
+ "author": "Karsten Schmidt <k+npm@thi.ng>",
25
+ "license": "Apache-2.0",
26
+ "scripts": {
27
+ "build": "yarn clean && tsc --declaration",
28
+ "clean": "rimraf '*.js' '*.d.ts' '*.map' doc",
29
+ "doc": "typedoc --excludePrivate --excludeInternal --out doc src/index.ts",
30
+ "doc:ae": "mkdir -p .ae/doc .ae/temp && api-extractor run --local --verbose",
31
+ "doc:readme": "yarn doc:stats && tools:readme",
32
+ "doc:stats": "tools:module-stats",
33
+ "pub": "yarn npm publish --access public",
34
+ "test": "testament test"
35
+ },
36
+ "dependencies": {
37
+ "@thi.ng/api": "^8.5.1",
38
+ "@thi.ng/arrays": "^2.4.4",
39
+ "@thi.ng/axidraw": "^0.2.0",
40
+ "@thi.ng/compare": "^2.1.18",
41
+ "@thi.ng/defmulti": "^2.1.23",
42
+ "@thi.ng/geom": "^4.0.0",
43
+ "@thi.ng/geom-accel": "^3.2.28",
44
+ "@thi.ng/geom-api": "^3.3.20",
45
+ "@thi.ng/geom-clip-line": "^2.2.0",
46
+ "@thi.ng/geom-isec": "^2.1.37",
47
+ "@thi.ng/vectors": "^7.5.26"
48
+ },
49
+ "devDependencies": {
50
+ "@microsoft/api-extractor": "^7.33.5",
51
+ "@thi.ng/testament": "^0.3.6",
52
+ "rimraf": "^3.0.2",
53
+ "tools": "^0.0.1",
54
+ "typedoc": "^0.23.20",
55
+ "typescript": "^4.8.4"
56
+ },
57
+ "keywords": [
58
+ "2d",
59
+ "axidraw",
60
+ "arc",
61
+ "bezier",
62
+ "circle",
63
+ "cubic",
64
+ "curve",
65
+ "ellipse",
66
+ "clipping",
67
+ "conversion",
68
+ "geometry",
69
+ "group",
70
+ "iterator",
71
+ "penplotter",
72
+ "path",
73
+ "points",
74
+ "polygon",
75
+ "polyline",
76
+ "polymorphic",
77
+ "quadratic",
78
+ "sample",
79
+ "shape",
80
+ "sort",
81
+ "triangle",
82
+ "typescript"
83
+ ],
84
+ "publishConfig": {
85
+ "access": "public"
86
+ },
87
+ "browser": {
88
+ "process": false,
89
+ "setTimeout": false
90
+ },
91
+ "engines": {
92
+ "node": ">=14"
93
+ },
94
+ "files": [
95
+ "./*.js",
96
+ "./*.d.ts"
97
+ ],
98
+ "exports": {
99
+ ".": {
100
+ "default": "./index.js"
101
+ },
102
+ "./api": {
103
+ "default": "./api.js"
104
+ },
105
+ "./as-axidraw": {
106
+ "default": "./as-axidraw.js"
107
+ },
108
+ "./sort": {
109
+ "default": "./sort.js"
110
+ }
111
+ },
112
+ "thi.ng": {
113
+ "parent": "@thi.ng/geom",
114
+ "related": [
115
+ "axidraw"
116
+ ],
117
+ "status": "alpha",
118
+ "year": 2022
119
+ },
120
+ "gitHead": "5178ea1d7f4b2de86cf5101bdd73f6567518c0bd\n"
121
+ }
package/sort.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { ReadonlyVec } from "@thi.ng/vectors/api";
2
+ import type { PointOrdering, ShapeOrdering } from "./api.js";
3
+ /**
4
+ * Higher order point ordering fn. Lazily sorts points by nearest neighbor
5
+ * distance, starting selection of first point based on given `ref` point
6
+ * (default: [0, 0]).
7
+ *
8
+ * @remarks
9
+ * Internally uses a
10
+ * [`KdTreeSet`](https://docs.thi.ng/umbrella/geom-accel/classes/KdTreeSet.html)
11
+ * to index all points and then successively perform efficient nearest neighbor
12
+ * searches (always w.r.t the most recent result point).
13
+ *
14
+ * @param ref
15
+ */
16
+ export declare const pointsByNearestNeighbor: (ref?: ReadonlyVec) => PointOrdering;
17
+ /**
18
+ * Higher order point ordering fn. Sorts points by proximity to given `ref` point
19
+ * (default: [0, 0]).
20
+ *
21
+ * @param ref
22
+ */
23
+ export declare const pointsByProximity: (ref?: ReadonlyVec) => PointOrdering;
24
+ /**
25
+ * Higher order shape sorting fn. Sorts shapes by their centroid's proximity to
26
+ * given `ref` point (default: [0, 0]).
27
+ *
28
+ * @param ref
29
+ */
30
+ export declare const shapesByProximity: (ref?: ReadonlyVec) => ShapeOrdering;
31
+ //# sourceMappingURL=sort.d.ts.map
package/sort.js ADDED
@@ -0,0 +1,45 @@
1
+ import { sortByCachedKey } from "@thi.ng/arrays/sort-cached";
2
+ import { compareNumAsc } from "@thi.ng/compare/numeric";
3
+ import { KdTreeSet } from "@thi.ng/geom-accel/kd-tree-set";
4
+ import { centroid } from "@thi.ng/geom/centroid";
5
+ import { ZERO2 } from "@thi.ng/vectors/api";
6
+ import { distSq2 } from "@thi.ng/vectors/distsq";
7
+ /**
8
+ * Higher order point ordering fn. Lazily sorts points by nearest neighbor
9
+ * distance, starting selection of first point based on given `ref` point
10
+ * (default: [0, 0]).
11
+ *
12
+ * @remarks
13
+ * Internally uses a
14
+ * [`KdTreeSet`](https://docs.thi.ng/umbrella/geom-accel/classes/KdTreeSet.html)
15
+ * to index all points and then successively perform efficient nearest neighbor
16
+ * searches (always w.r.t the most recent result point).
17
+ *
18
+ * @param ref
19
+ */
20
+ export const pointsByNearestNeighbor = (ref = ZERO2) => function* (pts) {
21
+ const index = new KdTreeSet(2, pts);
22
+ while (index.size) {
23
+ ref = index.queryKeys(ref, 1e4, 1)[0];
24
+ index.remove(ref);
25
+ yield ref;
26
+ }
27
+ };
28
+ /**
29
+ * Higher order point ordering fn. Sorts points by proximity to given `ref` point
30
+ * (default: [0, 0]).
31
+ *
32
+ * @param ref
33
+ */
34
+ export const pointsByProximity = (ref = ZERO2) => (pts) => {
35
+ return sortByCachedKey(pts.slice(), (p) => distSq2(p, ref), compareNumAsc);
36
+ };
37
+ /**
38
+ * Higher order shape sorting fn. Sorts shapes by their centroid's proximity to
39
+ * given `ref` point (default: [0, 0]).
40
+ *
41
+ * @param ref
42
+ */
43
+ export const shapesByProximity = (ref = ZERO2) => (shapes) => {
44
+ return sortByCachedKey(shapes.slice(), (s) => distSq2(centroid(s) || ZERO2, ref), compareNumAsc);
45
+ };