gcode-lib 1.2.0__py3-none-any.whl

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.
@@ -0,0 +1,2086 @@
1
+ Metadata-Version: 2.4
2
+ Name: gcode-lib
3
+ Version: 1.2.0
4
+ Summary: Parse, analyse, and transform G-code files — plain-text .gcode and Prusa .bgcode
5
+ Project-URL: Homepage, https://github.com/hyiger/gcode-lib
6
+ Project-URL: Repository, https://github.com/hyiger/gcode-lib
7
+ Project-URL: Bug Tracker, https://github.com/hyiger/gcode-lib/issues
8
+ Author: Hyiger
9
+ License: GNU GENERAL PUBLIC LICENSE
10
+ Version 3, 29 June 2007
11
+
12
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
13
+ Everyone is permitted to copy and distribute verbatim copies
14
+ of this license document, but changing it is not allowed.
15
+
16
+ Preamble
17
+
18
+ The GNU General Public License is a free, copyleft license for
19
+ software and other kinds of works.
20
+
21
+ The licenses for most software and other practical works are designed
22
+ to take away your freedom to share and change the works. By contrast,
23
+ the GNU General Public License is intended to guarantee your freedom to
24
+ share and change all versions of a program--to make sure it remains free
25
+ software for all its users. We, the Free Software Foundation, use the
26
+ GNU General Public License for most of our software; it applies also to
27
+ any other work released this way by its authors. You can apply it to
28
+ your programs, too.
29
+
30
+ When we speak of free software, we are referring to freedom, not
31
+ price. Our General Public Licenses are designed to make sure that you
32
+ have the freedom to distribute copies of free software (and charge for
33
+ them if you wish), that you receive source code or can get it if you
34
+ want it, that you can change the software or use pieces of it in new
35
+ free programs, and that you know you can do these things.
36
+
37
+ To protect your rights, we need to prevent others from denying you
38
+ these rights or asking you to surrender the rights. Therefore, you have
39
+ certain responsibilities if you distribute copies of the software, or if
40
+ you modify it: responsibilities to respect the freedom of others.
41
+
42
+ For example, if you distribute copies of such a program, whether
43
+ gratis or for a fee, you must pass on to the recipients the same
44
+ freedoms that you received. You must make sure that they, too, receive
45
+ or can get the source code. And you must show them these terms so they
46
+ know their rights.
47
+
48
+ Developers that use the GNU GPL protect your rights with two steps:
49
+ (1) assert copyright on the software, and (2) offer you this License
50
+ giving you legal permission to copy, distribute and/or modify it.
51
+
52
+ For the developers' and authors' protection, the GPL clearly explains
53
+ that there is no warranty for this free software. For both users' and
54
+ authors' sake, the GPL requires that modified versions be marked as
55
+ changed, so that their problems will not be attributed erroneously to
56
+ authors of previous versions.
57
+
58
+ Some devices are designed to deny users access to install or run
59
+ modified versions of the software inside them, although the manufacturer
60
+ can do so. This is fundamentally incompatible with the aim of
61
+ protecting users' freedom to change the software. The systematic
62
+ pattern of such abuse occurs in the area of products for individuals to
63
+ use, which is precisely where it is most unacceptable. Therefore, we
64
+ have designed this version of the GPL to prohibit the practice for those
65
+ products. If such problems arise substantially in other domains, we
66
+ stand ready to extend this provision to those domains in future versions
67
+ of the GPL, as needed to protect the freedom of users.
68
+
69
+ Finally, every program is threatened constantly by software patents.
70
+ States should not allow patents to restrict development and use of
71
+ software on general-purpose computers, but in those that do, we wish to
72
+ avoid the special danger that patents applied to a free program could
73
+ make it effectively proprietary. To prevent this, the GPL assures that
74
+ patents cannot be used to render the program non-free.
75
+
76
+ The precise terms and conditions for copying, distribution and
77
+ modification follow.
78
+
79
+ TERMS AND CONDITIONS
80
+
81
+ 0. Definitions.
82
+
83
+ "This License" refers to version 3 of the GNU General Public License.
84
+
85
+ "Copyright" also means copyright-like laws that apply to other kinds of
86
+ works, such as semiconductor masks.
87
+
88
+ "The Program" refers to any copyrightable work licensed under this
89
+ License. Each licensee is addressed as "you". "Licensees" and
90
+ "recipients" may be individuals or organizations.
91
+
92
+ To "modify" a work means to copy from or adapt all or part of the work
93
+ in a fashion requiring copyright permission, other than the making of an
94
+ exact copy. The resulting work is called a "modified version" of the
95
+ earlier work or a work "based on" the earlier work.
96
+
97
+ A "covered work" means either the unmodified Program or a work based
98
+ on the Program.
99
+
100
+ To "propagate" a work means to do anything with it that, without
101
+ permission, would make you directly or secondarily liable for
102
+ infringement under applicable copyright law, except executing it on a
103
+ computer or modifying a private copy. Propagation includes copying,
104
+ distribution (with or without modification), making available to the
105
+ public, and in some countries other activities as well.
106
+
107
+ To "convey" a work means any kind of propagation that enables other
108
+ parties to make or receive copies. Mere interaction with a user through
109
+ a computer network, with no transfer of a copy, is not conveying.
110
+
111
+ An interactive user interface displays "Appropriate Legal Notices"
112
+ to the extent that it includes a convenient and prominently visible
113
+ feature that (1) displays an appropriate copyright notice, and (2)
114
+ tells the user that there is no warranty for the work (except to the
115
+ extent that warranties are provided), that licensees may convey the
116
+ work under this License, and how to view a copy of this License. If
117
+ the interface presents a list of user commands or options, such as a
118
+ menu, a prominent item in the list meets this criterion.
119
+
120
+ 1. Source Code.
121
+
122
+ The "source code" for a work means the preferred form of the work
123
+ for making modifications to it. "Object code" means any non-source
124
+ form of a work.
125
+
126
+ A "Standard Interface" means an interface that either is an official
127
+ standard defined by a recognized standards body, or, in the case of
128
+ interfaces specified for a particular programming language, one that
129
+ is widely used among developers working in that language.
130
+
131
+ The "System Libraries" of an executable work include anything, other
132
+ than the work as a whole, that (a) is included in the normal form of
133
+ packaging a Major Component, but which is not part of that Major
134
+ Component, and (b) serves only to enable use of the work with that
135
+ Major Component, or to implement a Standard Interface for which an
136
+ implementation is available to the public in source code form. A
137
+ "Major Component", in this context, means a major essential component
138
+ (kernel, window system, and so on) of the specific operating system
139
+ (if any) on which the executable work runs, or a compiler used to
140
+ produce the work, or an object code interpreter used to run it.
141
+
142
+ The "Corresponding Source" for a work in object code form means all
143
+ the source code needed to generate, install, and (for an executable
144
+ work) run the object code and to modify the work, including scripts to
145
+ control those activities. However, it does not include the work's
146
+ System Libraries, or general-purpose tools or generally available free
147
+ programs which are used unmodified in performing those activities but
148
+ which are not part of the work. For example, Corresponding Source
149
+ includes interface definition files associated with source files for
150
+ the work, and the source code for shared libraries and dynamically
151
+ linked subprograms that the work is specifically designed to require,
152
+ such as by intimate data communication or control flow between those
153
+ subprograms and other parts of the work.
154
+
155
+ The Corresponding Source need not include anything that users
156
+ can regenerate automatically from other parts of the Corresponding
157
+ Source.
158
+
159
+ The Corresponding Source for a work in source code form is that
160
+ same work.
161
+
162
+ 2. Basic Permissions.
163
+
164
+ All rights granted under this License are granted for the term of
165
+ copyright on the Program, and are irrevocable provided the stated
166
+ conditions are met. This License explicitly affirms your unlimited
167
+ permission to run the unmodified Program. The output from running a
168
+ covered work is covered by this License only if the output, given its
169
+ content, constitutes a covered work. This License acknowledges your
170
+ rights of fair use or other equivalent, as provided by copyright law.
171
+
172
+ You may make, run and propagate covered works that you do not
173
+ convey, without conditions so long as your license otherwise remains
174
+ in force. You may convey covered works to others for the sole purpose
175
+ of having them make modifications exclusively for you, or provide you
176
+ with facilities for running those works, provided that you comply with
177
+ the terms of this License in conveying all material for which you do
178
+ not control copyright. Those thus making or running the covered works
179
+ for you must do so exclusively on your behalf, under your direction
180
+ and control, on terms that prohibit them from making any copies of
181
+ your copyrighted material outside their relationship with you.
182
+
183
+ Conveying under any other circumstances is permitted solely under
184
+ the conditions stated below. Sublicensing is not allowed; section 10
185
+ makes it unnecessary.
186
+
187
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
188
+
189
+ No covered work shall be deemed part of an effective technological
190
+ measure under any applicable law fulfilling obligations under article
191
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
192
+ similar laws prohibiting or restricting circumvention of such
193
+ measures.
194
+
195
+ When you convey a covered work, you waive any legal power to forbid
196
+ circumvention of technological measures to the extent such circumvention
197
+ is effected by exercising rights under this License with respect to
198
+ the covered work, and you disclaim any intention to limit operation or
199
+ modification of the work as a means of enforcing, against the work's
200
+ users, your or third parties' legal rights to forbid circumvention of
201
+ technological measures.
202
+
203
+ 4. Conveying Verbatim Copies.
204
+
205
+ You may convey verbatim copies of the Program's source code as you
206
+ receive it, in any medium, provided that you conspicuously and
207
+ appropriately publish on each copy an appropriate copyright notice;
208
+ keep intact all notices stating that this License and any
209
+ non-permissive terms added in accord with section 7 apply to the code;
210
+ keep intact all notices of the absence of any warranty; and give all
211
+ recipients a copy of this License along with the Program.
212
+
213
+ You may charge any price or no price for each copy that you convey,
214
+ and you may offer support or warranty protection for a fee.
215
+
216
+ 5. Conveying Modified Source Versions.
217
+
218
+ You may convey a work based on the Program, or the modifications to
219
+ produce it from the Program, in the form of source code under the
220
+ terms of section 4, provided that you also meet all of these conditions:
221
+
222
+ a) The work must carry prominent notices stating that you modified
223
+ it, and giving a relevant date.
224
+
225
+ b) The work must carry prominent notices stating that it is
226
+ released under this License and any conditions added under section
227
+ 7. This requirement modifies the requirement in section 4 to
228
+ "keep intact all notices".
229
+
230
+ c) You must license the entire work, as a whole, under this
231
+ License to anyone who comes into possession of a copy. This
232
+ License will therefore apply, along with any applicable section 7
233
+ additional terms, to the whole of the work, and all its parts,
234
+ regardless of how they are packaged. This License gives no
235
+ permission to license the work in any other way, but it does not
236
+ invalidate such permission if you have separately received it.
237
+
238
+ d) If the work has interactive user interfaces, each must display
239
+ Appropriate Legal Notices; however, if the Program has interactive
240
+ interfaces that do not display Appropriate Legal Notices, your
241
+ work need not make them do so.
242
+
243
+ A compilation of a covered work with other separate and independent
244
+ works, which are not by their nature extensions of the covered work,
245
+ and which are not combined with it such as to form a larger program,
246
+ in or on a volume of a storage or distribution medium, is called an
247
+ "aggregate" if the compilation and its resulting copyright are not
248
+ used to limit the access or legal rights of the compilation's users
249
+ beyond what the individual works permit. Inclusion of a covered work
250
+ in an aggregate does not cause this License to apply to the other
251
+ parts of the aggregate.
252
+
253
+ 6. Conveying Non-Source Forms.
254
+
255
+ You may convey a covered work in object code form under the terms
256
+ of sections 4 and 5, provided that you also convey the
257
+ machine-readable Corresponding Source under the terms of this License,
258
+ in one of these ways:
259
+
260
+ a) Convey the object code in, or embodied in, a physical product
261
+ (including a physical distribution medium), accompanied by the
262
+ Corresponding Source fixed on a durable physical medium
263
+ customarily used for software interchange.
264
+
265
+ b) Convey the object code in, or embodied in, a physical product
266
+ (including a physical distribution medium), accompanied by a
267
+ written offer, valid for at least three years and valid for as
268
+ long as you offer spare parts or customer support for that product
269
+ model, to give anyone who possesses the object code either (1) a
270
+ copy of the Corresponding Source for all the software in the
271
+ product that is covered by this License, on a durable physical
272
+ medium customarily used for software interchange, for a price no
273
+ more than your reasonable cost of physically performing this
274
+ conveying of source, or (2) access to copy the
275
+ Corresponding Source from a network server at no charge.
276
+
277
+ c) Convey individual copies of the object code with a copy of the
278
+ written offer to provide the Corresponding Source. This
279
+ alternative is allowed only occasionally and noncommercially, and
280
+ only if you received the object code with such an offer, in accord
281
+ with subsection 6b.
282
+
283
+ d) Convey the object code by offering access from a designated
284
+ place (gratis or for a charge), and offer equivalent access to the
285
+ Corresponding Source in the same way through the same place at no
286
+ further charge. You need not require recipients to copy the
287
+ Corresponding Source along with the object code. If the place to
288
+ copy the object code is a network server, the Corresponding Source
289
+ may be on a different server (operated by you or a third party)
290
+ that supports equivalent copying facilities, provided you maintain
291
+ clear directions next to the object code saying where to find the
292
+ Corresponding Source. Regardless of what server hosts the
293
+ Corresponding Source, you remain obligated to ensure that it is
294
+ available for as long as needed to satisfy these requirements.
295
+
296
+ e) Convey the object code using peer-to-peer transmission, provided
297
+ you inform other peers where the object code and Corresponding
298
+ Source of the work are being offered to the general public at no
299
+ charge under subsection 6d.
300
+
301
+ A separable portion of the object code, whose source code is excluded
302
+ from the Corresponding Source as a System Library, need not be
303
+ included in conveying the object code work.
304
+
305
+ A "User Product" is either (1) a "consumer product", which means any
306
+ tangible personal property which is normally used for personal, family,
307
+ or household purposes, or (2) anything designed or sold for incorporation
308
+ into a dwelling. In determining whether a product is a consumer product,
309
+ doubtful cases shall be resolved in favor of coverage. For a particular
310
+ product received by a particular user, "normally used" refers to a
311
+ typical or common use of that class of product, regardless of the status
312
+ of the particular user or of the way in which the particular user
313
+ actually uses, or expects or is expected to use, the product. A product
314
+ is a consumer product regardless of whether the product has substantial
315
+ commercial, industrial or non-consumer uses, unless such uses represent
316
+ the only significant mode of use of the product.
317
+
318
+ "Installation Information" for a User Product means any methods,
319
+ procedures, authorization keys, or other information required to install
320
+ and execute modified versions of a covered work in that User Product from
321
+ a modified version of its Corresponding Source. The information must
322
+ suffice to ensure that the continued functioning of the modified object
323
+ code is in no case prevented or interfered with solely because
324
+ modification has been made.
325
+
326
+ If you convey an object code work under this section in, or with, or
327
+ specifically for use in, a User Product, and the conveying occurs as
328
+ part of a transaction in which the right of possession and use of the
329
+ User Product is transferred to the recipient in perpetuity or for a
330
+ fixed term (regardless of how the transaction is characterized), the
331
+ Corresponding Source conveyed under this section must be accompanied
332
+ by the Installation Information. But this requirement does not apply
333
+ if neither you nor any third party retains the ability to install
334
+ modified object code on the User Product (for example, the work has
335
+ been installed in ROM).
336
+
337
+ The requirement to provide Installation Information does not include a
338
+ requirement to continue to provide support service, warranty, or updates
339
+ for a work that has been modified or installed by the recipient, or for
340
+ the User Product in which it has been modified or installed. Access to a
341
+ network may be denied when the modification itself materially and
342
+ adversely affects the operation of the network or violates the rules and
343
+ protocols for communication across the network.
344
+
345
+ Corresponding Source conveyed, and Installation Information provided,
346
+ in accord with this section must be in a format that is publicly
347
+ documented (and with an implementation available to the public in
348
+ source code form), and must require no special password or key for
349
+ unpacking, reading or copying.
350
+
351
+ 7. Additional Terms.
352
+
353
+ "Additional permissions" are terms that supplement the terms of this
354
+ License by making exceptions from one or more of its conditions.
355
+ Additional permissions that are applicable to the entire Program shall
356
+ be treated as though they were included in this License, to the extent
357
+ that they are valid under applicable law. If additional permissions
358
+ apply only to part of the Program, that part may be used separately
359
+ under those permissions, but the entire Program remains governed by
360
+ this License without regard to the additional permissions.
361
+
362
+ When you convey a copy of a covered work, you may at your option
363
+ remove any additional permissions from that copy, or from any part of
364
+ it. (Additional permissions may be written to require their own
365
+ removal in certain cases when you modify the work.) You may place
366
+ additional permissions on material, added by you to a covered work,
367
+ for which you have or can give appropriate copyright permission.
368
+
369
+ Notwithstanding any other provision of this License, for material you
370
+ add to a covered work, you may (if authorized by the copyright holders of
371
+ that material) supplement the terms of this License with terms:
372
+
373
+ a) Disclaiming warranty or limiting liability differently from the
374
+ terms of sections 15 and 16 of this License; or
375
+
376
+ b) Requiring preservation of specified reasonable legal notices or
377
+ author attributions in that material or in the Appropriate Legal
378
+ Notices displayed by works containing it; or
379
+
380
+ c) Prohibiting misrepresentation of the origin of that material, or
381
+ requiring that modified versions of such material be marked in
382
+ reasonable ways as different from the original version; or
383
+
384
+ d) Limiting the use for publicity purposes of names of licensors or
385
+ authors of the material; or
386
+
387
+ e) Declining to grant rights under trademark law for use of some
388
+ trade names, trademarks, or service marks; or
389
+
390
+ f) Requiring indemnification of licensors and authors of that
391
+ material by anyone who conveys the material (or modified versions of
392
+ it) with contractual assumptions of liability to the recipient, for
393
+ any liability that these contractual assumptions directly impose on
394
+ those licensors and authors.
395
+
396
+ All other non-permissive additional terms are considered "further
397
+ restrictions" within the meaning of section 10. If the Program as you
398
+ received it, or any part of it, contains a notice stating that it is
399
+ governed by this License along with a term that is a further
400
+ restriction, you may remove that term. If a license document contains
401
+ a further restriction but permits relicensing or conveying under this
402
+ License, you may add to a covered work material governed by the terms
403
+ of that license document, provided that the further restriction does
404
+ not survive such relicensing or conveying.
405
+
406
+ If you add terms to a covered work in accord with this section, you
407
+ must place, in the relevant source files, a statement of the
408
+ additional terms that apply to those files, or a notice indicating
409
+ where to find the applicable terms.
410
+
411
+ Additional terms, permissive or non-permissive, may be stated in the
412
+ form of a separately written license, or stated as exceptions;
413
+ the above requirements apply either way.
414
+
415
+ 8. Termination.
416
+
417
+ You may not propagate or modify a covered work except as expressly
418
+ provided under this License. Any attempt otherwise to propagate or
419
+ modify it is void, and will automatically terminate your rights under
420
+ this License (including any patent licenses granted under the third
421
+ paragraph of section 11).
422
+
423
+ However, if you cease all violation of this License, then your
424
+ license from a particular copyright holder is reinstated (a)
425
+ provisionally, unless and until the copyright holder explicitly and
426
+ finally terminates your license, and (b) permanently, if the copyright
427
+ holder fails to notify you of the violation by some reasonable means
428
+ prior to 60 days after the cessation.
429
+
430
+ Moreover, your license from a particular copyright holder is
431
+ reinstated permanently if the copyright holder notifies you of the
432
+ violation by some reasonable means, this is the first time you have
433
+ received notice of violation of this License (for any work) from that
434
+ copyright holder, and you cure the violation prior to 30 days after
435
+ your receipt of the notice.
436
+
437
+ Termination of your rights under this section does not terminate the
438
+ licenses of parties who have received copies or rights from you under
439
+ this License. If your rights have been terminated and not permanently
440
+ reinstated, you do not qualify to receive new licenses for the same
441
+ material under section 10.
442
+
443
+ 9. Acceptance Not Required for Having Copies.
444
+
445
+ You are not required to accept this License in order to receive or
446
+ run a copy of the Program. Ancillary propagation of a covered work
447
+ occurring solely as a consequence of using peer-to-peer transmission
448
+ to receive a copy likewise does not require acceptance. However,
449
+ nothing other than this License grants you permission to propagate or
450
+ modify any covered work. These actions infringe copyright if you do
451
+ not accept this License. Therefore, by modifying or propagating a
452
+ covered work, you indicate your acceptance of this License to do so.
453
+
454
+ 10. Automatic Licensing of Downstream Recipients.
455
+
456
+ Each time you convey a covered work, the recipient automatically
457
+ receives a license from the original licensors, to run, modify and
458
+ propagate that work, subject to this License. You are not responsible
459
+ for enforcing compliance by third parties with this License.
460
+
461
+ An "entity transaction" is a transaction transferring control of an
462
+ organization, or substantially all assets of one, or subdividing an
463
+ organization, or merging organizations. If propagation of a covered
464
+ work results from an entity transaction, each party to that
465
+ transaction who receives a copy of the work also receives whatever
466
+ licenses to the work the party's predecessor in interest had or could
467
+ give under the previous paragraph, plus a right to possession of the
468
+ Corresponding Source of the work from the predecessor in interest, if
469
+ the predecessor has it or can get it with reasonable efforts.
470
+
471
+ You may not impose any further restrictions on the exercise of the
472
+ rights granted or affirmed under this License. For example, you may
473
+ not impose a license fee, royalty, or other charge for exercise of
474
+ rights granted under this License, and you may not initiate litigation
475
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
476
+ any patent claim is infringed by making, using, selling, offering for
477
+ sale, or importing the Program or any portion of it.
478
+
479
+ 11. Patents.
480
+
481
+ A "contributor" is a copyright holder who authorizes use under this
482
+ License of the Program or a work on which the Program is based. The
483
+ work thus licensed is called the contributor's "contributor version".
484
+
485
+ A contributor's "essential patent claims" are all patent claims
486
+ owned or controlled by the contributor, whether already acquired or
487
+ hereafter acquired, that would be infringed by some manner, permitted
488
+ by this License, of making, using, or selling its contributor version,
489
+ but do not include claims that would be infringed only as a
490
+ consequence of further modification of the contributor version. For
491
+ purposes of this definition, "control" includes the right to grant
492
+ patent sublicenses in a manner consistent with the requirements of
493
+ this License.
494
+
495
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
496
+ patent license under the contributor's essential patent claims, to
497
+ make, use, sell, offer for sale, import and otherwise run, modify and
498
+ propagate the contents of its contributor version.
499
+
500
+ In the following three paragraphs, a "patent license" is any express
501
+ agreement or commitment, however denominated, not to enforce a patent
502
+ (such as an express permission to practice a patent or covenant not to
503
+ sue for patent infringement). To "grant" such a patent license to a
504
+ party means to make such an agreement or commitment not to enforce a
505
+ patent against the party.
506
+
507
+ If you convey a covered work, knowingly relying on a patent license,
508
+ and the Corresponding Source of the work is not available for anyone
509
+ to copy, free of charge and under the terms of this License, through a
510
+ publicly available network server or other readily accessible means,
511
+ then you must either (1) cause the Corresponding Source to be so
512
+ available, or (2) arrange to deprive yourself of the benefit of the
513
+ patent license for this particular work, or (3) arrange, in a manner
514
+ consistent with the requirements of this License, to extend the patent
515
+ license to downstream recipients. "Knowingly relying" means you have
516
+ actual knowledge that, but for the patent license, your conveying the
517
+ covered work in a country, or your recipient's use of the covered work
518
+ in a country, would infringe one or more identifiable patents in that
519
+ country that you have reason to believe are valid.
520
+
521
+ If, pursuant to or in connection with a single transaction or
522
+ arrangement, you convey, or propagate by procuring conveyance of, a
523
+ covered work, and grant a patent license to some of the parties
524
+ receiving the covered work authorizing them to use, propagate, modify
525
+ or convey a specific copy of the covered work, then the patent license
526
+ you grant is automatically extended to all recipients of the covered
527
+ work and works based on it.
528
+
529
+ A patent license is "discriminatory" if it does not include within
530
+ the scope of its coverage, prohibits the exercise of, or is
531
+ conditioned on the non-exercise of one or more of the rights that are
532
+ specifically granted under this License. You may not convey a covered
533
+ work if you are a party to an arrangement with a third party that is
534
+ in the business of distributing software, under which you make payment
535
+ to the third party based on the extent of your activity of conveying
536
+ the work, and under which the third party grants, to any of the
537
+ parties who would receive the covered work from you, a discriminatory
538
+ patent license (a) in connection with copies of the covered work
539
+ conveyed by you (or copies made from those copies), or (b) primarily
540
+ for and in connection with specific products or compilations that
541
+ contain the covered work, unless you entered into that arrangement,
542
+ or that patent license was granted, prior to 28 March 2007.
543
+
544
+ Nothing in this License shall be construed as excluding or limiting
545
+ any implied license or other defenses to infringement that may
546
+ otherwise be available to you under applicable patent law.
547
+
548
+ 12. No Surrender of Others' Freedom.
549
+
550
+ If conditions are imposed on you (whether by court order, agreement or
551
+ otherwise) that contradict the conditions of this License, they do not
552
+ excuse you from the conditions of this License. If you cannot convey a
553
+ covered work so as to satisfy simultaneously your obligations under this
554
+ License and any other pertinent obligations, then as a consequence you may
555
+ not convey it at all. For example, if you agree to terms that obligate you
556
+ to collect a royalty for further conveying from those to whom you convey
557
+ the Program, the only way you could satisfy both those terms and this
558
+ License would be to refrain entirely from conveying the Program.
559
+
560
+ 13. Use with the GNU Affero General Public License.
561
+
562
+ Notwithstanding any other provision of this License, you have
563
+ permission to link or combine any covered work with a work licensed
564
+ under version 3 of the GNU Affero General Public License into a single
565
+ combined work, and to convey the resulting work. The terms of this
566
+ License will continue to apply to the part which is the covered work,
567
+ but the special requirements of the GNU Affero General Public License,
568
+ section 13, concerning interaction through a network will apply to the
569
+ combination as such.
570
+
571
+ 14. Revised Versions of this License.
572
+
573
+ The Free Software Foundation may publish revised and/or new versions of
574
+ the GNU General Public License from time to time. Such new versions will
575
+ be similar in spirit to the present version, but may differ in detail to
576
+ address new problems or concerns.
577
+
578
+ Each version is given a distinguishing version number. If the
579
+ Program specifies that a certain numbered version of the GNU General
580
+ Public License "or any later version" applies to it, you have the
581
+ option of following the terms and conditions either of that numbered
582
+ version or of any later version published by the Free Software
583
+ Foundation. If the Program does not specify a version number of the
584
+ GNU General Public License, you may choose any version ever published
585
+ by the Free Software Foundation.
586
+
587
+ If the Program specifies that a proxy can decide which future
588
+ versions of the GNU General Public License can be used, that proxy's
589
+ public statement of acceptance of a version permanently authorizes you
590
+ to choose that version for the Program.
591
+
592
+ Later license versions may give you additional or different
593
+ permissions. However, no additional obligations are imposed on any
594
+ author or copyright holder as a result of your choosing to follow a
595
+ later version.
596
+
597
+ 15. Disclaimer of Warranty.
598
+
599
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
600
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
601
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
602
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
603
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
604
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
605
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
606
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
607
+
608
+ 16. Limitation of Liability.
609
+
610
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
611
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
612
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
613
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
614
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
615
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
616
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
617
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
618
+ SUCH DAMAGES.
619
+
620
+ 17. Interpretation of Sections 15 and 16.
621
+
622
+ If the disclaimer of warranty and limitation of liability provided
623
+ above cannot be given local legal effect according to their terms,
624
+ reviewing courts shall apply local law that most closely approximates
625
+ an absolute waiver of all civil liability in connection with the
626
+ Program, unless a warranty or assumption of liability accompanies a
627
+ copy of the Program in return for a fee.
628
+
629
+ END OF TERMS AND CONDITIONS
630
+
631
+ How to Apply These Terms to Your New Programs
632
+
633
+ If you develop a new program, and you want it to be of the greatest
634
+ possible use to the public, the best way to achieve this is to make it
635
+ free software which everyone can redistribute and change under these terms.
636
+
637
+ To do so, attach the following notices to the program. It is safest
638
+ to attach them to the start of each source file to most effectively
639
+ state the exclusion of warranty; and each file should have at least
640
+ the "copyright" line and a pointer to where the full notice is found.
641
+
642
+ <one line to give the program's name and a brief idea of what it does.>
643
+ Copyright (C) <year> <name of author>
644
+
645
+ This program is free software: you can redistribute it and/or modify
646
+ it under the terms of the GNU General Public License as published by
647
+ the Free Software Foundation, either version 3 of the License, or
648
+ (at your option) any later version.
649
+
650
+ This program is distributed in the hope that it will be useful,
651
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
652
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
653
+ GNU General Public License for more details.
654
+
655
+ You should have received a copy of the GNU General Public License
656
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
657
+
658
+ Also add information on how to contact you by electronic and paper mail.
659
+
660
+ If the program does terminal interaction, make it output a short
661
+ notice like this when it starts in an interactive mode:
662
+
663
+ <program> Copyright (C) <year> <name of author>
664
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
665
+ This is free software, and you are welcome to redistribute it
666
+ under certain conditions; type `show c' for details.
667
+
668
+ The hypothetical commands `show w' and `show c' should show the appropriate
669
+ parts of the General Public License. Of course, your program's commands
670
+ might be different; for a GUI interface, you would use an "about box".
671
+
672
+ You should also get your employer (if you work as a programmer) or school,
673
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
674
+ For more information on this, and how to apply and follow the GNU GPL, see
675
+ <https://www.gnu.org/licenses/>.
676
+
677
+ The GNU General Public License does not permit incorporating your program
678
+ into proprietary programs. If your program is a subroutine library, you
679
+ may consider it more useful to permit linking proprietary applications with
680
+ the library. If this is what you want to do, use the GNU Lesser General
681
+ Public License instead of this License. But first, please read
682
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
683
+ License-File: LICENSE
684
+ Keywords: 3d-printing,bgcode,cnc,fdm,gcode,post-processing,prusaslicer
685
+ Classifier: Development Status :: 5 - Production/Stable
686
+ Classifier: Intended Audience :: Developers
687
+ Classifier: Intended Audience :: Manufacturing
688
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
689
+ Classifier: Operating System :: OS Independent
690
+ Classifier: Programming Language :: Python :: 3
691
+ Classifier: Programming Language :: Python :: 3.10
692
+ Classifier: Programming Language :: Python :: 3.11
693
+ Classifier: Programming Language :: Python :: 3.12
694
+ Classifier: Programming Language :: Python :: 3.13
695
+ Classifier: Topic :: Scientific/Engineering
696
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
697
+ Classifier: Typing :: Typed
698
+ Requires-Python: >=3.10
699
+ Description-Content-Type: text/markdown
700
+
701
+ # gcode-lib
702
+
703
+ A general-purpose Python library for parsing, analysing, and transforming G-code files.
704
+ Supports both plain-text `.gcode` and Prusa binary `.bgcode` formats, with a full planar
705
+ post-processing toolkit optimised for PrusaSlicer FDM workflows.
706
+
707
+ **Requirements:** Python 3.10+ · stdlib only (no third-party dependencies)
708
+
709
+ ---
710
+
711
+ ## Table of contents
712
+
713
+ - [Installation](#installation)
714
+ - [Quick start](#quick-start)
715
+ - [Concepts](#concepts)
716
+ - [Loading and saving files](#loading-and-saving-files)
717
+ - [Parsing G-code](#parsing-g-code)
718
+ - [Tracking modal state](#tracking-modal-state)
719
+ - [Arc linearization](#arc-linearization)
720
+ - [XY transforms](#xy-transforms)
721
+ - [G91 and relative-mode handling](#g91-and-relative-mode-handling)
722
+ - [Translate arcs without linearization](#translate-arcs-without-linearization)
723
+ - [Bed placement and validation](#bed-placement-and-validation)
724
+ - [Layer iteration](#layer-iteration)
725
+ - [Transform analysis](#transform-analysis)
726
+ - [Statistics and bounds](#statistics-and-bounds)
727
+ - [Printer and filament presets](#printer-and-filament-presets)
728
+ - [Template rendering](#template-rendering)
729
+ - [Thumbnail encoding](#thumbnail-encoding)
730
+ - [Binary .bgcode files](#binary-bgcode-files)
731
+ - [BGCode bytes API](#bgcode-bytes-api)
732
+ - [PrusaSlicer CLI integration](#prusaslicer-cli-integration)
733
+ - [Slicer and vendor compatibility](#slicer-and-vendor-compatibility)
734
+ - [API reference](#api-reference)
735
+ - [Limitations](#limitations)
736
+ - [Running the tests](#running-the-tests)
737
+
738
+ ---
739
+
740
+ ## Installation
741
+
742
+ Copy `gcode_lib.py` into your project (or onto `PYTHONPATH`). No package installation required.
743
+
744
+ ```bash
745
+ cp gcode_lib.py /your/project/
746
+ ```
747
+
748
+ ---
749
+
750
+ ## Quick start
751
+
752
+ ```python
753
+ import gcode_lib as gl
754
+
755
+ # Load any .gcode or .bgcode file
756
+ gf = gl.load("benchy.gcode")
757
+
758
+ # Inspect basic statistics
759
+ stats = gl.compute_stats(gf.lines)
760
+ print(f"Moves: {stats.move_count}")
761
+ print(f"Layers: {stats.layer_count}")
762
+ print(f"Total extrusion: {stats.total_extrusion:.2f} mm")
763
+
764
+ bounds = stats.bounds
765
+ print(f"Print size: {bounds.width:.1f} x {bounds.height:.1f} mm")
766
+ print(f"Centred at: ({bounds.center_x:.1f}, {bounds.center_y:.1f})")
767
+
768
+ # Shift the print 10 mm to the right, 5 mm forward (arc-safe, no linearization needed)
769
+ lines = gl.translate_xy_allow_arcs(gf.lines, dx=10.0, dy=5.0)
770
+ gf.lines = lines
771
+
772
+ gl.save(gf, "benchy_shifted.gcode")
773
+ ```
774
+
775
+ ---
776
+
777
+ ## Concepts
778
+
779
+ ### GCodeLine
780
+
781
+ Every line of text becomes a `GCodeLine`:
782
+
783
+ ```python
784
+ line = gl.parse_line("G1 X10.5 Y20.0 E0.12345 F3600 ; perimeter")
785
+ print(line.command) # "G1"
786
+ print(line.words) # {"X": 10.5, "Y": 20.0, "E": 0.12345, "F": 3600.0}
787
+ print(line.comment) # "; perimeter"
788
+ print(line.raw) # "G1 X10.5 Y20.0 E0.12345 F3600 ; perimeter"
789
+ print(line.is_move) # True (G0 or G1)
790
+ print(line.is_arc) # False
791
+ print(line.is_blank) # False
792
+ ```
793
+
794
+ ### ModalState
795
+
796
+ G-code is stateful. `ModalState` tracks the printer's current mode and position:
797
+
798
+ ```python
799
+ state = gl.ModalState()
800
+ print(state.abs_xy) # True (G90 absolute XY by default)
801
+ print(state.abs_e) # True (M82 absolute E by default)
802
+ print(state.x, state.y, state.z) # 0.0, 0.0, 0.0
803
+ ```
804
+
805
+ ### GCodeFile
806
+
807
+ The top-level container returned by `load()` or `from_text()`:
808
+
809
+ ```python
810
+ gf = gl.load("print.gcode")
811
+ print(gf.source_format) # "text" or "bgcode"
812
+ print(len(gf.lines)) # number of GCodeLine objects
813
+ print(len(gf.thumbnails)) # populated for .bgcode and plain-text files with embedded thumbnails
814
+ ```
815
+
816
+ ---
817
+
818
+ ## Loading and saving files
819
+
820
+ ### Load from disk
821
+
822
+ `load()` auto-detects the file format:
823
+
824
+ ```python
825
+ gf = gl.load("print.gcode") # plain text
826
+ gf = gl.load("print.bgcode") # Prusa binary
827
+ ```
828
+
829
+ ### Load from a string
830
+
831
+ ```python
832
+ gcode_text = """\
833
+ G28 ; home all axes
834
+ G90 ; absolute positioning
835
+ G1 X50 Y50 Z0.2 F3000
836
+ G1 X100 Y50 E5.0 F1500
837
+ """
838
+
839
+ gf = gl.from_text(gcode_text)
840
+ print(len(gf.lines)) # 4
841
+ ```
842
+
843
+ ### Render back to a string
844
+
845
+ ```python
846
+ text = gl.to_text(gf)
847
+ print(text)
848
+ ```
849
+
850
+ ### Save to disk
851
+
852
+ `save()` writes atomically (temp file + rename) and preserves the original format:
853
+
854
+ ```python
855
+ gl.save(gf, "output.gcode")
856
+
857
+ # Save a .bgcode source back as .bgcode (thumbnails and metadata preserved)
858
+ gf = gl.load("print.bgcode")
859
+ gf.lines = gl.translate_xy_allow_arcs(gf.lines, dx=5.0, dy=0.0)
860
+ gl.save(gf, "print_shifted.bgcode")
861
+ ```
862
+
863
+ ---
864
+
865
+ ## Parsing G-code
866
+
867
+ ### Parse individual lines
868
+
869
+ ```python
870
+ # Single line
871
+ line = gl.parse_line("G1 X10 Y20 E0.5 F1500")
872
+
873
+ # Multi-line string
874
+ lines = gl.parse_lines("G28\nG90\nG1 X0 Y0\n")
875
+ ```
876
+
877
+ ### Low-level utilities
878
+
879
+ ```python
880
+ # Split a line into code and comment portions
881
+ code, comment = gl.split_comment("G1 X10 Y20 ; move to start")
882
+ # code → "G1 X10 Y20 "
883
+ # comment → "; move to start"
884
+
885
+ # Parse axis words from a code string
886
+ words = gl.parse_words("G1 X10.5 Y-3.2 E0.012 F3600")
887
+ # words → {"X": 10.5, "Y": -3.2, "E": 0.012, "F": 3600.0}
888
+ ```
889
+
890
+ ### Filtering moves and arcs
891
+
892
+ ```python
893
+ gf = gl.load("print.gcode")
894
+
895
+ move_lines = [line for line in gf.lines if line.is_move]
896
+ arc_lines = [line for line in gf.lines if line.is_arc]
897
+ non_blank = [line for line in gf.lines if not line.is_blank]
898
+ ```
899
+
900
+ ---
901
+
902
+ ## Tracking modal state
903
+
904
+ ### Advance state manually
905
+
906
+ ```python
907
+ state = gl.ModalState()
908
+ for line in gl.parse_lines("G90\nG1 X10 Y20 Z0.2 E1.0 F3000\n"):
909
+ gl.advance_state(state, line)
910
+
911
+ print(state.x, state.y, state.z) # 10.0, 20.0, 0.2
912
+ print(state.e) # 1.0
913
+ print(state.f) # 3000.0
914
+ ```
915
+
916
+ ### Iterate with state snapshots
917
+
918
+ `iter_with_state` yields `(line, state)` where `state` is a copy taken **before** the line runs:
919
+
920
+ ```python
921
+ gf = gl.load("print.gcode")
922
+
923
+ for line, state in gl.iter_with_state(gf.lines):
924
+ if line.is_move:
925
+ print(f"From ({state.x:.2f}, {state.y:.2f}) → {line.words}")
926
+ ```
927
+
928
+ ### Iterate over specific move types
929
+
930
+ ```python
931
+ # G0 and G1 moves only
932
+ for line, state in gl.iter_moves(gf.lines):
933
+ print(line.command, line.words)
934
+
935
+ # G2 and G3 arcs only
936
+ for line, state in gl.iter_arcs(gf.lines):
937
+ print(f"Arc at Z={state.z:.3f}")
938
+
939
+ # Extruding moves only (positive E delta)
940
+ for line, state in gl.iter_extruding(gf.lines):
941
+ e_delta = line.words.get("E", 0.0) - state.e # absolute mode
942
+ print(f"Extruded {e_delta:.4f} mm")
943
+ ```
944
+
945
+ ### Custom state with a non-zero start position
946
+
947
+ ```python
948
+ initial = gl.ModalState()
949
+ initial.x = 100.0
950
+ initial.y = 50.0
951
+ initial.z = 0.3
952
+ initial.abs_xy = True
953
+
954
+ for line, state in gl.iter_moves(gf.lines, initial_state=initial):
955
+ ...
956
+ ```
957
+
958
+ ### Detect mode changes
959
+
960
+ ```python
961
+ gf = gl.load("print.gcode")
962
+ state = gl.ModalState()
963
+
964
+ for line in gf.lines:
965
+ was_abs = state.abs_xy
966
+ gl.advance_state(state, line)
967
+ if state.abs_xy != was_abs:
968
+ mode = "G90" if state.abs_xy else "G91"
969
+ print(f"Switched to {mode}: {line.raw}")
970
+ ```
971
+
972
+ ---
973
+
974
+ ## Arc linearization
975
+
976
+ G2/G3 arc commands can be converted to G1 segments when an XY transform cannot preserve arc
977
+ geometry (e.g. rotation, scaling, skew). For simple translations, prefer
978
+ [`translate_xy_allow_arcs`](#translate-arcs-without-linearization) which avoids this step.
979
+
980
+ ### Basic linearization
981
+
982
+ ```python
983
+ gf = gl.load("print.gcode")
984
+
985
+ # Replace all G2/G3 with G1 segments (default 0.2 mm chord, 5° max sweep)
986
+ lines = gl.linearize_arcs(gf.lines)
987
+ gf.lines = lines
988
+ ```
989
+
990
+ ### Adjust precision
991
+
992
+ ```python
993
+ # Finer segments: 0.05 mm chord, 1° max sweep
994
+ lines = gl.linearize_arcs(
995
+ gf.lines,
996
+ seg_mm=0.05,
997
+ max_deg=1.0,
998
+ )
999
+
1000
+ # Coarser (faster) segments
1001
+ lines = gl.linearize_arcs(gf.lines, seg_mm=0.5, max_deg=10.0)
1002
+ ```
1003
+
1004
+ ### Count arcs before and after
1005
+
1006
+ ```python
1007
+ before = sum(1 for l in gf.lines if l.is_arc)
1008
+ lines = gl.linearize_arcs(gf.lines)
1009
+ after = sum(1 for l in lines if l.is_arc)
1010
+
1011
+ print(f"Arcs before: {before}, after: {after}") # after should be 0
1012
+ ```
1013
+
1014
+ ---
1015
+
1016
+ ## XY transforms
1017
+
1018
+ All transform functions return a **new list** and do not mutate their input.
1019
+
1020
+ ### Translate (shift) — requires linearized arcs
1021
+
1022
+ ```python
1023
+ gf = gl.load("print.gcode")
1024
+ lines = gl.linearize_arcs(gf.lines)
1025
+
1026
+ # Move print 10 mm right, 5 mm forward
1027
+ lines = gl.translate_xy(lines, dx=10.0, dy=5.0)
1028
+ gf.lines = lines
1029
+ gl.save(gf, "shifted.gcode")
1030
+ ```
1031
+
1032
+ ### Skew correction
1033
+
1034
+ Corrects XY skew in the same convention as Marlin's M852 parameter:
1035
+
1036
+ ```python
1037
+ gf = gl.load("print.gcode")
1038
+ lines = gl.linearize_arcs(gf.lines)
1039
+
1040
+ # Correct 0.5° of XY skew, relative to Y=0
1041
+ lines = gl.apply_skew(lines, skew_deg=0.5, y_ref=0.0)
1042
+ gf.lines = lines
1043
+ gl.save(gf, "corrected.gcode")
1044
+ ```
1045
+
1046
+ The transform applied is: `x' = x + (y - y_ref) * tan(skew_deg)`, `y' = y`.
1047
+
1048
+ ### Arbitrary XY transform
1049
+
1050
+ Supply any `fn(x, y) -> (x_new, y_new)` function:
1051
+
1052
+ ```python
1053
+ import math
1054
+ import gcode_lib as gl
1055
+
1056
+ gf = gl.load("print.gcode")
1057
+ lines = gl.linearize_arcs(gf.lines)
1058
+
1059
+ # Rotate 45° around the origin
1060
+ angle = math.radians(45)
1061
+ def rotate(x, y):
1062
+ return (
1063
+ x * math.cos(angle) - y * math.sin(angle),
1064
+ x * math.sin(angle) + y * math.cos(angle),
1065
+ )
1066
+
1067
+ lines = gl.apply_xy_transform(lines, fn=rotate)
1068
+ gf.lines = lines
1069
+ gl.save(gf, "rotated.gcode")
1070
+ ```
1071
+
1072
+ ```python
1073
+ # Mirror across X=100
1074
+ def mirror_x(x, y):
1075
+ return (200.0 - x, y)
1076
+
1077
+ lines = gl.apply_xy_transform(gl.linearize_arcs(gf.lines), fn=mirror_x)
1078
+ ```
1079
+
1080
+ ```python
1081
+ # Scale uniformly around the bed centre (150, 150)
1082
+ cx, cy = 150.0, 150.0
1083
+ scale = 0.95
1084
+
1085
+ def scale_around_centre(x, y):
1086
+ return (cx + (x - cx) * scale, cy + (y - cy) * scale)
1087
+
1088
+ lines = gl.apply_xy_transform(gl.linearize_arcs(gf.lines), fn=scale_around_centre)
1089
+ ```
1090
+
1091
+ ### Controlling output precision
1092
+
1093
+ All transform functions accept optional decimal place parameters:
1094
+
1095
+ ```python
1096
+ lines = gl.translate_xy(
1097
+ lines,
1098
+ dx=5.0,
1099
+ dy=0.0,
1100
+ xy_decimals=4, # default 3
1101
+ other_decimals=6, # default 5 (E, F, Z, I, J, K)
1102
+ )
1103
+ ```
1104
+
1105
+ ---
1106
+
1107
+ ## G91 and relative-mode handling
1108
+
1109
+ Many slicer-generated files use `G91` for short relative moves (for example retraction and
1110
+ unretraction sequences). `to_absolute_xy()` converts all relative XY motion to absolute G90
1111
+ coordinates so the file can then be passed to any XY transform.
1112
+
1113
+ ```python
1114
+ import gcode_lib as gl
1115
+
1116
+ gf = gl.load("print.gcode")
1117
+
1118
+ # Convert any G91 segments to absolute G90 equivalents
1119
+ lines = gl.to_absolute_xy(gf.lines)
1120
+
1121
+ # Now all transforms work safely — no more G91 ValueError
1122
+ lines = gl.translate_xy(lines, dx=5.0, dy=0.0)
1123
+ gf.lines = lines
1124
+ gl.save(gf, "output.gcode")
1125
+ ```
1126
+
1127
+ `to_absolute_xy` drops all `G91` commands, rewrites the affected `G0`/`G1` lines with their
1128
+ accumulated absolute XY positions, and prepends a single `G90` line when any relative moves
1129
+ were found. Z, E, F, and comments are always preserved unchanged.
1130
+
1131
+ ```python
1132
+ # Supply an explicit starting state if the file begins mid-print
1133
+ initial = gl.ModalState()
1134
+ initial.x = 50.0
1135
+ initial.y = 50.0
1136
+
1137
+ lines = gl.to_absolute_xy(gf.lines, initial_state=initial)
1138
+ ```
1139
+
1140
+ ---
1141
+
1142
+ ## Translate arcs without linearization
1143
+
1144
+ `translate_xy_allow_arcs()` shifts XY coordinates without first requiring arc linearization.
1145
+ It translates `G0`/`G1` endpoints **and** `G2`/`G3` arc endpoints in one pass, leaving arc
1146
+ parameters (`I`, `J`) untouched (they are always relative to the arc start point in default
1147
+ `G91.1` mode).
1148
+
1149
+ ```python
1150
+ import gcode_lib as gl
1151
+
1152
+ gf = gl.load("print.gcode")
1153
+
1154
+ # Shift without destroying arc commands — no linearize_arcs needed
1155
+ lines = gl.translate_xy_allow_arcs(gf.lines, dx=10.0, dy=5.0)
1156
+ gf.lines = lines
1157
+ gl.save(gf, "shifted.gcode")
1158
+ ```
1159
+
1160
+ > **Absolute IJ mode (`G90.1`):** If the file uses absolute IJ offsets, `I` and `J` are also
1161
+ > shifted by `(dx, dy)` so that arc centres remain correct.
1162
+
1163
+ > **G91 in file:** `translate_xy_allow_arcs` raises `ValueError` for relative XY moves, the
1164
+ > same as `translate_xy`. Pre-process with `to_absolute_xy()` if needed.
1165
+
1166
+ ---
1167
+
1168
+ ## Bed placement and validation
1169
+
1170
+ ### Out-of-bounds detection
1171
+
1172
+ `find_oob_moves()` reports every XY move that lands outside a given bed polygon:
1173
+
1174
+ ```python
1175
+ import gcode_lib as gl
1176
+
1177
+ gf = gl.load("print.gcode")
1178
+
1179
+ # Rectangular bed 0..250 x 0..220
1180
+ bed = [(0, 0), (250, 0), (250, 220), (0, 220)]
1181
+
1182
+ hits = gl.find_oob_moves(gf.lines, bed_polygon=bed)
1183
+ for hit in hits:
1184
+ print(
1185
+ f"Line {hit.line_number}: ({hit.x:.2f}, {hit.y:.2f}) "
1186
+ f"{hit.distance_outside:.3f} mm outside bed"
1187
+ )
1188
+
1189
+ # Quick check: how far out is the worst offender?
1190
+ worst = gl.max_oob_distance(gf.lines, bed_polygon=bed)
1191
+ print(f"Max OOB distance: {worst:.3f} mm")
1192
+ ```
1193
+
1194
+ The `bed_polygon` is any sequence of `(x, y)` tuples; the polygon is automatically closed.
1195
+ Non-rectangular (e.g. delta or custom-shape) beds are fully supported.
1196
+
1197
+ ```python
1198
+ # Validate before saving
1199
+ if gl.max_oob_distance(gf.lines, bed_polygon=bed) > 0.0:
1200
+ raise ValueError("Print exceeds bed boundaries!")
1201
+ gl.save(gf, "safe.gcode")
1202
+ ```
1203
+
1204
+ ### Recenter or fit to bed
1205
+
1206
+ `recenter_to_bed()` positions the print on the bed in one call:
1207
+
1208
+ ```python
1209
+ p = gl.PRINTER_PRESETS["MK4"]
1210
+
1211
+ lines = gl.recenter_to_bed(
1212
+ gf.lines,
1213
+ bed_min_x=0.0, bed_max_x=p["bed_x"],
1214
+ bed_min_y=0.0, bed_max_y=p["bed_y"],
1215
+ margin=5.0, # mm clearance on each side
1216
+ mode="center", # "center" or "fit"
1217
+ )
1218
+ gf.lines = lines
1219
+ gl.save(gf, "recentered.gcode")
1220
+ ```
1221
+
1222
+ | Mode | Effect |
1223
+ |---|---|
1224
+ | `"center"` | Translates the print so its bounding box is centred within the usable bed area (bed minus margin). Arc commands are preserved — no linearization required. |
1225
+ | `"fit"` | Scales **and** centres the print using the largest uniform scale factor that keeps it within the usable area. Arcs are consumed during the scale; the result contains only `G1` lines. |
1226
+
1227
+ ---
1228
+
1229
+ ## Layer iteration
1230
+
1231
+ ### Iterate over layers
1232
+
1233
+ `iter_layers()` groups lines by Z height, yielding each layer as a `(z_height, [lines])` pair:
1234
+
1235
+ ```python
1236
+ import gcode_lib as gl
1237
+
1238
+ gf = gl.load("print.gcode")
1239
+
1240
+ for z, layer_lines in gl.iter_layers(gf.lines):
1241
+ print(f"Layer Z={z:.3f} lines={len(layer_lines)}")
1242
+ ```
1243
+
1244
+ The Z-change line (the `G1 Z…` that initiates the new layer) is included as the **first** line
1245
+ of its new layer, not the last line of the previous one.
1246
+
1247
+ ```python
1248
+ # Count lines per layer and find the thickest
1249
+ layer_sizes = {z: len(ll) for z, ll in gl.iter_layers(gf.lines)}
1250
+ busiest_z = max(layer_sizes, key=layer_sizes.get)
1251
+ print(f"Busiest layer: Z={busiest_z:.3f} ({layer_sizes[busiest_z]} lines)")
1252
+ ```
1253
+
1254
+ ### Apply a transform to selected layers only
1255
+
1256
+ `apply_xy_transform_by_layer()` runs a transform on a subset of layers, identified by Z range:
1257
+
1258
+ ```python
1259
+ import math
1260
+
1261
+ angle = math.radians(45)
1262
+
1263
+ def rotate(x, y):
1264
+ return (
1265
+ x * math.cos(angle) - y * math.sin(angle),
1266
+ x * math.sin(angle) + y * math.cos(angle),
1267
+ )
1268
+
1269
+ # Only rotate layers at Z >= 2.0 mm
1270
+ lines = gl.apply_xy_transform_by_layer(
1271
+ gf.lines,
1272
+ transform_fn=rotate,
1273
+ z_min=2.0, # skip layers below this Z
1274
+ z_max=None, # no upper limit
1275
+ )
1276
+ gf.lines = lines
1277
+ ```
1278
+
1279
+ Both `z_min` and `z_max` are inclusive bounds. Set either to `None` to leave that bound open.
1280
+ Layers outside the Z range pass through unchanged.
1281
+
1282
+ ```python
1283
+ # Apply a different shift to a specific Z band
1284
+ lines = gl.apply_xy_transform_by_layer(
1285
+ gf.lines,
1286
+ transform_fn=lambda x, y: (x + 2.0, y),
1287
+ z_min=1.0,
1288
+ z_max=3.0,
1289
+ )
1290
+ ```
1291
+
1292
+ ---
1293
+
1294
+ ## Transform analysis
1295
+
1296
+ `analyze_xy_transform()` performs a **dry run** of any transform function and returns a summary
1297
+ dict — without modifying any G-code. Use it to validate a transform before committing the
1298
+ result to disk.
1299
+
1300
+ ```python
1301
+ import gcode_lib as gl
1302
+
1303
+ gf = gl.load("print.gcode")
1304
+
1305
+ def my_shift(x, y):
1306
+ return (x + 10.0, y + 5.0)
1307
+
1308
+ info = gl.analyze_xy_transform(gf.lines, my_shift)
1309
+ print(f"Max X displacement : {info['max_dx']:.3f} mm")
1310
+ print(f"Max Y displacement : {info['max_dy']:.3f} mm")
1311
+ print(f"Max total displace : {info['max_displacement']:.3f} mm")
1312
+ print(f"Worst line : {info['line_number']}")
1313
+ print(f"Total moves : {info['move_count']}")
1314
+ ```
1315
+
1316
+ ### Validate against bed limits before transforming
1317
+
1318
+ ```python
1319
+ bed = [(0, 0), (250, 0), (250, 220), (0, 220)]
1320
+
1321
+ # Check the transform stays in bounds before applying it
1322
+ info = gl.analyze_xy_transform(gf.lines, my_shift)
1323
+ worst_x = info["max_dx"]
1324
+ worst_y = info["max_dy"]
1325
+
1326
+ # Then apply
1327
+ lines = gl.translate_xy_allow_arcs(gf.lines, dx=10.0, dy=5.0)
1328
+ hits = gl.find_oob_moves(lines, bed_polygon=bed)
1329
+ if hits:
1330
+ raise ValueError(f"{len(hits)} moves outside bed after transform")
1331
+ ```
1332
+
1333
+ ---
1334
+
1335
+ ## Statistics and bounds
1336
+
1337
+ ### Print statistics
1338
+
1339
+ ```python
1340
+ gf = gl.load("print.gcode")
1341
+ stats = gl.compute_stats(gf.lines)
1342
+
1343
+ print(f"Total lines : {stats.total_lines}")
1344
+ print(f"Blank lines : {stats.blank_lines}")
1345
+ print(f"Comment-only : {stats.comment_only_lines}")
1346
+ print(f"G0/G1 moves : {stats.move_count}")
1347
+ print(f"G2/G3 arcs : {stats.arc_count}")
1348
+ print(f"Travel moves : {stats.travel_count}")
1349
+ print(f"Extrude moves : {stats.extrude_count}")
1350
+ print(f"Retract moves : {stats.retract_count}")
1351
+ print(f"Total extrusion : {stats.total_extrusion:.2f} mm")
1352
+ print(f"Layers : {stats.layer_count}")
1353
+ print(f"Z heights : {stats.z_heights}")
1354
+ print(f"Feedrates (mm/m) : {stats.feedrates}")
1355
+ ```
1356
+
1357
+ ### Bounding box
1358
+
1359
+ ```python
1360
+ bounds = stats.bounds # included in GCodeStats
1361
+
1362
+ if bounds.valid:
1363
+ print(f"X: {bounds.x_min:.2f} – {bounds.x_max:.2f} ({bounds.width:.2f} mm)")
1364
+ print(f"Y: {bounds.y_min:.2f} – {bounds.y_max:.2f} ({bounds.height:.2f} mm)")
1365
+ print(f"Z: {bounds.z_min:.2f} – {bounds.z_max:.2f}")
1366
+ print(f"Centre: ({bounds.center_x:.2f}, {bounds.center_y:.2f})")
1367
+ ```
1368
+
1369
+ ### Bounds from extruding moves only
1370
+
1371
+ Useful for finding the actual printed area without including travel moves:
1372
+
1373
+ ```python
1374
+ extruding_bounds = gl.compute_bounds(
1375
+ gf.lines,
1376
+ extruding_only=True,
1377
+ include_arcs=True,
1378
+ )
1379
+ print(f"Extruded area: {extruding_bounds.width:.1f} x {extruding_bounds.height:.1f} mm")
1380
+ ```
1381
+
1382
+ ### Centre a print on the bed (manual method)
1383
+
1384
+ ```python
1385
+ gf = gl.load("print.gcode")
1386
+
1387
+ bounds = gl.compute_bounds(gf.lines)
1388
+ bed_cx, bed_cy = 125.0, 110.0 # MK4 bed centre
1389
+
1390
+ dx = bed_cx - bounds.center_x
1391
+ dy = bed_cy - bounds.center_y
1392
+
1393
+ lines = gl.translate_xy_allow_arcs(gf.lines, dx=dx, dy=dy)
1394
+ gf.lines = lines
1395
+ gl.save(gf, "centred.gcode")
1396
+ ```
1397
+
1398
+ Or use `recenter_to_bed()` for a one-call equivalent — see [Bed placement and validation](#bed-placement-and-validation).
1399
+
1400
+ ---
1401
+
1402
+ ## Printer and filament presets
1403
+
1404
+ Built-in presets provide common bed dimensions and printing parameters for Prusa printers.
1405
+
1406
+ ### Printer presets
1407
+
1408
+ ```python
1409
+ print(list(gl.PRINTER_PRESETS.keys()))
1410
+ # ['COREONE', 'MK4', 'MK3S', 'MINI', 'XL']
1411
+
1412
+ p = gl.PRINTER_PRESETS["MK4"]
1413
+ print(p["bed_x"], p["bed_y"], p["max_z"]) # 250.0 220.0 220.0
1414
+ ```
1415
+
1416
+ | Key | `bed_x` mm | `bed_y` mm | `max_z` mm |
1417
+ |---|---|---|---|
1418
+ | `COREONE` | 250.0 | 220.0 | 250.0 |
1419
+ | `MK4` | 250.0 | 220.0 | 220.0 |
1420
+ | `MK3S` | 250.0 | 210.0 | 210.0 |
1421
+ | `MINI` | 180.0 | 180.0 | 180.0 |
1422
+ | `XL` | 360.0 | 360.0 | 360.0 |
1423
+
1424
+ ### Filament presets
1425
+
1426
+ ```python
1427
+ print(list(gl.FILAMENT_PRESETS.keys()))
1428
+ # ['PLA', 'PETG', 'ASA', 'TPU', 'ABS']
1429
+
1430
+ f = gl.FILAMENT_PRESETS["PLA"]
1431
+ print(f["hotend"], f["bed"], f["fan"], f["retract"])
1432
+ # 215 60 100 0.8
1433
+ ```
1434
+
1435
+ | Key | `hotend` °C | `bed` °C | `fan` % | `retract` mm |
1436
+ |---|---|---|---|---|
1437
+ | `PLA` | 215 | 60 | 100 | 0.8 |
1438
+ | `PETG` | 240 | 80 | 40 | 0.8 |
1439
+ | `ASA` | 255 | 90 | 20 | 1.0 |
1440
+ | `TPU` | 225 | 45 | 30 | 1.5 |
1441
+ | `ABS` | 245 | 100 | 30 | 1.0 |
1442
+
1443
+ ### Using presets for bed operations
1444
+
1445
+ ```python
1446
+ p = gl.PRINTER_PRESETS["MK4"]
1447
+
1448
+ lines = gl.recenter_to_bed(
1449
+ gf.lines,
1450
+ bed_min_x=0.0, bed_max_x=p["bed_x"],
1451
+ bed_min_y=0.0, bed_max_y=p["bed_y"],
1452
+ margin=5.0,
1453
+ mode="center",
1454
+ )
1455
+ ```
1456
+
1457
+ ---
1458
+
1459
+ ## Template rendering
1460
+
1461
+ `render_template()` substitutes `{variable}` placeholders in G-code start/end scripts.
1462
+
1463
+ Only **simple `{lowercase_identifier}` patterns** are replaced — identifiers that start with a
1464
+ lowercase letter and contain only lowercase letters, digits, and underscores. All other `{…}`
1465
+ tokens (PrusaSlicer conditionals like `{if …}`, `{elsif …}`, `{else}`, `{endif}`, and any
1466
+ uppercase or complex expressions) are left **exactly as written**.
1467
+
1468
+ ```python
1469
+ import gcode_lib as gl
1470
+
1471
+ template = """\
1472
+ M104 S{hotend_temp} ; set hotend
1473
+ M140 S{bed_temp} ; set bed
1474
+ G28 ; home
1475
+ {if is_first_layer}
1476
+ M106 S0 ; fan off first layer
1477
+ {endif}
1478
+ """
1479
+
1480
+ variables = {
1481
+ "hotend_temp": 215,
1482
+ "bed_temp": 60,
1483
+ }
1484
+
1485
+ rendered = gl.render_template(template, variables)
1486
+ print(rendered)
1487
+ # M104 S215 ; set hotend
1488
+ # M140 S60 ; set bed
1489
+ # G28 ; home
1490
+ # {if is_first_layer} ← preserved (not a simple lowercase identifier)
1491
+ # M106 S0 ; fan off first layer
1492
+ # {endif} ← preserved
1493
+ ```
1494
+
1495
+ ### Combine with filament presets
1496
+
1497
+ ```python
1498
+ pla = gl.FILAMENT_PRESETS["PLA"]
1499
+
1500
+ rendered = gl.render_template(template, {
1501
+ "hotend_temp": pla["hotend"],
1502
+ "bed_temp": pla["bed"],
1503
+ })
1504
+ ```
1505
+
1506
+ Unknown `{keys}` that are not in the `variables` dict are left untouched (no `KeyError`).
1507
+
1508
+ ---
1509
+
1510
+ ## Thumbnail encoding
1511
+
1512
+ `encode_thumbnail_comment_block()` creates a PrusaSlicer-compatible thumbnail comment block
1513
+ from raw PNG bytes. The resulting string can be prepended to any G-code file.
1514
+
1515
+ ```python
1516
+ import gcode_lib as gl
1517
+
1518
+ # Read a PNG thumbnail from disk
1519
+ with open("thumb_16x16.png", "rb") as f:
1520
+ png_bytes = f.read()
1521
+
1522
+ block = gl.encode_thumbnail_comment_block(16, 16, png_bytes)
1523
+ print(block)
1524
+ # ; thumbnail begin 16x16 584
1525
+ # ; iVBORw0KGgoAAAANSUhEUgAAAA...
1526
+ # ; thumbnail end
1527
+ ```
1528
+
1529
+ ### Embed a thumbnail into a plain-text G-code file
1530
+
1531
+ ```python
1532
+ gf = gl.load("print.gcode")
1533
+
1534
+ with open("thumb_220x124.png", "rb") as f:
1535
+ png_bytes = f.read()
1536
+
1537
+ header_block = gl.encode_thumbnail_comment_block(220, 124, png_bytes)
1538
+ thumb_lines = gl.parse_lines(header_block)
1539
+
1540
+ # Prepend the thumbnail block before the G-code body
1541
+ gf.lines = thumb_lines + gf.lines
1542
+ gl.save(gf, "print_with_thumb.gcode")
1543
+ ```
1544
+
1545
+ The format produced is identical to PrusaSlicer's output and is automatically read back into
1546
+ `gf.thumbnails` on the next `load()`.
1547
+
1548
+ ---
1549
+
1550
+ ## Binary .bgcode files
1551
+
1552
+ Prusa `.bgcode` files are handled transparently. Thumbnails and all other metadata blocks are
1553
+ preserved automatically on save.
1554
+
1555
+ ### Load and inspect thumbnails
1556
+
1557
+ ```python
1558
+ gf = gl.load("print.bgcode")
1559
+
1560
+ print(f"Thumbnails: {len(gf.thumbnails)}")
1561
+ for thumb in gf.thumbnails:
1562
+ print(f" {thumb.width}×{thumb.height} px format_code={thumb.format_code}")
1563
+ print(f" {len(thumb.data)} bytes of image data")
1564
+ ```
1565
+
1566
+ ### Round-trip transform on .bgcode
1567
+
1568
+ ```python
1569
+ gf = gl.load("print.bgcode")
1570
+
1571
+ # Arc-safe translation — no linearization needed for a simple shift
1572
+ lines = gl.translate_xy_allow_arcs(gf.lines, dx=10.0, dy=0.0)
1573
+ gf.lines = lines
1574
+
1575
+ # Save back as .bgcode — thumbnails and metadata are preserved
1576
+ gl.save(gf, "print_shifted.bgcode")
1577
+ ```
1578
+
1579
+ ### Convert .bgcode to plain text
1580
+
1581
+ ```python
1582
+ gf = gl.load("print.bgcode")
1583
+ gf.source_format = "text" # tell save() to write plain text
1584
+ gl.save(gf, "print_converted.gcode")
1585
+ ```
1586
+
1587
+ ---
1588
+
1589
+ ## BGCode bytes API
1590
+
1591
+ In addition to `load()` / `save()` which work with file paths, two functions work directly with
1592
+ `bytes` objects for in-memory or streaming workflows:
1593
+
1594
+ ```python
1595
+ import gcode_lib as gl
1596
+
1597
+ # Decode raw BGCode bytes (e.g. received over a network socket)
1598
+ with open("print.bgcode", "rb") as f:
1599
+ raw = f.read()
1600
+
1601
+ gf = gl.read_bgcode(raw)
1602
+ print(f"Lines: {len(gf.lines)}")
1603
+ print(f"Thumbnails: {len(gf.thumbnails)}")
1604
+
1605
+ # Transform the G-code
1606
+ gf.lines = gl.translate_xy_allow_arcs(gf.lines, dx=5.0, dy=0.0)
1607
+
1608
+ # Re-encode as BGCode bytes — thumbnails preserved
1609
+ output_bytes = gl.write_bgcode(gl.to_text(gf), thumbnails=gf.thumbnails)
1610
+
1611
+ with open("output.bgcode", "wb") as f:
1612
+ f.write(output_bytes)
1613
+ ```
1614
+
1615
+ ```python
1616
+ # Create a brand-new BGCode file from plain-text G-code (no thumbnails)
1617
+ gcode_text = "G28\nG90\nG1 X50 Y50 Z0.2 F3000\n"
1618
+ bgcode_bytes = gl.write_bgcode(gcode_text)
1619
+ ```
1620
+
1621
+ > **Note:** `write_bgcode` produces a valid BGCode v2 file with DEFLATE-compressed G-code.
1622
+ > The same Heatshrink limitation described in [Slicer and vendor compatibility](#slicer-and-vendor-compatibility)
1623
+ > applies to reading: only DEFLATE-compressed and uncompressed G-code blocks can be decoded.
1624
+
1625
+ ---
1626
+
1627
+ ## PrusaSlicer CLI integration
1628
+
1629
+ A set of helpers wraps the PrusaSlicer command-line interface for scripted slicing workflows.
1630
+
1631
+ ### Discover the executable
1632
+
1633
+ ```python
1634
+ import gcode_lib as gl
1635
+
1636
+ exe = gl.find_prusaslicer_executable()
1637
+ print(exe)
1638
+ # e.g. /Applications/PrusaSlicer.app/Contents/MacOS/prusa-slicer-console
1639
+ ```
1640
+
1641
+ `find_prusaslicer_executable` searches `PATH` and a list of well-known install locations.
1642
+
1643
+ | Parameter | Default | Description |
1644
+ |---|---|---|
1645
+ | `prefer_console` | `True` | Prefer the headless console binary over the GUI binary |
1646
+ | `explicit_path` | `None` | Use this exact path (skip discovery) |
1647
+
1648
+ Raises `FileNotFoundError` if no binary can be found.
1649
+
1650
+ ### Probe capabilities
1651
+
1652
+ ```python
1653
+ caps = gl.probe_prusaslicer_capabilities(exe)
1654
+ print(caps.version_text) # "PrusaSlicer-2.8.0+win64 ..."
1655
+ print(caps.has_export_gcode) # True
1656
+ print(caps.has_load_config) # True
1657
+ print(caps.supports_binary_gcode) # True / False
1658
+ print(caps.has_help_fff) # True / False
1659
+ ```
1660
+
1661
+ ### Run with arbitrary arguments
1662
+
1663
+ ```python
1664
+ result = gl.run_prusaslicer(exe, ["--version"])
1665
+ if result.ok:
1666
+ print(result.stdout)
1667
+ else:
1668
+ print("Error:", result.stderr)
1669
+ print("Return code:", result.returncode)
1670
+ ```
1671
+
1672
+ `run_prusaslicer` captures stdout and stderr, enforces a configurable timeout, and always
1673
+ returns a `RunResult` — it never raises on non-zero exit codes.
1674
+
1675
+ ### Slice a single model
1676
+
1677
+ ```python
1678
+ req = gl.SliceRequest(
1679
+ input_path="model.stl",
1680
+ output_path="model.gcode",
1681
+ config_ini="my_profile.ini", # path to a PrusaSlicer .ini config, or None for defaults
1682
+ )
1683
+
1684
+ result = gl.slice_model(exe, req)
1685
+ if not result.ok:
1686
+ raise RuntimeError(f"Slice failed:\n{result.stderr}")
1687
+
1688
+ print(f"Sliced OK → {req.output_path}")
1689
+ ```
1690
+
1691
+ ```python
1692
+ # Add extra CLI flags (e.g. override layer height)
1693
+ req = gl.SliceRequest(
1694
+ input_path="model.stl",
1695
+ output_path="model_draft.gcode",
1696
+ config_ini="base.ini",
1697
+ extra_args=["--layer-height", "0.3"],
1698
+ )
1699
+ result = gl.slice_model(exe, req)
1700
+ ```
1701
+
1702
+ ### Batch slicing
1703
+
1704
+ `slice_batch` slices multiple STL files in parallel using a thread pool:
1705
+
1706
+ ```python
1707
+ import os
1708
+
1709
+ stl_files = [
1710
+ os.path.join("models", f)
1711
+ for f in os.listdir("models")
1712
+ if f.endswith(".stl")
1713
+ ]
1714
+
1715
+ results = gl.slice_batch(
1716
+ exe,
1717
+ inputs=stl_files,
1718
+ output_dir="sliced/",
1719
+ config_ini="my_profile.ini",
1720
+ naming="{stem}.gcode", # {stem} = input filename without extension
1721
+ parallelism=4, # up to 4 concurrent PrusaSlicer processes
1722
+ )
1723
+
1724
+ for r in results:
1725
+ status = "OK" if r.ok else "FAILED"
1726
+ print(f"{status}: {r.cmd[-1]}")
1727
+ ```
1728
+
1729
+ The `naming` pattern supports `{stem}` (filename without extension) and `{name}` (full
1730
+ filename). Output files are written to `output_dir`.
1731
+
1732
+ ---
1733
+
1734
+ ## Slicer and vendor compatibility
1735
+
1736
+ ### G-code parsing and transforms
1737
+
1738
+ All parsing, state tracking, arc linearization, XY transforms, and statistics functions are
1739
+ **fully vendor-agnostic**. Any standards-compliant FFF G-code file produced by any slicer —
1740
+ PrusaSlicer, SuperSlicer, OrcaSlicer, Cura, ideaMaker, Simplify3D, Bambu Studio, or any other
1741
+ — can be loaded, parsed, and transformed.
1742
+
1743
+ ### Plain-text thumbnails
1744
+
1745
+ Embedded thumbnails in plain-text `.gcode` files use the comment-block convention established
1746
+ by PrusaSlicer:
1747
+
1748
+ ```
1749
+ ; thumbnail begin 16x16 584
1750
+ ; <base64 data lines>
1751
+ ; thumbnail end
1752
+ ```
1753
+
1754
+ The following slicers write thumbnails in this format and are **fully supported**:
1755
+
1756
+ | Slicer | Notes |
1757
+ |---|---|
1758
+ | **PrusaSlicer** | All three image formats: `thumbnail` (PNG), `thumbnail_JPG`, `thumbnail_QOI` |
1759
+ | **SuperSlicer** | Same convention as PrusaSlicer |
1760
+ | **OrcaSlicer** | Same convention as PrusaSlicer |
1761
+ | **Cura** | Uses `thumbnail` (PNG) blocks |
1762
+
1763
+ **Bambu Lab slicers** (Bambu Studio, OrcaSlicer for Bambu) use an incompatible format:
1764
+ thumbnail data is written as a single long comment line prefixed with `;gimage:` or `;simage:`.
1765
+ This format is **not supported**. Bambu thumbnail lines will be left as ordinary comment lines
1766
+ in `gf.lines` and `gf.thumbnails` will be empty.
1767
+
1768
+ ### Binary `.bgcode` format
1769
+
1770
+ The Prusa binary G-code format (`.bgcode`) is a **Prusa-specific** format. No other slicer
1771
+ produces `.bgcode` files.
1772
+
1773
+ Two limitations apply when loading `.bgcode`:
1774
+
1775
+ - **Heatshrink-compressed GCode blocks are not supported.** Current releases of PrusaSlicer
1776
+ compress the embedded G-code using Heatshrink (compression type 3). Attempting to load such
1777
+ a file raises `ValueError: Heatshrink decompression is not supported`.
1778
+ *Workaround:* export as plain `.gcode` from PrusaSlicer's export dialog.
1779
+ - **DEFLATE-compressed and uncompressed GCode blocks** are fully supported.
1780
+
1781
+ Thumbnail and metadata blocks in `.bgcode` are unaffected by this limitation and are always
1782
+ read correctly regardless of GCode block compression type.
1783
+
1784
+ ---
1785
+
1786
+ ## API reference
1787
+
1788
+ ### Constants
1789
+
1790
+ | Name | Default | Description |
1791
+ |---|---|---|
1792
+ | `EPS` | `1e-9` | Floating-point comparison tolerance |
1793
+ | `DEFAULT_ARC_SEG_MM` | `0.20` | Max chord length (mm) per arc segment |
1794
+ | `DEFAULT_ARC_MAX_DEG` | `5.0` | Max sweep angle (°) per arc segment |
1795
+ | `DEFAULT_XY_DECIMALS` | `3` | Output decimal places for X/Y |
1796
+ | `DEFAULT_OTHER_DECIMALS` | `5` | Output decimal places for E/F/Z/I/J/K |
1797
+
1798
+ ### Presets
1799
+
1800
+ | Name | Type | Description |
1801
+ |---|---|---|
1802
+ | `PRINTER_PRESETS` | `Dict[str, Dict]` | Bed and Z dimensions for Prusa printers (`COREONE`, `MK4`, `MK3S`, `MINI`, `XL`) |
1803
+ | `FILAMENT_PRESETS` | `Dict[str, Dict]` | Hotend/bed temperatures and retraction for common materials (`PLA`, `PETG`, `ASA`, `TPU`, `ABS`) |
1804
+
1805
+ ### Data classes
1806
+
1807
+ #### `GCodeLine`
1808
+
1809
+ | Attribute | Type | Description |
1810
+ |---|---|---|
1811
+ | `raw` | `str` | Original line text (trailing newline stripped) |
1812
+ | `command` | `str` | Uppercased command token (e.g. `"G1"`) or `""` |
1813
+ | `words` | `Dict[str, float]` | Parsed axis words |
1814
+ | `comment` | `str` | Comment portion including leading `;`, or `""` |
1815
+ | `is_move` | `bool` | `True` if G0 or G1 |
1816
+ | `is_arc` | `bool` | `True` if G2 or G3 |
1817
+ | `is_blank` | `bool` | `True` if no command and no meaningful content |
1818
+
1819
+ #### `ModalState`
1820
+
1821
+ | Attribute | Type | Default | Description |
1822
+ |---|---|---|---|
1823
+ | `abs_xy` | `bool` | `True` | G90 (absolute) / G91 (relative) XY mode |
1824
+ | `abs_e` | `bool` | `True` | M82 (absolute) / M83 (relative) E mode |
1825
+ | `ij_relative` | `bool` | `True` | G91.1 (relative) / G90.1 (absolute) IJ mode |
1826
+ | `x` | `float` | `0.0` | Current X position |
1827
+ | `y` | `float` | `0.0` | Current Y position |
1828
+ | `z` | `float` | `0.0` | Current Z position |
1829
+ | `e` | `float` | `0.0` | Current E accumulator |
1830
+ | `f` | `Optional[float]` | `None` | Current feedrate (None until first F seen) |
1831
+
1832
+ #### `GCodeFile`
1833
+
1834
+ | Attribute | Type | Description |
1835
+ |---|---|---|
1836
+ | `lines` | `List[GCodeLine]` | All lines in source order |
1837
+ | `thumbnails` | `List[Thumbnail]` | Thumbnails extracted from `.bgcode` or plain-text files with embedded thumbnail blocks |
1838
+ | `source_format` | `str` | `"text"` or `"bgcode"` |
1839
+
1840
+ #### `Bounds`
1841
+
1842
+ | Member | Description |
1843
+ |---|---|
1844
+ | `x_min`, `x_max`, `y_min`, `y_max`, `z_min`, `z_max` | Extents |
1845
+ | `valid` | `True` if at least one XY point was added |
1846
+ | `width` | `x_max - x_min` |
1847
+ | `height` | `y_max - y_min` |
1848
+ | `center_x`, `center_y` | Midpoint of XY extents |
1849
+ | `expand(x, y)` | Expand box to include point |
1850
+ | `expand_z(z)` | Expand Z range |
1851
+
1852
+ #### `GCodeStats`
1853
+
1854
+ | Attribute | Description |
1855
+ |---|---|
1856
+ | `total_lines` | Total line count |
1857
+ | `blank_lines` | Lines with no command or comment |
1858
+ | `comment_only_lines` | Lines with comment but no command |
1859
+ | `move_count` | G0 + G1 total |
1860
+ | `arc_count` | G2 + G3 total |
1861
+ | `travel_count` | Moves without positive extrusion |
1862
+ | `extrude_count` | Moves with positive E delta |
1863
+ | `retract_count` | Moves with negative E delta |
1864
+ | `total_extrusion` | Total E deposited (mm) |
1865
+ | `bounds` | `Bounds` object |
1866
+ | `z_heights` | Unique Z values in order seen |
1867
+ | `feedrates` | Unique F values in order seen |
1868
+ | `layer_count` | `len(z_heights)` |
1869
+
1870
+ #### `Thumbnail`
1871
+
1872
+ | Attribute | Description |
1873
+ |---|---|
1874
+ | `data` | Decompressed image bytes |
1875
+ | `width` | Image width in pixels |
1876
+ | `height` | Image height in pixels |
1877
+ | `format_code` | Raw format code from bgcode block params |
1878
+
1879
+ #### `OOBHit`
1880
+
1881
+ | Attribute | Type | Description |
1882
+ |---|---|---|
1883
+ | `line_number` | `int` | 0-based index of the offending line in the input list |
1884
+ | `x` | `float` | X coordinate of the out-of-bounds point |
1885
+ | `y` | `float` | Y coordinate of the out-of-bounds point |
1886
+ | `distance_outside` | `float` | Distance (mm) from the point to the nearest polygon edge |
1887
+
1888
+ #### `PrusaSlicerCapabilities`
1889
+
1890
+ | Attribute | Type | Description |
1891
+ |---|---|---|
1892
+ | `version_text` | `str` | Raw version string from `--version` |
1893
+ | `has_export_gcode` | `bool` | `--export-gcode` flag is available |
1894
+ | `has_load_config` | `bool` | `--load` (config) flag is available |
1895
+ | `has_help_fff` | `bool` | `--help-fff` flag is available |
1896
+ | `supports_binary_gcode` | `bool` | Binary G-code output is supported |
1897
+ | `raw_help` | `str` | Full output of `--help` |
1898
+ | `raw_help_fff` | `str \| None` | Output of `--help-fff`, or `None` |
1899
+
1900
+ #### `RunResult`
1901
+
1902
+ | Attribute | Type | Description |
1903
+ |---|---|---|
1904
+ | `cmd` | `List[str]` | The command that was executed |
1905
+ | `returncode` | `int` | Process exit code |
1906
+ | `stdout` | `str` | Captured standard output |
1907
+ | `stderr` | `str` | Captured standard error |
1908
+ | `ok` | `bool` (property) | `True` if `returncode == 0` |
1909
+
1910
+ #### `SliceRequest`
1911
+
1912
+ | Attribute | Type | Default | Description |
1913
+ |---|---|---|---|
1914
+ | `input_path` | `str` | — | Path to the input model file (STL, 3MF, …) |
1915
+ | `output_path` | `str` | — | Path for the output G-code file |
1916
+ | `config_ini` | `str \| None` | — | Path to a PrusaSlicer `.ini` config, or `None` |
1917
+ | `printer_technology` | `str` | `"FFF"` | Printer technology flag |
1918
+ | `extra_args` | `List[str]` | `[]` | Additional CLI arguments appended to the command |
1919
+
1920
+ ### Functions
1921
+
1922
+ #### I/O
1923
+
1924
+ ```
1925
+ load(path: str) -> GCodeFile
1926
+ save(gf: GCodeFile, path: str) -> None
1927
+ from_text(text: str) -> GCodeFile
1928
+ to_text(gf: GCodeFile) -> str
1929
+ read_bgcode(data: bytes) -> GCodeFile
1930
+ write_bgcode(ascii_gcode: str, thumbnails=None) -> bytes
1931
+ ```
1932
+
1933
+ #### Parsing
1934
+
1935
+ ```
1936
+ parse_line(raw_line: str) -> GCodeLine
1937
+ parse_lines(text: str) -> List[GCodeLine]
1938
+ split_comment(line: str) -> Tuple[str, str]
1939
+ parse_words(code: str) -> Dict[str, float]
1940
+ ```
1941
+
1942
+ #### State
1943
+
1944
+ ```
1945
+ advance_state(state: ModalState, line: GCodeLine) -> None
1946
+ iter_with_state(lines, initial_state=None) -> Iterator[Tuple[GCodeLine, ModalState]]
1947
+ iter_moves(lines, initial_state=None) -> Iterator[Tuple[GCodeLine, ModalState]]
1948
+ iter_arcs(lines, initial_state=None) -> Iterator[Tuple[GCodeLine, ModalState]]
1949
+ iter_extruding(lines, initial_state=None) -> Iterator[Tuple[GCodeLine, ModalState]]
1950
+ ```
1951
+
1952
+ #### Transforms
1953
+
1954
+ ```
1955
+ linearize_arcs(lines, seg_mm=0.20, max_deg=5.0,
1956
+ xy_decimals=3, other_decimals=5,
1957
+ initial_state=None) -> List[GCodeLine]
1958
+
1959
+ apply_xy_transform(lines, fn, xy_decimals=3, other_decimals=5,
1960
+ initial_state=None) -> List[GCodeLine]
1961
+
1962
+ apply_skew(lines, skew_deg, y_ref=0.0,
1963
+ xy_decimals=3, other_decimals=5,
1964
+ initial_state=None) -> List[GCodeLine]
1965
+
1966
+ translate_xy(lines, dx, dy,
1967
+ xy_decimals=3, other_decimals=5,
1968
+ initial_state=None) -> List[GCodeLine]
1969
+
1970
+ to_absolute_xy(lines, initial_state=None,
1971
+ xy_decimals=3, other_decimals=5) -> List[GCodeLine]
1972
+
1973
+ translate_xy_allow_arcs(lines, dx, dy,
1974
+ xy_decimals=3, other_decimals=5,
1975
+ initial_state=None) -> List[GCodeLine]
1976
+
1977
+ apply_xy_transform_by_layer(lines, transform_fn,
1978
+ z_min=None, z_max=None,
1979
+ xy_decimals=3, other_decimals=5,
1980
+ initial_state=None) -> List[GCodeLine]
1981
+
1982
+ recenter_to_bed(lines, bed_min_x, bed_max_x, bed_min_y, bed_max_y,
1983
+ margin=0.0, mode="center") -> List[GCodeLine]
1984
+ ```
1985
+
1986
+ #### Statistics
1987
+
1988
+ ```
1989
+ compute_bounds(lines, extruding_only=False, include_arcs=True,
1990
+ arc_seg_mm=0.20, arc_max_deg=5.0,
1991
+ initial_state=None) -> Bounds
1992
+
1993
+ compute_stats(lines, initial_state=None) -> GCodeStats
1994
+ ```
1995
+
1996
+ #### Layer iteration
1997
+
1998
+ ```
1999
+ iter_layers(lines, initial_state=None) -> Iterator[Tuple[float, List[GCodeLine]]]
2000
+ ```
2001
+
2002
+ #### Bed validation
2003
+
2004
+ ```
2005
+ find_oob_moves(lines, bed_polygon,
2006
+ initial_state=None) -> List[OOBHit]
2007
+
2008
+ max_oob_distance(lines, bed_polygon,
2009
+ initial_state=None) -> float
2010
+ ```
2011
+
2012
+ #### Transform analysis
2013
+
2014
+ ```
2015
+ analyze_xy_transform(lines, transform_fn,
2016
+ initial_state=None) -> Dict[str, Any]
2017
+ ```
2018
+
2019
+ Return keys: `max_dx`, `max_dy`, `max_displacement`, `line_number`, `move_count`.
2020
+
2021
+ #### Template and thumbnail
2022
+
2023
+ ```
2024
+ render_template(template_text: str, variables: dict) -> str
2025
+
2026
+ encode_thumbnail_comment_block(width: int, height: int,
2027
+ png_bytes: bytes) -> str
2028
+ ```
2029
+
2030
+ #### PrusaSlicer CLI
2031
+
2032
+ ```
2033
+ find_prusaslicer_executable(prefer_console=True,
2034
+ explicit_path=None) -> str
2035
+
2036
+ probe_prusaslicer_capabilities(exe: str) -> PrusaSlicerCapabilities
2037
+
2038
+ run_prusaslicer(exe: str, args: List[str],
2039
+ timeout_s: int = 600) -> RunResult
2040
+
2041
+ slice_model(exe: str, req: SliceRequest) -> RunResult
2042
+
2043
+ slice_batch(exe: str, inputs: List[str], output_dir: str,
2044
+ config_ini: str | None,
2045
+ naming: str = "{stem}.gcode",
2046
+ parallelism: int = 1) -> List[RunResult]
2047
+ ```
2048
+
2049
+ #### Formatting helpers
2050
+
2051
+ ```
2052
+ fmt_float(v: float, places: int) -> str
2053
+ fmt_axis(axis: str, v: float, xy_decimals=3, other_decimals=5) -> str
2054
+ replace_or_append(code: str, axis: str, val: float,
2055
+ xy_decimals=3, other_decimals=5) -> str
2056
+ ```
2057
+
2058
+ ---
2059
+
2060
+ ## Limitations
2061
+
2062
+ - **G91 relative XY in transforms:** `apply_xy_transform`, `apply_skew`, `translate_xy`, and
2063
+ `translate_xy_allow_arcs` raise `ValueError` if a `G0`/`G1` move with X/Y words is encountered
2064
+ while the modal state is in G91 mode. Use `to_absolute_xy()` to convert relative segments to
2065
+ absolute before transforming — see [G91 and relative-mode handling](#g91-and-relative-mode-handling).
2066
+ - **Arc endpoint tracking only.** `advance_state` updates position to the G2/G3 endpoint but
2067
+ does not interpolate intermediate arc positions. Use `linearize_arcs` if you need full path
2068
+ coverage.
2069
+ - **No helical arc support.** G2/G3 with a simultaneous Z move (helical arcs) are not supported.
2070
+ All arcs are treated as planar (XY only).
2071
+ - **No G-code validation.** The library parses and transforms; it does not validate that the
2072
+ resulting G-code is printable or within machine limits. Use `find_oob_moves` for basic bed
2073
+ boundary checking.
2074
+ - **Heatshrink BGCode decompression not supported.** See [Slicer and vendor compatibility](#slicer-and-vendor-compatibility).
2075
+
2076
+ ---
2077
+
2078
+ ## Running the tests
2079
+
2080
+ ```bash
2081
+ python -m pytest tests/ -v
2082
+ ```
2083
+
2084
+ Tests cover I/O, parsing, state tracking, statistics, all transform functions, bed placement,
2085
+ layer iteration, presets, template rendering, thumbnail encoding, BGCode round-trips, and
2086
+ PrusaSlicer CLI helpers — using only stdlib and pytest.