Repository navigation
Expand file tree
/
Copy pathminigltf.py
More file actions
2320 lines (2025 loc) · 101 KB
/
Copy pathminigltf.py
File metadata and controls
2320 lines (2025 loc) · 101 KB
Open symbols panel
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
import bpy
from io import BytesIO
import json
import math
import mathutils
import numpy as np
import os
import re
import struct
import bisect
import time
import warnings
timings = {}
def _fc_val(fc, t):
"""Value of keyframe index t from fc; 0.0 when fc is absent or index out of range."""
if fc is None:
return 0.0
kps = fc.keyframe_points
return kps[t].co.y if t < len(kps) else 0.0
def _curves_time_mismatch(cs):
"""GLTF expects keyframe value on every curve in loc/rot/scale."""
present = [fc for fc in cs if fc is not None and len(fc.keyframe_points)]
if len(present) < 2:
return False
ref = [kp.co.x for kp in present[0].keyframe_points]
return any([kp.co.x for kp in fc.keyframe_points] != ref for fc in present[1:])
def _action_fcurves(action):
"""Return all fcurves for an action, compatible with Blender 4.3 and 4.4+/5.x."""
if hasattr(action, 'fcurves'):
return action.fcurves
# Blender 5.0+: collect fcurves from all channelbags across every strip
result = []
for layer in action.layers:
for strip in layer.strips:
if hasattr(strip, 'channelbags'):
for bag in strip.channelbags:
result.extend(bag.fcurves)
return result
def _slot_fcurves(action, slot_handle):
"""Return the fcurves of one action slot.
A single action can drive several IDs through different slots; `slot_handle`
picks the channelbag for the slot actually used by a given assignment/strip.
Falls back to action.fcurves on Blender <= 4.4 (no slots)."""
if hasattr(action, 'fcurves'):
return action.fcurves
result = []
for layer in action.layers:
for strip in layer.strips:
for bag in getattr(strip, 'channelbags', []):
if slot_handle is None or bag.slot_handle == slot_handle:
result.extend(bag.fcurves)
return result
def _bake_mismatched(action):
"""Insert keys so every curve in a channel group shares keyframe time"""
if hasattr(action, 'fcurves'):
_bake_curve_groups(list(action.fcurves))
return
by_slot = {}
for _layer in action.layers:
for _strip in _layer.strips:
for _bag in getattr(_strip, 'channelbags', []):
by_slot.setdefault(_bag.slot_handle, []).extend(_bag.fcurves)
for _fcs in by_slot.values():
_bake_curve_groups(_fcs)
def _bake_curve_groups(fcs):
groups = {}
for fc in fcs:
last = fc.data_path.rsplit('.', 1)[-1]
if last in ('location', 'rotation_quaternion', 'scale', 'color'):
groups.setdefault(fc.data_path, []).append(fc)
sk = [fc for fc in fcs
if fc.data_path.startswith('key_blocks[') and fc.data_path.endswith('.value')]
if len(sk) >= 2:
groups['__shapekeys__'] = sk
for key, flist in groups.items():
if len(flist) < 2:
continue
frames = sorted({kp.co.x for fc in flist for kp in fc.keyframe_points})
plan = []
for fc in flist:
existing = sorted((kp.co.x, kp.interpolation) for kp in fc.keyframe_points)
xs = [x for x, _ in existing]
have = set(xs)
samples = []
for f in frames:
if f in have:
continue
i = bisect.bisect_left(xs, f)
interp = existing[i - 1][1] if i else None
samples.append((f, fc.evaluate(f), interp))
if samples:
plan.append((fc, samples))
if not plan:
continue
inserted = failed = 0
for fc, samples in plan:
for f, value, interp in samples:
try:
kp = fc.keyframe_points.insert(f, value, options={'FAST'})
if interp is not None:
kp.interpolation = interp
inserted += 1
except Exception:
failed += 1
fc.update()
label = "shape key weights" if key == '__shapekeys__' else key
if inserted:
print(f"[minigltf] baked {inserted} matching keyframe(s) into '{label}'")
if failed:
print(f"[minigltf] WARNING: could not bake {failed} keyframe(s) into "
f"'{label}' - exported animation may have incorrect keyframes")
def _alpha_mode(material, albedo):
"""Return alphamode to use."""
alphaMode = None
alphaCutoff = None
# We do not have albedo or the albedo is explicitly marked as not transparent
if not albedo or albedo.alpha_mode == 'NONE':
return (alphaMode, alphaCutoff)
# We have albedo, but it does not have 4 channels
if albedo.channels != 4:
return (alphaMode, alphaCutoff)
# Do we have any transparent pixels?
w, h = albedo.size
arr = np.empty(w*h*4, dtype=np.float32)
albedo.pixels.foreach_get(arr)
alphas = arr[3::4]
has_transparency = np.any(alphas < 1.0)
if not has_transparency:
return (alphaMode, alphaCutoff)
# Alpha mode from Blender material transparency settings.
# Blender 5.x uses surface_render_method (BLENDED/DITHERED).
# Blender 4.x uses blend_method (BLEND/CLIP/OPAQUE/HASHED).
srm = getattr(material, 'surface_render_method', None)
blend = getattr(material, 'blend_method', 'OPAQUE')
if blend == 'CLIP':
alphaMode = 'MASK'
alphaCutoff = round(float(getattr(m, 'alpha_threshold', 0.5)), 4)
else:
alphaMode = 'BLEND'
return (alphaMode, alphaCutoff)
class _BinWriter:
"""Append-only binary buffer backed by a single pre-allocated bytearray."""
def __init__(self, size):
self.buf = bytearray(size)
self.mv = memoryview(self.buf)
self.offset = 0
def tell(self):
return self.offset
def write(self, data):
src = memoryview(data).cast('B')
n = src.nbytes
self.mv[self.offset:self.offset + n] = src
self.offset += n
def view(self, n_elems, dtype=np.float32):
"""Reserve n_elems of dtype at the current offset and return a writable
numpy view onto them. Advances the write position past the reservation."""
dt = np.dtype(dtype)
arr = np.frombuffer(self.mv, dtype=dt, count=n_elems, offset=self.offset)
self.offset += n_elems * dt.itemsize
return arr
def getbuffer(self):
return self.mv[:self.offset]
def _je(s: str) -> bytes:
"""JSON-encode a string value (with surrounding quotes, properly escaped)."""
return json.dumps(s).encode()
# --- Cutscene (NLA schedule) support -----------------------------------------
#
# glTF cannot express the NLA timeline (camera cuts + per-actor strip schedule),
# so the schedule is stored as JSON in the extras of a synthetic "CutsceneData"
# node inside the glb. The Godot addon in addons/minigltf/ (a registered
# GLTFDocumentExtension) reads it back at import time and builds the "Cutscene"
# AnimationPlayer:
# - value tracks toggle <Camera>:current at the marker times,
# - animation-playback tracks drive <Actor>/AnimationPlayer, naming the glb
# clip to play. Two characters can therefore run different clips at once.
# The addon also splits the master AnimationPlayer Godot's importer creates
# into one AnimationPlayer per animated top-level node (per Blender animation
# target), pruning each clip down to the tracks that drive that node, and
# resolves extras.link linked-library glbs.
def _anim_data_holders(obj):
"""The animation_data holders that contribute glTF animations for obj."""
holders = []
if obj.animation_data:
holders.append(obj.animation_data)
if obj.type == 'MESH' and obj.data.shape_keys and obj.data.shape_keys.animation_data:
holders.append(obj.data.shape_keys.animation_data)
if obj.type == 'LIGHT' and obj.data.animation_data:
holders.append(obj.data.animation_data)
return holders
def _action_target_counts(scene):
"""{action_name: number of distinct LOCAL target objects that use it} - mirrors
the 'multiple users => suffix the name' rule in the animation export. Linked
actions are excluded: they live in a library glb where they target a single
character, so they keep their bare name there and must be referenced bare
from the schedule."""
targets = {}
for obj in scene.objects:
used = set()
for ad in _anim_data_holders(obj):
if ad.action and not ad.action.library:
used.add(ad.action.name)
for tr in ad.nla_tracks:
for st in tr.strips:
if st.action and not st.action.library:
used.add(st.action.name)
for name in used:
targets.setdefault(name, set()).add(obj.name)
return {name: len(objs) for name, objs in targets.items()}
def _clip_name(action_name, target_name, counts):
return action_name if counts.get(action_name, 1) <= 1 else f"{action_name}_{target_name}"
# Godot's glTF importer runs every animation name through
# AnimationLibrary.validate_library_name, which replaces '/', ':', ',' and '['
# with '_'. Sanitize the names we emit (and reference in the schedule) the same
# way so a punctuated action name still round-trips: the glTF name Godot keeps
# equals the map key the addon looks up, and the bare name the addon assigns is a
# valid clip name the schedule can match.
_GD_NAME_TRANS = str.maketrans('/:,[', '____')
def _gd_clip_name(name):
return name.translate(_GD_NAME_TRANS)
def _clip_name_registry(scene):
"""Globally-unique glTF animation name for every clip the exporter emits.
The animation writer and the cutscene schedule must reference identical clip
names, and no two animations may share one. Godot's importer silently renames
duplicate animation names on import (``foo``, ``foo2``, ...), so if the name
the export generates for one lane (e.g. a multi-target ``crawl_rigB``) happens
to equal another action's name, the schedule ends up pointing a lane at the
renamed - i.e. wrong - clip. Which one gets renamed is import-order dependent,
so the breakage is intermittent. Assigning names here, once, and having both
callers look them up keeps them in agreement and every emitted name unique.
Returns (nla_names, direct_names):
nla_names[(object_name, action_name)] -> per-target NLA lane clip name
direct_names[action_name] -> merged direct-assignment clip name
"""
counts = _action_target_counts(scene)
used = set()
def _uniq(preferred):
name = preferred
i = 2
while name in used:
name = f"{preferred}_{i}"
i += 1
used.add(name)
return name
nla_names = {}
direct_names = {}
# Deterministic pass mirroring the export's direct-vs-NLA split: a holder's
# active action becomes one merged clip; every NLA strip whose action isn't
# that active action is its own per-target lane. First claimant of a name
# keeps it; any later collision (with another lane or a like-named action)
# gets a numeric suffix, identically for both callers.
# Keys stay the raw action/object names (the export and schedule look them up
# by those); the value is the Godot-sanitized, de-duplicated glTF name.
for obj in scene.objects:
for ad in _anim_data_holders(obj):
# In NLA tweak mode the active action is a strip being edited; treat
# it as its NLA lane (below), not as a direct/active-action clip.
active = (ad.action if (ad.action and not ad.action.library
and not getattr(ad, 'use_tweak_mode', False))
else None)
if active is not None and active.name not in direct_names:
direct_names[active.name] = _uniq(_gd_clip_name(active.name))
for tr in ad.nla_tracks:
for st in tr.strips:
act = st.action
if act is None or act.library or act is active:
continue
key = (obj.name, act.name)
if key not in nla_names:
nla_names[key] = _uniq(_gd_clip_name(_clip_name(act.name, obj.name, counts)))
# Reserve linked strip-action names so no local clip claims a name the
# schedule resolves from another file (direct assignments still win ties).
for obj in scene.objects:
for ad in _anim_data_holders(obj):
for tr in ad.nla_tracks:
for st in tr.strips:
act = st.action
if act is not None and getattr(act, 'library', None):
_uniq(_gd_clip_name(act.name))
# Loose local actions (created but never assigned) still export as a bare
# merged clip; reserve their names too so nothing collides with them.
for a in bpy.data.actions:
if getattr(a, 'library', None) or a.name in direct_names:
continue
if any(k[1] == a.name for k in nla_names):
continue
direct_names[a.name] = _uniq(_gd_clip_name(a.name))
return nla_names, direct_names
def _source_collection(obj):
if obj.type == 'EMPTY' and getattr(obj, 'instance_type', None) == 'COLLECTION':
return obj.instance_collection
ref = getattr(getattr(obj, 'override_library', None), 'reference', None)
lib = getattr(ref, 'library', None)
if lib is None:
return None
return next((c for c in ref.users_collection if getattr(c, 'library', None) == lib), None)
def _linked_clip_name(name, lib_path, taken):
if name not in taken:
return name
base = f"{name}_{_gd_clip_name(os.path.splitext(os.path.basename(lib_path))[0])}"
out, i = base, 2
while out in taken:
out = f"{base}_{i}"
i += 1
return out
def _frame_num(f):
"""A frame number for the JSON schedule: int when whole, else float."""
f = float(f)
return int(f) if f.is_integer() else round(f, 4)
def _offset_clip_name(name, frame, taken):
f = int(frame) if float(frame).is_integer() else frame
base = _gd_clip_name(f"{name}_f{f}".replace('.', '_').replace('-', 'm'))
out, i = base, 2
while out in taken:
out = f"{base}_{i}"
i += 1
return out
def _cutscene_schedule(output_file: str):
"""The NLA schedule for the current scene as a JSON-ready dict, or None
when there is no cutscene (no camera-bound markers and no NLA strips)."""
scene = bpy.context.scene
fps = scene.render.fps * scene.render.fps_base
_glb_dir = os.path.dirname(os.path.abspath(output_file))
# Camera cuts from camera-bound markers.
markers = sorted((m for m in scene.timeline_markers if m.camera is not None),
key=lambda m: m.frame)
cuts = [{'frame': _frame_num(m.frame), 'camera': m.camera.name} for m in markers]
# Per-actor playback schedule plus `sources` provenance for strips driven
# by a foreign-library action (same-library clips need no entry).
playback = []
end_frame = 0.0
# A linked clip never takes a local action's name: the addon would find the
# local clip in the lane player and skip grafting the linked one.
_local_names = {_gd_clip_name(a.name) for a in bpy.data.actions
if getattr(a, 'library', None) is None}
for obj in scene.objects:
keys = []
sources = {}
aliases = {}
_raw = [] # [strip start frame, base lane clip, action start frame, direct?]
_linked = {} # (library path, action name) -> lane clip name
_src_col = _source_collection(obj)
_inst_col = None
if obj.type == 'EMPTY' and getattr(obj, 'instance_type', None) == 'COLLECTION':
_inst_col = obj.instance_collection
for ad in _anim_data_holders(obj):
# The holder's direct clip (mirrors _clip_name_registry).
_active = (ad.action if (ad.action and not ad.action.library
and not getattr(ad, 'use_tweak_mode', False))
else None)
for tr in ad.nla_tracks:
if tr.mute:
continue
for st in tr.strips:
if st.mute or st.action is None:
continue
# The Godot addon renames each per-actor clip to its bare
# action name, so the schedule references that (a lane clip
# name only has to be unique within one actor's player).
# Sanitize to match the name the addon assigns in Godot.
_clip = _gd_clip_name(st.action.name)
_lib = getattr(st.action, 'library', None)
if _lib is not None:
_lib_path = os.path.abspath(bpy.path.abspath(_lib.filepath))
_key = (_lib_path, st.action.name)
if _key not in _linked:
_linked[_key] = _linked_clip_name(
_clip, _lib_path, _local_names | set(_linked.values()))
_renamed = _linked[_key] != _clip
_clip = _linked[_key]
_same = False
if not _renamed and _inst_col is not None \
and getattr(_inst_col, 'library', None) is not None:
try:
_same = (os.path.abspath(bpy.path.abspath(_inst_col.library.filepath))
== _lib_path)
except ValueError:
_same = False
if not _same and _clip not in sources:
try:
_rel = os.path.relpath(_lib_path, _glb_dir)
except ValueError:
_rel = _lib_path
sources[_clip] = {
'file': _rel.replace('\\', '/'),
'collection': _src_col.name if _src_col is not None else '',
'clip': _gd_clip_name(st.action.name),
}
_raw.append([st.frame_start, _clip, st.action_frame_start,
st.action is _active])
end_frame = max(end_frame, st.frame_end)
_raw.sort(key=lambda r: r[0])
_taken = _local_names | set(_linked.values()) | {r[1] for r in _raw}
_start_of = {} # lane clip -> its (rounded) action start frame
_variant = {} # (base clip, action start) -> lane clip
for _f0, _clip, _afs, _direct in _raw:
_a = round(_afs, 3)
if not _direct and _start_of.setdefault(_clip, _a) == _a:
_name = _clip
elif (_clip, _a) in _variant:
_name = _variant[(_clip, _a)]
else:
_name = _offset_clip_name(_clip, _a, _taken)
_taken.add(_name)
_variant[(_clip, _a)] = _name
if _clip in sources:
sources[_name] = dict(sources[_clip])
else:
aliases[_name] = _clip
keys.append([_frame_num(_f0), _name, _
10BC8
frame_num(_afs)])
if keys:
lane = {'actor': obj.name, 'keys': keys}
if sources:
lane['sources'] = sources
if aliases:
lane['aliases'] = aliases
playback.append(lane)
if not cuts and not playback:
return None
for c in cuts:
end_frame = max(end_frame, c['frame'])
for lane in playback:
end_frame = max(end_frame, lane['keys'][-1][0])
return {'version': 1, 'fps': fps, 'end_frame': _frame_num(end_frame),
'cuts': cuts, 'playback': playback}
def _sound_missing(sound) -> bool:
try:
return not sound.filepath or not os.path.isfile(bpy.path.abspath(sound.filepath))
except Exception:
return True
def _sound_uri(sound, output_file: str) -> str:
"""Return a relative URI for an audio file, mirroring _image_uri."""
fp = sound.filepath
if not fp:
# Packed sounds with no on-disk path cannot be referenced by URI.
warnings.warn(f"minigltf: sound '{sound.name}' is packed with no filepath; skipping")
return ""
if getattr(sound, 'library', None):
lib_dir = os.path.dirname(bpy.path.abspath(sound.library.filepath))
rel_fp = fp[2:] if fp.startswith('//') else fp
abs_path = os.path.normpath(os.path.join(lib_dir, rel_fp))
else:
abs_path = bpy.path.abspath(fp)
glb_dir = os.path.dirname(os.path.abspath(output_file))
try:
rel = os.path.relpath(abs_path, glb_dir)
except ValueError:
rel = abs_path
return rel.replace('\\', '/')
def _speaker_volume_keys(obj, fps):
"""Keyframes on the Speaker data-block's volume property, [[time_sec, linear], ...].
Reads from obj.data.animation_data (the Speaker data-block action, not the object action)."""
ad = getattr(obj.data, 'animation_data', None)
if ad is None or ad.action is None:
return []
slot_handle = getattr(getattr(ad, 'action_slot', None), 'handle', None)
keys = []
for fc in _slot_fcurves(ad.action, slot_handle):
if fc.data_path == 'volume':
for kp in fc.keyframe_points:
keys.append([kp.co.x / fps, float(kp.co.y)])
keys.sort(key=lambda k: k[0])
return keys
def _audio_schedule(output_file):
"""Collect spatial (Speaker + VSE) and non-spatial (VSE) audio cues.
Returns None when the scene has no audio to export.
VSE sound strips drive audio. A strip whose name matches a Speaker
object in the scene is treated as a spatial sound; the strip supplies the
timing while the Speaker object supplies the 3D properties (position,
volume, attenuation, cone). Multiple strips with the same name trigger
multiple clips on one emitter. Strips with no matching speaker are
non-spatial and each gets its own AudioStreamPlayer."""
scene = bpy.context.scene
fps = scene.render.fps * scene.render.fps_base
# Index Speaker objects by name
speakers = {obj.name: obj for obj in scene.objects if obj.type == 'SPEAKER'}
# Accumulate onsets per speaker name from VSE strips.
speaker_onsets: dict[str, list[float]] = {}
tracks = []
se = scene.sequence_editor
if se:
# Blender 5.x renamed sequences_all to strips_all
_all = se.strips_all if hasattr(se, 'strips_all') else se.sequences_all
for seq in sorted(_all, key=lambda s: s.frame_final_start):
if seq.type != 'SOUND' or getattr(seq, 'mute', False):
continue
if seq.sound is None:
continue
if _sound_missing(seq.sound):
warnings.warn(f"minigltf: VSE strip '{seq.name}' sound file is missing on disk; skipping")
continue
# Blender appends exactly .001/.002/.003 to keep VSE strip names
# unique. Strip that suffix before matching speaker object names.
base_name = re.sub(r'\.\d{3}$', '', seq.name)
sp_match = seq.name if seq.name in speakers else \
(base_name if base_name in speakers else None)
if sp_match:
speaker_onsets.setdefault(sp_match, []).append(
seq.frame_final_start / fps)
else:
tracks.append({
'name': seq.name,
'file': _sound_uri(seq.sound, output_file),
'onset': seq.frame_final_start / fps,
'stop': seq.frame_final_end / fps,
'src_offset': seq.animation_offset_start / fps,
'volume': seq.volume,
'pan': seq.pan,
})
emitters = []
for sp_name, onsets in speaker_onsets.items():
obj = speakers[sp_name]
sp = obj.data
if sp.sound is None:
warnings.warn(f"minigltf: speaker '{sp_name}' has VSE onset strips but no sound assigned; skipping")
continue
if _sound_missing(sp.sound):
warnings.warn(f"minigltf: speaker '{sp_name}' sound file is missing on disk; skipping")
continue
vol_keys = _speaker_volume_keys(obj, fps)
entry = {
'speaker': obj.name,
'file': _sound_uri(sp.sound, output_file),
'onsets': sorted(onsets),
'volume': sp.volume,
'attenuation': sp.attenuation,
'distance_reference': sp.distance_reference,
'distance_max': sp.distance_max,
'cone_angle_inner': sp.cone_angle_inner,
'cone_angle_outer': sp.cone_angle_outer,
'cone_volume_outer': sp.cone_volume_outer,
}
if vol_keys:
entry['volume_keys'] = vol_keys
emitters.append(entry)
if not emitters and not tracks:
return None
return {'emitters': emitters, 'tracks': tracks}
# Watts -> lumens, matching Blender's glTF exporter (SPEC mode). Used for both the
# static light intensity and its animation so the two stay consistent.
_WATTS_TO_LUMENS = 683.0
def _light_intensity(lt, energy: float) -> float:
"""glTF KHR_lights_punctual intensity for a Blender light energy value.
Sun lights are lux (energy passes through); others are candela."""
if lt.type == 'SUN':
return energy
return energy * _WATTS_TO_LUMENS / (4.0 * math.pi)
def _image_uri(img, output_file: str) -> str:
"""Return a URI for a texture, relative to the output GLB location.
For linked images the filepath is relative to the LIBRARY file, not the
current .blend - resolve via img.library when present.
"""
fp = img.filepath
if getattr(img, 'library', None):
lib_dir = os.path.dirname(bpy.path.abspath(img.library.filepath))
rel_fp = fp[2:] if fp.startswith('//') else fp
abs_tex = os.path.normpath(os.path.join(lib_dir, rel_fp))
else:
abs_tex = bpy.path.abspath(fp)
glb_dir = os.path.dirname(os.path.abspath(output_file))
try:
rel = os.path.relpath(abs_tex, glb_dir)
except ValueError:
# os.path.relpath raises ValueError on Windows when paths are on
# different drives - fall back to the absolute path.
rel = abs_tex
return rel.replace('\\', '/')
_ANCHOR_NAME = '__minigltf_AnimAnchor'
def _has_cutscene() -> bool:
# True when a schedule will be exported (markers or NLA strips).
sc = bpy.context.scene
if any(m.camera is not None for m in sc.timeline_markers):
return True
for o in sc.objects:
ad = getattr(o, 'animation_data', None)
if ad is not None and any(not t.mute and any(not s.mute and s.action is not None for s in t.strips) for t in ad.nla_tracks):
return True
return False
def _is_unedited_shell(obj, instanced_cols) -> bool:
# Unedited override mesh inside a live-linked collection (authoring shell).
if obj.type != 'MESH':
return False
ref = getattr(getattr(obj, 'override_library', None), 'reference', None)
data = getattr(obj, 'data', None)
if ref is None or data is None:
return False
if getattr(data, 'override_library', None) is not None:
return False
if getattr(data, 'library', None) is None:
return False
return any(ref == m for c in instanced_cols for m in c.objects)
def _has_edited_duplicate(col, objs) -> bool:
# True when an edited mesh override of this collection exports.
for m in col.objects:
if m.type != 'MESH':
continue
for ob in objs:
if not isinstance(ob, bpy.types.Object):
continue
ref = getattr(getattr(ob, 'override_library', None), 'reference', None)
data = getattr(ob, 'data', None)
if ref is not None and ref == m and data is not None \
and getattr(data, 'override_library', None) is not None:
return True
return False
def _rig_for_instance(inst_col, objs):
# Armature in objs backing a collection instance (direct or override).
for a in objs:
if not isinstance(a, bpy.types.Object) or a.type != 'ARMATURE':
continue
for m in inst_col.objects:
if a == m:
return a
ref = getattr(getattr(a, 'override_library', None), 'reference', None)
if ref is not None and ref == m:
return a
return None
def _uses_bone_anim(rig) -> bool:
# True when a local action keys one of the rig's bones.
names = {b.name for b in rig.data.bones}
if not names:
return False
for a in bpy.data.actions:
if getattr(a, 'library', None):
continue
for f in _action_fcurves(a):
if f.data_path.startswith('pose.bones["') and f.data_path.split('"')[1] in names:
return True
return False
def _has_skin(rig, objs) -> bool:
# True when a skinned mesh already drives this rig.
for m in objs:
if not isinstance(m, bpy.types.Object) or m.type != 'MESH':
continue
if any(md.type == 'ARMATURE' and md.object is rig for md in m.modifiers):
return True
return False
def _remove_stale_anchors():
# Drop orphan anchors left by a prior run.
for o in list(bpy.data.objects):
if o.name == _ANCHOR_NAME and not o.library and not list(o.users_collection):
md = o.data
bpy.data.objects.remove(o, do_unlink=True)
if md is not None and md.users == 0:
bpy.data.meshes.remove(md)
def _make_anchor(rig):
# Degenerate skinned triangle forcing a Skeleton3D; never visible.
names = sorted(b.name for b in rig.data.bones)
me = bpy.data.meshes.new(_ANCHOR_NAME)
me.from_pydata([(0, 0, 0)] * 3, [], [(0, 1, 2)])
me.update()
ob = bpy.data.objects.new(_ANCHOR_NAME, me)
ob.vertex_groups.new(name=names[0]).add([0, 1, 2], 1.0, 'REPLACE')
ob.modifiers.new('Armature', 'ARMATURE').object = rig
ob.parent = rig
return ob, me
def _clear_anchors(anchors):
# Remove temp anchors from the Blender session.
for ao, ame in anchors:
try:
bpy.data.objects.remove(ao, do_unlink=True)
if ame.users == 0:
bpy.data.meshes.remove(ame)
except Exception:
pass
def mini_export(output_file: str) -> None:
# If we're in Edit Mode, we have to switch to object mode first.
edited = []
for o in bpy.context.scene.objects:
if o.mode == 'EDIT':
edited.append(o)
bpy.context.view_layer.objects.active = o
bpy.ops.object.mode_set(mode='OBJECT')
axis_basis_change = mathutils.Matrix(
((1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, 1.0, 0.0),
(0.0, -1.0, 0.0, 0.0),
(0.0, 0.0, 0.0, 1.0)))
_basis_inv = axis_basis_change.inverted_safe()
_identity = mathutils.Matrix.Identity(4)
_t = time.perf_counter()
_scene_fps = bpy.context.scene.render.fps / bpy.context.scene.render.fps_base
if abs(_scene_fps - 30.0) > 1e-6:
print(f"[minigltf] WARNING: scene frame rate is {_scene_fps:g} fps; Godot imports "
f"animation baked at 30 fps, so keys off the 30 fps grid get resampled "
f"(set Blender's frame rate to 30)")
jsn = BytesIO()
jsn.write(b'{')
jsn.write(b'"asset":{"version":"2.0","generator":"minigltf"},\n')
# World flag: export_non_linked_only = True -> skip objects that come
# directly from a linked library (only local and override objects are kept).
_world = bpy.context.scene.world
_non_linked_only = bool(_world.get('export_non_linked_only', False)) if _world else False
# Linked objects that have a local override: always skip the original so we
# never export both the linked source and its override duplicate.
_overridden_originals = set()
for _o in bpy.context.scene.objects:
_ovlib = getattr(_o, 'override_library', None)
if _ovlib and getattr(_ovlib, 'reference', None):
_overridden_originals.add(_ovlib.reference)
_scene_objs = bpy.context.scene.objects
# Live-linked collections need no authoring-shell duplicates.
_instanced_cols = []
for _e in _scene_objs:
if _e.type == 'EMPTY' and getattr(_e, 'instance_type', None) == 'COLLECTION':
_c = _e.instance_collection
if _c is not None and getattr(_c, 'library', None) is not None:
_instanced_cols.append(_c)
objs = []
for _o in _scene_objs:
if _o.type not in ('MESH', 'ARMATURE', 'CAMERA', 'LIGHT', 'SPEAKER'):
continue
if _o in _overridden_originals:
continue
if _non_linked_only and _o.library is not None:
continue
if _is_unedited_shell(_o, _instanced_cols):
continue
objs.append(_o)
# Linked collection empties export as transform nodes with a link hint.
_collection_instances = []
for _o in _scene_objs:
if _o.type != 'EMPTY' or getattr(_o, 'instance_type', None) != 'COLLECTION':
continue
_col = _o.instance_collection
if _col is None or getattr(_col, 'library', None) is None:
continue
# Edited duplicates render instead; shells and bare rigs don't hide it.
if _has_edited_duplicate(_col, objs):
continue
_collection_instances.append(_o)
objs += _collection_instances
# Plain empties that parent exported objects become transform-only nodes,
# otherwise their children would lose the hierarchy (and the scene root).
_objs_set = set(objs)
for _o in list(objs):
_p = _o.parent
while _p is not None and _p not in _objs_set:
if (_p.type == 'EMPTY' and _p not in _overridden_originals
and not (_non_linked_only and _p.library is not None)
and not (getattr(_p, 'instance_type', None) == 'COLLECTION'
and getattr(_p.instance_collection, 'library', None) is not None)):
objs.append(_p)
_objs_set.add(_p)
_p = _p.parent
# Add bones only from armatures that passed the filter above.
_scene_armatures = set()
for _o in list(objs):
if _o.type == 'ARMATURE':
_scene_armatures.add(_o.data)
objs += list(_o.data.bones)
# Bone-only rigs in cutscenes get an anchor so grafts stay in bone space.
_has_schedule = _has_cutscene()
_remove_stale_anchors()
_anchors = []
for _o in [x for x in objs if isinstance(x, bpy.types.Object) and x.type == 'ARMATURE']:
if not _has_schedule or not _uses_bone_anim(_o) or _has_skin(_o, objs):
continue
_ao, _ame = _make_anchor(_o)
objs.append(_ao)
_anchors.append((_ao, _ame))
def _chain_world(_o):
_m = _o.matrix_parent_inverse @ _o.matrix_basis
return _chain_world(_o.parent) @ _m if _o.parent is not None else _o.matrix_basis
# Objects whose parent was not exported keep their world transform and
# become roots, so they are still reachable from the scene.
_objs_set = set(objs)
_orphans = {x for x in objs if isinstance(x, bpy.types.Object)
and x.parent is not None and x.parent not in _objs_set}
# Collection nodes mirror the collection hierarchy (nested included); each
# parentless object goes to its deepest direct home. Appended after real nodes.
_coll_pre = [] # [(collection, depth)] in pre-order
def _walk(_c, _depth):
_coll_pre.append((_c, _depth))
for _sub in _c.children:
_walk(_sub, _depth + 1)
for _top in bpy.context.scene.collection.children:
_walk(_top, 0)
_direct = {id(_c): set(_c.objects) for _c, _ in _coll_pre}
# Deepest directly-containing collection wins each parentless object.
_owner_of = {} # id(obj) -> collection
for _o in objs:
if not (isinstance(_o, bpy.types.Object) and (_o.parent is None or _o in _orphans)):
continue
_best_c, _best_d = None, -1
for _c, _d in _coll_pre:
if _o in _direct[id(_c)] and _d > _best_d:
_best_c, _best_d = _c, _d
if _best_c is not None:
_owner_of[id(_o)] = _best_c
_members_of = {id(_c): [] for _c, _ in _coll_pre}
_claimed = set()
for _o in objs: # objs order keeps member order deterministic
if id(_o) in _owner_of:
_members_of[id(_owner_of[id(_o)])].append(_o)
_claimed.add(_o)
# A collection is contentful with members or contentful children
# (reverse pre-order visits children before parents).
_contentful = set()
for _c, _d in reversed(_coll_pre):
if _members_of[id(_c)] or any(id(_s) in _contentful for _s in _c.children):
_contentful.add(id(_c))
_coll_nodes = [(_c, _members_of[id(_c)]) for _c, _ in _coll_pre
if id(_c) in _contentful]
world_matrix = {}
for a in _scene_objs:
if a.type != 'ARMATURE':
continue
armature = a.data
for b in armature.bones:
# Armature-space, NOT world: bone nodes are children of the armature
# node, which already carries the object's world transform.
world_matrix[b] = b.matrix_local
accessors = []
bufferViews = []
meshes = []
materials = []
images = []
skins = []
cameras = [] # bpy.types.Camera data-blocks, deduped; index == glTF camera index
lights = [] # bpy.types.Light data-blocks, deduped; index == KHR light index
_used_emissive_strength = False # set when any material exports KHR_materials_emissive_strength
joints_index = {}
for o in objs:
if not isinstance(o, bpy.types.Object):
continue
if o.type != 'MESH':
continue
for m in o.data.materials:
if m is not None and m not in materials:
materials.append(m)
timings['setup'] = time.perf_counter() - _t
# Bake matching keys into mismatched channel groups first, so the
# index-based reader below sees correct values (local actions only;
# linked ones belong to their own file's export).
for _a in bpy.data.actions:
if not getattr(_a, 'library', None):
_bake_mismatched(_a)
# Pre-scan to size the binary buffer accurately and avoid costly reallocs in
# Blender's allocator (observed 29x slowdown vs a single pre-allocated buffer).
_bin_size = 0
for _o in objs:
if not isinstance(_o, bpy.types.Object) or _o.type != 'MESH':
continue
_md = _o.data
_md.calc_loop_triangles()
if len(_md.loops) == 0:
continue
_nl = len(_md.loops); _nt = len(_md.loop_triangles)
_bin_size += _nl * (12 + 12 + 8) # pos + normal + uv0
if len(_md.uv_layers) > 1: _bin_size += _nl * 8 # uv1
_is_skinned = any(mod.type == 'ARMATURE' and mod.object for mod in _o.modifiers)
if _is_skinned: _bin_size += _nl * (8 + 16) # joints (uint16) + weights
_bin_size += _nt * 12 # indices
if _md.shape_keys and len(_md.shape_keys.key_blocks) > 1:
_bin_size += (len(_md.shape_keys.key_blocks) - 1) * _nl * 12
for _sk in [o for o in objs if isinstance(o, bpy.types.Object) and o.type == 'ARMATURE']:
_bin_size += len(_sk.data.bones) * 64 # inverse bind matrices
_local_actions = [_a for _a in bpy.data.actions if not getattr(_a, 'library', None)]
for _a in _local_actions:
for _f in _action_fcurves(_a):
_bin_size += len(_f.keyframe_points) * 32 # anim samples (rough)
bchunk = _BinWriter(_bin_size + 65536)
_t = time.perf_counter()
# Cutscene schedule (NLA timeline) and audio schedule - stored together in a
# synthetic CutsceneData node appended after the real nodes; must be known
# before the nodes section is streamed.
# Clip naming is resolved once here and shared by the schedule, the animation
# writer and the Godot addon. glTF animations live in one flat, name-keyed
# list (Godot renames duplicates on import), so each exported clip gets a