-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathbase.py
More file actions
1930 lines (1571 loc) · 64.8 KB
/
Copy pathbase.py
File metadata and controls
1930 lines (1571 loc) · 64.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""PythonOpenScad is a thin layer API for generating OpenSCAD scripts.
PythonOpenScad aims to remain a minimal layer for generating OpenScad scripts while providing:
* Type checking and conversion of arguments with accurate error messages
* Support for both OpenPyScad and SolidPython style APIs
* Comprehensive documentation with links to OpenSCAD reference docs
* Module functionality for reducing code duplication
The primary client for PythonOpenScad is anchorSCAD, which provides higher-level
functionality for building complex models.
See:
`PythonOpenScad <https://github.com/owebeeone/pythonopenscad>` (this)
`OpenSCAD <http://www.openscad.org/documentation.html>`
`OpenPyScad <http://github.com/taxpon/openpyscad>`
`SolidPython <http://github.com/SolidCode/SolidPython>`
`anchorscad <https://github.com/owebeeone/anchorscad>`
License:
Copyright (C) 2025 Gianni Mariani
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
import copy
from numbers import Integral
import sys
from dataclasses import dataclass, field
from collections import defaultdict
from typing import List, Tuple
from pythonopenscad.m3dapi import M3dRenderer, RenderContext, RenderContextCrossSection
from pythonopenscad.modifier import (
PoscBaseException,
PoscRendererBase,
get_fragments_from_fn_fa_fs
)
class ConversionException(PoscBaseException):
"""Exception for conversion errors."""
class TooManyParameters(PoscBaseException):
"""Exception when more unnamed parameters are provided than total
parameters specified."""
class ParameterNotDefined(PoscBaseException):
"""Exception when passing a named parameter that has not been provided."""
class ParameterDefinedMoreThanOnce(PoscBaseException):
"""Exception when passing a named parameter that has already been provided."""
class RequiredParameterNotProvided(PoscBaseException):
"""Exception when a required parameter is not provided."""
class InitializerNotAllowed(PoscBaseException):
"""An initializer (def __init__) was defined and is not allowed."""
class InvalidIndentLevel(PoscBaseException):
"""Indentation level was set to an invalid number."""
class IndentLevelStackEmpty(PoscBaseException):
"""Indentation level was set to an invalid number."""
class InvalidValueForBool(PoscBaseException):
"""Conversion failure for bool value."""
class InvalidValueForStr(PoscBaseException):
"""Conversion failure for str value."""
class InvalidValue(PoscBaseException):
"""Invalid value provided.."""
class DuplicateNamingOfArgs(PoscBaseException):
"""OpenScadApiSpecifier args has names used more than once."""
class NameCollissionFieldNameReserved(PoscBaseException):
"""An attempt to define an arg with the same name as a field."""
class AttemptingToAddNonPoscBaseNode(PoscBaseException):
"""Attempted to add ad invalid object to child nodes."""
class NotProvided:
"""A value that is not provided. Used to indicate that a parameter is not provided."""
def __bool__(self):
return False
def __repr__(self):
return 'None'
def __str__(self):
return ''
NOT_PROVIDED = NotProvided()
@dataclass
class PoscGlobals:
"""Global OpenSCAD parameters. Modifies the global parameters for the generated script."""
_fn: int | None = None
_fa: float | None = None
_fs: float | None = None
def overrides(self, _fn: int | None, _fa: float | None, _fs: float | None) -> \
tuple[tuple[str, int | float | None], ...]:
return (
('$fn', self._fn if _fn is None else _fn),
('$fa', self._fa if _fa is None else _fa),
('$fs', self._fs if _fs is None else _fs)
)
def clear(self):
"""Clears the global variables."""
self._fn = None
self._fa = None
self._fs = None
# Setting the _fn, _fs and _fa variables will result in the header to
# the generated script to include the global parameters.
POSC_GLOBALS = PoscGlobals()
class Arg(object):
"""Defines an argument and field for PythonOpenScad PoscBase based APIs."""
def __init__(
self,
name,
typ,
default_value,
docstring,
required=False,
osc_name=None,
attr_name=None,
init=True,
compare=True,
):
"""Args:
name: The pythonopenscad name of this parameter.
osc_name: The name used by OpenScad. Defaults to name.
attr_name: Object attribute name.
typ: The converter for the argument.
default:_value: Default value for argument (this will be converted by typ).
docstring: The python doc for the arg.
required: Throws if the value is not provided.
init: If True then the arg is added to the __init__ function.
compare: If True then the arg is compared in the equals function.
"""
self.name = name
self.osc_name = osc_name or name
self.attr_name = attr_name or name
self.typ = typ
self.default_value = default_value
self.docstring = docstring
self.required = required
self.init = init
self.compare = compare
def to_dataclass_field(self):
kwds = dict()
if not self.required:
kwds['default'] = self.default_value
if not self.init:
kwds['init'] = False
if not self.compare:
kwds['compare'] = False
return field(**kwds)
def annotation(self):
return (self.name, self.typ)
def default_value_str(self):
"""Returns the default value as a string otherwise '' if no default provided."""
if self.default_value is None or self.default_value is NOT_PROVIDED:
return ''
try:
return repr(self.default_value)
except: # noqa: E722
return ''
def document(self):
"Returns formatted documentation for this arg."
default_str = self.default_value_str()
default_str = (' Default ' + default_str) if default_str else default_str
attribute_name = (
'' if self.attr_name == self.name else ' (Attribute name: %s) ' % self.attr_name
)
if self.name == self.osc_name:
return '%s%s: %s%s' % (self.name, attribute_name, self.docstring, default_str)
else:
return '%s%s (converts to %s): %s %s' % (
self.name,
attribute_name,
self.osc_name,
self.docstring,
default_str,
)
# Some special common Args. These are not consistently documented.
FA_ARG = Arg('_fa', float, None, 'minimum angle (in degrees) of each segment', osc_name='$fa')
FS_ARG = Arg('_fs', float, None, 'minimum length of each segment', osc_name='$fs')
FN_ARG = Arg('_fn', int, None, 'fixed number of segments. Overrides $fa and $fs', osc_name='$fn')
@dataclass(frozen=True)
class _ConverterWrapper:
func: object
def __repr__(self):
return self.func.__name__
def __str__(self):
return self.func.__name__
def __call__(self, v):
return self.func(v)
@property
def __name__(self):
return self.func.__name__
def _as_converter(arg=None):
if isinstance(arg, str):
def decorator(f):
f.__name__ = arg
return _ConverterWrapper(f)
return decorator
return _ConverterWrapper(arg)
def list_of(typ, len_min_max=(3, 3), fill_to_min=None):
"""Defines a converter for an iterable to a list of elements of a given type.
Args:
typ: The type of list elements.
len_min_max: A tuple of the (min,max) length, (0, 0) indicates no limits.
fill_to_min: If the provided list is too short then use this value.
Returns:
A function that performs the conversion.
"""
description = 'list_of(%s, len_min_max=%r, fill_to_min=%r)' % (
typ.__name__,
len_min_max,
fill_to_min,
)
@_as_converter(description)
def list_converter(value):
"""Converts provided value as a list of the given type.
value: The value to be converted
"""
converted_value = []
for v in value:
if len_min_max[1] and len(converted_value) >= len_min_max[1]:
raise ConversionException('provided length too large, max is %d' % len_min_max[1])
converted_value.append(typ(v))
if len_min_max[0] and len(value) < len_min_max[0]:
if fill_to_min is None:
raise ConversionException(
'provided length (%d) too small and fill_to_min is None, min is %d'
% (len(converted_value), len_min_max[0])
)
fill_converted = typ(fill_to_min)
for _ in range(len_min_max[0] - len(converted_value)):
converted_value.append(fill_converted)
return converted_value
return list_converter
def one_of(typ, *args):
"""Provides a converter that will iterate over the provided converters until it succeeds.
Args:
typ: The first converter argument.
args: A list of supplemental type argument converters.
"""
largs = [typ] + list(args)
description = 'one_of(%s)' % ', '.join(t.__name__ for t in largs)
@_as_converter(description)
def one_of_converter(value):
"""Converts a value to one of the list provided to one_of().
Throws:
ConversionException if the value failed all conversions."""
for atyp in largs:
try:
converted_value = atyp(value)
return converted_value
except: # noqa: E722
continue
raise ConversionException("The value %r can't convert using %s" % (value, description))
return one_of_converter
class OscKeyword(object):
"""Converts to the given string for allowing True to to true and False to false conversion.
In the special case of the 'false' keyword, it converts to False on bool cast.
"""
def __init__(self, kw):
self.kw = kw
self._bool_value = (0, 1)[kw != 'false']
def __str__(self):
return self.kw
def __repr__(self):
return self.kw
def __len__(self):
return self._bool_value
OSC_TRUE = OscKeyword('true')
OSC_FALSE = OscKeyword('false')
@_as_converter
def bool_strict(value):
"""Returns an OscKeyword given bool i.e. 'true' if True else 'false'.
Args:
value: A boolean value.
Throws:
InvalidValueForBool if the provided value is not a bool.
"""
if not isinstance(value, bool):
raise InvalidValueForBool(
'expected a bool value but got "%r" of type %s' % (value, value.__class__.__name__)
)
return OSC_TRUE if value else OSC_FALSE
@_as_converter
def str_strict(value):
"""Returns the given value if it is a str object otherwise raises
InvalidValueForStr exception.
Args:
value: A string value.
Throws:
InvalidValueForStr if the provided value is not a str.
"""
if not isinstance(value, str) and not isinstance(value, bytes):
raise InvalidValueForStr(
'expected a string value but got "%r" of type %s' % (value, value.__class__.__name__)
)
return value
@_as_converter
def int_strict(value):
"""Returns the given value if it is a Number object otherwise raises
InvalidValueForStr exception.
Args:
value: A string value.
Throws:
ValueError if the provided value is not a str.
"""
if not isinstance(value, Integral):
raise ValueError(
f'expected an integer value but got "{value!r}" of type {value.__class__.__name__}')
return int(value)
def of_set(*args):
"""Returns a converter function that will throw if the the value to be converted is not
one of args:
Args:
*args: The set of allowed values.
Throws:
InvalidValue if the value is not one of the args.
"""
allowed_values = set(args)
description = 'of_set(allowed_values=%r)' % (tuple(allowed_values),)
@_as_converter(description)
def of_set_converter(value):
if value not in allowed_values:
raise InvalidValue('%r is not allowed with %s.' % (value, description))
return value
return of_set_converter
# The base URL for OpenScad documentation,
OPEN_SCAD_BASE_URL = 'http://en.wikibooks.org/wiki/OpenSCAD_User_Manual/'
class OpenScadApiSpecifier(object):
"""Contains the specification of an OpenScad primitive."""
def __init__(self, openscad_name, args, url_base, alt_url_anchor=None):
"""
Args:
openscad_name: The OpenScad primitive name.
args: A tuple of Arg()s for each value passed in.
url_base: The base of the document URL for OpenScad documentation.
"""
self.openscad_name = openscad_name
self.args = args
self.url_base = url_base
self.alt_url_anchor = alt_url_anchor
self.args_map = dict((arg.name, arg) for arg in args)
if len(self.args) != len(self.args_map):
all_names = [arg.name for arg in self.args]
dupes = list(set([name for name in all_names if all_names.count(name) > 1]))
raise DuplicateNamingOfArgs('Duplicate parameter names %r' % dupes)
def generate_class_doc(self):
"""Generates class level documentation."""
lines = ['\nConverts to an OpenScad "%s" primitive.' % self.openscad_name]
if self.url_base:
anchor = self.openscad_name if self.alt_url_anchor is None else self.alt_url_anchor
url = OPEN_SCAD_BASE_URL + self.url_base + '#' + anchor
lines.append(
'See OpenScad `%s docs <%s>` for more information.' % (self.openscad_name, url)
)
return '\n'.join(lines)
def generate_init_doc(self):
if self.args:
return 'Args:\n ' + ('\n '.join(arg.document() for arg in self.args))
return 'No arguments allowed.'
class StringWriter(object):
"""A CodeDumper writer that writes to a string. This can API can be implemented for
file writers or other uses."""
def __init__(self):
self._builder = []
def get(self):
"""Returns the contents. This is used by PythonOpenScad code in only the str
and repr conversions which specifically create a StringWriter writer. Append
is the only mentod called by the PythonOpenScad renderer."""
return '\n'.join(self._builder + [''])
def append(self, line):
"""Called by the PythonOpenScad renderer/code_dump to write generated model
representation. Override this function to implement other output mechanisms."""
self._builder.append(line)
class FileWriter(object):
"""A CodeDumper writer that writes to a file."""
def __init__(self, fp):
self.fp = fp
def finish(self):
"""Writes the final components to the output"""
self.fp.write('\n')
def append(self, line):
"""Called by the PythonOpenScad renderer/code_dump to write generated model
representation. Override this function to implement other output mechanisms."""
self.fp.write(line)
self.fp.write('\n')
class CodeDumper(object):
"""Helper for pretty printing OpenScad scripts (and other scripts too)."""
class IndentLevelState:
"""Indent level state."""
def __init__(self, level, is_last):
self.level = level
self.is_last = is_last
DUMPS_OPENSCAD = True
def get(self):
return self.level, self.is_last
def __init__(
self,
indent_char=' ',
indent_multiple=2,
writer=None,
str_quotes='"',
block_ends=(' {', '}', ';', '//', 'module', '', ''),
target_max_column=100,
):
"""
Args:
indent_char: the character used to indent.
indent_multiple: the number of indent_char added per indent level.
writer: A writer, like StringWriter.
target_max_column: The max column number where line continuation may be used.
variables: A list of variables to be defined at the top of the script.
"""
self.indent_char = indent_char
self.indent_multiple = indent_multiple
self.writer = writer or StringWriter()
self.str_quotes = str_quotes
self.block_ends = block_ends
self.current_indent_level = 0
self.target_max_column = target_max_column
self.current_indent_string = ''
self.is_last = False
self.indent_level_stack = []
self.modules_dict = dict()
self.modules_num = defaultdict(int)
def check_indent_level(self, level):
"""Check the adding of the resulting indent level will be in range.
Args:
level: The new requested indent level.
Throws:
InvalidIndentLevel level would is out of range
"""
if level < 0:
raise InvalidIndentLevel('Requested indent level below zero is not allowed.')
def push_increase_indent(self, amount=1):
"""Push an indent level change and increase indent level.
Args:
amount: the amount to increase the indent level, Amount can be negative. default 1
"""
current_level_state = CodeDumper.IndentLevelState(self.current_indent_level, self.is_last)
try:
self.set_indent_level(current_level_state.level + amount)
finally:
self.indent_level_stack.append(current_level_state)
def set_indent_level(self, level):
self.check_indent_level(level)
self.current_indent_level = level
self.current_indent_string = (
self.indent_char * self.indent_multiple * self.current_indent_level
)
def pop_indent_level(self):
"""Pops the indent level stack and sets the indent level to the popped value."""
if len(self.indent_level_stack) == 0:
raise IndentLevelStackEmpty('Empty indent level stack cannot be popped.')
level_state = self.indent_level_stack.pop()
self.set_indent_level(level_state.level)
self.is_last = level_state.is_last
def set_is_last(self, is_last):
"""Set this to False if there is another item to be rendered after this one."""
self.is_last = is_last
def get_is_last(self):
"""Clients that care if a suffix needs adding if it is on the end of the list
can check this."""
return self.is_last
def add_line(self, line):
"""Adds the given line as a whole line the output.
Args:
line: string to be added.
"""
self.writer.append(line)
def write_line(self, line):
"""Adds an indented line to the output. This could be used for comments."""
self.add_line(self.current_indent_string + line)
def write_function(
self, function_name, params_list, mod_prefix='', mod_suffix='', suffix=';', comment=None
):
"""Dumps a function like lines (may wrap).
Args:
function_name: name of function.
prefix: a string added in front of the function name
params_list: list of parameters (no commas separating them)
suffix: A string at the end
"""
if comment:
self.add_line(''.join([self.current_indent_string, comment]))
strings = [self.current_indent_string, mod_prefix, function_name, '(']
strings.append(', '.join(params_list))
strings.append(')')
strings.append(mod_suffix)
strings.append(suffix)
self.add_line(''.join(strings))
def render_value(self, value):
"""Returns a string representing the given value."""
if isinstance(value, str):
return self.str_quotes + repr(value)[1:-1] + self.str_quotes
return repr(value)
def render_name_value(self, arg, value):
return '%s=%s' % (arg.osc_name, self.render_value(value))
def should_add_suffix(self):
"""Returns true if the suffix should be added. OpenScad is always true."""
return True
def get_modifiers_prefix_suffix(self, obj):
"""Returns the OpenScad modifiers string."""
return (obj.get_modifiers(), '')
def add_modules(self, modules: List['Module']):
"""Adds the modules to the output. If a module name is already in use then
a new name is generated."""
for module in modules:
while module.get_name() in self.modules_dict:
other_module = self.modules_dict[module.name]
if other_module != module:
# Two different modules with the same name. Change the name of the new one.
newnum = 1 + self.modules_num[module.name]
self.modules_num[module.name] = newnum
# In theoru this name could a manuallu created name, so we need to
# continue to increment until we find a unique name.
module.gen_name = f'{module.name}_{newnum}'
else:
break
self.modules_dict[module.get_name()] = module
def reset_modules(self, modules):
"""Resets the module names."""
for module in modules:
module.gen_name = None
def dump_modules(self):
"""Writes the modules to the output."""
start_comment = self.block_ends[3]
if self.modules_dict:
self.add_line('')
self.add_line(f'{start_comment} Modules.')
module_names = [k for k in self.modules_dict.keys()]
module_names.sort()
for module_name in module_names:
self.render_modules(self.modules_dict[module_name])
def render_modules(self, module):
"""Returns a string representing the given variable."""
start_func = self.block_ends[0]
end_func = self.block_ends[1]
start_comment = self.block_ends[3]
name = module.get_name()
metadataName = module.getMetadataName()
self.add_line('')
if metadataName:
comment = start_comment + ' ' + repr(metadataName)
self.add_line(comment)
end_func_decl = self.block_ends[6]
return_func = self.block_ends[5]
define_module = self.block_ends[4]
self.add_line(f'{define_module} {name}(){end_func_decl}{return_func}{start_func}')
self.push_increase_indent()
module.code_dump_contained(self)
self.pop_indent_level()
self.add_line(f'{end_func} {start_comment} end module {name}')
class CodeDumperForPython(CodeDumper):
"""Helper for pretty printing to Python code compatible with SolidPython
and PythonOpenScad.
Args:
Same parameters as CodeDumper but overrides defaults for str_quotes and
block_ends.
"""
DUMPS_OPENSCAD = False
def __init__(self, *args, **kwds):
kwds.setdefault('str_quotes', "'")
kwds.setdefault('block_ends', (' (', '),', ',', '#', 'def', ' return', ':'))
super().__init__(*args, **kwds)
self.is_last = True
def render_value(self, value):
"""Returns a string representing the given value."""
if value == OSC_TRUE:
return 'True'
elif value == OSC_FALSE:
return 'False'
return repr(value)
def render_name_value(self, arg, value):
return '%s=%s' % (arg.name, self.render_value(value))
def should_add_suffix(self):
"""Returns true if the suffix should be added. Python is true of if not at the
end.."""
return not self.is_last
def get_modifiers_prefix_suffix(self, obj):
"""Returns a Python mosifiers mutator."""
s = obj.get_modifiers_repr()
if not s:
return ('', '')
return ('', '.add_modifier(*%s)' % s)
class PoscBase(PoscRendererBase):
DUMP_CONTAINER = True
DUMP_MODULE = False
def __post_init__(self):
for arg in self.OSC_API_SPEC.args:
value = getattr(self, arg.name)
is_different_name = arg.name != arg.attr_name
if is_different_name:
delattr(self, arg.name)
if value is not None and value is not NOT_PROVIDED:
setattr(self, arg.attr_name, arg.typ(value))
elif is_different_name:
setattr(self, arg.attr_name, None)
self.init_children()
# Object should be fully constructed now.
self.check_valid()
def init_children(self):
"""Initalizes objects that contain parents."""
# This node has no children.
def check_valid(self):
"""Checks that the construction of the object is valid."""
self.check_required_parameters()
def check_required_parameters(self):
"""Checks that required parameters are set and not None."""
for arg in self.OSC_API_SPEC.args:
if arg.required and (getattr(self, arg.attr_name, None) is None):
raise RequiredParameterNotProvided(
'"%s" is required and not provided' % arg.attr_name
)
def collect_args(self, code_dumper):
"""Returns a list of arg=value pairs as strings."""
posc_args = self.OSC_API_SPEC.args
result = []
for arg in posc_args:
v = getattr(self, arg.attr_name, None)
if v is not None:
result.append(code_dumper.render_name_value(arg, v))
return result
def has_children(self):
return False
def children(self):
"""This is a childless node, always returns empty tuple."""
return ()
def code_dump_scad(self, code_dumper: CodeDumper):
"""Dump the OpenScad equivalent of this script into the provided dumper."""
termial_suffix = code_dumper.block_ends[2] if code_dumper.should_add_suffix() else ''
suffix = code_dumper.block_ends[0] if self.has_children() else termial_suffix
function_name = self.OSC_API_SPEC.openscad_name
params_list = self.collect_args(code_dumper)
mod_prefix, mod_suffix = code_dumper.get_modifiers_prefix_suffix(self)
comment = None
metadataName = self.getMetadataName()
if metadataName:
comment = code_dumper.block_ends[3] + ' ' + repr(metadataName)
code_dumper.write_function(
function_name, params_list, mod_prefix, mod_suffix, suffix, comment
)
if self.has_children():
code_dumper.push_increase_indent()
left = len(self.children())
for child in self.children():
left -= 1
code_dumper.set_is_last(left == 0)
child.code_dump(code_dumper)
code_dumper.pop_indent_level()
code_dumper.write_line(code_dumper.block_ends[1])
def code_dump_contained(self, code_dumper: CodeDumper):
code_dumper.write_line(
code_dumper.block_ends[3] + ' Start: ' + self.OSC_API_SPEC.openscad_name
)
for child in self.children():
child.code_dump(code_dumper)
code_dumper.write_line(
code_dumper.block_ends[3] + ' End: ' + self.OSC_API_SPEC.openscad_name
)
def code_dump(self, code_dumper: CodeDumper):
if self.DUMP_CONTAINER or not code_dumper.DUMPS_OPENSCAD:
self.code_dump_scad(code_dumper)
else:
# Must be a LazyUnion or Module dumping to OpenScad. Dump the children directly
# to invoke the "lazy" union behavior.
self.code_dump_contained(code_dumper)
def get_modules(self):
return ()
def dump_with_code_dumper(self, code_dumper: CodeDumper, _fn: int = None, _fa: float = None, _fs: float = None):
"""Returns the OpenScad equivalent code for this node."""
if code_dumper.DUMPS_OPENSCAD:
header = self._header(_fn, _fa, _fs)
if header:
code_dumper.add_line(header)
code_dumper.add_modules(self.get_modules())
self.code_dump(code_dumper)
code_dumper.dump_modules()
# Reset the module names sp that these can be reused.
code_dumper.reset_modules(self.get_modules())
return code_dumper
def __str__(self):
"""Returns the OpenScad equivalent code for this node."""
return self.dump_with_code_dumper(CodeDumper()).writer.get()
def __repr__(self):
"""Returns the SolidPython equivalent code for this node."""
return self.dump_with_code_dumper(CodeDumperForPython()).writer.get()
def clone(self):
return copy.deepcopy(self)
def equals(self, other):
if not hasattr(other, 'OSC_API_SPEC'):
return False
# Since we create other classes with the same OpenScadApiSpecifier, this
# is the indicator of the object's type.
if self.OSC_API_SPEC is not other.OSC_API_SPEC:
return False
for arg in self.OSC_API_SPEC.args:
if getattr(self, arg.attr_name) != getattr(other, arg.attr_name):
return False
return self.children() == other.children()
def _header(self, _fn: int = None, _fa: float = None, _fs: float = None) -> str:
header = ""
for name, val in POSC_GLOBALS.overrides(_fn, _fa, _fs):
if val is not None:
header += f"{name} = {val};\n"
return header
# OpenPyScad compat functions.
def dumps(self, _fn: int = None, _fa: float = None, _fs: float = None) -> str:
"""Returns a string of this object's OpenScad script."""
return self.dump_with_code_dumper(CodeDumper(), _fn, _fa, _fs).writer.get()
def dump(self, fp, _fn: int = None, _fa: float = None, _fs: float = None):
"""Writes this object's OpenScad script to the given file.
Args:
fp: The python file object to use.
"""
self.dump_with_code_dumper(CodeDumper(writer=FileWriter(fp)), _fn, _fa, _fs).writer.finish()
def write(self, filename, encoding='utf-8', _fn: int = None, _fa: float = None, _fs: float = None):
"""Writes the OpenScad script to the given file name.
Args:
filename: The filename to create.
"""
with open(filename, 'w', encoding=encoding) as fp:
self.dump(fp, _fn, _fa, _fs)
def get_fn_fa_fs_args(self) -> dict[str, int | float]:
"""Returns a dictionary of the fn, fa and fs arguments."""
args = {}
for attr in ['fn', 'fa', 'fs']:
if hasattr(self, attr):
val = getattr(self, attr)
if val is None:
val = getattr(POSC_GLOBALS, attr)
args[attr] = val
else:
args[attr] = None
return args
def renderObj(self, renderer: M3dRenderer) -> RenderContext:
assert False, "Not implemented"
def module(self, name):
"""Returns a variable that references this object."""
return Module(name)(self)
# Documentation for the following functions is generated by the decorator
# apply_posc_transformation_attributes.
def translate(self, *args, **kwds):
return Translate(*args, **kwds)(self)
def rotate(self, *args, **kwds):
return Rotate(*args, **kwds)(self)
def scale(self, *args, **kwds):
return Scale(*args, **kwds)(self)
def resize(self, *args, **kwds):
return Resize(*args, **kwds)(self)
def mirror(self, *args, **kwds):
return Mirror(*args, **kwds)(self)
def color(self, *args, **kwds):
return Color(*args, **kwds)(self)
def multmatrix(self, *args, **kwds):
return Multmatrix(*args, **kwds)(self)
def offset(self, *args, **kwds):
return Offset(*args, **kwds)(self)
def projection(self, *args, **kwds):
return Projection(*args, **kwds)(self)
def minkowski(self, *args, **kwds):
return Minkowski(*args, **kwds)(self)
def hull(self, *args, **kwds):
return Hull(*args, **kwds)(self)
def linear_extrude(self, *args, **kwds):
return Linear_Extrude(*args, **kwds)(self)
def render(self, *args, **kwds):
return Render(*args, **kwds)(self)
def rotate_extrude(self, *args, **kwds):
return Rotate_Extrude(*args, **kwds)(self)
def fill(self, *args, **kwds):
return Fill(*args, **kwds)(self)
def __eq__(self, other):
"""Exact object tree equality. (Not resulting shape equality)"""
return self.equals(other)
def __ne__(self, other):
"""Exact object tree inequality. (Not resulting shape equality)"""
return not self.equals(other)
def __add__(self, other):
"""Union of this with other 3D object. See Union."""
return Union()(self, other)
def __sub__(self, other):
"""Difference of this with other 3D object. See Difference."""
return Difference()(self, other)
# OpenPyScad compatability
def __and__(self, other):
"""Intersect this with other 3D object. See Intersection."""
return Intersection()(self, other)
# SolidPython compatability
def __mul__(self, other):
"""Intersect this with other 3D object. See Intersection."""
return Intersection()(self, other)
# A decorator for PoscBase classes.
def apply_posc_attributes(clazz):
"""Decorator that applies an equivalent constructor with it's own generated
docstring. Also adds some SolidPython script compatibility class by providing an alias
class in the current module.
"""
if clazz.__init__ != PoscBase.__init__:
raise InitializerNotAllowed('class %s should not define __init__' % clazz.__name__)
# Check for name collision.
args: Tuple[Arg] = clazz.OSC_API_SPEC.args
for arg in args:
if hasattr(clazz, arg.attr_name):
raise NameCollissionFieldNameReserved(
"There exists an attribute '%s' for class %s that collides with an arg."
% (arg.name, clazz.__name__)
)