Repository navigation
Expand file tree
/
Copy pathguided.py
More file actions
4240 lines (3660 loc) · 214 KB
/
Copy pathguided.py
File metadata and controls
4240 lines (3660 loc) · 214 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
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 Andrew Rainsberger and CurioMesh contributors
"""Guided Retopo: importance points steer a live, adaptive quad preview you can partly redo by hand.
Points (Detail / Loop / Sharp / Calm) live on the source object. A density field built from them drives
either the whole mesh (adaptive triangle remesh -> TRIAD-Q PairClosure -> fit to surface) or only the union
of the point spheres (the region machinery in triadq/patch.py, seam kept). Faces locked on the preview stay
fixed; Redraw Strip rebuilds a selected strip; Next spot points at the worst area.
"""
from __future__ import annotations
import json
import math
import os
import shutil
import time
from dataclasses import dataclass
from pathlib import Path
import bmesh
import bpy
import numpy as np
from bpy_extras.io_utils import ExportHelper, ImportHelper
from mathutils import Matrix, Vector
from mathutils.bvhtree import BVHTree
from mathutils.kdtree import KDTree
from . import guides, live, overlay, region, segments, sliced, symmetry, textures
from . import loops as edgeloops
from . import autofix_live, autoretopo, blockout, faceloops, flowedit, hard_surface, hardware, history, jobpack, ladder, multires, organize, profiles, teach, turbo
from .triadq import areas, detail, fit, patch
from . import uv_hooks # main-only: uv
from .triadq.budget import density_drop
from .triadq.engine import RemeshOptions, remesh_mesh
from .triadq.shading import sharp_edges
from .triadq.types import FlatFaces, MeshData
from .triadq.uvs import chart_codes
from . import translations
from .translations import tip, tr
PREVIEW_NAME = "CurioMesh_GuidedPreview"
SPARE_MESHES = (PREVIEW_NAME + "_Size", PREVIEW_NAME + "_Organize") # preview meshes kept for a quick swap, with no users
REGION_READY = False # Selected Faces Only: off until it re-stitches its seam (226 of 398 outline vertices joined on a bust). Redo Inside Shapes covers it
POINT_TAG = "curiomesh_point"
DEBOUNCE_SECONDS = 0.35
AREA_DEBOUNCE_SECONDS = 0.12
POLL_SECONDS = 0.2
LIVE_QUAD_CAP = 2_500 # predicted quads above which the live preview waits for "Update"
HARD_QUAD_CAP = 60_000
CHORDS_PROFILES = ("ANIMATION", "SUBDIV") # uses where Redraw Messy Quads starts on
CHORDS_MOST_PIECES = 40 # more loose pieces than this and it stays off: the compressor (250) took 984 s
LIVE_REGION_CAP = 3_000
LIVE_SOURCE_FACES = 120_000
LIVE_SLOW_MS = 4_000.0 # after an update this slow, wait for "Update" instead of freezing Blender on every edit
KIND_ITEMS = [
("DETAIL", "Detail", "More, smaller quads around the point (eyes, fingers, a face)", "SNAP_VERTEX", 0),
("LOOP", "Loop", "Edge loops ring around the point (eyes, mouth, elbows): the quads flow around it", "MESH_CIRCLE", 1),
("SHARP", "Sharp", "Keep hard edges near the point; the quads are smaller and the creases are not rounded off", "SHARPCURVE", 2),
("CALM", "Calm", "Fewer, bigger quads near the point (flat or boring areas). Also cuts a hole in the region of Points Only", "SMOOTHCURVE", 3),
]
KIND_KEYS = ("DETAIL", "LOOP", "SHARP", "CALM")
CURVE_KIND_ITEMS = [
("GUIDE", "Guide", "A thin line the quads follow, like a panel line", "CURVE_DATA", 0),
("LOOP", "Edge Loop", "A loop or flow line drawn by hand: it becomes real continuous edge loops of regular quads, with the poles outside it", "MESH_CIRCLE", 1),
("BEND", "Deformation", "A line across a joint or crease: several evenly spaced loops so the mesh bends without pinching", "MOD_SIMPLEDEFORM", 2),
]
SCOPE_ITEMS = [
("WHOLE", "Whole Mesh", "Remesh the whole mesh; the points change the quad size across it", "MESH_DATA", 0),
("POINTS", "Points Only", "Remesh only inside the point spheres; the rest of the mesh stays exactly as it is", "SELECT_SET", 1),
("AREAS", "Work Areas", "Each point is its own area with its own density and fill style. They are remeshed one at a time in the background, so you can keep working", "BRUSH_DATA", 2),
("AUTO", "Auto Segments", "Splits the mesh into parts, finds the fewest faces that still look the same (checked by camera), then makes quads. Blender stays usable while it works", "MOD_EXPLODE", 3),
]
AIM_ITEMS = [
("KEEP", "Keep Detail", "Keep what you can see: the fewest faces that still look like your mesh, within Detail", "ZOOM_ALL", 0),
("REDUCE", "Reduce To", "Land on a face count you pick (a percent of your faces, or a number). It then tells you how much the view changed, so you can judge it", "MOD_DECIM", 1),
]
REDUCE_BY_ITEMS = [
("PERCENT", "Percent", "A share of the faces your mesh has now", "FIXED_SIZE", 0),
("COUNT", "Face Count", "An exact number of faces to aim for", "LINENUMBERS_ON", 1),
]
SHAPE_OP_ITEMS = [
("UNION", "Union", "Redo the faces inside this shape, in addition to the shapes above it", "SELECT_EXTEND", 0),
("SUBTRACT", "Subtract", "Take the faces inside this shape out of what the shapes above it cover", "SELECT_SUBTRACT", 1),
("INTERSECT", "Intersect", "Keep only the faces that the shapes above it and this shape both cover", "SELECT_INTERSECT", 2),
]
SYMMETRY_ITEMS = [
("OFF", "Off", "Solve the whole mesh", "BLANK1", 0),
("AUTO", "Auto", "Find the mirror plane (X, Y or Z). It is used only when the mesh is symmetric enough", "MOD_MIRROR", 1),
("X", "X", "Mirror across the plane facing X", "BLANK1", 2),
("Y", "Y", "Mirror across the plane facing Y", "BLANK1", 3),
("Z", "Z", "Mirror across the plane facing Z", "BLANK1", 4),
]
APPLY_ITEMS = [
("NEW", "New Object", "Write the result to a new object called <name>_Retopo", "DUPLICATE", 0),
("REPLACE", "Replace Mesh", "Put the result into your object (Undo restores it)", "FILE_REFRESH", 1),
]
BAKE_ITEMS = [
("OFF", "Off", "Keep the UVs and materials of your mesh. No textures are made", "X", 0),
("NORMAL", "Normal Map", "Keep your materials and add a baked normal map, so the fine shape still shows", "NORMALS_FACE", 1),
("NORMAL_COLOR", "Normal + Color", "Bake a normal map and the base color into one new material with new UVs. Press Update after choosing it: Auto Segments then ignores the old UV seams and needs fewer faces", "IMAGE_DATA", 2),
]
BAKE_SIZES = [(str(s), f"{s} px", f"Textures of {s} by {s} pixels") for s in (512, 1024, 2048, 4096)]
PRESET_ITEMS = [
("CHARACTER", "Character", "Organic bodies and faces: Detail points, flowing quads", "ARMATURE_DATA", 0),
("HARD_SURFACE", "Hard-Surface Prop", "Props with hard edges: Sharp points, grid-like quads", "MOD_BEVEL", 1),
("SCAN", "Scan / Photogrammetry", "Noisy scans: broad strokes, smoothed curvature, flowing quads", "OUTLINER_OB_POINTCLOUD", 2),
("GAME_LOD", "Game LOD", "Few quads, spent only where it matters", "MOD_DECIM", 3),
("ANIMATION", "Animation", "Bodies and creatures that bend: like Character, and Auto Segments asks for Deformation Lines across the joints", "BONE_DATA", 4),
]
PRESETS = {
"CHARACTER": dict(base_faces=3000, kind="DETAIL", strategy="FLOW", feature=40.0, radius=0.08, smooth=1),
"HARD_SURFACE": dict(base_faces=1500, kind="SHARP", strategy="GRID", feature=25.0, radius=0.06, smooth=0),
"SCAN": dict(base_faces=4000, kind="DETAIL", strategy="FLOW", feature=50.0, radius=0.10, smooth=3),
"GAME_LOD": dict(base_faces=800, kind="DETAIL", strategy="FLOW", feature=40.0, radius=0.10, smooth=1),
"ANIMATION": dict(base_faces=3000, kind="LOOP", strategy="FLOW", feature=40.0, radius=0.08, smooth=1),
}
state = {
"no_ask": False, # the user ticked "Don't ask again this session" in a long-job dialog
"source": "",
"sig": None,
"changed_at": 0.0,
"dirty": False,
"message": "",
"ms": 0.0,
"src": None,
"res": None,
"lock": None,
"spot": None,
"hover": None,
"draw": None,
"draw_key": None,
"batches": None,
"L0": 0.1,
"predicted": 0,
"work": None,
"auto_cache": (None, {}), # (mesh signature, measurements of it): Start again with another amount skips the looking
"fixes": [], # remembered fixes, when the user's file can't be written
"fixes_in_memory": False,
"found": [], # (fix, match) pairs of remembered fixes that fit the result, best first
"lod": None, # the LOD set being made: {"made": [(name, faces, view change, bake text)]}
"lod_report": "",
"applied": "", # what the last Apply wrote, shown in step 5 until the next search
"region": None, # faces of the source (a boolean each) that Selected Faces Only redoes, taken when Start was pressed
"curve_sig": None, # what the drawn curves looked like when the search last started: a change restarts it
"curve_at": 0.0,
"auto_base": None, # the finished Auto Segments result that step 4 (Live Boolean) works on
"auto_inputs": None, # what the last search was started with, so the size ladder can run it again at other sizes
"machine": None, # what this computer is (hardware.detect), read on demand
"rays": 0.0, # camera rays per second measured on it
"parts": None, # (mesh signature, loose pieces) counted by Check This Computer
}
def status() -> str:
return state["message"]
# --------------------------------------------------------------------------- points
@dataclass
class Pt:
kind: str
co: np.ndarray
nrm: np.ndarray
r: float
s: float
fill: str = "FLOW"
def _on_point_edit(self, context):
overlay.tag_redraw()
class CURIOMESH_PG_guided_point(bpy.types.PropertyGroup):
co: bpy.props.FloatVectorProperty(name="Location", description="Where the point sits on the surface (object space)", size=3, subtype="XYZ", update=_on_point_edit)
normal: bpy.props.FloatVectorProperty(name="Normal", description="Surface direction at the point", size=3, default=(0.0, 0.0, 1.0))
kind: bpy.props.EnumProperty(name="Type", description="What this point asks for", items=KIND_ITEMS, default="DETAIL", update=_on_point_edit)
radius: bpy.props.FloatProperty(name="Radius", description="How far the point reaches (object-space units)", default=0.1, min=1e-4, soft_max=10.0, subtype="DISTANCE", update=_on_point_edit)
strength: bpy.props.FloatProperty(name="Strength", description="How strongly the point changes the quad size: 1 = about three times smaller (or bigger for Calm) at the centre", default=1.0, min=0.1, soft_max=4.0, max=100.0, update=_on_point_edit)
fill: bpy.props.EnumProperty(name="Fill Style", description="Pattern of the new quads in this area (Work Areas only)", items=region.STRATEGY_ITEMS, default="FLOW", update=_on_point_edit)
auto: bpy.props.BoolProperty(name="Suggested", description="Placed by Auto-suggest (replaced when you suggest again)", default=False)
def _preset_update(self, context):
p = PRESETS[self.preset]
self.base_faces = p["base_faces"]
self.strategy = p["strategy"]
self.new_kind = p["kind"]
self.feature_angle = p["feature"]
if self.preset == "ANIMATION":
self.bend_use = True
diag = state["src"]["diag"] if state["src"] else 0.0
if diag > 0:
self.new_radius = p["radius"] * diag
overlay.tag_redraw()
def _enabled_update(self, context):
if self.enabled:
_start(context)
else:
_stop()
_applying = False
def _profile_update(self, context):
"""Picking a use sets Detail, Method and Output."""
global _applying
values = profiles.preset(self.auto_profile)
if values is not None:
_applying = True
try:
self.auto_detail, self.auto_method, self.auto_output = values
self.bend_use = self.auto_profile == "ANIMATION" # Deformation Lines are for joints: on with Animation, off again with any other use
self.auto_chords = self.auto_profile in CHORDS_PROFILES # tidiness first: Animation and Subdivision
hard = self.auto_profile == "HARD" # Hard Surface: clean panels, even cylinders, hard edges marked on Apply
self.hs_panels = self.hs_cylinders = hard
self.hs_edges = "MARK" if hard else "NONE"
finally:
_applying = False
if self.multires_on != (self.auto_profile == "ANIMATION"): # Animation's route: a QuadriFlow cage, with the detail in Multires levels
self.multires_on = self.auto_profile == "ANIMATION"
_redraw_update(self, context)
def _multires_update(self, context):
"""Multires Detail brings the shape back, so the mesh itself can go for clean rows: QuadriFlow, to a low face count."""
global _applying
values = profiles.preset(self.auto_profile)
_applying = True
try:
if self.multires_on:
obj = _source_mesh(context)
self.auto_method = "QUADRIFLOW"
self.auto_output = "QUADS"
self.auto_aim, self.auto_reduce_by = "REDUCE", "COUNT"
if obj is not None:
self.auto_reduce_count = profiles.cage_faces(len(obj.data.polygons))
elif values is not None:
self.auto_detail, self.auto_method, self.auto_output = values
self.auto_aim = "KEEP"
finally:
_applying = False
_redraw_update(self, context)
def _custom_update(self, context):
"""Changing Detail, Method or Output by hand leaves the preset."""
if not _applying and self.auto_profile != "CUSTOM" and not self.multires_on:
if profiles.preset(self.auto_profile) != (self.auto_detail, self.auto_method, self.auto_output):
self.auto_profile = "CUSTOM"
_redraw_update(self, context)
def _redraw_update(self, context):
overlay.tag_redraw()
def _search_update(name: str):
"""A setting the search reads moved (a Fine-tune Tweak slider, Mirror, Symmetrize): its own History step (one drag is
one step), which the search it starts fills in, so Ctrl+Z goes back to the setting and its result together."""
def update(self, context):
history.note(context, "search", name)
overlay.tag_redraw()
return update
# Stored by number in .blend files: the numbers of these items never change.
STYLE_ITEMS = [
("DETAIL", "Fewest Faces", "The fewest faces that hold the look you asked for. Quads follow the shape, so some can look slanted", 0),
("BALANCED", "Balanced", "The same look with far fewer messy points, for more faces", 1),
("ROWS", "Even Rows", "Even, square quads in long rows. The look changes a little more and small sharp detail softens", 2),
]
# The Detail dropdown: one choice over Aim, Detail and the face count (nothing of its own is saved).
DETAIL_STEPS = (("MOST", "Keep Most", 1.5), ("LOT", "Keep a Lot", 3.0), ("BALANCED", "Balanced", 6.0), ("LIGHTER", "Lighter", 10.0), ("LIGHTEST", "Lightest", 20.0))
DETAIL_PICK_ITEMS = [
*((key, f"{label} ({value:g}%)", f"Up to {value:g}% of the view may change. " + ("More faces, small bumps kept" if value < 5 else "Fewer faces, small bumps soften"), i) for i, (key, label, value) in enumerate(DETAIL_STEPS)),
("CUSTOM", "Custom %", "Type how much of the view may change yourself", 5),
("PERCENT", "Share of Faces", "Aim for a share of your faces instead of a look; the result then says how much the look changed", 6),
("COUNT", "Exact Face Count", "Aim for a number of faces instead of a look; the result then says how much the look changed", 7),
]
CLEANUP_ITEMS = [
("QUICK", "Quick", "No extra tidying after the search. Fastest", 0),
("NORMAL", "Normal", "Rebuilds the small spots where faces point inward, fold or cross. Adds up to a minute; recommended", 1),
("THOROUGH", "Thorough", "Also redraws messy patches as grids and evens out the quads. Tidiest; adds a few minutes", 2),
]
def _detail_get(self) -> int:
if self.auto_aim == "REDUCE":
return 7 if self.auto_reduce_by == "COUNT" else 6
return next((i for i, (_k, _l, value) in enumerate(DETAIL_STEPS) if abs(self.auto_detail - value) < 1e-4), 5)
def _detail_set(self, value: int) -> None:
"""Picking a Detail keeps the Use (it is not Custom) and turns Auto off: Auto would pick the Detail again."""
global _applying
_applying = True
try:
if value >= 6:
self.auto_aim, self.auto_reduce_by = "REDUCE", "COUNT" if value == 7 else "PERCENT"
else:
self.auto_aim = "KEEP"
if value < 5:
self.auto_detail = DETAIL_STEPS[value][2]
elif any(abs(self.auto_detail - v) < 1e-4 for _k, _l, v in DETAIL_STEPS):
self.auto_detail += 0.5 # off the steps, so the field to type it in shows
finally:
_applying = False
self.use_auto = False
def _cleanup_get(self) -> int:
return 2 if self.auto_tidy else 1 if self.auto_redo_rough or self.auto_fix else 0
def _cleanup_set(self, value: int) -> None:
"""Quick, Normal, Thorough over the three tidy switches (still in Pro > Engine one by one)."""
self.auto_redo_rough = value >= 1
self.auto_fix = value >= 1
self.auto_tidy = value == 2
self.auto_chords = value == 2 or self.auto_profile in CHORDS_PROFILES
def _shape_poll(self, obj) -> bool:
return obj.type in {"EMPTY", "LATTICE", "MESH"} and not overlay.is_preview(obj) and obj.name != state["source"]
class CURIOMESH_PG_guided_shape(bpy.types.PropertyGroup):
obj: bpy.props.PointerProperty(name="Shape", description="A box, a sphere, a lattice or any closed mesh that marks a part to redo", type=bpy.types.Object, poll=_shape_poll)
operation: bpy.props.EnumProperty(name="Combine", description="How this shape joins the ones above it. They are worked out from top to bottom, so start with a Union", items=SHAPE_OP_ITEMS, default="UNION", update=_redraw_update)
def _guide_poll(self, obj) -> bool:
return guides.is_guide_object(obj) and not overlay.is_preview(obj) and obj.name != state["source"]
class CURIOMESH_PG_guided_guide(bpy.types.PropertyGroup):
obj: bpy.props.PointerProperty(name="Guide", description="A curve, a Grease Pencil drawing, or a mesh made of edges only. The quads are made to follow it", type=bpy.types.Object, poll=_guide_poll)
kind: bpy.props.EnumProperty(name="Type", description="What the quads do with this curve", items=CURVE_KIND_ITEMS, default="GUIDE", update=_redraw_update)
class CURIOMESH_PG_guided(bpy.types.PropertyGroup):
enabled: bpy.props.BoolProperty(name="Guided Preview", description="Classic Guided: shows the point cage and keeps a live preview of the new quads beside your mesh", default=False, update=_enabled_update)
preset: bpy.props.EnumProperty(name="Mesh Type", description="Classic Guided: the starting quad size, point type and fill style for this kind of mesh", items=PRESET_ITEMS, default="CHARACTER", update=_preset_update)
scope: bpy.props.EnumProperty(name="Remesh", description="Which tool rebuilds the mesh. Auto Segments is the main path; the other three are the older point tools in the Pro tab", items=SCOPE_ITEMS, default="AUTO")
strategy: bpy.props.EnumProperty(name="Fill Style", description="Pattern of the new quads in a region: Flow follows the surface, Grid is a regular grid", items=region.STRATEGY_ITEMS, default="FLOW")
base_faces: bpy.props.IntProperty(name="Base Quads", description="Roughly how many quads the whole mesh would get with no points. The points make some areas denser or coarser than this", default=3000, min=50, soft_max=60000)
new_kind: bpy.props.EnumProperty(name="New Point Type", description="Type of the next point you place (keys 1-4 while placing)", items=KIND_ITEMS, default="DETAIL", update=_redraw_update)
new_radius: bpy.props.FloatProperty(name="New Radius", description="Reach of the next point (scroll while placing). 0 picks a size from the mesh", default=0.0, min=0.0, soft_max=10.0, subtype="DISTANCE")
new_strength: bpy.props.FloatProperty(name="New Strength", description="Strength of the next point (Shift + scroll while placing)", default=1.0, min=0.1, soft_max=4.0, max=100.0)
auto_update: bpy.props.BoolProperty(name="Auto-Update", description="Rebuild the preview shortly after you change a point or a setting", default=True)
auto_profile: bpy.props.EnumProperty(name="Use", description="What you will do with the result. Each choice sets the Detail, layout and kind of faces for you", items=profiles.PROFILE_ITEMS, default="GAME", update=_profile_update)
multires_on: bpy.props.BoolProperty(name="Multires Detail", description="Make a clean low-poly mesh and, on Apply, add a Multires modifier whose levels bring the detail back. Animate or export level 0; your mesh is only read", default=False, update=_multires_update)
multires_levels: bpy.props.IntProperty(name="Levels", description="How many Multires levels to add. Each level has four times the faces of the one below it", default=2, min=1, max=5, update=_redraw_update)
auto_why: bpy.props.StringProperty(name="Why", description="What Auto picked for this mesh and why", default="")
use_auto: bpy.props.BoolProperty(name="Auto", description="Start looks at your mesh and picks the Use for it, then says what it picked and why. Pick another tile to choose yourself", default=False, update=_redraw_update)
detail_pick: bpy.props.EnumProperty(name="Detail", description="How close to your mesh the result stays. More detail keeps more faces", items=DETAIL_PICK_ITEMS, get=_detail_get, set=_detail_set, update=_redraw_update)
cleanup: bpy.props.EnumProperty(name="Cleanup", description="How much tidying runs after the search. More is tidier and takes longer", items=CLEANUP_ITEMS, get=_cleanup_get, set=_cleanup_set, update=_redraw_update)
ui_setup_open: bpy.props.BoolProperty(name="Settings", description="The settings the result was made with, to change them and start again", default=False)
auto_detail: bpy.props.FloatProperty(name="Detail", description="How close to your mesh the result must look, as the share of the view that may change. Lower keeps more faces; higher gives a rougher, lighter mesh", default=6.0, min=0.1, max=80.0, soft_max=50.0, precision=1, subtype="PERCENTAGE", update=_custom_update)
auto_gpu: bpy.props.BoolProperty(name="Use Graphics Card", description="Draws the camera checks of big parts on the graphics card when one works. Off uses the processor: almost the same result, a little slower", default=True, update=_redraw_update)
auto_effort: bpy.props.EnumProperty(name="Effort", description="How hard to work this computer. Light keeps Blender smooth while it works; Full finishes soonest; Auto picks from your cores and free memory", items=hardware.EFFORT_ITEMS, default="AUTO", update=_redraw_update)
auto_style: bpy.props.EnumProperty(name="Style", description="What to favour. Fewest Faces keeps the look with the least faces, Balanced has fewer messy points but more faces, and Even Rows makes square quads but changes the look more", items=STYLE_ITEMS, default="DETAIL", update=_redraw_update)
auto_method: bpy.props.EnumProperty(name="Method", description="How each part's faces are made. Auto suits nearly every mesh; you can give each part its own method after the search", items=profiles.METHOD_ITEMS, default="AUTO", update=_custom_update)
auto_output: bpy.props.EnumProperty(name="Output", description="Which kind of faces the result has: all triangles, all quads, or quads with the leftover triangles kept", items=profiles.OUTPUT_ITEMS, default="QUADS", update=_custom_update)
auto_aim: bpy.props.EnumProperty(name="Aim", description="Keep Detail aims for a look; Reduce To aims for a face count and then tells you how much the look changed", items=AIM_ITEMS, default="KEEP", update=_redraw_update)
auto_reduce_by: bpy.props.EnumProperty(name="Reduce By", description="Give the face count as a share of your faces or as a number", items=REDUCE_BY_ITEMS, default="PERCENT", update=_redraw_update)
auto_reduce_percent: bpy.props.FloatProperty(name="Faces Left", description="How many faces to end up with, as a share of your mesh's faces now. 25% turns 40,000 faces into about 10,000", default=25.0, min=0.1, max=100.0, precision=1, subtype="PERCENTAGE", update=_redraw_update)
auto_reduce_count: bpy.props.IntProperty(name="Faces", description="How many faces to end up with. The result lands within about 10% of it unless the parts can't go that low", default=5000, min=12, soft_max=500000, update=_redraw_update)
seg_colors: bpy.props.BoolProperty(name="Part Colors", description="Tints each part of the result in its own colour, so you can see where the parts are", default=True, update=segments.on_view)
seg_heat: bpy.props.BoolProperty(name="Where It Changed", description="Colours each part by how much it changed: purple not at all, yellow the most. Readable with colour blindness", default=False, update=segments.on_view)
seg_bad: bpy.props.BoolProperty(name="Bad Faces", description="Paints in red the faces that point inward, sink into your mesh, cross or fold over others", default=True, update=segments.on_view)
seg_wire: bpy.props.BoolProperty(name="Wireframe", description="Shows the edges of the result", default=True, update=segments.on_view)
seg_compare: bpy.props.EnumProperty(name="Original", description="Where your own mesh is shown: next to the result, or under it as a white wireframe", items=[("BESIDE", "Beside", "The result sits next to your mesh"), ("OVER", "Over", "The result sits on your mesh, which is drawn over it as a white wireframe")], default="BESIDE", update=segments.on_view)
seg_goal: bpy.props.EnumProperty(name="Use", description="What the selected parts are for when you press Redo", items=segments.segment_goals.GOAL_ITEMS, default="ANIMATION")
seg_goal_detail: bpy.props.FloatProperty(name="Detail", description="How many faces the selected parts get when you press Redo. The middle keeps the quad size they have now", default=0.5, min=-4.0, max=5.0, soft_min=0.0, soft_max=1.0, subtype="FACTOR")
seg_method: bpy.props.EnumProperty(name="Method", description="How the selected parts' quads are made when their Use is Reduce or Low Poly", items=segments.METHOD_ITEMS, default="AUTO")
seg_parts: bpy.props.CollectionProperty(type=segments.CURIOMESH_PG_segpart)
seg_index: bpy.props.IntProperty(default=-1, update=segments.on_index)
sym_axis: bpy.props.EnumProperty(name="Mirror", description="Builds one half and mirrors it, so both sides match exactly. Used only when the mesh really is symmetric, unless Symmetrize is on", items=SYMMETRY_ITEMS, default="OFF", update=_search_update("Mirror"))
sym_force: bpy.props.BoolProperty(name="Symmetrize", description="Mirrors even when the two sides differ, so the result is exactly symmetric. Differences on the other side are lost", default=False, update=_search_update("Symmetrize"))
sym_side: bpy.props.EnumProperty(name="Keep Side", description="Which half is built and then mirrored", items=(("AUTO", "Auto", "The side with more surface"), ("POS", "+", "The side with larger coordinates"), ("NEG", "-", "The side with smaller coordinates")), default="AUTO", update=_redraw_update)
sym_offset_use: bpy.props.BoolProperty(name="Set Plane", description="Puts the mirror plane where you say, in object space, instead of finding it", default=False, update=_redraw_update)
sym_offset: bpy.props.FloatProperty(name="Plane Offset", description="Where the mirror plane crosses the axis, in object space", default=0.0, subtype="DISTANCE", update=_redraw_update)
guide_use: bpy.props.BoolProperty(name="Use Guide Curves", description="Makes the quads follow the curves in the list, such as a line along a panel. The curves are laid onto the mesh", default=False, update=_redraw_update)
guide_curves: bpy.props.CollectionProperty(type=CURIOMESH_PG_guided_guide)
guide_index: bpy.props.IntProperty(default=0)
region_use: bpy.props.BoolProperty(name="Selected Faces Only", description="Redoes only the faces selected in Edit Mode and leaves the rest exactly as it is", default=False, update=_redraw_update)
loop_use: bpy.props.BoolProperty(name="Edge Loops", description="Lines you draw (round an eye or the mouth) become real edge loops with even rows of quads beside them", default=False, update=_redraw_update)
loop_count: bpy.props.IntProperty(name="Loops", description="How many parallel loops each drawn line makes: the line itself plus one more on each side is 3", default=3, min=3, soft_max=9, max=99, update=_redraw_update)
bend_use: bpy.props.BoolProperty(name="Deformation Lines", description="Lines drawn across a joint (elbow, knee, mouth corner) become evenly spaced loops, so the mesh bends without pinching", default=False, update=_redraw_update)
bend_loops: bpy.props.IntProperty(name="Loops", description="How many parallel loops each joint line makes. 3 is the least that bends well; use more across a big joint", default=3, min=3, soft_max=9, max=99, update=_redraw_update)
loop_gap: bpy.props.FloatProperty(name="Loop Gap", description="The distance between two loops of a drawn line, in object units. 0 picks about one quad", default=0.0, min=0.0, soft_max=10.0, subtype="DISTANCE", update=_redraw_update)
bend_crease: bpy.props.BoolProperty(name="Crease", description="On Apply, marks the middle loop of each joint line with an edge crease, for Subdivision Surface", default=False)
bend_sharp: bpy.props.BoolProperty(name="Sharp", description="On Apply, marks the middle loop of each joint line as sharp edges", default=False)
density_use: bpy.props.BoolProperty(name="Detail Markers", description="Keeps more faces where you marked More Detail and fewer where you marked Less Detail. Paint the marks or place marker balls", default=False, update=_redraw_update)
density_group: bpy.props.StringProperty(name="Group", description="The vertex group of the mesh that holds the More Detail paint", default="CM_Density")
less_group: bpy.props.StringProperty(name="Less Group", description="The vertex group of the mesh that holds the Less Detail paint", default="CM_LessDetail")
density_strength: bpy.props.FloatProperty(name="Strength", description="How strongly the marks move faces. 1 keeps about four times as many faces under More Detail as under Less Detail", default=1.0, min=0.25, soft_max=4.0, max=100.0)
bool_on: bpy.props.BoolProperty(name="Redo Inside Shapes", description="Redoes the result inside the shapes, live; everything outside stays as it is. Move or resize a shape and the quads follow", default=False, update=_redraw_update)
bool_shapes: bpy.props.CollectionProperty(type=CURIOMESH_PG_guided_shape)
bool_index: bpy.props.IntProperty(default=0)
quad_size: bpy.props.FloatProperty(name="Quad Size", description="Left: smaller quads that keep more detail. Right: bigger quads and fewer faces. Each stop is a full result, worked out in the background", default=0.5, min=0.0, max=1.0, subtype="FACTOR", update=ladder.on_size)
quad_order: bpy.props.FloatProperty(name="Rows", description="Left: fewest faces, quads follow the shape. Right: even rows of square quads, with more faces and a little softer detail", default=0.0, min=0.0, max=1.0, subtype="FACTOR", update=ladder.on_rows)
organize: bpy.props.FloatProperty(name="Tidy Up", description="How strong one tidying pass is: fewer poles and straighter rows, for a little detail. Again and Keep Tidying run more passes on top of this one", default=0.0, min=0.0, max=1.0, subtype="FACTOR", update=organize.on_slider)
organize_cap_use: bpy.props.BoolProperty(name="Most Detail Loss", description="Stops Tidy Up, over all its passes, before the look changes by more than the amount next to it. Off: passes go on while they still make the mesh tidier", default=False, update=organize.on_cap)
organize_cap: bpy.props.FloatProperty(name="Most Detail Loss", description="How much more of the look Tidy Up may change, in percent, on top of the result before the first pass. You can type more than the slider shows", default=1.0, min=0.1, soft_max=20.0, max=100.0, precision=1, subtype="NONE", update=organize.on_cap)
tidy_poles: bpy.props.BoolProperty(name="Fewer Poles", description="Walks pairs of poles together until they cancel, and redraws messy patches as plain grids. Takes away a few faces where pairs merge", default=True, update=organize.on_options)
tidy_rows: bpy.props.BoolProperty(name="Straighter Rows", description="Straightens each edge loop along its own bend and stacks neighbouring loops evenly. Wiggles go, steady curves stay", default=True, update=organize.on_options)
tidy_sizes: bpy.props.BoolProperty(name="Even Sizes", description="Moves each corner toward the middle of its neighbours, on your mesh. Quads of similar size sit next to each other", default=True, update=organize.on_options)
tidy_square: bpy.props.BoolProperty(name="Square Corners", description="Pulls each quad toward a rectangle of its own size instead of plain evening out. Corners near 90 degrees, at a little more detail loss", default=False, update=organize.on_options)
tidy_selected: bpy.props.BoolProperty(name="Selection Only", description="Tidies only the faces of the result you selected in Edit Mode. Everything else, and the edge of the selection, stays exactly as it is", default=False, update=organize.on_options)
# Hard surface (hard_surface.py): two search switches and the hard-edge finish on Apply
hs_panels: hard_surface.prop("hs_panels")
hs_cylinders: hard_surface.prop("hs_cylinders")
hs_edges: hard_surface.prop("hs_edges")
hs_angle: hard_surface.prop("hs_angle")
hs_hold_unit: hard_surface.prop("hs_hold_unit")
hs_hold_percent: hard_surface.prop("hs_hold_percent")
hs_hold_mm: hard_surface.prop("hs_hold_mm")
time_limits: bpy.props.EnumProperty(
name="Time Limits",
description="How long Start may spend on repairs, redrawing messy quads and rough spots before it moves on. Longer and No Limit can take much longer, but keep improving the mesh",
items=(("NORMAL", "Normal", "The usual time for each step"), ("LONGER", "Longer", "Four times the usual time for each step"), ("NONE", "No Limit", "Each step runs until it stops finding anything to fix. Same model and settings give the same result every time")),
default="NORMAL",
)
organize_flow: bpy.props.BoolProperty(name="Loop Flow", description="Draws each face loop (a strip of quads, as Alt+click selects) of the result in its own colour, and its poles (points where 3 or 5+ edges meet) as dots", default=False, update=_redraw_update)
flow_live: bpy.props.BoolProperty(name="Live", description="Flow Editor: redo the quads around each stroke as soon as you draw, move or erase it. Off: strokes are only kept for the next Start", default=True)
flow_size: bpy.props.FloatProperty(name="Shape Size", description="Flow Editor: how wide a clicked eye ring, mouth ring or nose-to-mouth shape is. 0 picks a size from your mesh", default=0.0, min=0.0, soft_max=10.0, subtype="DISTANCE")
flow_pair: bpy.props.BoolProperty(name="Both Sides", description="Flow Editor: a clicked eye ring also goes on the other side, mirrored across the middle of your mesh (always on when the result is mirrored)", default=True)
bool_detail: bpy.props.FloatProperty(name="Organized / Detailed", description="Inside the shapes: left makes fewer, bigger, tidier quads; the middle keeps the quad size; right makes smaller quads with more detail", default=0.5, min=0.0, max=1.0, subtype="FACTOR", update=_redraw_update)
show_cage: bpy.props.BoolProperty(name="Show Cage", description="Classic Guided: draws each point's reach and the outline of the area it covers", default=True, update=_redraw_update)
blockout_sides: bpy.props.IntProperty(name="Primitive Sides", description="How many sides each cylinder and ball has (small parts get half). More sides look rounder and cost faces", default=12, min=4, soft_max=32, max=512, step=2)
blockout_separate: bpy.props.BoolProperty(name="Each Part Its Own Object", description="On Apply, writes one object per loose part of your mesh instead of one merged mesh", default=False)
auto_instances: bpy.props.BoolProperty(name="Keep Copies as Instances", description="Repeated parts become linked copies that cost no extra geometry; the copies share UVs. Off makes one merged mesh", default=False)
apply_mode: bpy.props.EnumProperty(name="Result", description="Where Apply writes the result: a new object, or into your own object (Undo brings yours back)", items=APPLY_ITEMS, default="NEW")
auto_rough: bpy.props.BoolProperty(name="Rough As Texture", description="For rough scans (rock, ground): judges bumps on average. Far fewer faces; bumps smaller than a few pixels are lost", default=False)
auto_parallel: bpy.props.BoolProperty(name="Use Several Cores", description="Works on several parts at once in background copies of Blender. Faster on big meshes; uses more memory", default=True)
auto_drop_hidden: bpy.props.BoolProperty(name="Leave Out Hidden Pieces", description="Leaves out loose pieces that no camera outside the model can see. The result says how many were left out", default=False)
auto_baked: bpy.props.BoolProperty(name="Judge After Baking (Experimental)", description="Experimental, Low Poly on scans you will bake: judges the look after baking, so far fewer faces remain. Can leave thin slivers; check the result", default=False)
auto_chords: bpy.props.BoolProperty(name="Redraw Messy Quads", description="Redraws messy patches as plain grids of quads. Much tidier loops; adds a minute or two, and can stall on models of many loose pieces", default=False)
auto_tidy: bpy.props.BoolProperty(name="Tidy Quads", description="Evens out the quads after the search, closer to hand-made. Slow, and the shape changes a little more", default=False)
auto_fix: bpy.props.BoolProperty(name="Auto Fix", description="After the search, each tidy tool finds the spots it is made for and fixes them, keeping only fixes that make the quads better within Most Detail Loss. Every fix is a step you can undo", default=True)
auto_redo_rough: bpy.props.BoolProperty(name="Redo Rough Spots", description="Rebuilds the small spots where faces point inward, fold or cross. Adds up to a minute; recommended", default=False)
keep_uvs: bpy.props.BoolProperty(name="Keep UV Seams", description="Keeps quads inside each piece of your UV map so textures stay in place. Can double the faces; for game assets, baking is usually better", default=False)
lod0_percent: bpy.props.FloatProperty(name="LOD0", description="Faces of the most detailed LOD, as a share of your mesh's faces", default=profiles.LOD_PERCENTS[0], min=0.1, max=100.0, precision=1, subtype="PERCENTAGE")
lod1_percent: bpy.props.FloatProperty(name="LOD1", description="Faces of the middle LOD, as a share of your mesh's faces", default=profiles.LOD_PERCENTS[1], min=0.1, max=100.0, precision=1, subtype="PERCENTAGE")
lod2_percent: bpy.props.FloatProperty(name="LOD2", description="Faces of the lightest LOD, as a share of your mesh's faces", default=profiles.LOD_PERCENTS[2], min=0.1, max=100.0, precision=1, subtype="PERCENTAGE")
bake_detail: bpy.props.EnumProperty(name="Bake Detail", description="On Apply, bakes your mesh's fine detail into textures on the result. Can take minutes", items=BAKE_ITEMS, default="OFF")
bake_size: bpy.props.EnumProperty(name="Bake Size", description="Width and height of the baked textures. Bigger is sharper and slower", items=BAKE_SIZES, default="2048")
bake_sets: bpy.props.IntProperty(name="Texture Sets", description="Normal + Color: bakes onto this many sets of maps, each its own material, so a big model keeps detail", default=1, min=1, soft_max=16, max=256)
fit_iterations: bpy.props.IntProperty(name="Surface Fit Passes", description="Classic Guided: how many passes settle the new quads onto your surface. More follows it closer, slower", default=2, min=0, soft_max=30, max=1000)
tweak_rows: bpy.props.FloatProperty(name="Rows on Round Areas", description="How readily round, smooth areas become rows of quads that follow their curve. Right finds more of them and adds faces. Reruns the search", default=0.5, min=0.0, max=1.0, subtype="FACTOR", update=_search_update("Rows on Round Areas"))
tweak_flat: bpy.props.FloatProperty(name="Flat Area Size", description="How big quads inside flat areas may get. Left makes them smaller and more even; right fewer and longer. Reruns the search", default=0.5, min=0.0, max=1.0, subtype="FACTOR", update=_search_update("Flat Area Size"))
tweak_poles: bpy.props.BoolProperty(name="Avoid Poles", description="Turns edges so rows of quads keep going past poles (points where 3 or 5+ edges meet). Off: about a fifth more poles, a touch more detail", default=True, update=_search_update("Avoid Poles"))
feature_angle: bpy.props.FloatProperty(name="Hard Edge Angle", description="Classic Guided: edges sharper than this angle count as hard edges and are kept", default=40.0, min=5.0, max=180.0)
pure_quads: bpy.props.BoolProperty(name="All Quads", description="Classic Guided, Whole Mesh: makes every face a quad. Off is faster on big meshes and leaves a few triangles", default=True)
suggest_count: bpy.props.IntProperty(name="Suggestions", description="Classic Guided: how many points Auto-suggest places", default=8, min=1, soft_max=40, max=1000)
# --------------------------------------------------------------------------- density maths
def _fac(kind: str, s: float) -> float:
"""Edge-length multiplier at the centre of a point."""
if kind == "DETAIL":
return 1.0 / (1.0 + 2.0 * s)
if kind == "CALM":
return 1.0 + 2.0 * s
if kind == "SHARP":
return 1.0 / (1.0 + s)
return float(np.sqrt(1.0 / (1.0 + 2.0 * s) / (1.0 + 0.5 * s))) # LOOP, isotropic mean
def _weight(P: np.ndarray, p: Pt) -> np.ndarray:
t = np.clip(np.linalg.norm(P - p.co, axis=1) / max(p.r, 1e-9), 0.0, 1.0)
return 1.0 - t * t * (3.0 - 2.0 * t) # 1 at the centre, 0 at the radius (smoothstep)
def multiplier(P: np.ndarray, pts: list[Pt], E: np.ndarray | None = None) -> np.ndarray:
"""Target edge length / base edge length at points P. E: unit edge directions (Loop points go anisotropic)."""
f = np.ones(len(P))
for p in pts:
w = _weight(P, p)
if p.kind == "LOOP" and E is not None:
fr = 1.0 + w * (1.0 / (1.0 + 2.0 * p.s) - 1.0) # across the ring: small steps = many rings
ft = 1.0 + w * (1.0 / (1.0 + 0.5 * p.s) - 1.0) # along the ring
d = P - p.co
d = d - np.outer(d @ p.nrm, p.nrm)
d /= np.maximum(np.linalg.norm(d, axis=1), 1e-12)[:, None]
c2 = np.einsum("ij,ij->i", d, E) ** 2
f *= 1.0 / np.sqrt(c2 / fr**2 + (1.0 - c2) / ft**2)
else:
f *= 1.0 + w * (_fac(p.kind, p.s) - 1.0)
return np.clip(f, 0.125, 8.0)
def region_sd(P: np.ndarray, pts: list[Pt], scope: str) -> np.ndarray:
"""Signed distance of the point-sphere region: union of adding spheres minus the subtracting ones (<0 inside)."""
add = {"POINTS": ("DETAIL", "LOOP"), "AREAS": KIND_KEYS}.get(scope, ("DETAIL", "LOOP", "SHARP"))
sub = {"POINTS": ("CALM", "SHARP"), "AREAS": ()}.get(scope, ("CALM",))
def union(kinds):
sd = np.full(len(P), np.inf)
for p in pts:
if p.kind in kinds:
sd = np.minimum(sd, np.linalg.norm(P - p.co, axis=1) - p.r)
return sd
return np.maximum(union(add), -union(sub))
def stepped_intensity(kind: str, strength: float, up: bool, step: float = 0.25) -> tuple[str, float]:
"""One scroll notch: up is always denser. Detail fades into Calm and back through the base density."""
was = -strength if kind == "CALM" else strength
now = was + (step if up else -step)
if abs(now) < 0.1 or now * was < 0:
now = 0.1 if up else -0.1
now = float(np.clip(now, -4.0, 4.0))
return "CALM" if now < 0 else ("DETAIL" if kind == "CALM" else kind), round(abs(now), 3)
# --------------------------------------------------------------------------- mesh helpers
def _edge_table(tris: np.ndarray):
"""Unique edges of a triangle array: (lo, hi, face0, face1 or -1, count)."""
n = int(tris.max()) + 1 if len(tris) else 1
a = tris.ravel()
b = tris[:, [1, 2, 0]].ravel()
f = np.repeat(np.arange(len(tris)), 3)
lo, hi = np.minimum(a, b), np.maximum(a, b)
key = lo.astype(np.int64) * n + hi
order = np.argsort(key, kind="stable")
ks = key[order]
start = np.flatnonzero(np.r_[True, ks[1:] != ks[:-1]])
count = np.diff(np.r_[start, len(ks)])
f1 = np.where(count > 1, f[order][np.minimum(start + 1, len(ks) - 1)], -1)
return lo[order][start], hi[order][start], f[order][start], f1, count
def _tri_normals(co: np.ndarray, tris: np.ndarray) -> np.ndarray:
n = np.cross(co[tris[:, 1]] - co[tris[:, 0]], co[tris[:, 2]] - co[tris[:, 0]])
return n / np.maximum(np.linalg.norm(n, axis=1), 1e-30)[:, None]
def _vert_normals(co: np.ndarray, tris: np.ndarray) -> np.ndarray:
n = np.cross(co[tris[:, 1]] - co[tris[:, 0]], co[tris[:, 2]] - co[tris[:, 0]]) # area weighted
out = np.zeros_like(co)
for k in range(3):
for axis in range(3):
out[:, axis] += np.bincount(tris[:, k], n[:, axis], len(co))
return out / np.maximum(np.linalg.norm(out, axis=1), 1e-30)[:, None]
def _creases(co: np.ndarray, tris: np.ndarray, degrees: float):
"""(edge table, crease edge mask, crease vertex mask, boundary vertex mask)."""
lo, hi, f0, f1, count = _edge_table(tris)
nrm = _tri_normals(co, tris)
inner = f1 >= 0
cos = np.ones(len(lo))
cos[inner] = np.einsum("ij,ij->i", nrm[f0[inner]], nrm[f1[inner]])
crease = inner & (cos < np.cos(np.radians(degrees)))
cv = np.zeros(len(co), dtype=bool)
cv[lo[crease]] = cv[hi[crease]] = True
bv = np.zeros(len(co), dtype=bool)
bv[lo[~inner]] = bv[hi[~inner]] = True
return (lo, hi, f0, f1, count), crease, cv, bv
def _fan(faces) -> np.ndarray:
return np.asarray([(f[0], f[k], f[k + 1]) for f in faces for k in range(1, len(f) - 1)], dtype=np.int64).reshape(-1, 3)
def _source_data(obj) -> dict:
"""Welded copy of the source (glTF/FBX imports split vertices at seams), cached per geometry."""
mesh = obj.data
nv = len(mesh.vertices)
co = np.empty(nv * 3, dtype=np.float64)
mesh.vertices.foreach_get("co", co)
co = co.reshape(-1, 3)
sig = (obj.name, nv, len(mesh.polygons), round(float(co.sum()), 5), mesh.as_pointer())
cached = state["src"]
if cached is not None and cached["sig"] == sig:
return cached
starts = np.empty(len(mesh.polygons), dtype=np.int64)
sizes = np.empty(len(mesh.polygons), dtype=np.int64)
mesh.polygons.foreach_get("loop_start", starts)
mesh.polygons.foreach_get("loop_total", sizes)
corners = np.empty(len(mesh.loops), dtype=np.int64)
mesh.loops.foreach_get("vertex_index", corners)
mat = np.zeros(len(starts), dtype=np.int32)
mesh.polygons.foreach_get("material_index", mat)
diag = float(np.linalg.norm(co.max(axis=0) - co.min(axis=0))) or 1.0
key = np.round(co / (diag * 1e-6)).astype(np.int64)
_u, first, inv = np.unique(key, axis=0, return_index=True, return_inverse=True)
inv = inv.reshape(-1)
wco = co[first]
if len(sizes) and (sizes == 3).all(): # a scan: no per-face Python, and the faces stay as arrays
rows = inv[corners[starts[:, None] + np.arange(3)]]
keep = np.flatnonzero((rows[:, 0] != rows[:, 1]) & (rows[:, 1] != rows[:, 2]) & (rows[:, 0] != rows[:, 2]))
edges = np.arange(0, 3 * len(keep) + 1, 3)
wfaces = FlatFaces(edges, rows[keep].ravel())
wloops = FlatFaces(edges, (starts[keep, None] + np.arange(3)).ravel())
tris = wfaces.flat.reshape(-1, 3)
tri_loops = wloops.flat.reshape(-1, 3)
else:
keep, wfaces, wloops = [], [], []
for i, (start, size) in enumerate(zip(starts.tolist(), sizes.tolist())):
first: dict[int, int] = {}
for corner, v in enumerate(corners[start : start + size].tolist()):
first.setdefault(int(inv[v]), start + corner)
if len(first) >= 3:
wfaces.append(tuple(first))
wloops.append(tuple(first.values()))
keep.append(i)
keep = np.asarray(keep, dtype=np.int64)
tris = _fan(wfaces)
tri_loops = _fan(wloops)
area = 0.5 * np.linalg.norm(np.cross(wco[tris[:, 1]] - wco[tris[:, 0]], wco[tris[:, 2]] - wco[tris[:, 0]]), axis=1)
data = {
"sig": sig,
"diag": diag,
"co": wco,
"faces": wfaces,
"tris": tris,
"tri_area": area,
"tri_cent": wco[tris].mean(axis=1),
"tri_face": np.repeat(np.arange(len(wfaces)), np.diff(FlatFaces.of(wfaces).indptr) - 2),
"tri_loops": tri_loops,
"loops": wloops,
"mat": mat[keep],
"bvh": None,
"weld": inv,
"keep": keep,
}
state["src"] = data
return data
def _bvh(src: dict) -> BVHTree:
if src["bvh"] is None:
src["bvh"] = BVHTree.FromPolygons(src["co"].tolist(), src["tris"].tolist())
return src["bvh"]
def _centroids(co: np.ndarray, faces) -> np.ndarray:
return np.asarray([co[list(f)].mean(axis=0) for f in faces]).reshape(-1, 3)
def _nearest_tris(bvh: BVHTree, points: np.ndarray) -> np.ndarray:
return sliced.finish(_nearest_steps(bvh, points, 2))
def _nearest_steps(bvh: BVHTree, points: np.ndarray, field: int, dtype=np.int64):
"""Generator -> field `field` of `bvh.find_nearest` for each point (2: the triangle, 3: the distance), yielding
every fit.CHUNK points so an Apply's timer slices stay short (sliced)."""
points = np.asarray(points, dtype=np.float64).reshape(-1, 3)
out = np.empty(len(points), dtype=dtype)
for i in range(0, len(points), fit.CHUNK):
out[i:i + fit.CHUNK] = [bvh.find_nearest(p)[field] for p in points[i:i + fit.CHUNK].tolist()]
yield
return out
def _barycentric(co: np.ndarray, tris: np.ndarray, points: np.ndarray) -> np.ndarray:
"""Barycentric coordinates of each point's projection on its own triangle, kept inside the triangle."""
a, b, c = co[tris[:, 0]], co[tris[:, 1]], co[tris[:, 2]]
v0, v1, v2 = b - a, c - a, points - a
d00, d01, d11 = (v0 * v0).sum(axis=1), (v0 * v1).sum(axis=1), (v1 * v1).sum(axis=1)
d20, d21 = (v2 * v0).sum(axis=1), (v2 * v1).sum(axis=1)
denom = d00 * d11 - d01 * d01
denom = np.where(np.abs(denom) < 1e-30, np.inf, denom) # degenerate triangle: use its first corner
v, w = (d11 * d20 - d01 * d21) / denom, (d00 * d21 - d01 * d20) / denom
bary = np.clip(np.stack((1.0 - v - w, v, w), axis=1), 0.0, 1.0)
return bary / bary.sum(axis=1, keepdims=True)
def _uv_islands(src: dict, uv: np.ndarray) -> np.ndarray:
"""UV island of each source face: faces that share an edge with the same UVs on both sides belong together."""
return sliced.finish(_uv_islands_steps(src, uv))
def _uv_islands_steps(src: dict, uv: np.ndarray):
"""Generator: `_uv_islands` in short steps (sliced). One row per face side: its two points, lower first, and their UVs."""
faces, loops = FlatFaces.of(src["faces"]), FlatFaces.of(src["loops"])
here = np.arange(len(faces.flat))
nxt = here + 1
nxt[faces.indptr[1:] - 1] = faces.indptr[:-1]
first = faces.flat < faces.flat[nxt]
a, b = np.where(first, here, nxt), np.where(first, nxt, here)
rows = np.column_stack((faces.flat[a], faces.flat[b], uv[loops.flat[a]], uv[loops.flat[b]])).astype(np.float64)
owner = np.repeat(np.arange(len(faces)), np.diff(faces.indptr))
rows[:, 2:] = np.round(rows[:, 2:], 5)
yield
order = np.lexsort(rows.T[::-1]) # equal rows side by side, in their first order (as np.unique(axis=0) and a stable sort did)
yield
rows = rows[order]
twin = (rows[1:] == rows[:-1]).all(axis=1)
yield
return patch._labels(len(src["faces"]), owner[order][:-1][twin], owner[order][1:][twin])
def _transfer_uvs(mesh, source, src, res) -> None:
"""Copy every UV layer: each corner reads the source at its nearest point on the UV island of its own face."""
sliced.finish(_transfer_uvs_steps(mesh, source, src, res))
def _transfer_uvs_steps(mesh, source, src, res):
"""Generator: `_transfer_uvs` in short steps (sliced)."""
co, faces = res["co"], res["faces"]
known = res.get("chart") # Auto Segments remembers each face's island in the active layer
if known is not None and len(known) != len(faces):
known = None
flat = np.fromiter((v for f in faces for v in f), dtype=np.int64)
bvh = _bvh(src)
yield
corner_tri = (yield from _nearest_steps(bvh, co, 2))[flat]
owner_tri = np.repeat((yield from _nearest_steps(bvh, _centroids(co, faces), 2)), [len(f) for f in faces])
points = co[flat]
for layer in source.data.uv_layers:
uv = np.empty(len(source.data.loops) * 2, dtype=np.float64)
layer.data.foreach_get("uv", uv)
uv = uv.reshape(-1, 2)
island = (yield from _uv_islands_steps(src, uv))[src["tri_face"]]
yield
tri = corner_tri.copy()
owner = island[owner_tri]
if known is not None and layer.active:
owner = np.repeat(known, [len(f) for f in faces])
off = np.flatnonzero(island[corner_tri] != owner) # a corner on a UV seam: stay on this face's side
for chart in np.unique(owner[off]).tolist():
members = np.flatnonzero(island == chart)
used, local = np.unique(src["tris"][members], return_inverse=True)
chart_bvh = BVHTree.FromPolygons(src["co"][used].tolist(), local.reshape(-1, 3).tolist())
yield
here = off[owner[off] == chart]
tri[here] = members[(yield from _nearest_steps(chart_bvh, points[here], 2))]
out = np.einsum("ijk,ij->ik", uv[src["tri_loops"][tri]], _barycentric(src["co"], src["tris"][tri], points))
target = mesh.uv_layers.new(name=layer.name)
target.data.foreach_set("uv", out.astype(np.float32).ravel())
active = source.data.uv_layers.active_index
if 0 <= active < len(mesh.uv_layers):
mesh.uv_layers.active_index = active
def _transfer_normals(mesh, src, res) -> None:
"""Shade the result like the source: each face corner gets its normal from the source samples around it."""
sliced.finish(_transfer_normals_steps(mesh, src, res))
def _transfer_normals_steps(mesh, src, res):
"""Generator: `_transfer_normals` in short steps (sliced)."""
points, faces = res["co"], res["faces"]
keep = src["tri_area"] > 0.0
tree = KDTree(int(keep.sum()))
for index, point in enumerate(src["tri_cent"][keep].tolist()):
tree.insert(point, index)
if index % (4 * fit.CHUNK) == 4 * fit.CHUNK - 1:
yield
tree.balance()
yield
normals, area = _tri_normals(src["co"], src["tris"])[keep], src["tri_area"][keep]
fa, fb = patch.face_adjacency(src["faces"])
sample_part = np.unique(patch._labels(len(src["faces"]), fa, fb), return_inverse=True)[1][src["tri_face"]][keep]
yield
part, source_of = yield from fit.vertex_parts_steps(points, faces, sample_part, lambda at: np.fromiter((tree.find(p)[1] for p in at.tolist()), dtype=np.int64, count=len(at)))
out = yield from fit.corner_normals_steps(points, faces, normals, area, sample_part, source_of[part], tree.find_n)
mesh.normals_split_custom_set(out.tolist())
# --------------------------------------------------------------------------- whole-mesh path
def _read(me):
co = np.empty(len(me.vertices) * 3, dtype=np.float64)
me.vertices.foreach_get("co", co)
tris = np.empty(len(me.polygons) * 3, dtype=np.int64)
me.polygons.foreach_get("vertices", tris)
tris = tris.reshape(-1, 3)
return co.reshape(-1, 3), tris[(tris[:, 0] != tris[:, 1]) & (tris[:, 1] != tris[:, 2]) & (tris[:, 0] != tris[:, 2])]
def _write_co(me, co):
me.vertices.foreach_set("co", co.astype(np.float32).ravel())
me.update()
def _bm_edges(bm, lo, hi, idx):
bm.verts.ensure_lookup_table()
return [e for e in (bm.edges.get((bm.verts[int(lo[i])], bm.verts[int(hi[i])])) for i in idx) if e is not None]
def _targets(co, lo, hi, pts, L0):
d = co[hi] - co[lo]
length = np.linalg.norm(d, axis=1)
return length, L0 * multiplier(0.5 * (co[lo] + co[hi]), pts, d / np.maximum(length, 1e-30)[:, None])
def _split_pass(me, pts, L0) -> int:
co, tris = _read(me)
lo, hi, _f0, _f1, _c = _edge_table(tris)
length, target = _targets(co, lo, hi, pts, L0)
idx = np.flatnonzero(length > 4.0 / 3.0 * target)
if not len(idx):
return 0
bm = bmesh.new()
try:
bm.from_mesh(me)
edges = _bm_edges(bm, lo, hi, idx)
bmesh.ops.subdivide_edges(bm, edges=edges, cuts=1, use_grid_fill=False)
bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method="SHORT_EDGE")
bm.to_mesh(me)
finally:
bm.free()
return len(idx)
def _neighbours(count, lo, hi):
a = np.concatenate((lo, hi))
b = np.concatenate((hi, lo))
order = np.argsort(a, kind="stable")
start = np.searchsorted(a[order], np.arange(count + 1))
return start, b[order]
def _collapse_pass(me, pts, L0, crease_deg) -> int:
co, tris = _read(me)
(lo, hi, _f0, _f1, count), crease, cv, bv = _creases(co, tris, crease_deg)
length, target = _targets(co, lo, hi, pts, L0)
ok = (length < 0.8 * target) & (count == 2) & ~bv[lo] & ~bv[hi] & (~(cv[lo] | cv[hi]) | (crease & cv[lo] & cv[hi]))
idx = np.flatnonzero(ok)
if not len(idx):
return 0
idx = idx[np.argsort(length[idx])]
start, nbr = _neighbours(len(co), lo, hi)
locked = np.zeros(len(co), dtype=bool)
chosen = []
for i in idx.tolist():
a, b = int(lo[i]), int(hi[i])
if locked[a] or locked[b]:
continue
na, nb = nbr[start[a] : start[a + 1]], nbr[start[b] : start[b + 1]]
if len(set(na.tolist()) & set(nb.tolist())) != 2 or len(na) + len(nb) - 4 < 4:
continue
ring = np.union1d(na, nb)
mid = 0.5 * (co[a] + co[b])
far = np.linalg.norm(co[ring[(ring != a) & (ring != b)]] - mid, axis=1).max()
if far > 4.0 / 3.0 * target[i]:
continue
locked[ring] = locked[a] = locked[b] = True
chosen.append(i)
if not chosen:
return 0
bm = bmesh.new()
try:
bm.from_mesh(me)
bmesh.ops.collapse(bm, edges=_bm_edges(bm, lo, hi, chosen))
bm.to_mesh(me)
finally:
bm.free()
return len(chosen)
def _flip_pass(me, crease_deg) -> int:
co, tris = _read(me)
(lo, hi, f0, f1, count), crease, _cv, _bv = _creases(co, tris, crease_deg)
val = np.bincount(np.concatenate((lo, hi)), minlength=len(co))
inner = (count == 2) & ~crease
g0, g1 = np.where(inner, f0, 0), np.where(inner, f1, 0)
n = len(co)
c = np.where(inner, np.clip(tris[g0].sum(axis=1) - lo - hi, 0, n - 1), 0)
d = np.where(inner, np.clip(tris[g1].sum(axis=1) - lo - hi, 0, n - 1), 0)
dev = np.abs
before = dev(val[lo] - 6) + dev(val[hi] - 6) + dev(val[c] - 6) + dev(val[d] - 6)
after = dev(val[lo] - 7) + dev(val[hi] - 7) + dev(val[c] - 5) + dev(val[d] - 5)
new_len = np.linalg.norm(co[c] - co[d], axis=1)
old_len = np.linalg.norm(co[hi] - co[lo], axis=1)
nrm = _tri_normals(co, tris)
flat = np.einsum("ij,ij->i", nrm[g0], nrm[g1]) > 0.85
good = inner & flat & (after < before) & (new_len < 1.5 * old_len) & (c != d) & (val[lo] > 3) & (val[hi] > 3)
idx = np.flatnonzero(good)
if not len(idx):
return 0
used = np.zeros(len(tris), dtype=bool)
existing = set(zip(lo.tolist(), hi.tolist()))
chosen = []
for i in idx[np.argsort(before[idx] - after[idx])[::-1]].tolist():
if used[f0[i]] or used[f1[i]] or (min(c[i], d[i]), max(c[i], d[i])) in existing:
continue
used[f0[i]] = used[f1[i]] = True
existing.add((min(c[i], d[i]), max(c[i], d[i])))
chosen.append(i)
bm = bmesh.new()
try:
bm.from_mesh(me)
for e in _bm_edges(bm, lo, hi, chosen):
bmesh.utils.edge_rotate(e, True)
bm.to_mesh(me)
finally:
bm.free()
return len(chosen)
def _smooth_pass(me, project, crease_deg, strength=0.5) -> None:
co, tris = _read(me)
(lo, hi, _f0, _f1, _c), _crease, cv, bv = _creases(co, tris, crease_deg)
nrm = _vert_normals(co, tris)
total = np.zeros_like(co)
for axis in range(3):
total[:, axis] = np.bincount(lo, co[hi, axis], len(co)) + np.bincount(hi, co[lo, axis], len(co))
deg = np.bincount(np.concatenate((lo, hi)), minlength=len(co)).astype(np.float64)
delta = total / np.maximum(deg, 1)[:, None] - co
delta -= nrm * np.einsum("ij,ij->i", delta, nrm)[:, None]
free = ~bv & ~cv & (deg > 0)
moved = co.copy()
moved[free] += strength * delta[free]
if project is not None:
moved[free] = project(moved[free])
_write_co(me, moved)
def adaptive_triangles(co, tris, pts, L0, project, crease_deg, max_iter=8):
"""Isotropic remeshing (split / collapse / flip / smooth) towards the per-edge target length."""
me = bpy.data.meshes.new("CM_guided_tmp")
try:
me.from_pydata(co.tolist(), [], tris.tolist())
me.update()
for it in range(max_iter):
changed = _split_pass(me, pts, L0) + _collapse_pass(me, pts, L0, crease_deg)
if it >= 1:
_flip_pass(me, crease_deg)
_smooth_pass(me, project, crease_deg)
if changed < 0.01 * max(len(me.vertices), 1) and it >= 2:
break
_flip_pass(me, crease_deg)
_smooth_pass(me, project, crease_deg)
out_co, out_tris = _read(me)
finally:
bpy.data.meshes.remove(me)
used = np.zeros(len(out_co), dtype=bool)
used[out_tris.ravel()] = True
remap = np.cumsum(used) - 1
return out_co[used], remap[out_tris]
def _proxy(context, obj, src, max_tris):
"""Source triangles, decimated (native, fast) when there are many more than the result needs."""
tris = src["tris"]
if len(tris) <= max_tris:
return src["co"], tris
welded = bpy.data.meshes.new("CM_guided_proxy") # the welded copy: seams split by an importer would tear apart
welded.from_pydata(src["co"].tolist(), [], tris.tolist())
welded.update()
tmp = bpy.data.objects.new("CM_guided_proxy", welded)
context.scene.collection.objects.link(tmp)
try:
mod = tmp.modifiers.new("d", "DECIMATE")
mod.ratio = max(0.01, max_tris / max(len(tris), 1))
evaluated = tmp.evaluated_get(context.evaluated_depsgraph_get())
mesh = evaluated.to_mesh()
try:
co = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
mesh.vertices.foreach_get("co", co)
mesh.calc_loop_triangles()
t = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int64)
mesh.loop_triangles.foreach_get("vertices", t)
finally:
evaluated.to_mesh_clear()
finally:
data = tmp.data
bpy.data.objects.remove(tmp, do_unlink=True)
bpy.data.meshes.remove(data)
co = co.reshape(-1, 3)
t = t.reshape(-1, 3)
key = np.round(co / (src["diag"] * 1e-6)).astype(np.int64)
_u, first, inv = np.unique(key, axis=0, return_index=True, return_inverse=True)
t = inv.reshape(-1)[t]
t = t[(t[:, 0] != t[:, 1]) & (t[:, 1] != t[:, 2]) & (t[:, 0] != t[:, 2])]
return co[first], t
def _whole_mesh(context, obj, src, pts, gs, L0, project):
qe = float(np.sum(src["tri_area"] / (L0 * multiplier(src["tri_cent"], pts)) ** 2))
state["predicted"] = int(qe)
pco, ptris = _proxy(context, obj, src, int(np.clip(8 * qe, 3000, 60000)))
crease = min(gs.feature_angle, 30.0) if any(p.kind == "SHARP" for p in pts) else gs.feature_angle
ico, itris = adaptive_triangles(pco, ptris, pts, L0, project, crease)
mesh = MeshData(vertices=ico, faces=[tuple(t) for t in itris.tolist()], name="guided")
open_before = int((_edge_table(itris)[4] == 1).sum())