-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblender_splat_export.py
More file actions
1212 lines (1005 loc) · 42.8 KB
/
blender_splat_export.py
File metadata and controls
1212 lines (1005 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
bl_info = {
"name": "Gaussian Splat Exporter",
"author": "PLAN8",
"version": (0, 3, 0),
"blender": (3, 0, 0),
"location": "View3D > Sidebar > Gaussian Splat | File > Export > Gaussian Splat (.ply/.sog)",
"description": "Export mesh geometry to Gaussian Splat format with direct PLY export or via splat-transform",
"category": "Import-Export",
}
import bpy
import bmesh
import json
import os
import subprocess
from bpy.props import StringProperty, FloatProperty, IntProperty, BoolProperty, EnumProperty, PointerProperty
from bpy_extras.io_utils import ExportHelper
from mathutils import Vector, Matrix
import math
class GaussianSplatSettings(bpy.types.PropertyGroup):
"""Settings for Gaussian Splat export"""
export_format: EnumProperty(
name="Export Format",
description="Choose the output file format",
items=(
('PLY', ".ply", "Export as PLY format"),
('SOG', ".sog", "Export as SOG format"),
),
default='PLY',
)
use_splat_transform: BoolProperty(
name="Use splat-transform",
description="Use external splat-transform tool (requires installation). If disabled, writes PLY directly",
default=False
)
splat_transform_path: StringProperty(
name="splat-transform Command",
description="Command to run splat-transform (e.g., 'splat-transform' if globally installed, or full path)",
default="splat-transform",
)
overwrite_output: BoolProperty(
name="Overwrite Existing File",
description="Overwrite output file if it exists",
default=True
)
keep_mjs_file: BoolProperty(
name="Export .mjs File",
description="Save the .mjs generator file in the export directory (only used with splat-transform)",
default=False
)
use_frame_number: BoolProperty(
name="Use Frame Number in Filename",
description="Append the current frame number to the exported filename",
default=False
)
batch_export_animation: BoolProperty(
name="Batch Export Animation",
description="Export all frames from timeline start to end",
default=False
)
sample_density: FloatProperty(
name="Sample Density",
description="Number of splats per square unit (only used in Surface Sampling mode)",
default=100.0,
min=1.0,
max=10000.0
)
sampling_mode: EnumProperty(
name="Sampling Mode",
description="How to generate splats from the mesh",
items=(
('VERTICES', "Use Vertices", "Create one splat per vertex"),
('SURFACE', "Surface Sampling", "Sample splats across surface area"),
),
default='VERTICES',
)
splat_scale: FloatProperty(
name="Global Scale Multiplier",
description="Global scale multiplier applied to all splats (multiplied with auto-calculated size based on vertex proximity)",
default=1.0,
min=0.001,
max=100.0
)
use_auto_scale: BoolProperty(
name="Auto Scale from Vertex Proximity",
description="Automatically scale splats based on distance to nearest vertices",
default=True
)
auto_scale_neighbors: IntProperty(
name="Auto Scale Neighbor Count",
description="Number of nearest neighbors to average for auto-scaling (higher = smoother)",
default=5,
min=1,
max=20
)
splat_opacity: FloatProperty(
name="Global Opacity Multiplier",
description="Global opacity multiplier applied to all splats (multiplied with color attribute alpha)",
default=1.0,
min=0.0,
max=1.0
)
use_vertex_colors: BoolProperty(
name="Use Vertex Colors",
description="Use vertex colors if available",
default=True
)
use_normals: BoolProperty(
name="Orient to Normals",
description="Orient splats perpendicular to surface normals",
default=True
)
axis_forward: EnumProperty(
name="Forward",
items=(
('X', "X Forward", ""),
('Y', "Y Forward", ""),
('Z', "Z Forward", ""),
('-X', "-X Forward", ""),
('-Y', "-Y Forward", ""),
('-Z', "-Z Forward", ""),
),
default='Z',
)
axis_up: EnumProperty(
name="Up",
items=(
('X', "X Up", ""),
('Y', "Y Up", ""),
('Z', "Z Up", ""),
('-X', "-X Up", ""),
('-Y', "-Y Up", ""),
('-Z', "-Z Up", ""),
),
default='-Y',
)
export_path: StringProperty(
name="Export Path",
description="Path for the exported file",
default="",
subtype='FILE_PATH'
)
class GAUSSIANSPLAT_PT_MainPanel(bpy.types.Panel):
"""Main panel for Gaussian Splat export in 3D view sidebar"""
bl_label = "Gaussian Splat Export"
bl_idname = "GAUSSIANSPLAT_PT_main_panel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Gaussian Splat'
def draw(self, context):
layout = self.layout
settings = context.scene.gaussian_splat_settings
# Export path
box = layout.box()
box.label(text="Export Settings:", icon='EXPORT')
box.prop(settings, "export_path")
box.prop(settings, "export_format")
box.prop(settings, "use_splat_transform")
if settings.use_splat_transform:
box.prop(settings, "splat_transform_path")
box.prop(settings, "keep_mjs_file")
box.prop(settings, "overwrite_output")
# Animation export options
box = layout.box()
box.label(text="Animation Export:", icon='TIME')
box.prop(settings, "use_frame_number")
box.prop(settings, "batch_export_animation")
if settings.batch_export_animation:
row = box.row()
row.label(text=f"Will export frames {context.scene.frame_start} to {context.scene.frame_end}")
# Sampling options
box = layout.box()
box.label(text="Sampling Options:", icon='MESH_DATA')
box.prop(settings, "sampling_mode")
if settings.sampling_mode == 'SURFACE':
box.prop(settings, "sample_density")
# Splat properties
box = layout.box()
box.label(text="Splat Properties:", icon='PARTICLE_DATA')
box.prop(settings, "use_auto_scale")
if settings.use_auto_scale:
box.prop(settings, "auto_scale_neighbors")
box.prop(settings, "splat_scale")
box.prop(settings, "splat_opacity")
# Color options
box = layout.box()
box.label(text="Color Options:", icon='COLOR')
box.prop(settings, "use_vertex_colors")
box.prop(settings, "use_normals")
# Axis conversion
box = layout.box()
box.label(text="Axis Conversion:", icon='ORIENTATION_GIMBAL')
box.prop(settings, "axis_forward")
box.prop(settings, "axis_up")
# Export button
layout.separator()
row = layout.row(align=True)
row.scale_y = 1.5
row.operator("export_scene.gaussian_splat_direct", text="Export Gaussian Splat", icon='EXPORT')
class GAUSSIANSPLAT_OT_DirectExport(bpy.types.Operator):
"""Export Gaussian Splat directly from the side panel"""
bl_idname = "export_scene.gaussian_splat_direct"
bl_label = "Export Gaussian Splat"
bl_options = {'REGISTER'}
def execute(self, context):
settings = context.scene.gaussian_splat_settings
# Validate export path
if not settings.export_path:
self.report({'ERROR'}, "Please specify an export path")
return {'CANCELLED'}
# Get selected objects
selected_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'ERROR'}, "No mesh objects selected")
return {'CANCELLED'}
# Check if batch export is enabled
if settings.batch_export_animation:
return self.batch_export_frames(context, settings, selected_objects)
else:
return self.export_single_frame(context, settings, selected_objects, context.scene.frame_current)
def export_single_frame(self, context, settings, selected_objects, frame_number):
"""Export a single frame"""
# Set the frame
context.scene.frame_set(frame_number)
# Get file extension based on format
file_ext = '.ply' if settings.export_format == 'PLY' else '.sog'
# Build filepath with optional frame number
base_path = settings.export_path
# Remove existing extension if present
for ext in ['.ply', '.sog']:
if base_path.lower().endswith(ext):
base_path = base_path[:-len(ext)]
break
if settings.use_frame_number:
# Insert frame number before extension
filepath = f"{base_path}_{frame_number:04d}{file_ext}"
else:
filepath = base_path + file_ext
# Derive output directory
export_dir = os.path.dirname(filepath)
if not export_dir:
export_dir = bpy.path.abspath("//")
filepath = os.path.join(export_dir, os.path.basename(filepath))
try:
# Get axis conversion matrix
axis_matrix = get_axis_conversion_matrix(settings)
# Sample points from meshes
all_samples = []
for obj in selected_objects:
if settings.sampling_mode == 'VERTICES':
samples = sample_vertices(obj, context, axis_matrix, settings)
else:
samples = sample_mesh(obj, context, axis_matrix, settings)
all_samples.extend(samples)
self.report({'INFO'}, f"Frame {frame_number}: Sampled {len(all_samples)} points from {len(selected_objects)} object(s)")
# Choose export method
if settings.use_splat_transform:
# Use splat-transform method
base_name = os.path.splitext(os.path.basename(filepath))[0]
generator_path = os.path.join(export_dir, f"{base_name}.mjs")
create_mesh_generator(generator_path, all_samples)
# Build splat-transform command
cmd = [settings.splat_transform_path]
if settings.overwrite_output:
cmd.append('-w')
cmd.extend([generator_path, filepath])
# Run splat-transform
result = subprocess.run(
cmd,
capture_output=True,
text=True,
shell=True
)
if result.returncode != 0:
self.report({'ERROR'}, f"splat-transform failed: {result.stderr}")
return {'CANCELLED'}
# Delete .mjs file if not keeping it
if not settings.keep_mjs_file and os.path.exists(generator_path):
try:
os.remove(generator_path)
except Exception as e:
self.report({'WARNING'}, f"Could not delete .mjs file: {str(e)}")
else:
# Write PLY directly
if settings.export_format == 'PLY':
write_ply_direct(filepath, all_samples, settings.overwrite_output)
else:
self.report({'ERROR'}, "Direct export only supports PLY format. Use splat-transform for SOG format.")
return {'CANCELLED'}
self.report({'INFO'}, f"Successfully exported to {filepath}")
return {'FINISHED'}
except Exception as e:
import traceback
self.report({'ERROR'}, f"Export failed: {str(e)}")
print(traceback.format_exc()) # Print full traceback to console
return {'CANCELLED'}
def batch_export_frames(self, context, settings, selected_objects):
"""Export all frames in the timeline range"""
start_frame = context.scene.frame_start
end_frame = context.scene.frame_end
original_frame = context.scene.frame_current
total_frames = end_frame - start_frame + 1
self.report({'INFO'}, f"Starting batch export of {total_frames} frames...")
success_count = 0
fail_count = 0
for frame in range(start_frame, end_frame + 1):
result = self.export_single_frame(context, settings, selected_objects, frame)
if result == {'FINISHED'}:
success_count += 1
else:
fail_count += 1
# Restore original frame
context.scene.frame_set(original_frame)
if fail_count == 0:
self.report({'INFO'}, f"Batch export complete! Successfully exported {success_count} frames.")
return {'FINISHED'}
else:
self.report({'WARNING'}, f"Batch export finished with errors. Success: {success_count}, Failed: {fail_count}")
return {'FINISHED'}
class GaussianSplatExporter(bpy.types.Operator, ExportHelper):
"""Export mesh to Gaussian Splat format"""
bl_idname = "export_scene.gaussian_splat"
bl_label = "Export Gaussian Splat"
filename_ext = ".ply"
filter_glob: StringProperty(
default="*.ply;*.sog",
options={'HIDDEN'},
)
export_format: EnumProperty(
name="Export Format",
description="Choose the output file format",
items=(
('PLY', ".ply", "Export as PLY format"),
('SOG', ".sog", "Export as SOG format"),
),
default='PLY',
)
use_splat_transform: BoolProperty(
name="Use splat-transform",
description="Use external splat-transform tool (requires installation). If disabled, writes PLY directly",
default=False
)
splat_transform_path: StringProperty(
name="splat-transform Command",
description="Command to run splat-transform (e.g., 'splat-transform' if globally installed, or full path)",
default="splat-transform",
)
overwrite_output: BoolProperty(
name="Overwrite Existing File",
description="Overwrite output file if it exists",
default=True
)
keep_mjs_file: BoolProperty(
name="Export .mjs File",
description="Save the .mjs generator file in the export directory (only used with splat-transform)",
default=False
)
use_frame_number: BoolProperty(
name="Use Frame Number in Filename",
description="Append the current frame number to the exported filename",
default=False
)
batch_export_animation: BoolProperty(
name="Batch Export Animation",
description="Export all frames from timeline start to end",
default=False
)
sample_density: FloatProperty(
name="Sample Density",
description="Number of splats per square unit (only used in Surface Sampling mode)",
default=100.0,
min=1.0,
max=10000.0
)
sampling_mode: EnumProperty(
name="Sampling Mode",
description="How to generate splats from the mesh",
items=(
('VERTICES', "Use Vertices", "Create one splat per vertex"),
('SURFACE', "Surface Sampling", "Sample splats across surface area"),
),
default='VERTICES',
)
splat_scale: FloatProperty(
name="Global Scale Multiplier",
description="Global scale multiplier applied to all splats (multiplied with auto-calculated size based on vertex proximity)",
default=1.0,
min=0.001,
max=1000.0
)
use_auto_scale: BoolProperty(
name="Auto Scale from Vertex Proximity",
description="Automatically scale splats based on distance to nearest vertices",
default=True
)
auto_scale_neighbors: IntProperty(
name="Auto Scale Neighbor Count",
description="Number of nearest neighbors to average for auto-scaling (higher = smoother)",
default=5,
min=1,
max=20
)
splat_opacity: FloatProperty(
name="Global Opacity Multiplier",
description="Global opacity multiplier applied to all splats (multiplied with color attribute alpha)",
default=1.0,
min=0.0,
max=1.0
)
use_vertex_colors: BoolProperty(
name="Use Vertex Colors",
description="Use vertex colors if available",
default=True
)
use_normals: BoolProperty(
name="Orient to Normals",
description="Orient splats perpendicular to surface normals",
default=True
)
axis_forward: EnumProperty(
name="Forward",
items=(
('X', "X Forward", ""),
('Y', "Y Forward", ""),
('Z', "Z Forward", ""),
('-X', "-X Forward", ""),
('-Y', "-Y Forward", ""),
('-Z', "-Z Forward", ""),
),
default='-Z',
)
axis_up: EnumProperty(
name="Up",
items=(
('X', "X Up", ""),
('Y', "Y Up", ""),
('Z', "Z Up", ""),
('-X', "-X Up", ""),
('-Y', "-Y Up", ""),
('-Z', "-Z Up", ""),
),
default='Y',
)
def draw(self, context):
"""Draw the export options in the file browser"""
layout = self.layout
layout.prop(self, "use_splat_transform")
if self.use_splat_transform:
layout.prop(self, "splat_transform_path")
layout.prop(self, "keep_mjs_file")
layout.prop(self, "export_format")
layout.prop(self, "overwrite_output")
layout.separator()
layout.label(text="Animation Export:")
layout.prop(self, "use_frame_number")
layout.prop(self, "batch_export_animation")
if self.batch_export_animation:
layout.label(text=f"Will export frames {context.scene.frame_start} to {context.scene.frame_end}")
layout.separator()
layout.label(text="Sampling Options:")
layout.prop(self, "sampling_mode")
if self.sampling_mode == 'SURFACE':
layout.prop(self, "sample_density")
layout.separator()
layout.label(text="Splat Properties:")
layout.prop(self, "use_auto_scale")
if self.use_auto_scale:
layout.prop(self, "auto_scale_neighbors")
layout.prop(self, "splat_scale")
layout.prop(self, "splat_opacity")
layout.separator()
layout.label(text="Color Options:")
layout.prop(self, "use_vertex_colors")
layout.prop(self, "use_normals")
layout.separator()
layout.label(text="Axis Conversion:")
layout.prop(self, "axis_forward")
layout.prop(self, "axis_up")
def execute(self, context):
selected_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'ERROR'}, "No mesh objects selected")
return {'CANCELLED'}
# Check if batch export is enabled
if self.batch_export_animation:
return self.batch_export_frames(context, selected_objects)
else:
return self.export_single_frame(context, selected_objects, context.scene.frame_current)
def export_single_frame(self, context, selected_objects, frame_number):
"""Export a single frame"""
# Set the frame
context.scene.frame_set(frame_number)
# Get file extension based on format
file_ext = '.ply' if self.export_format == 'PLY' else '.sog'
# Build filepath with optional frame number and correct extension
base_path = self.filepath
# Remove existing extension if present
for ext in ['.ply', '.sog']:
if base_path.lower().endswith(ext):
base_path = base_path[:-len(ext)]
break
if self.use_frame_number:
filepath = f"{base_path}_{frame_number:04d}{file_ext}"
else:
filepath = base_path + file_ext
export_dir = os.path.dirname(filepath)
try:
axis_matrix = get_axis_conversion_matrix(self)
all_samples = []
for obj in selected_objects:
if self.sampling_mode == 'VERTICES':
samples = sample_vertices(obj, context, axis_matrix, self)
else:
samples = sample_mesh(obj, context, axis_matrix, self)
all_samples.extend(samples)
self.report({'INFO'}, f"Frame {frame_number}: Sampled {len(all_samples)} points from {len(selected_objects)} object(s)")
# Choose export method
if self.use_splat_transform:
# Use splat-transform method
base_name = os.path.splitext(os.path.basename(filepath))[0]
generator_path = os.path.join(export_dir, f"{base_name}.mjs")
create_mesh_generator(generator_path, all_samples)
# Build splat-transform command
cmd = [self.splat_transform_path]
if self.overwrite_output:
cmd.append('-w')
cmd.extend([generator_path, filepath])
result = subprocess.run(
cmd,
capture_output=True,
text=True,
shell=True
)
if result.returncode != 0:
self.report({'ERROR'}, f"splat-transform failed: {result.stderr}")
return {'CANCELLED'}
# Delete .mjs file if not keeping it
if not self.keep_mjs_file and os.path.exists(generator_path):
try:
os.remove(generator_path)
except Exception as e:
self.report({'WARNING'}, f"Could not delete .mjs file: {str(e)}")
else:
# Write PLY directly
if self.export_format == 'PLY':
write_ply_direct(filepath, all_samples, self.overwrite_output)
else:
self.report({'ERROR'}, "Direct export only supports PLY format. Use splat-transform for SOG format.")
return {'CANCELLED'}
self.report({'INFO'}, f"Successfully exported to {filepath}")
return {'FINISHED'}
except Exception as e:
import traceback
self.report({'ERROR'}, f"Export failed: {str(e)}")
print(traceback.format_exc()) # Print full traceback to console
return {'CANCELLED'}
def batch_export_frames(self, context, selected_objects):
"""Export all frames in the timeline range"""
start_frame = context.scene.frame_start
end_frame = context.scene.frame_end
original_frame = context.scene.frame_current
total_frames = end_frame - start_frame + 1
self.report({'INFO'}, f"Starting batch export of {total_frames} frames...")
success_count = 0
fail_count = 0
for frame in range(start_frame, end_frame + 1):
result = self.export_single_frame(context, selected_objects, frame)
if result == {'FINISHED'}:
success_count += 1
else:
fail_count += 1
# Restore original frame
context.scene.frame_set(original_frame)
if fail_count == 0:
self.report({'INFO'}, f"Batch export complete! Successfully exported {success_count} frames.")
return {'FINISHED'}
else:
self.report({'WARNING'}, f"Batch export finished with errors. Success: {success_count}, Failed: {fail_count}")
return {'FINISHED'}
# Shared utility functions
def get_axis_conversion_matrix(settings):
"""Create a conversion matrix based on axis settings"""
from bpy_extras.io_utils import axis_conversion
conv_matrix = axis_conversion(
from_forward='-Y',
from_up='Z',
to_forward=settings.axis_forward,
to_up=settings.axis_up,
).to_4x4()
return conv_matrix
def sample_vertices(obj, context, axis_matrix, settings):
"""Create splats directly from mesh vertices"""
depsgraph = context.evaluated_depsgraph_get()
obj_eval = obj.evaluated_get(depsgraph)
mesh = obj_eval.to_mesh()
matrix_world = axis_matrix @ obj.matrix_world
material = obj.active_material
color_attribute = None
has_vertex_colors = False
if hasattr(mesh, 'color_attributes') and len(mesh.color_attributes) > 0:
color_attribute = mesh.color_attributes.active_color
if color_attribute:
has_vertex_colors = True
elif hasattr(mesh, 'vertex_colors') and len(mesh.vertex_colors) > 0:
color_attribute = mesh.vertex_colors.active
has_vertex_colors = True
# Build KD-tree for nearest neighbor searches if auto-scale is enabled
kd = None
if settings.use_auto_scale:
from mathutils import kdtree
kd = kdtree.KDTree(len(mesh.vertices))
for i, v in enumerate(mesh.vertices):
kd.insert(v.co, i)
kd.balance()
samples = []
for vert in mesh.vertices:
world_pos = matrix_world @ vert.co
color, alpha = get_vertex_color(vert.index, mesh, has_vertex_colors, color_attribute, material, settings)
normal = matrix_world.to_3x3() @ vert.normal if settings.use_normals else Vector((0, 0, 1))
# Calculate scale based on average nearest neighbor distance
if settings.use_auto_scale and kd:
# Find N+1 nearest vertices (first will be the vertex itself at distance 0)
num_neighbors = settings.auto_scale_neighbors + 1
nearest = kd.find_n(vert.co, num_neighbors)
if len(nearest) > 1:
# Skip the first result (self) and average the distances
distances = [n[2] for n in nearest[1:]] # n[2] is the distance
avg_dist = sum(distances) / len(distances)
# Use average distance as the scale (will give roughly correct coverage)
auto_scale = max(avg_dist, 0.0001)
else:
auto_scale = 0.01 # Fallback for isolated vertices
final_scale = auto_scale * settings.splat_scale
else:
final_scale = settings.splat_scale
# Ensure final_scale is always positive and non-zero
final_scale = max(final_scale, 0.0001)
# Multiply alpha with global opacity
final_opacity = alpha * settings.splat_opacity
samples.append({
'position': world_pos,
'color': color,
'normal': normal,
'scale': final_scale,
'opacity': final_opacity
})
obj_eval.to_mesh_clear()
return samples
def sample_mesh(obj, context, axis_matrix, settings):
"""Sample points from mesh surface"""
depsgraph = context.evaluated_depsgraph_get()
obj_eval = obj.evaluated_get(depsgraph)
mesh = obj_eval.to_mesh()
matrix_world = axis_matrix @ obj.matrix_world
bm = bmesh.new()
bm.from_mesh(mesh)
bm.faces.ensure_lookup_table()
material = obj.active_material
color_attribute = None
has_vertex_colors = False
if hasattr(mesh, 'color_attributes') and len(mesh.color_attributes) > 0:
color_attribute = mesh.color_attributes.active_color
if color_attribute:
has_vertex_colors = True
elif hasattr(mesh, 'vertex_colors') and len(mesh.vertex_colors) > 0:
color_attribute = mesh.vertex_colors.active
has_vertex_colors = True
# Build KD-tree for nearest neighbor searches if auto-scale is enabled
kd = None
if settings.use_auto_scale:
from mathutils import kdtree
kd = kdtree.KDTree(len(mesh.vertices))
for i, v in enumerate(mesh.vertices):
kd.insert(v.co, i)
kd.balance()
samples = []
total_area = sum(face.calc_area() for face in bm.faces)
num_samples = int(total_area * settings.sample_density)
for face in bm.faces:
face_area = face.calc_area()
face_samples = max(1, int((face_area / total_area) * num_samples))
for _ in range(face_samples):
r1 = math.sqrt(bpy.context.scene.frame_current * 0.001 + len(samples) * 0.1) % 1.0
r2 = (len(samples) * 0.7) % 1.0
if r1 + r2 > 1:
r1 = 1 - r1
r2 = 1 - r2
v0, v1, v2 = [v.co for v in face.verts[:3]]
pos = v0 + (v1 - v0) * r1 + (v2 - v0) * r2
world_pos = matrix_world @ pos
color, alpha = get_face_color(face, obj, mesh, has_vertex_colors, color_attribute, material, settings)
normal = matrix_world.to_3x3() @ face.normal if settings.use_normals else Vector((0, 0, 1))
# Calculate scale based on average nearest vertex distance
if settings.use_auto_scale and kd:
# Find N nearest vertices
num_neighbors = settings.auto_scale_neighbors
nearest_list = kd.find_n(pos, num_neighbors)
if nearest_list:
# Average the distances to all found neighbors
distances = [n[2] for n in nearest_list] # n[2] is the distance
avg_dist = sum(distances) / len(distances)
auto_scale = max(avg_dist, 0.0001)
else:
auto_scale = 0.01 # Fallback
final_scale = auto_scale * settings.splat_scale
else:
final_scale = settings.splat_scale
# Ensure final_scale is always positive and non-zero
final_scale = max(final_scale, 0.0001)
# Multiply alpha with global opacity
final_opacity = alpha * settings.splat_opacity
samples.append({
'position': world_pos,
'color': color,
'normal': normal,
'scale': final_scale,
'opacity': final_opacity
})
bm.free()
obj_eval.to_mesh_clear()
return samples
def get_face_color(face, obj, mesh, has_vertex_colors, color_attribute, material, settings):
"""Get color and alpha for a face"""
if settings.use_vertex_colors and has_vertex_colors and color_attribute:
try:
colors = []
alphas = []
if hasattr(color_attribute, 'domain'):
domain = color_attribute.domain
if domain == 'CORNER':
for loop in face.loops:
mesh_loop_index = loop.index
if mesh_loop_index < len(color_attribute.data):
color_data = color_attribute.data[mesh_loop_index].color
colors.append(color_data[:3])
# Get alpha (4th component)
alphas.append(color_data[3] if len(color_data) > 3 else 1.0)
elif domain == 'POINT':
for vert in face.verts:
vert_index = vert.index
if vert_index < len(color_attribute.data):
color_data = color_attribute.data[vert_index].color
colors.append(color_data[:3])
alphas.append(color_data[3] if len(color_data) > 3 else 1.0)
elif domain == 'FACE':
face_index = face.index
if face_index < len(color_attribute.data):
color_data = color_attribute.data[face_index].color
alpha = color_data[3] if len(color_data) > 3 else 1.0
return list(color_data[:3]), alpha
else:
for loop_elem in mesh.loops:
for loop in face.loops:
if loop.index == loop_elem.index:
if loop_elem.index < len(color_attribute.data):
color_data = color_attribute.data[loop_elem.index].color
colors.append(color_data[:3])
alphas.append(color_data[3] if len(color_data) > 3 else 1.0)
break
if colors:
avg_color = [sum(c[i] for c in colors) / len(colors) for i in range(3)]
avg_alpha = sum(alphas) / len(alphas) if alphas else 1.0
return avg_color, avg_alpha
except (IndexError, AttributeError):
pass
if material and material.use_nodes:
for node in material.node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs['Base Color'].default_value
alpha = base_color[3] if len(base_color) > 3 else 1.0
return list(base_color[:3]), alpha
return [1.0, 1.0, 1.0], 1.0
def get_vertex_color(vert_index, mesh, has_vertex_colors, color_attribute, material, settings):
"""Get color and alpha for a specific vertex"""
if settings.use_vertex_colors and has_vertex_colors and color_attribute:
try:
if hasattr(color_attribute, 'domain'):
domain = color_attribute.domain
if domain == 'POINT':
if vert_index < len(color_attribute.data):
color_data = color_attribute.data[vert_index].color
alpha = color_data[3] if len(color_data) > 3 else 1.0
return list(color_data[:3]), alpha
elif domain == 'CORNER':
colors = []
alphas = []
for loop in mesh.loops:
if loop.vertex_index == vert_index:
if loop.index < len(color_attribute.data):
color_data = color_attribute.data[loop.index].color
colors.append(color_data[:3])
alphas.append(color_data[3] if len(color_data) > 3 else 1.0)
if colors:
avg_color = [sum(c[i] for c in colors) / len(colors) for i in range(3)]
avg_alpha = sum(alphas) / len(alphas) if alphas else 1.0
return avg_color, avg_alpha
elif domain == 'FACE':
colors = []
alphas = []
for poly in mesh.polygons:
if vert_index in poly.vertices:
if poly.index < len(color_attribute.data):
color_data = color_attribute.data[poly.index].color
colors.append(color_data[:3])
alphas.append(color_data[3] if len(color_data) > 3 else 1.0)
if colors:
avg_color = [sum(c[i] for c in colors) / len(colors) for i in range(3)]
avg_alpha = sum(alphas) / len(alphas) if alphas else 1.0
return avg_color, avg_alpha
except (IndexError, AttributeError):
pass
if material and material.use_nodes:
for node in material.node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs['Base Color'].default_value
alpha = base_color[3] if len(base_color) > 3 else 1.0
return list(base_color[:3]), alpha
return [1.0, 1.0, 1.0], 1.0
def create_mesh_generator(path, samples):
"""Create a generator file for splat-transform"""
def normal_to_quat(normal):
up = Vector((0, 0, 1))
if abs(normal.dot(up)) > 0.999:
return [0, 0, 0, 1]
axis = up.cross(normal).normalized()
angle = math.acos(up.dot(normal))
half_angle = angle / 2
s = math.sin(half_angle)
return [axis.x * s, axis.y * s, axis.z * s, math.cos(half_angle)]
SH_C0 = 0.28209479177387814