Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
935 lines (835 loc) · 35.6 KB
/
Copy pathsetup.py
File metadata and controls
935 lines (835 loc) · 35.6 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
import os
import re
import shutil
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from ctypes.util import find_library
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
IS_WINDOWS = sys.platform == "win32"
IS_DARWIN = sys.platform == "darwin"
def apply_wheel_build_env():
"""Load env written by cibuildwheel before-all hooks (needed on Windows)."""
here = os.path.dirname(os.path.abspath(__file__))
env_file = os.path.join(here, "scripts", "cibuildwheel", "wheel-build-env.env")
if not os.path.isfile(env_file):
return
with open(env_file, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
key, _, value = line.partition("=")
key = key.strip()
value = value.strip()
if key and value:
os.environ[key] = value
winflex = os.environ.get("WINFLEXBISON_DIR")
if winflex and os.path.isdir(winflex):
path = os.environ.get("PATH", "")
os.environ["PATH"] = winflex + os.pathsep + path if path else winflex
msys2_usr_bin = os.environ.get("MSYS2_USR_BIN")
if msys2_usr_bin and os.path.isdir(msys2_usr_bin):
path = os.environ.get("PATH", "")
os.environ["PATH"] = path + os.pathsep + msys2_usr_bin if path else msys2_usr_bin
def get_version():
override = os.environ.get("PYTHONSCAD_VERSION_OVERRIDE", "").strip()
if override:
return override
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, "VERSION.txt")) as f:
return f.read().strip()
def get_version_parts():
version = get_version()
# Build metadata and pre-release/development suffixes are allowed for wheel
# versions, but OPENSCAD_* macros still need numeric major/minor/patch.
match = re.match(r"^(([0-9]+)\.([0-9]+)(?:\.([0-9]+))?)(?:[.-].*)?(?:\+.*)?$", version)
if not match:
raise RuntimeError(f"Version string '{version}' doesn't match expected semantic version format")
major = str(int(match.group(2)))
minor = str(int(match.group(3)))
patch = str(int(match.group(4) or "0"))
shortversion = match.group(1)
return version, shortversion, major, minor, patch
def pkg_config_cmd():
"""Return the pkg-config executable (supports vcpkg pkgconf on Windows)."""
return os.environ.get("PKG_CONFIG", "pkg-config")
def pkg_config_flags(packages, flag):
"""Query pkg-config for the given flag (e.g. '--cflags-only-I', '--libs-only-l')."""
try:
out = subprocess.check_output(
[pkg_config_cmd(), flag] + packages,
text=True, stderr=subprocess.DEVNULL,
env=os.environ,
)
return out.strip().split()
except (subprocess.CalledProcessError, FileNotFoundError):
return []
def pkg_config_exists(package):
"""Return True if pkg-config can find the given package."""
try:
subprocess.check_call(
[pkg_config_cmd(), "--exists", package],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
env=os.environ,
)
return True
except (subprocess.CalledProcessError, FileNotFoundError):
return False
def pkg_config_version(package):
"""Return the version string for a pkg-config package, or None."""
try:
out = subprocess.check_output(
[pkg_config_cmd(), "--modversion", package],
text=True, stderr=subprocess.DEVNULL,
env=os.environ,
)
return out.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return None
def get_vcpkg_installed_dir():
"""Return the vcpkg installed prefix for the active triplet, if any."""
root = os.environ.get("VCPKG_ROOT") or os.environ.get("PYTHONSCAD_VCPKG_ROOT")
if not root:
return None
triplet = os.environ.get("VCPKG_DEFAULT_TRIPLET", "x64-windows")
installed = os.path.join(root, "installed", triplet)
return installed if os.path.isdir(installed) else None
def get_pkg_config_include_dirs():
"""Return include directories discovered via pkg-config."""
pkgs = ["eigen3", "harfbuzz", "libxml-2.0", "freetype2", "glib-2.0", "cairo"]
raw = pkg_config_flags(pkgs, "--cflags-only-I")
dirs = [flag[2:] for flag in raw if flag.startswith("-I")]
# Fallback paths used when pkg-config is unavailable or incomplete
fallbacks = [
"/usr/include/eigen3",
"/usr/include/harfbuzz",
"/usr/include/libxml2",
"/usr/include/freetype2",
"/usr/include/glib-2.0",
"/usr/include/cairo",
"/usr/lib64/glib-2.0/include",
"/usr/lib/x86_64-linux-gnu/glib-2.0/include",
"/usr/lib/aarch64-linux-gnu/glib-2.0/include",
"/opt/homebrew/include",
"/opt/homebrew/include/eigen3",
"/opt/homebrew/include/harfbuzz",
"/opt/homebrew/include/freetype2",
"/opt/homebrew/include/glib-2.0",
"/opt/homebrew/include/cairo",
"/opt/homebrew/lib/glib-2.0/include",
"/usr/local/include",
"/usr/local/include/eigen3",
"/usr/local/include/harfbuzz",
"/usr/local/include/freetype2",
"/usr/local/include/glib-2.0",
"/usr/local/include/cairo",
"/usr/local/lib/glib-2.0/include",
]
vcpkg_installed = get_vcpkg_installed_dir()
if vcpkg_installed:
fallbacks.insert(0, os.path.join(vcpkg_installed, "include"))
for fb in fallbacks:
if fb not in dirs and os.path.isdir(fb):
dirs.append(fb)
return dirs
def get_pkg_config_libraries():
"""Return library names discovered via pkg-config."""
pkgs = ["freetype2", "libxml-2.0", "fontconfig", "glib-2.0", "harfbuzz"]
raw = pkg_config_flags(pkgs, "--libs-only-l")
libs = [flag[2:] for flag in raw if flag.startswith("-l")]
required = ["freetype", "xml2", "fontconfig", "double-conversion", "gmp",
"harfbuzz", "mpfr", "glib-2.0"]
for lib in required:
if lib not in libs:
libs.append(lib)
return libs
def get_link_libraries():
"""Return the full set of libraries to link the pip extension against."""
libs = get_pkg_config_libraries()
# Link concrete Boost libraries so auditwheel/delocate/delvewheel can
# bundle them. Boost.System has been header-only by default since 1.69,
# but some Linux Boost builds still depend on its shared library.
boost_libs = ["boost_program_options"]
if not IS_DARWIN and not IS_WINDOWS and find_library("boost_system"):
boost_libs.append("boost_system")
# On Windows, Boost.Regex is selected via MSVC autolink; vcpkg's release
# triplet does not provide a stable unversioned boost_regex.lib to name here.
if not IS_WINDOWS:
boost_libs.insert(0, "boost_regex")
for lib in boost_libs:
if lib not in libs:
libs.append(lib)
if IS_WINDOWS:
for lib in ("libpng16", "shell32"):
if lib not in libs:
libs.append(lib)
cgal_raw = pkg_config_flags(["CGAL"], "--libs-only-l")
if cgal_raw:
for flag in cgal_raw:
if flag.startswith("-l") and flag[2:] not in libs:
libs.append(flag[2:])
else:
# CGAL 5+ is header-only on many distros (e.g. EL8); GMP/MPFR suffice.
for lib in ("CGAL", "CGAL_Core"):
for libdir in ("/usr/lib64", "/usr/lib"):
if any(
os.path.isfile(os.path.join(libdir, f"lib{lib}{suffix}"))
for suffix in (".so", ".a")
):
if lib not in libs:
libs.append(lib)
break
return libs
def get_library_dirs():
"""Return linker search paths for the active platform."""
dirs = []
vcpkg_installed = get_vcpkg_installed_dir()
if vcpkg_installed:
dirs.append(os.path.join(vcpkg_installed, "lib"))
dirs.append(os.path.join(vcpkg_installed, "lib", "manual-link"))
if IS_DARWIN:
for prefix in ("/opt/homebrew", "/usr/local"):
libdir = os.path.join(prefix, "lib")
if os.path.isdir(libdir):
dirs.append(libdir)
elif not IS_WINDOWS:
for libdir in ("/usr/lib64", "/usr/lib"):
if os.path.isdir(libdir):
dirs.append(libdir)
return dirs
def normalize_windows_link_libraries(libs, library_dirs):
"""Translate pkg-config library names to MSVC/vcpkg import library names."""
if not IS_WINDOWS:
return libs
system_libs = {"advapi32", "bcrypt", "kernel32", "shell32", "user32", "winmm", "ws2_32"}
aliases = {
"3mf": "lib3mf",
"xml2": "libxml2",
"z": "zlib",
}
normalized = []
for lib in libs:
candidates = [aliases.get(lib, lib)]
if lib.startswith("boost_"):
candidates.append(lib)
resolved = None
for libdir in library_dirs:
if not os.path.isdir(libdir):
continue
for candidate in candidates:
if os.path.isfile(os.path.join(libdir, f"{candidate}.lib")):
resolved = candidate
break
if resolved:
break
if lib.startswith("boost_"):
prefixes = (f"{lib}-".lower(), f"lib{lib}-".lower())
for name in os.listdir(libdir):
lowered = name.lower()
if lowered.endswith(".lib") and lowered.startswith(prefixes):
resolved = os.path.splitext(name)[0]
break
if resolved:
break
if not resolved and lib in system_libs:
resolved = lib
if not resolved:
resolved = aliases.get(lib, lib)
if resolved and resolved not in normalized:
normalized.append(resolved)
return normalized
def get_extra_compile_args():
"""Return platform-specific compiler flags."""
if IS_WINDOWS:
# Disable MSVC whole-program optimization; the wheel links the full
# extension for every Python ABI and /GL exhausts linker heap on CI.
return ["/bigobj", "/EHsc", "/std:c++20", "/Zc:strictStrings-", "/Zc:char8_t-", "/GL-"]
args = ["-std=c++17"]
if IS_DARWIN:
args.append("-stdlib=libc++")
return args
def get_platform_sources():
"""Return platform-specific utility sources."""
sources = ["src/platform/PlatformUtils.cc"]
if IS_WINDOWS:
sources.append("src/platform/PlatformUtils-win.cc")
elif IS_DARWIN:
sources.append("src/platform/PlatformUtils-mac.mm")
else:
sources.append("src/platform/PlatformUtils-posix.cc")
return sources
def get_extra_link_args():
"""Return platform-specific linker flags."""
if IS_DARWIN:
return ["-framework", "Foundation"]
return []
def get_extra_defines():
"""Return platform-specific preprocessor defines."""
defines = []
if IS_WINDOWS:
defines.extend([
("NOMINMAX", None),
("NOGDI", None),
("WIN32_LEAN_AND_MEAN", None),
("_USE_MATH_DEFINES", None),
("CGAL_DISABLE_ROUNDING_MATH_CHECK", None),
])
return defines
def detect_lib3mf():
"""Detect lib3mf and return (sources, include_dirs, libraries, defines) or dummy fallback."""
# lib3mf v2 uses pkg-config name "lib3mf", v1 uses "lib3MF"
for pkg_name in ("lib3mf", "lib3MF"):
ver = pkg_config_version(pkg_name)
if ver is None:
continue
inc_raw = pkg_config_flags([pkg_name], "--cflags-only-I")
inc_dirs = [f[2:] for f in inc_raw if f.startswith("-I")]
lib_raw = pkg_config_flags([pkg_name], "--libs-only-l")
libraries = [f[2:] for f in lib_raw if f.startswith("-l")]
major = int(ver.split(".")[0])
if major >= 2:
for base in list(inc_dirs):
cpp_bindings_dir = os.path.join(base, "Bindings", "Cpp")
if (cpp_bindings_dir not in inc_dirs and
os.path.isfile(os.path.join(cpp_bindings_dir, "lib3mf_implicit.hpp"))):
inc_dirs.append(cpp_bindings_dir)
sources = ["src/io/export_3mf_v2.cc", "src/io/import_3mf_v2.cc"]
print(f"lib3mf: found v{ver} (v2 API)")
else:
for base in list(inc_dirs):
legacy_dir = os.path.join(base, "lib3mf")
if (legacy_dir not in inc_dirs and
os.path.isfile(os.path.join(legacy_dir, "Model", "COM", "NMR_DLLInterfaces.h"))):
inc_dirs.append(legacy_dir)
sources = ["src/io/export_3mf_v1.cc", "src/io/import_3mf_v1.cc"]
print(f"lib3mf: found v{ver} (v1 API)")
defines = [("ENABLE_LIB3MF", "1")]
return sources, inc_dirs, libraries, defines
print("lib3mf: not found, using dummy stubs")
sources = ["src/io/export_3mf_dummy.cc", "src/io/import_3mf_dummy.cc"]
return sources, [], [], []
def detect_libfive():
"""Detect libfive submodule and return (sources, include_dirs, defines) or empty fallback."""
libfive_include = os.path.join("submodules", "libfive", "libfive", "include")
libfive_src = os.path.join("submodules", "libfive", "libfive", "src")
if not os.path.isdir(libfive_src):
print("libfive: submodule not found, skipping")
return [], [], []
src_prefix = libfive_src + os.sep
sources = [
src_prefix + "eval/base.cpp",
src_prefix + "eval/deck.cpp",
src_prefix + "eval/eval_interval.cpp",
src_prefix + "eval/eval_jacobian.cpp",
src_prefix + "eval/eval_array.cpp",
src_prefix + "eval/eval_deriv_array.cpp",
src_prefix + "eval/eval_feature.cpp",
src_prefix + "eval/tape.cpp",
src_prefix + "eval/feature.cpp",
src_prefix + "render/discrete/heightmap.cpp",
src_prefix + "render/discrete/voxels.cpp",
src_prefix + "render/brep/contours.cpp",
src_prefix + "render/brep/edge_tables.cpp",
src_prefix + "render/brep/manifold_tables.cpp",
src_prefix + "render/brep/mesh.cpp",
src_prefix + "render/brep/neighbor_tables.cpp",
src_prefix + "render/brep/progress.cpp",
src_prefix + "render/brep/dc/marching.cpp",
src_prefix + "render/brep/dc/dc_contourer.cpp",
src_prefix + "render/brep/dc/dc_mesher.cpp",
src_prefix + "render/brep/dc/dc_neighbors2.cpp",
src_prefix + "render/brep/dc/dc_neighbors3.cpp",
src_prefix + "render/brep/dc/dc_worker_pool2.cpp",
src_prefix + "render/brep/dc/dc_worker_pool3.cpp",
src_prefix + "render/brep/dc/dc_tree2.cpp",
src_prefix + "render/brep/dc/dc_tree3.cpp",
src_prefix + "render/brep/dc/dc_xtree2.cpp",
src_prefix + "render/brep/dc/dc_xtree3.cpp",
src_prefix + "render/brep/dc/dc_object_pool2.cpp",
src_prefix + "render/brep/dc/dc_object_pool3.cpp",
src_prefix + "render/brep/hybrid/hybrid_debug.cpp",
src_prefix + "render/brep/hybrid/hybrid_worker_pool2.cpp",
src_prefix + "render/brep/hybrid/hybrid_worker_pool3.cpp",
src_prefix + "render/brep/hybrid/hybrid_neighbors2.cpp",
src_prefix + "render/brep/hybrid/hybrid_neighbors3.cpp",
src_prefix + "render/brep/hybrid/hybrid_tree2.cpp",
src_prefix + "render/brep/hybrid/hybrid_tree3.cpp",
src_prefix + "render/brep/hybrid/hybrid_xtree2.cpp",
src_prefix + "render/brep/hybrid/hybrid_xtree3.cpp",
src_prefix + "render/brep/hybrid/hybrid_object_pool2.cpp",
src_prefix + "render/brep/hybrid/hybrid_object_pool3.cpp",
src_prefix + "render/brep/hybrid/hybrid_mesher.cpp",
src_prefix + "render/brep/simplex/simplex_debug.cpp",
src_prefix + "render/brep/simplex/simplex_neighbors2.cpp",
src_prefix + "render/brep/simplex/simplex_neighbors3.cpp",
src_prefix + "render/brep/simplex/simplex_worker_pool2.cpp",
src_prefix + "render/brep/simplex/simplex_worker_pool3.cpp",
src_prefix + "render/brep/simplex/simplex_tree2.cpp",
src_prefix + "render/brep/simplex/simplex_tree3.cpp",
src_prefix + "render/brep/simplex/simplex_xtree2.cpp",
src_prefix + "render/brep/simplex/simplex_xtree3.cpp",
src_prefix + "render/brep/simplex/simplex_object_pool2.cpp",
src_prefix + "render/brep/simplex/simplex_object_pool3.cpp",
src_prefix + "render/brep/simplex/simplex_mesher.cpp",
src_prefix + "render/brep/vol/vol_neighbors.cpp",
src_prefix + "render/brep/vol/vol_object_pool.cpp",
src_prefix + "render/brep/vol/vol_tree.cpp",
src_prefix + "render/brep/vol/vol_worker_pool.cpp",
src_prefix + "solve/solver.cpp",
src_prefix + "tree/opcode.cpp",
src_prefix + "tree/archive.cpp",
src_prefix + "tree/data.cpp",
src_prefix + "tree/deserializer.cpp",
src_prefix + "tree/serializer.cpp",
src_prefix + "tree/tree.cpp",
src_prefix + "tree/operations.cpp",
src_prefix + "oracle/oracle_clause.cpp",
src_prefix + "oracle/transformed_oracle.cpp",
src_prefix + "oracle/transformed_oracle_clause.cpp",
src_prefix + "libfive.cpp",
]
stdlib_dir = os.path.join("submodules", "libfive", "libfive", "stdlib")
if os.path.isdir(stdlib_dir):
sources.append(os.path.join(stdlib_dir, "stdlib.cpp"))
sources.append(os.path.join(stdlib_dir, "stdlib_impl.cpp"))
sources.append("src/python/FrepNode.cc")
include_dirs = [libfive_include]
defines = [
("ENABLE_LIBFIVE", "1"),
("GIT_TAG", '"N/A"'),
("GIT_REV", '"N/A"'),
("GIT_BRANCH", '"N/A"'),
]
print(f"libfive: enabled ({len(sources)} source files)")
return sources, include_dirs, defines
class BuildExtWithLexYacc(build_ext):
"""Custom build_ext command to run lex/yacc before building extension modules."""
cxx_only_compile_args = {"-std=c++17", "-stdlib=libc++"}
def finalize_options(self):
super().finalize_options()
build_parallel = os.environ.get("PYTHONSCAD_BUILD_PARALLEL")
if build_parallel and not self.parallel:
try:
self.parallel = int(build_parallel)
except ValueError as exc:
raise RuntimeError(
"PYTHONSCAD_BUILD_PARALLEL must be an integer when set"
) from exc
def build_extensions(self):
if IS_DARWIN and hasattr(self.compiler, "src_extensions"):
if ".mm" not in self.compiler.src_extensions:
self.compiler.src_extensions.append(".mm")
original_compile = self.compiler.compile
original_single_compile = None
if not IS_WINDOWS and hasattr(self.compiler, "_compile"):
original_single_compile = self.compiler._compile
def compile_without_cxx_args_for_c_sources(obj, src, ext, cc_args, extra_postargs, pp_opts):
if src.endswith(".c") and extra_postargs:
extra_postargs = [
arg for arg in extra_postargs
if arg not in self.cxx_only_compile_args
]
return original_single_compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
self.compiler._compile = compile_without_cxx_args_for_c_sources
workers = self.parallel
if workers is True:
workers = os.cpu_count()
parallel_compile_methods = ("_setup_compile", "_get_cc_args", "_compile")
supports_parallel_compile = all(
hasattr(self.compiler, method) for method in parallel_compile_methods
)
if workers and workers > 1 and supports_parallel_compile:
def compile_in_parallel(
sources,
output_dir=None,
macros=None,
include_dirs=None,
debug=False,
extra_preargs=None,
extra_postargs=None,
depends=None,
):
macros, objects, extra_postargs, pp_opts, build = self.compiler._setup_compile(
output_dir,
macros,
include_dirs,
sources,
depends,
extra_postargs,
)
cc_args = self.compiler._get_cc_args(pp_opts, debug, extra_preargs)
def compile_object(obj):
src, ext = build[obj]
self.compiler._compile(
obj,
src,
ext,
cc_args,
extra_postargs,
pp_opts,
)
print(f"Compiling C/C++ sources with {workers} parallel jobs")
with ThreadPoolExecutor(max_workers=workers) as executor:
list(executor.map(compile_object, objects))
return objects
self.compiler.compile = compile_in_parallel
try:
super().build_extensions()
finally:
self.compiler.compile = original_compile
if original_single_compile is not None:
self.compiler._compile = original_single_compile
def run(self):
yacc_src = "src/core/parser.y"
lex_src = "src/core/lexer.l"
yacc_out = "src/core/parser.cc"
yacc_hdr = "src/core/parser.tab.h"
lex_out = "src/core/lexer.cc"
def needs_rebuild(src, targets):
if not all(os.path.exists(t) for t in targets):
return True
src_time = os.path.getmtime(src)
target_time = min(os.path.getmtime(t) for t in targets)
return src_time > target_time
def resolve_tool(env_var, candidates):
env_value = os.environ.get(env_var)
if env_value:
if os.path.isfile(env_value) or shutil.which(env_value):
return env_value
raise RuntimeError(f"{env_var} points to missing executable: {env_value}")
for candidate in candidates:
resolved = shutil.which(candidate)
if resolved:
return resolved
raise RuntimeError(f"Could not find any of: {', '.join(candidates)}")
bison_cmd = resolve_tool("BISON", ["win_bison", "bison"] if IS_WINDOWS else ["bison"])
flex_cmd = resolve_tool("FLEX", ["win_flex", "flex"] if IS_WINDOWS else ["flex"])
if needs_rebuild(yacc_src, [yacc_out, yacc_hdr]):
print(f"Generating Yacc: {yacc_src}")
subprocess.run([bison_cmd, "-d", "-p", "parser", yacc_src], check=True)
os.rename("parser.tab.c", yacc_out)
shutil.copyfile("parser.tab.h", "src/core/parser.hxx")
os.rename("parser.tab.h", yacc_hdr)
else:
print(f"{yacc_src} is up to date")
if needs_rebuild(lex_src, [lex_out]):
print(f"Generating Lex: {lex_src}")
subprocess.run([flex_cmd, "-o", lex_out, lex_src], check=True)
else:
print(f"{lex_src} is up to date")
super().run()
def main():
apply_wheel_build_env()
root = [
"src/Feature.cc",
"src/FontCache.cc",
"src/handle_dep.cc"
]
python =[
"src/genlang/genlang.cc",
"src/python/pyfunctions.cc",
"src/python/py_math.cc",
"src/python/py_primitives.cc",
"src/python/py_transform.cc",
"src/python/py_extrude.cc",
"src/python/py_csg.cc",
"src/python/py_analysis.cc",
"src/python/py_ops.cc",
"src/python/py_io.cc",
"src/python/pyconversion.cc",
"src/python/pydata.cc",
"src/python/pyopenscad.cc",
"src/python/python_runtime.cc",
"src/python/pymod.cc",
"src/python/pip_fixer.cc"
]
geometry = [
"src/geometry/GeometryEvaluator.cc",
"src/geometry/rotate_extrude.cc",
"src/geometry/roof_ss.cc",
"src/geometry/roof_vd.cc",
"src/geometry/skin.cc",
"src/geometry/linear_extrude.cc",
"src/geometry/organic_resample.cc",
"src/geometry/cgal/CGALCache.cc",
"src/geometry/cgal/cgalutils.cc",
"src/geometry/cgal/cgalutils-kernel.cc",
"src/geometry/cgal/cgalutils-applyops.cc",
"src/geometry/cgal/cgalutils-applyops-minkowski.cc",
"src/geometry/cgal/cgalutils-mesh.cc",
"src/geometry/cgal/cgalutils-triangulate.cc",
"src/geometry/cgal/cgalutils-tess.cc",
"src/geometry/cgal/cgalutils-orient.cc",
"src/geometry/cgal/CGALNefGeometry.cc",
"src/geometry/cgal/cgalutils-polyhedron.cc",
"src/geometry/cgal/cgalutils-convex.cc",
"src/geometry/cgal/cgalutils-project.cc",
"src/geometry/cgal/cgalutils-closed.cc",
"src/geometry/Geometry.cc",
"src/geometry/GeometryCache.cc",
"src/geometry/GeometryUtils.cc",
"src/geometry/Polygon2d.cc",
"src/geometry/Barcode1d.cc",
"src/geometry/PolySet.cc",
"src/geometry/PolySetBuilder.cc",
"src/geometry/PolySetUtils.cc",
"src/geometry/Surface.cc",
"src/geometry/Curve.cc",
"src/geometry/ClipperUtils.cc",
"src/geometry/linalg.cc",
"src/geometry/manifold/ManifoldGeometry.cc",
"src/geometry/manifold/manifold-applyops.cc",
"src/geometry/manifold/manifoldutils.cc",
"src/geometry/manifold/manifold-applyops-minkowski.cc",
"src/geometry/boolean_utils.cc" ]
ext= [
"src/ext/libtess2/Source/bucketalloc.c",
"src/ext/libtess2/Source/sweep.c",
"src/ext/libtess2/Source/mesh.c",
"src/ext/libtess2/Source/dict.c",
"src/ext/libtess2/Source/tess.c",
"src/ext/libtess2/Source/geom.c",
"src/ext/libtess2/Source/priorityq.c" ]
nodes = [
"src/core/primitives.cc",
"src/core/CgalAdvNode.cc",
"src/core/FilletNode.cc",
"src/core/ProjectionNode.cc",
"src/core/SurfaceNode.cc",
"src/core/ColorNode.cc",
"src/core/ImportNode.cc",
"src/core/PullNode.cc",
"src/core/TextNode.cc",
"src/core/SheetNode.cc",
"src/core/LinearExtrudeNode.cc",
"src/core/RotateExtrudeNode.cc",
"src/core/RenderNode.cc",
"src/core/CSGNode.cc",
"src/core/OffsetNode.cc",
"src/core/RoofNode.cc",
"src/core/TransformNode.cc",
"src/core/CsgOpNode.cc",
"src/core/OversampleNode.cc",
"src/core/WrapNode.cc",
"src/core/DebugNode.cc",
"src/core/PathExtrudeNode.cc",
"src/core/GroupModule.cc",
"src/core/SkinNode.cc",
"src/core/RepairNode.cc"
]
context = [
"src/core/ContextFrame.cc",
"src/core/ScopeContext.cc",
"src/core/LocalScope.cc",
"src/core/Context.cc",
"src/core/ContextMemoryManager.cc",
"src/core/BuiltinContext.cc",
"src/core/EvaluationSession.cc",
"src/core/Parameters.cc",
"src/core/SourceFileCache.cc",
]
arith = [
"src/core/FunctionType.cc",
"src/core/UndefType.cc",
"src/core/Value.cc",
"src/core/Assignment.cc",
"src/core/Arguments.cc",
"src/core/Expression.cc",
"src/core/SourceFile.cc",
]
language = [
"src/core/ModuleInstantiation.cc",
"src/core/UserModule.cc",
"src/core/module.cc",
"src/core/Children.cc",
"src/core/AST.cc",
"src/core/Builtins.cc",
"src/core/builtin_functions.cc",
"src/core/control.cc" ,
"src/core/function.cc"
]
core = [
"src/core/CurveDiscretizer.cc",
"src/core/FreetypeRenderer.cc",
"src/core/DrawingCallback.cc",
"src/core/customizer/Annotation.cc",
"src/core/node.cc",
"src/core/node_clone.cc",
"src/core/progress.cc",
"src/core/parsersettings.cc",
"src/core/NodeVisitor.cc",
"src/core/Settings.cc",
"src/core/Tree.cc",
"src/core/ColorUtil.cc",
"src/core/NodeDumper.cc",
"src/core/StatCache.cc",
] + language + arith + context + nodes
io_export = [
"src/io/export_stl.cc",
"src/io/export_dxf.cc",
"src/io/export_off.cc",
"src/io/export_pov.cc",
"src/io/export_svg.cc",
"src/io/export_gcode.cc",
"src/io/export_foldable.cc",
"src/io/export_ps.cc",
"src/io/export_wrl.cc",
"src/io/export_amf.cc",
"src/io/export_nef.cc",
"src/io/export_pdf.cc",
"src/io/export_obj.cc",
"src/io/export_step.cc"
]
io_import = [
"src/io/import_json.cc",
"src/io/import_obj.cc",
"src/io/import_step.cc",
"src/io/import_amf.cc",
"src/io/import_nef.cc",
"src/io/import_svg.cc",
"src/io/import_off.cc",
"src/io/import_stl.cc" ]
libsvg = [
"src/libsvg/circle.cc",
"src/libsvg/line.cc",
"src/libsvg/shape.cc",
"src/libsvg/use.cc",
"src/libsvg/data.cc",
"src/libsvg/path.cc",
"src/libsvg/svgpage.cc",
"src/libsvg/util.cc",
"src/libsvg/ellipse.cc",
"src/libsvg/polygon.cc",
"src/libsvg/text.cc",
"src/libsvg/group.cc",
"src/libsvg/polyline.cc",
"src/libsvg/transformation.cc",
"src/libsvg/libsvg.cc",
"src/libsvg/rect.cc",
"src/libsvg/tspan.cc"
]
io = [
"src/io/export.cc",
"src/io/DxfData.cc",
"src/io/fileutils.cc",
"src/io/StepKernel.cc",
"src/io/dxfdim.cc" ] + io_export + io_import
manifold = [
"submodules/manifold/src/manifold.cpp",
"submodules/manifold/src/quickhull.cpp",
"submodules/manifold/src/boolean_result.cpp",
"submodules/manifold/src/cross_section/cross_section.cpp",
"submodules/manifold/src/constructors.cpp",
"submodules/manifold/src/smoothing.cpp",
"submodules/manifold/src/subdivision.cpp",
"submodules/manifold/src/properties.cpp",
"submodules/manifold/src/face_op.cpp",
"submodules/manifold/src/boolean3.cpp",
"submodules/manifold/src/edge_op.cpp",
"submodules/manifold/src/csg_tree.cpp",
"submodules/manifold/src/sort.cpp",
"submodules/manifold/src/sdf.cpp",
"submodules/manifold/src/polygon.cpp",
"submodules/manifold/src/tree2d.cpp",
"submodules/manifold/src/minkowski.cpp",
"submodules/manifold/src/impl.cpp" ]
clipper = [
"submodules/Clipper2/CPP/Clipper2Lib/src/clipper.engine.cpp",
"submodules/Clipper2/CPP/Clipper2Lib/src/clipper.offset.cpp",
"submodules/Clipper2/CPP/Clipper2Lib/src/clipper.rectclip.cpp" ]
utils = [
"src/utils/printutils.cc",
"src/utils/degree_trig.cc",
"src/utils/hash.cc",
"src/utils/svg.cc",
"src/utils/vector_math.cc",
"src/utils/png_util.cc",
"src/utils/calc.cc" ]
platform = get_platform_sources()
glview = [
"src/glview/Camera.cc",
# "src/glview/PolySetRenderer.cc",
"src/glview/ColorMap.cc",
"src/glview/RenderSettings.cc" ]
lex_yacc = [
"src/core/parser.cc",
"src/core/lexer.cc"
]
lodepng = [ "src/ext/lodepng/lodepng.cpp" ]
# Detect optional dependencies
lib3mf_sources, lib3mf_incdirs, lib3mf_libs, lib3mf_defines = detect_lib3mf()
libfive_sources, libfive_incdirs, libfive_defines = detect_libfive()
project_include_dirs = [
".",
"src",
"src/core",
"src/ext",
"src/geometry",
"src/io",
"src/utils",
"src/platform",
"src/ext/libtess2/Include",
"submodules/Clipper2/CPP/Clipper2Lib/include",
"submodules/manifold/include",
] + get_pkg_config_include_dirs() + lib3mf_incdirs + libfive_incdirs
all_sources = (root + python + geometry + ext + io + lib3mf_sources +
libsvg + core + manifold + clipper + utils + platform +
glview + lex_yacc + lodepng + libfive_sources)
version, shortversion, version_major, version_minor, version_patch = get_version_parts()
all_defines = [
("ENABLE_PYTHON", "1"),
("ENABLE_CGAL", "1"),
("ENABLE_MANIFOLD", "1"),
("EXPERIMENTAL", "1"),
("OPENSCAD_NOGUI", "1"),
("PYTHON_EXECUTABLE_NAME", '"pythonscad"'),
("MANIFOLD_PAR", "-1"),
("OPENSCAD_VERSION", version),
("OPENSCAD_SHORTVERSION", shortversion),
("OPENSCAD_MAJOR", version_major),
("OPENSCAD_MINOR", version_minor),
("OPENSCAD_PATCH", version_patch),
("OPENSCAD_YEAR", version_major),
("OPENSCAD_MONTH", version_minor),
("OPENSCAD_DAY", version_patch),
("STACKSIZE", "524288"),
] + lib3mf_defines + libfive_defines + get_extra_defines()
library_dirs = get_library_dirs()
raw_link_libraries = get_link_libraries() + lib3mf_libs
link_libraries = normalize_windows_link_libraries(raw_link_libraries, library_dirs)
pythonscad_ext = Extension(
"_openscad",
sources=all_sources,
include_dirs=project_include_dirs,
library_dirs=library_dirs,
libraries=link_libraries,
define_macros=all_defines,
extra_compile_args=get_extra_compile_args(),
extra_link_args=get_extra_link_args(),
)
# The pure-Python overlay packages live under libraries/python/{openscad,pythonscad}
# so they are already shipped alongside the binary by the standalone CMake install
# (the libraries/ tree). The stub-only package supplies the static contract for
# the raw C extension; the overlays carry py.typed markers and inline annotations.
# Shipping all three in this wheel makes `pip install pythonscad` sufficient for
# both runtime use and IDE/type-checker support.
setup(
version=get_version(),
cmdclass={"build_ext": BuildExtWithLexYacc},
ext_modules=[pythonscad_ext],
packages=["openscad", "pythonscad", "_openscad-stubs"],
package_dir={
"openscad": "libraries/python/openscad",
"pythonscad": "libraries/python/pythonscad",
"_openscad-stubs": "libraries/python/stubs/_openscad-stubs",
},
package_data={
"openscad": ["py.typed"],
"pythonscad": ["py.typed"],
"_openscad-stubs": ["__init__.pyi", "py.typed"],
},
)
if __name__ == "__main__":
main()