-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglb_exporter.py
More file actions
1823 lines (1641 loc) · 85.2 KB
/
glb_exporter.py
File metadata and controls
1823 lines (1641 loc) · 85.2 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
import maya.cmds as cmds
import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
import os, struct, sys, subprocess, io, json, math, re, threading
# ---------------------------------------------------------------------------
# Drive detection + paths
# ---------------------------------------------------------------------------
LIB_PATH = ""
DEFAULT_EXPORT_DIR = ""
SETTINGS_DIR = ""
SETTINGS_FILE = ""
PRESETS_FILE = ""
ACTIVE_DRIVE = ""
def _setup_paths(drive):
global LIB_PATH, DEFAULT_EXPORT_DIR, SETTINGS_DIR, SETTINGS_FILE, PRESETS_FILE, ACTIVE_DRIVE
drive = drive.rstrip("/\\")
if not drive.endswith(":"): drive += ":"
ACTIVE_DRIVE = drive
LIB_PATH = drive + "/MayaGLB/PythonPlugins"
DEFAULT_EXPORT_DIR = drive + "/MayaGLB/Exports"
SETTINGS_DIR = drive + "/MayaGLB/Settings"
SETTINGS_FILE = SETTINGS_DIR + "/exporter_settings.json"
PRESETS_FILE = SETTINGS_DIR + "/exporter_presets.json"
for p in [LIB_PATH, DEFAULT_EXPORT_DIR, SETTINGS_DIR]:
if not os.path.exists(p):
try: os.makedirs(p)
except: pass
if LIB_PATH not in sys.path:
sys.path.insert(0, LIB_PATH)
print(f"[GLB] Drive: {drive} LIB: {LIB_PATH} EXPORT: {DEFAULT_EXPORT_DIR}")
def _find_mayaglb_drive():
for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
candidate = letter + ":/MayaGLB"
if os.path.isdir(candidate):
print(f"[GLB] Found existing MayaGLB folder on {letter}:")
return letter + ":"
return None
def _show_drive_picker():
_win = "GLB_DriveSelector"
if cmds.window(_win, exists=True): cmds.deleteUI(_win)
cmds.window(_win, title="Select MayaGLB Drive", w=370, sizeable=False)
cmds.columnLayout(adj=True, rs=8, co=["both", 16])
cmds.text(l="")
cmds.text(l="No MayaGLB folder found on any drive.", fn="boldLabelFont", al="left")
cmds.text(l="Enter the drive letter where MayaGLB should live:", fn="smallPlainLabelFont", al="left")
cmds.text(l="(The folder will be created automatically.)", fn="smallPlainLabelFont", al="left")
field = cmds.textFieldGrp(l="Drive letter:", text="N", cw2=[100, 60])
warn = cmds.text(l="", fn="smallPlainLabelFont", al="left")
def _on_confirm(*a):
letter = cmds.textFieldGrp(field, q=True, text=True).strip().upper()
letter = letter.rstrip("/\\:").strip()
if not letter or len(letter) != 1 or not letter.isalpha():
cmds.text(warn, e=True, l=" Enter a single drive letter (e.g. N)."); return
drive = letter + ":"
if not os.path.exists(drive + "/"):
cmds.text(warn, e=True, l=f" {drive}\\ not found — check and try again."); return
cmds.deleteUI(_win)
_setup_paths(drive)
_boot()
def _on_cancel(*a):
cmds.deleteUI(_win)
print("[GLB] Drive picker cancelled.")
cmds.rowLayout(nc=2, cw2=[155, 155])
cmds.button(l="Confirm", w=145, bgc=(0.18, 0.42, 0.78), c=_on_confirm)
cmds.button(l="Cancel", w=145, c=_on_cancel)
cmds.setParent("..")
cmds.text(l="")
cmds.setParent("..")
cmds.showWindow(_win)
_found_drive = _find_mayaglb_drive()
if _found_drive:
_setup_paths(_found_drive)
else:
print("[GLB] No existing MayaGLB folder found — showing drive picker.")
_show_drive_picker()
# ---------------------------------------------------------------------------
# Auto shelf button installer
# ---------------------------------------------------------------------------
_GLB_SHELF_NAME = "MayaGLB Exporter" # dedicated shelf — no ambiguity
def _install_shelf_button():
cmd_str = (
"python(\"import urllib.request as r; "
"exec(compile(r.urlopen("
"'https://raw.githubusercontent.com/CodeByCon/MayaGLB/main/glb_exporter.py'"
").read(),'<glb>','exec'))\")"
)
def _do_install():
try:
import maya.mel as mel
top = mel.eval('$tmp = $gShelfTopLevel')
# Create our shelf if it doesn't exist yet
if not cmds.shelfLayout(_GLB_SHELF_NAME, exists=True):
cmds.shelfLayout(_GLB_SHELF_NAME, parent=top)
print(f"[GLB] Created shelf: {_GLB_SHELF_NAME}")
# Skip if the button already exists on our shelf
for btn in (cmds.shelfLayout(_GLB_SHELF_NAME, q=True, childArray=True) or []):
try:
if cmds.shelfButton(btn, q=True, exists=True):
lbl = cmds.shelfButton(btn, q=True, label=True) or ""
if "GLB" in lbl:
print(f"[GLB] Shelf button already exists — skipping.")
return
except: pass
cmds.shelfButton(
parent=_GLB_SHELF_NAME,
label="Export as GLB",
annotation="Open Ultimate GLB Exporter v2.0",
image="out_mesh.png",
imageOverlayLabel="GLB",
overlayLabelColor=(0.2, 0.9, 0.4),
overlayLabelBackColor=(0, 0, 0, 0.4),
style="iconAndTextCentered",
command=cmd_str,
sourceType="mel",
)
# Write shelf file to disk immediately so it persists across restarts
mel.eval('saveAllShelves $gShelfTopLevel')
print(f"[GLB] Shelf button installed and saved on '{_GLB_SHELF_NAME}' shelf.")
except Exception as e:
import traceback
print(f"[GLB] Shelf button install warning: {e}")
traceback.print_exc()
try:
cmds.evalDeferred(_do_install)
except Exception as e:
print(f"[GLB] Shelf button evalDeferred failed: {e}")
# ---------------------------------------------------------------------------
# Settings save / load
# ---------------------------------------------------------------------------
# FIX 1: "yup" → True, "unit_scale" → 0.01
_SETTINGS_DEFAULTS = {
# Transform
"yup": False,
"unit_scale": 1.0,
# Mesh
"export_uvs": True,
"uv_set_count": 1,
"export_norms": True,
"flip_norms": False,
"export_vcs": False,
"double_sided": True,
"fix_nm": True,
"apply_trs": False,
"merge_verts": False,
"merge_thresh": 0.001,
# Morph / blend shapes
"export_morphs": False,
# LOD
"export_lod": False,
"lod_mode": "name", # "name" | "manual"
"lod_levels": 4,
# Collision
"tag_collision": True,
# Skeleton / anim
"export_skel": False,
"export_anim": False,
"anim_interp": "LINEAR",
# Texture
"export_imgs": True,
"tex_jpeg": False,
"tex_res": "No limit",
"tex_srgb": True,
# Material
"export_mats": True,
"unlit": False,
"alpha_mode": "OPAQUE",
"alpha_cutoff": 0.5,
"orm_mode": "make_orm",
"export_emissive": False,
# Thumbnail
"export_thumb": False,
# Export mode
"export_mode": 1,
"export_path": "",
}
def save_settings(data):
if not SETTINGS_FILE:
print("[GLB] Settings path not initialised — skipping save."); return
try:
with open(SETTINGS_FILE, 'w') as f: json.dump(data, f, indent=2)
print(f"[GLB] Settings saved → {SETTINGS_FILE}")
except Exception as e:
print(f"[GLB] Could not save settings: {e}")
def load_settings():
s = dict(_SETTINGS_DEFAULTS)
if not SETTINGS_FILE or not os.path.exists(SETTINGS_FILE): return s
try:
with open(SETTINGS_FILE, 'r') as f: saved = json.load(f)
s.update({k: v for k, v in saved.items() if k in s})
print(f"[GLB] Settings loaded ← {SETTINGS_FILE}")
except Exception as e:
print(f"[GLB] Could not load settings: {e}")
return s
# ---------------------------------------------------------------------------
# Presets save / load / delete
# ---------------------------------------------------------------------------
def load_presets():
"""Return dict of {preset_name: settings_dict}."""
if not PRESETS_FILE or not os.path.exists(PRESETS_FILE): return {}
try:
with open(PRESETS_FILE, 'r') as f: return json.load(f)
except: return {}
def save_preset(name, data):
presets = load_presets()
presets[name] = data
try:
with open(PRESETS_FILE, 'w') as f: json.dump(presets, f, indent=2)
print(f"[GLB] Preset saved: {name}")
except Exception as e:
print(f"[GLB] Could not save preset: {e}")
def delete_preset(name):
presets = load_presets()
if name in presets:
del presets[name]
try:
with open(PRESETS_FILE, 'w') as f: json.dump(presets, f, indent=2)
print(f"[GLB] Preset deleted: {name}")
except: pass
# ---------------------------------------------------------------------------
# glTF constants
# ---------------------------------------------------------------------------
FLOAT = 5126
UNSIGNED_INT = 5125
UNSIGNED_SHORT = 5123
ARRAY_BUFFER = 34962
ELEMENT_ARRAY_BUFFER = 34963
PILLOW_OK = False
Image = None
# ---------------------------------------------------------------------------
# Utilities
# ---------------------------------------------------------------------------
def _make_file_friendly(name):
name = name.split('|')[-1]
name = name.split(':')[-1]
name = re.sub(r'[^\w\-]', '_', name)
name = re.sub(r'_+', '_', name)
return name.strip('_') or "Mesh"
def _show_error_popup(title, message):
win_id = "GLB_ErrorPopup"
if cmds.window(win_id, exists=True): cmds.deleteUI(win_id)
longest = max((len(line) for line in message.splitlines()), default=len(message))
win_w = max(360, min(longest * 7 + 60, 680))
txt_w = win_w - 28
cmds.window(win_id, title=title, w=win_w, sizeable=False, toolbox=True)
cmds.columnLayout(adj=False, w=win_w, rs=5, co=["both", 14])
cmds.text(l="")
cmds.text(l=f" \u2718 {title}", fn="boldLabelFont", al="left",
w=txt_w, bgc=(0.45, 0.12, 0.12))
cmds.separator(h=5, style='in', w=txt_w)
for line in message.splitlines():
cmds.text(l=f" {line}", fn="smallPlainLabelFont", al="left", w=txt_w)
cmds.text(l="")
cmds.button(l="OK", h=28, w=txt_w, bgc=(0.35, 0.35, 0.35),
c=lambda *a: cmds.deleteUI(win_id))
cmds.text(l="")
cmds.setParent("..")
cmds.showWindow(win_id)
def _show_success_popup(mesh_name, export_path):
win_id = "GLB_SuccessPopup"
if cmds.window(win_id, exists=True): cmds.deleteUI(win_id)
basename = os.path.basename(export_path)
cmds.window(win_id, title="Export Successful", w=400, sizeable=False, toolbox=True)
cmds.columnLayout(adj=True, rs=6, co=["both", 14])
cmds.text(l="")
cmds.text(l=" ✔ Export Successful", fn="boldLabelFont", al="left", bgc=(0.10, 0.38, 0.18))
cmds.separator(h=6, style='in')
cmds.text(l=f" Mesh: {mesh_name}", fn="smallPlainLabelFont", al="left")
cmds.text(l=f" File: {basename}", fn="smallPlainLabelFont", al="left")
cmds.text(l="")
cmds.button(l="OK", h=28, bgc=(0.35, 0.35, 0.35),
c=lambda *a: cmds.deleteUI(win_id))
cmds.text(l="")
cmds.setParent("..")
cmds.showWindow(win_id)
# ---------------------------------------------------------------------------
# Pillow installer
# ---------------------------------------------------------------------------
def _cleanup_pip_artifacts(lib_path):
import shutil
removed = []
for item in os.listdir(lib_path):
full = os.path.join(lib_path, item)
if (item.endswith('.dist-info') or item.endswith('.data') or
item in ('bin', 'scripts', 'Scripts', '__pycache__')):
try:
shutil.rmtree(full) if os.path.isdir(full) else os.remove(full)
removed.append(item)
except Exception as e:
print(f"[GLB] Cleanup warning: {e}")
if removed: print(f"[GLB] Cleaned up: {', '.join(removed)}")
def ensure_libraries(lib_path):
if lib_path and lib_path not in sys.path:
sys.path.insert(0, lib_path)
try:
from PIL import Image
print("[GLB] Pillow already installed — ready.")
return True
except ImportError:
print(f"[GLB] Pillow not found — installing to {lib_path} ...")
try:
import maya.mel as mel
main_pb = mel.eval('$tmp = $gMainProgressBar')
cmds.progressBar(main_pb, edit=True, beginProgress=True,
isInterruptable=False,
status=f'Installing Pillow to {lib_path} ...',
maxValue=100)
except: main_pb = None
try:
_maya_bin = os.path.dirname(sys.executable)
_candidates = [
os.path.join(_maya_bin, "mayapy.exe"),
os.path.join(_maya_bin, "mayapy"),
os.path.join(_maya_bin, "python.exe"),
os.path.join(_maya_bin, "python"),
]
_python_exe = next((c for c in _candidates if os.path.exists(c)), None)
if _python_exe is None: return False
result = subprocess.run(
[_python_exe, "-m", "pip", "install", "--target", lib_path, "Pillow"],
capture_output=True, text=True)
if result.returncode == 0:
print("[GLB] Pillow installed!")
if lib_path not in sys.path: sys.path.insert(0, lib_path)
import importlib; importlib.invalidate_caches()
_cleanup_pip_artifacts(lib_path)
return True
else:
print(f"[GLB] Pillow install FAILED:\n{result.stderr}"); return False
except Exception as e:
print(f"[GLB] Pillow install EXCEPTION: {e}"); return False
finally:
try:
if main_pb: cmds.progressBar(main_pb, edit=True, endProgress=True)
except: pass
# ---------------------------------------------------------------------------
# GLB packer
# ---------------------------------------------------------------------------
def _pad4(data, pad_byte=b'\x00'):
r = len(data) % 4
return data + pad_byte * ((4 - r) % 4)
def pack_glb(gltf_dict, bin_blob):
json_bytes = _pad4(json.dumps(gltf_dict, separators=(',', ':')).encode('utf-8'), b' ')
bin_blob = _pad4(bin_blob)
json_chunk = struct.pack('<II', len(json_bytes), 0x4E4F534A) + json_bytes
bin_chunk = struct.pack('<II', len(bin_blob), 0x004E4942) + bin_blob
header = struct.pack('<III', 0x46546C67, 2, 12 + len(json_chunk) + len(bin_chunk))
return header + json_chunk + bin_chunk
# ---------------------------------------------------------------------------
# Non-manifold helpers
# ---------------------------------------------------------------------------
def check_non_manifold(mesh_transform):
shape = (cmds.listRelatives(mesh_transform, shapes=True, type='mesh') or [None])[0]
if not shape: return [], []
nm_e = cmds.polyInfo(shape, nonManifoldEdges=True) or []
nm_v = cmds.polyInfo(shape, nonManifoldVertices=True) or []
return nm_e, nm_v
def fix_non_manifold(mesh_transform):
cmds.polyClean(mesh_transform, cleanEdges=1, cleanVertices=1, constructionHistory=False)
print(f"[GLB] Non-manifold cleaned: {mesh_transform}")
# ---------------------------------------------------------------------------
# Collision mesh detection
# ---------------------------------------------------------------------------
_COLLISION_PREFIXES = ("UCX_", "UBX_", "USP_", "UCP_")
_COLLISION_TYPE_MAP = {
"UCX_": "convex",
"UBX_": "box",
"USP_": "sphere",
"UCP_": "capsule",
}
def _is_collision_mesh(name):
short = name.split('|')[-1].split(':')[-1]
for p in _COLLISION_PREFIXES:
if short.upper().startswith(p):
return True, _COLLISION_TYPE_MAP[p], short[len(p):]
return False, None, None
# ---------------------------------------------------------------------------
# ORM helpers
# ---------------------------------------------------------------------------
def pack_orm_textures(o_path, r_path, m_path):
ref_size = (1024, 1024)
for p in [o_path, r_path, m_path]:
if p and os.path.exists(p):
ref_size = Image.open(p).size; break
def ch(path, default):
if path and os.path.exists(path):
return Image.open(path).convert('L').resize(ref_size, Image.LANCZOS)
return Image.new('L', ref_size, default)
return Image.merge('RGB', (ch(o_path, 255), ch(r_path, 128), ch(m_path, 0)))
# ---------------------------------------------------------------------------
# Thumbnail capture
# ---------------------------------------------------------------------------
def capture_thumbnail(export_path, size=256):
thumb_path = os.path.splitext(export_path)[0] + "_thumb.png"
try:
cmds.playblast(
frame=[cmds.currentTime(q=True)],
format="image",
completeFilename=thumb_path,
compression="png",
widthHeight=[size, size],
percent=100,
viewer=False,
showOrnaments=False,
offScreen=True,
)
print(f"[GLB] Thumbnail saved: {thumb_path}")
if os.path.exists(thumb_path) and Image:
return Image.open(thumb_path).convert("RGBA"), thumb_path
except Exception as e:
print(f"[GLB] Thumbnail capture failed: {e}")
return None, None
# ---------------------------------------------------------------------------
# Shader reader
# ---------------------------------------------------------------------------
def get_shader_data_for_sg(sg_name):
data = {
'color_path': None, 'normal_path': None,
'occlusion_path':None, 'roughness_path':None, 'metallic_path': None,
'emissive_path': None,
'factor': [1.0, 1.0, 1.0, 1.0],
'metallic_val': 0.0, 'roughness_val': 0.5,
'emissive_factor':[0.0, 0.0, 0.0],
}
try:
shader_conn = cmds.listConnections(sg_name + ".surfaceShader") or []
if not shader_conn: return data
shader = shader_conn[0]
print(f"[GLB] Shader: '{shader}' type={cmds.nodeType(shader)}")
for attr in ["baseColor", "color", "diffuseColor", "base_color"]:
if not cmds.attributeQuery(attr, n=shader, ex=True): continue
full = shader + "." + attr
fn = cmds.listConnections(full, type='file') or []
if fn:
data['color_path'] = cmds.getAttr(fn[0] + ".fileTextureName")
else:
try:
raw = cmds.getAttr(full)
if isinstance(raw, (list, tuple)):
flat = raw[0] if isinstance(raw[0], (list, tuple)) else raw
r = float(flat[0]) if len(flat) > 0 else 1.0
g = float(flat[1]) if len(flat) > 1 else 1.0
b = float(flat[2]) if len(flat) > 2 else 1.0
else:
r = g = b = 1.0
data['factor'] = [
min(max(r, 0.0), 1.0),
min(max(g, 0.0), 1.0),
min(max(b, 0.0), 1.0), 1.0]
except Exception as ce:
print(f"[GLB] Could not read colour factor: {ce}")
break
for attr in ["normalCamera", "normalMap", "normal"]:
if not cmds.attributeQuery(attr, n=shader, ex=True): continue
upstream = cmds.listConnections(shader + "." + attr, source=True, destination=False) or []
for node in upstream:
node_type = cmds.nodeType(node)
if node_type == 'aiNormalMap':
nf = cmds.listConnections(node + ".input", type='file') or []
if nf: data['normal_path'] = cmds.getAttr(nf[0] + ".fileTextureName"); break
elif node_type == 'bump2d':
nf = cmds.listConnections(node + ".bumpValue", type='file') or []
if nf: data['normal_path'] = cmds.getAttr(nf[0] + ".fileTextureName"); break
elif node_type == 'file':
data['normal_path'] = cmds.getAttr(node + ".fileTextureName"); break
if data['normal_path']: break
for attr in ["specularRoughness", "roughness"]:
if not cmds.attributeQuery(attr, n=shader, ex=True): continue
f2 = cmds.listConnections(shader + "." + attr, type='file') or []
if f2:
data['roughness_path'] = cmds.getAttr(f2[0] + ".fileTextureName")
print(f"[GLB] Roughness: {data['roughness_path']}"); break
else:
try: data['roughness_val'] = float(cmds.getAttr(shader + "." + attr))
except: pass
for attr in ["metalness", "metallic"]:
if not cmds.attributeQuery(attr, n=shader, ex=True): continue
f2 = cmds.listConnections(shader + "." + attr, type='file') or []
if f2:
data['metallic_path'] = cmds.getAttr(f2[0] + ".fileTextureName")
print(f"[GLB] Metallic: {data['metallic_path']}"); break
else:
try: data['metallic_val'] = float(cmds.getAttr(shader + "." + attr))
except: pass
for attr in ["ambientOcclusion", "occlusion", "ao"]:
if not cmds.attributeQuery(attr, n=shader, ex=True): continue
f2 = cmds.listConnections(shader + "." + attr, type='file') or []
if f2:
data['occlusion_path'] = cmds.getAttr(f2[0] + ".fileTextureName")
print(f"[GLB] Occlusion: {data['occlusion_path']}"); break
for attr in ["emissionColor", "emissiveColor", "emission", "incandescence"]:
if not cmds.attributeQuery(attr, n=shader, ex=True): continue
full = shader + "." + attr
f2 = cmds.listConnections(full, type='file') or []
if f2:
data['emissive_path'] = cmds.getAttr(f2[0] + ".fileTextureName")
data['emissive_factor'] = [1.0, 1.0, 1.0]
print(f"[GLB] Emissive: {data['emissive_path']}")
else:
try:
raw = cmds.getAttr(full)
if isinstance(raw, (list, tuple)):
flat = raw[0] if isinstance(raw[0], (list, tuple)) else raw
er = float(flat[0]) if len(flat) > 0 else 0.0
eg = float(flat[1]) if len(flat) > 1 else 0.0
eb = float(flat[2]) if len(flat) > 2 else 0.0
data['emissive_factor'] = [er, eg, eb]
except: pass
break
except Exception as e:
import traceback
print(f"[GLB] get_shader_data_for_sg ERROR: {e}"); traceback.print_exc()
return data
# ---------------------------------------------------------------------------
# Blend shape / morph target extraction
# ---------------------------------------------------------------------------
def get_blend_shapes(mesh_transform):
shape = (cmds.listRelatives(mesh_transform, shapes=True, type='mesh') or [None])[0]
if not shape: return []
blend_nodes = []
for node in (cmds.listHistory(shape) or []):
if cmds.nodeType(node) == 'blendShape':
blend_nodes.append(node)
if not blend_nodes: return []
sel = om.MSelectionList(); sel.add(mesh_transform)
dag = sel.getDagPath(0)
base_fn = om.MFnMesh(dag)
base_pts = base_fn.getPoints(om.MSpace.kObject)
num_verts = base_fn.numVertices
targets = []
for bs_node in blend_nodes:
aliases = cmds.aliasAttr(bs_node, q=True) or []
pairs = [(aliases[i], aliases[i+1]) for i in range(0, len(aliases)-1, 2)]
for alias, attr_name in pairs:
if not alias: continue
idx_match = re.search(r'\[(\d+)\]', attr_name)
if not idx_match: continue
t_idx = int(idx_match.group(1))
try:
old_val = cmds.getAttr(f"{bs_node}.{alias}")
for a2, _ in pairs:
try: cmds.setAttr(f"{bs_node}.{a2}", 0.0)
except: pass
cmds.setAttr(f"{bs_node}.{alias}", 1.0)
cmds.dgeval(shape)
target_fn = om.MFnMesh(dag)
target_pts = target_fn.getPoints(om.MSpace.kObject)
deltas = []
for vi in range(num_verts):
bp = base_pts[vi]; tp = target_pts[vi]
deltas.append((tp.x - bp.x, tp.y - bp.y, tp.z - bp.z))
targets.append({'name': alias, 'deltas': deltas})
for a2, _ in pairs:
try: cmds.setAttr(f"{bs_node}.{a2}", 0.0)
except: pass
cmds.setAttr(f"{bs_node}.{alias}", old_val)
cmds.dgeval(shape)
print(f"[GLB] Morph target captured: {alias}")
except Exception as e:
print(f"[GLB] Morph target '{alias}' failed: {e}")
return targets
# ---------------------------------------------------------------------------
# LOD helpers
# ---------------------------------------------------------------------------
_LOD_SUFFIXES = ["_LOD0","_LOD1","_LOD2","_LOD3","_LOD4",
"_lod0","_lod1","_lod2","_lod3","_lod4",
"LOD0","LOD1","LOD2","LOD3","LOD4"]
def find_lod_meshes(mesh_transform):
base = mesh_transform.split('|')[-1].split(':')[-1]
root = base
for suf in _LOD_SUFFIXES:
if base.upper().endswith(suf.upper()):
root = base[:-len(suf)]; break
lod_list = [(0, mesh_transform)]
for level in range(1, 5):
for pattern in [f"{root}_LOD{level}", f"{root}_lod{level}",
f"{root}LOD{level}", f"{root}lod{level}"]:
found = cmds.ls(pattern, type='transform')
if found and cmds.listRelatives(found[0], shapes=True, type='mesh'):
lod_list.append((level, found[0])); break
return sorted(lod_list, key=lambda x: x[0])
# ---------------------------------------------------------------------------
# Per-face-material geometry extraction (multi-UV)
# ---------------------------------------------------------------------------
def extract_geometry_by_material(mesh_transform, unit_scale=1.0, uv_set_count=1):
shape = (cmds.listRelatives(mesh_transform, shapes=True, type='mesh') or [None])[0]
if not shape: return []
sel_list = om.MSelectionList()
sel_list.add(mesh_transform.split('|')[-1])
dag_path = sel_list.getDagPath(0)
m_fn = om.MFnMesh(dag_path)
face_to_sg = {}
sg_order = []
shaders_mobjs, face_shader_idx = m_fn.getConnectedShaders(0)
sg_names = []
for mob in shaders_mobjs:
fn = om.MFnDependencyNode(mob)
name = fn.name()
sg_names.append(name)
if name not in sg_order: sg_order.append(name)
for fi, si in enumerate(face_shader_idx):
sg = sg_names[si] if 0 <= si < len(sg_names) else (sg_names[0] if sg_names else None)
if sg: face_to_sg[fi] = sg
sgs = sg_order if sg_order else (cmds.listConnections(shape, type='shadingEngine') or [])
if not sgs: return []
for fi in range(m_fn.numPolygons):
if fi not in face_to_sg: face_to_sg[fi] = sgs[0]
raw_pts = m_fn.getPoints(om.MSpace.kWorld)
raw_nrms = m_fn.getNormals(om.MSpace.kWorld)
fv_counts, fv_verts = m_fn.getVertices()
_, fv_nrm_ids = m_fn.getNormalIds()
tri_counts, tri_vis = m_fn.getTriangles()
all_uv_set_names = m_fn.getUVSetNames()
uv_sets_to_export = all_uv_set_names[:max(1, min(uv_set_count, 4, len(all_uv_set_names)))]
uv_data = {}
for uv_set in uv_sets_to_export:
try:
u_arr, v_arr = m_fn.getUVs(uv_set)
_, fv_uv_ids = m_fn.getAssignedUVs(uv_set)
uv_data[uv_set] = (u_arr, v_arr, fv_uv_ids)
except Exception as e:
print(f"[GLB] UV set '{uv_set}' read error: {e}")
primary_uv_set = uv_sets_to_export[0] if uv_sets_to_export else None
_, primary_fv_uv_ids = (m_fn.getAssignedUVs(primary_uv_set)
if primary_uv_set else (None, []))
sg_geom = {sg: {
'positions': [], 'normals': [], 'indices': [],
'vert_ids': [], 'next_idx': 0,
'uvs': {uv: [] for uv in uv_sets_to_export},
} for sg in sgs}
fv_off = tri_off = 0
for fi in range(m_fn.numPolygons):
fvc = fv_counts[fi]
face_verts = [fv_verts[fv_off+lv] for lv in range(fvc)]
ntris = tri_counts[fi]
sg = face_to_sg.get(fi, sgs[0])
g = sg_geom[sg]
for t in range(ntris):
for v in range(3):
gvi = tri_vis[tri_off + t*3 + v]
try: lv = face_verts.index(gvi)
except: lv = 0
fvi = fv_off + lv
rp = raw_pts[gvi]
g['positions'].append((rp.x * unit_scale, rp.y * unit_scale, rp.z * unit_scale))
rn = raw_nrms[fv_nrm_ids[fvi]]
g['normals'].append((rn.x, rn.y, rn.z))
g['indices'].append(g['next_idx'])
g['vert_ids'].append(gvi)
g['next_idx'] += 1
for uv_set in uv_sets_to_export:
if uv_set in uv_data:
u_arr, v_arr, fv_uv_ids = uv_data[uv_set]
ui = fv_uv_ids[fvi] if fvi < len(fv_uv_ids) else -1
g['uvs'][uv_set].append(
(u_arr[ui], 1.0 - v_arr[ui]) if ui >= 0 else (0.0, 0.0))
fv_off += fvc
tri_off += ntris * 3
return [{'sg': sg,
'positions': sg_geom[sg]['positions'],
'normals': sg_geom[sg]['normals'],
'uvs': sg_geom[sg]['uvs'],
'uv_sets': uv_sets_to_export,
'indices': sg_geom[sg]['indices'],
'vert_ids': sg_geom[sg]['vert_ids']}
for sg in sgs if sg_geom[sg]['positions']]
# ---------------------------------------------------------------------------
# Skeleton helpers
# ---------------------------------------------------------------------------
def collect_joint_hierarchy(root_joint):
joints = []
def _walk(j):
joints.append(j)
for child in (cmds.listRelatives(j, children=True, type='joint') or []):
_walk(child)
_walk(root_joint)
return joints
def get_skin_cluster(mesh_transform):
shape = (cmds.listRelatives(mesh_transform, shapes=True, type='mesh') or [None])[0]
if not shape: return None
for node in (cmds.listHistory(shape) or []):
if cmds.nodeType(node) == 'skinCluster': return node
return None
def _mat4_col_major(mm):
return [mm[r*4+c] for c in range(4) for r in range(4)]
def get_inverse_bind_matrices(joints, unit_scale, yup):
ibms = []
for j in joints:
sel = om.MSelectionList(); sel.add(j)
dag = sel.getDagPath(0)
mm = dag.inclusiveMatrix()
mm.setElement(0, 3, mm.getElement(0, 3) * unit_scale)
mm.setElement(1, 3, mm.getElement(1, 3) * unit_scale)
mm.setElement(2, 3, mm.getElement(2, 3) * unit_scale)
if yup:
for c in range(4):
y = mm.getElement(1, c); z = mm.getElement(2, c)
mm.setElement(1, c, z); mm.setElement(2, c, -y)
for r in range(4):
y = mm.getElement(r, 1); z = mm.getElement(r, 2)
mm.setElement(r, 1, z); mm.setElement(r, 2, -y)
ibms.append(_mat4_col_major(mm.inverse()))
return ibms
def extract_skin_weights(skin_cluster, mesh_transform, joints):
shape = cmds.listRelatives(mesh_transform, shapes=True, type='mesh')[0]
joint_idx = {j: i for i, j in enumerate(joints)}
num_verts = cmds.polyEvaluate(mesh_transform, vertex=True)
all_j = []; all_w = []
for vi in range(num_verts):
comp = f"{shape}.vtx[{vi}]"
raw_jnts = cmds.skinPercent(skin_cluster, comp, query=True, transform=None) or []
raw_wts = cmds.skinPercent(skin_cluster, comp, query=True, value=True) or []
pairs = sorted(zip(raw_wts, raw_jnts), reverse=True)[:4]
while len(pairs) < 4: pairs.append((0.0, joints[0]))
total = sum(p[0] for p in pairs) or 1.0
all_j.append([joint_idx.get(p[1], 0) for p in pairs])
all_w.append([p[0] / total for p in pairs])
return all_j, all_w
def get_fps():
fps_map = {
'film':24,'ntsc':30,'pal':25,'game':15,'show':48,'palf':50,
'ntscf':60,'23.976fps':23.976,'29.97fps':29.97,'59.94fps':59.94,
'48fps':48,'72fps':72,'2fps':2,'3fps':3,'4fps':4,'5fps':5,
'6fps':6,'8fps':8,'10fps':10,'12fps':12,'16fps':16,
}
return fps_map.get(cmds.currentUnit(q=True, time=True), 24.0)
def extract_animation(joints, unit_scale, yup):
start = int(cmds.playbackOptions(q=True, minTime=True))
end = int(cmds.playbackOptions(q=True, maxTime=True))
fps = get_fps()
times = [(f - start) / fps for f in range(start, end+1)]
current_frame = cmds.currentTime(q=True)
anim = {j: {'T':[], 'R':[], 'S':[]} for j in joints}
for frame in range(start, end+1):
cmds.currentTime(frame, update=True)
for j in joints:
sel = om.MSelectionList(); sel.add(j)
xfm = om.MFnTransform(sel.getDagPath(0))
t = xfm.translation(om.MSpace.kTransform)
r = xfm.rotation(om.MSpace.kTransform, asQuaternion=True)
s = xfm.scale()
tx, ty, tz = t.x*unit_scale, t.y*unit_scale, t.z*unit_scale
if yup:
tx, ty, tz = tx, tz, -ty
qx, qy, qz, qw = r.x, r.z, -r.y, r.w
else:
qx, qy, qz, qw = r.x, r.y, r.z, r.w
anim[j]['T'].append((tx, ty, tz))
anim[j]['R'].append((qx, qy, qz, qw))
anim[j]['S'].append((s[0], s[1], s[2]))
cmds.currentTime(current_frame, update=True)
return times, anim
# ---------------------------------------------------------------------------
# Core GLB builder v2.0
# ---------------------------------------------------------------------------
def build_glb(mesh_list, opts=None):
if opts is None: opts = {}
orm_mode = opts.get('orm_mode', 'make_orm')
yup = opts.get('yup', False)
unit_scale = opts.get('unit_scale', 1.0)
export_uvs = opts.get('export_uvs', True)
uv_set_count = opts.get('uv_set_count', 1)
export_norms = opts.get('export_norms', True)
flip_norms = opts.get('flip_norms', False)
export_vcs = opts.get('export_vcs', False)
double_sided = opts.get('double_sided', True)
apply_trs = opts.get('apply_trs', False)
merge_verts = opts.get('merge_verts', False)
merge_thresh = opts.get('merge_thresh', 0.001)
export_mats = opts.get('export_mats', True)
export_imgs = opts.get('export_imgs', True)
tex_jpeg = opts.get('tex_jpeg', False)
max_tex_size = opts.get('max_tex_size', None)
unlit = opts.get('unlit', False)
alpha_mode = opts.get('alpha_mode', 'OPAQUE')
alpha_cutoff = opts.get('alpha_cutoff', 0.5)
anim_interp = opts.get('anim_interp', 'LINEAR')
export_skeleton = opts.get('export_skeleton', False)
export_anim = opts.get('export_anim', False)
export_morphs = opts.get('export_morphs', False)
export_lod = opts.get('export_lod', False)
lod_mode = opts.get('lod_mode', 'name')
lod_manual = opts.get('lod_manual', [])
export_emissive = opts.get('export_emissive', False) # FIX 2: was True
tex_srgb = opts.get('tex_srgb', True)
export_thumb = opts.get('export_thumb', False)
tag_collision = opts.get('tag_collision', True)
export_path = opts.get('export_path', '')
print(f"[GLB] Settings → orm_mode={orm_mode!r} "
f"export_imgs={export_imgs} export_emissive={export_emissive} yup={yup} unit_scale={unit_scale}")
gltf = {
"asset": {"version":"2.0","generator":"Maya Ultimate GLB Exporter v2.0"},
"scene": 0,
"scenes": [{"nodes":[0]}],
"nodes": [{"mesh":0}],
"meshes": [{"primitives":[], "extras":{}}],
"accessors": [],
"bufferViews": [],
"buffers": [{"byteLength":0}],
"materials": [],
"textures": [],
"images": [],
}
bin_blob = b''
bv_idx = acc_idx = tex_idx = img_idx = 0
tex_cache = {}
collision_meshes = []
def add_bv(data, target=None):
nonlocal bin_blob, bv_idx
data = _pad4(data); start = len(bin_blob); bin_blob += data
bv = {"buffer":0,"byteOffset":start,"byteLength":len(data)}
if target: bv["target"] = target
gltf["bufferViews"].append(bv)
i = bv_idx; bv_idx += 1; return i
def add_acc(bv, comp, count, atype, normalized=False, mn=None, mx=None):
nonlocal acc_idx
a = {"bufferView":bv,"byteOffset":0,"componentType":comp,"count":count,"type":atype}
if normalized: a["normalized"] = True
if mn is not None: a["min"] = mn
if mx is not None: a["max"] = mx
gltf["accessors"].append(a)
i = acc_idx; acc_idx += 1; return i
def embed_pil(pil_img, cache_key=None):
nonlocal bin_blob, bv_idx, tex_idx, img_idx
if cache_key and cache_key in tex_cache: return tex_cache[cache_key]
if max_tex_size: pil_img.thumbnail((max_tex_size, max_tex_size), Image.LANCZOS)
buf = io.BytesIO()
if tex_jpeg:
pil_img.convert('RGB').save(buf, format="JPEG", quality=90); mime = "image/jpeg"
else:
pil_img.save(buf, format="PNG"); mime = "image/png"
data = _pad4(buf.getvalue()); start = len(bin_blob); bin_blob += data
gltf["bufferViews"].append({"buffer":0,"byteOffset":start,"byteLength":len(data)})
gltf["images"].append({"bufferView":bv_idx,"mimeType":mime})
gltf["textures"].append({"source":img_idx})
ti = tex_idx; bv_idx += 1; img_idx += 1; tex_idx += 1
if cache_key: tex_cache[cache_key] = ti
return ti
def embed_file(path):
if not path or not os.path.exists(path): return None
if path in tex_cache: return tex_cache[path]
img = Image.open(path)
img = img.convert('RGBA') if tex_srgb else img.convert('RGB')
return embed_pil(img, cache_key=path)
thumb_tex_idx = None
if export_thumb and export_path:
thumb_img, thumb_path = capture_thumbnail(export_path)
if thumb_img:
thumb_tex_idx = embed_pil(thumb_img, cache_key="__thumb__")
gltf["asset"]["extras"] = {"thumbnail": {"index": thumb_tex_idx}}
joint_list = []
joint_node_start = 1
if export_skeleton:
sel_joints = [j for j in (cmds.ls(sl=True) or []) if cmds.nodeType(j) == 'joint']
if not sel_joints:
sel_joints = cmds.ls(type='joint') or []
roots = [j for j in sel_joints
if not (cmds.listRelatives(j, parent=True, type='joint') or [])]
for root in roots:
joint_list += collect_joint_hierarchy(root)
joint_list = list(dict.fromkeys(joint_list))
temps = []
all_vert_ids = []
prim_mesh_sg = []
meshes_with_lod = []
for mesh_transform in mesh_list:
is_col, col_type, col_base = _is_collision_mesh(mesh_transform)
if is_col and tag_collision:
collision_meshes.append({
'transform': mesh_transform,
'type': col_type,
'base_name': col_base,
})
print(f"[GLB] Collision mesh tagged: {mesh_transform} ({col_type})")
if export_lod and lod_mode == 'name':
lod_pairs = find_lod_meshes(mesh_transform)
elif export_lod and lod_mode == 'manual':
# lod_manual is [lod1_name, lod2_name, lod3_name, lod4_name]
# LOD0 is always the base mesh_transform
lod_pairs = [(0, mesh_transform)]
for level, name in enumerate(lod_manual, start=1):
name = (name or '').strip()
if name and cmds.objExists(name) and cmds.listRelatives(name, shapes=True, type='mesh'):
lod_pairs.append((level, name))
elif name:
print(f"[GLB] Manual LOD{level} '{name}' not found — skipped")
else:
lod_pairs = [(0, mesh_transform)]
meshes_with_lod.append((mesh_transform, lod_pairs))
if collision_meshes and tag_collision:
gltf["scenes"][0].setdefault("extras", {})
gltf["scenes"][0]["extras"]["collision_meshes"] = collision_meshes
for mesh_idx, (mesh_transform, lod_pairs) in enumerate(meshes_with_lod):
print(f"\n[GLB] ── Processing: {mesh_transform} ({len(lod_pairs)} LOD levels)")
cur_mesh_idx = 0
lod_prim_ranges = {}
for lod_level, lod_transform in lod_pairs:
print(f"[GLB] LOD{lod_level}: {lod_transform}")
dup_result = cmds.duplicate(lod_transform, returnRootsOnly=True)[0]
tmp = cmds.rename(dup_result, f"_GLB_tmp_{id(dup_result)}")
if cmds.listRelatives(tmp, parent=True):
tmp = cmds.parent(tmp, world=True)[0]
if apply_trs:
cmds.makeIdentity(tmp, apply=True, t=True, r=True, s=True)
if merge_verts:
cmds.polyMergeVertex(tmp, d=merge_thresh, constructionHistory=False)
cmds.polyTriangulate(tmp)
tmp = cmds.ls(tmp, long=False)[0]