-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpck_skin_helper.js
More file actions
3753 lines (3467 loc) · 164 KB
/
pck_skin_helper.js
File metadata and controls
3753 lines (3467 loc) · 164 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
(function () {
"use strict";
const fs = require("fs");
const registered = [];
function track(item) {
registered.push(item);
return item;
}
const LOCKED_BONES = new Set(["HEAD", "BODY", "ARM0", "ARM1", "LEG0", "LEG1", "WAIST", "ROOT"]);
// When false the bone guards are fully disabled, letting the user freely move
// pivots and reparent bones. Toggled via the "Lock Root Bones" action.
let boneLockEnabled = true;
// Set to true during PSM import so the finished_edit guard doesn't roll back
// the pivot changes that the import deliberately applies.
let suppressBoneGuard = false;
// cubeName = display name shown in outliner
// animFlag = ANIM bit (mask) that hides/shows this cube when toggled
// (undefined = always visible, can never be hidden via ANIM)
// ANIM masks:
// HEAD_DISABLED = 0x400 (bit 10)
// LEFT_ARM_DISABLED = 0x1000 (bit 12)
// RIGHT_ARM_DISABLED = 0x800 (bit 11)
// BODY_DISABLED = 0x2000 (bit 13)
// LEFT_LEG_DISABLED = 0x8000 (bit 15)
// RIGHT_LEG_DISABLED = 0x4000 (bit 14)
// HEAD_OVERLAY_DISABLED = 0x10000 (bit 16)
// LEFT_ARM_OVERLAY_DISABLED = 0x100000 (bit 20)
// RIGHT_ARM_OVERLAY_DISABLED = 0x200000 (bit 21)
// LEFT_LEG_OVERLAY_DISABLED = 0x400000 (bit 22)
// RIGHT_LEG_OVERLAY_DISABLED = 0x800000 (bit 23)
// BODY_OVERLAY_DISABLED = 0x1000000 (bit 24)
const TEMPLATE_BONES = [
{
name: "HEAD",
pivot: [0, 24, 0],
cubes: [
{ cubeName: "HEAD", origin: [-4, 24, -4], size: [8, 8, 8], uv: [0, 0], inflate: 0, animFlag: 0x400 },
{
cubeName: "HEADWEAR",
origin: [-4.5, 23.5, -4.5],
size: [8, 8, 8],
uv: [32, 0],
inflate: 0.5,
animFlag: 0x10000,
},
],
},
{
name: "BODY",
pivot: [0, 24, 0],
cubes: [
{ cubeName: "BODY", origin: [-4, 12, -2], size: [8, 12, 4], uv: [16, 16], inflate: 0, animFlag: 0x2000 },
{
cubeName: "JACKET",
origin: [-4.25, 11.75, -2.25],
size: [8, 12, 4],
uv: [16, 32],
inflate: 0.25,
animFlag: 0x1000000,
},
],
},
{
name: "ARM0",
pivot: [6, 22, 0],
cubes: [
{ cubeName: "ARM0", origin: [4, 12, -2], size: [4, 12, 4], uv: [40, 16], inflate: 0, animFlag: 0x800 },
{
cubeName: "SLEEVE0",
origin: [3.7, 11.75, -2.25],
size: [4, 12, 4],
uv: [40, 32],
inflate: 0.25,
animFlag: 0x200000,
},
],
},
{
name: "ARM1",
pivot: [-6, 22, 0],
cubes: [
{ cubeName: "ARM1", origin: [-8, 12, -2], size: [4, 12, 4], uv: [32, 48], inflate: 0, animFlag: 0x1000 },
{
cubeName: "SLEEVE1",
origin: [-8.28, 11.75, -2.25],
size: [4, 12, 4],
uv: [48, 48],
inflate: 0.25,
animFlag: 0x100000,
},
],
},
{
name: "LEG0",
pivot: [2, 12, 0],
cubes: [
{ cubeName: "LEG0", origin: [0, 0, -2], size: [4, 12, 4], uv: [0, 16], inflate: 0, animFlag: 0x4000 },
{
cubeName: "PANT0",
origin: [-0.25, -0.3, -2.25],
size: [4, 12, 4],
uv: [0, 32],
inflate: 0.25,
animFlag: 0x800000,
},
],
},
{
name: "LEG1",
pivot: [-2, 12, 0],
cubes: [
{ cubeName: "LEG1", origin: [-4, 0, -2], size: [4, 12, 4], uv: [16, 48], inflate: 0, animFlag: 0x8000 },
{
cubeName: "PANT1",
origin: [-4.25, -0.3, -2.25],
size: [4, 12, 4],
uv: [0, 48],
inflate: 0.25,
animFlag: 0x400000,
},
],
},
];
// Map from template cube name -> ANIM flag mask that controls visibility.
const TEMPLATE_CUBE_FLAG = {};
TEMPLATE_BONES.forEach((boneDef) => {
boneDef.cubes.forEach((c) => {
if (c.animFlag !== undefined) TEMPLATE_CUBE_FLAG[c.cubeName] = c.animFlag;
});
});
// Flat set of all template cube names (for guard checks).
const TEMPLATE_CUBE_NAMES = new Set(Object.keys(TEMPLATE_CUBE_FLAG));
// ── Template Ghost Meshes ────────────────────────────────────────────────
// Instead of real Cube objects (which appear in the outliner), we inject
// pure Three.js meshes directly into the scene. They are completely
// invisible to the outliner and cannot be selected, moved, or deleted.
// Container added once to the scene; all ghost meshes live here.
// Rotated 180° around Y so that +Z faces the viewer (matching Blockbench's
// convention where the model front faces -Z in world space).
const _templateGhostRoot = new THREE.Object3D();
_templateGhostRoot.name = "pck_template_ghosts";
_templateGhostRoot.rotation.y = Math.PI;
scene.add(_templateGhostRoot);
track({
remove() {
scene.remove(_templateGhostRoot);
},
});
// Default fallback skin texture — loaded once from the plugin's own base64.
// Used when the project has no texture yet (or the texture map isn't ready).
let _fallbackSkinMap = null;
function _getFallbackSkinMap(defaultSkinB64) {
if (_fallbackSkinMap) return _fallbackSkinMap;
const img = new Image();
img.src = defaultSkinB64;
const map = new THREE.Texture(img);
map.magFilter = THREE.NearestFilter;
map.minFilter = THREE.NearestFilter;
img.onload = () => {
map.needsUpdate = true;
};
_fallbackSkinMap = map;
return map;
}
// Build UV attribute for a THREE.BoxGeometry matching Minecraft box-UV layout.
//
// Minecraft box-UV pixel regions (W=sizeX, H=sizeY, D=sizeZ, u/v = uv_offset):
// right (+X): [u, v+D] .. [u+D, v+D+H]
// left (-X): [u+D+W, v+D] .. [u+D+W+D, v+D+H]
// top (+Y): [u+D, v ] .. [u+D+W, v+D ]
// bottom (-Y): [u+D+W, v ] .. [u+D+W+W, v+D ]
// front (+Z): [u+D, v+D] .. [u+D+W, v+D+H]
// back (-Z): [u+D+W+D, v+D] .. [u+D+W+D+W, v+D+H]
//
// THREE.BoxGeometry face order: +X, -X, +Y, -Y, +Z, -Z
// Each face has 4 vertices written as: tl, bl, tr, br
// (top-left, bottom-left, top-right, bottom-right of the face as seen from outside)
//
// Mirror analysis (derived from BoxGeometry buildPlane udir/vdir):
// +X right: Three.js uv.x=0 -> +Z front, Minecraft left col = back -> mirrorU=YES
// -X left: Three.js uv.x=0 -> -Z back, Minecraft left col = front -> mirrorU=YES
// +Y top: no mirror needed
// -Y bottom: no mirror needed
// +Z front: no mirror needed
// -Z back: no mirror needed
// mirrorX: when true, mirrors the entire box horizontally (left/right faces swap,
// all U coordinates flipped). Used for the 64x32 classic layout where ARM1/LEG1
// share the same UV strip as ARM0/LEG0 but are rendered on the opposite side.
function _buildBoxUVs(W, H, D, uvOffset, uvW, uvH, mirrorX, mirrorBottom) {
const u = uvOffset[0];
const v = uvOffset[1];
// pixel (px,py) -> normalised UV. Three.js V=0 is bottom so we flip V.
function n(px, py) {
return [px / uvW, 1.0 - py / uvH];
}
// Build 8 UV values for one face in BoxGeometry vertex order: tl, tr, bl, br.
// mirrorU swaps left/right so the texture strip reads in the correct direction.
// When mirrorX is active the effective mirror is inverted for every face.
function face(fu, fv, fw, fh, mirrorU, mirrorV) {
const m = mirrorX ? !mirrorU : mirrorU;
const l = m ? fu + fw : fu;
const r = m ? fu : fu + fw;
const t = mirrorV ? fv + fh : fv;
const b = mirrorV ? fv : fv + fh;
return [...n(l, t), ...n(r, t), ...n(l, b), ...n(r, b)];
}
// Face order: +X, -X, +Y, -Y, +Z, -Z
// When mirrorX is set the +X and -X slots are swapped so the side panels
// sample the correct (now-mirrored) region of the UV strip.
const faceRight = face(u + D + W, v + D, D, H, false); // +X side
const faceLeft = face(u, v + D, D, H, false); // -X side
const faces = [
mirrorX ? faceLeft : faceRight, // +X slot
mirrorX ? faceRight : faceLeft, // -X slot
face(u + D, v, W, D, false), // +Y top
face(u + D + W, v, W, D, false, !!mirrorBottom), // -Y bottom
face(u + D, v + D, W, H, false), // +Z front
face(u + D + W + D, v + D, W, H, false), // -Z back
];
const arr = new Float32Array(24 * 2);
faces.forEach((f, fi) => {
for (let i = 0; i < 8; i++) arr[fi * 8 + i] = f[i];
});
return arr;
}
function _getSkinMap() {
const tex = Texture.all[0];
if (!tex) return null;
const mat = tex.getMaterial && tex.getMaterial();
if (!mat) return null;
return mat.map || (mat.uniforms && mat.uniforms.map && mat.uniforms.map.value) || null;
}
const GHOST_VERT = [
"varying vec2 vUv;",
"varying float light;",
"uniform bool SHADE;",
"void main() {",
" if (SHADE) {",
" vec3 N = vec3(modelMatrix * vec4(normal, 0.0));",
" float yLight = (1.0 - N.z) * 0.5;",
" light = yLight * 0.4 + N.x*N.x * 0.075 + N.y*N.y * 0.175 + 0.6;",
" } else { light = 1.0; }",
" vUv = uv;",
" gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);",
"}",
].join("\n");
const GHOST_FRAG = [
"#ifdef GL_ES",
"precision highp float;",
"#endif",
"uniform sampler2D t0;",
"varying vec2 vUv;",
"varying float light;",
"void main(void) {",
" vec4 tx = texture2D(t0, vUv);",
" gl_FragColor = vec4(tx.rgb * light, tx.a);",
" if (gl_FragColor.a < 0.05) discard;",
"}",
].join("\n");
function _buildGhostMaterial(map) {
return new THREE.ShaderMaterial({
uniforms: {
t0: { value: map },
SHADE: { value: settings.shading.value },
},
vertexShader: GHOST_VERT,
fragmentShader: GHOST_FRAG,
side: THREE.DoubleSide,
transparent: true,
depthWrite: true,
});
}
// Slim-arm overrides applied when the SLIM_MODEL ANIM flag (0x80000) is set.
// These replace the standard 4-wide arm/sleeve cubes with the 3-wide Alex variants.
// Both arms are shifted 1 unit towards the body (ARM0 origin.x +1, ARM1 origin.x +1).
const SLIM_ARM_OVERRIDES = {
ARM0: { origin: [4, 12, -2], size: [3, 12, 4], uv: [40, 16] },
SLEEVE0: { origin: [3.75, 11.75, -2.25], size: [3, 12, 4], uv: [40, 32] },
ARM1: { origin: [-7, 12, -2], size: [3, 12, 4], uv: [32, 48] },
SLEEVE1: { origin: [-7.25, 11.75, -2.25], size: [3, 12, 4], uv: [48, 48] },
};
// Classic 64×32 layout overrides applied when neither SLIM_MODEL (0x80000)
// nor RESOLUTION_64x64 (0x40000) is set.
//
// The 64×32 texture has no second-layer rows (V ≥ 32), so:
// • All overlay cubes (HEADWEAR, JACKET, SLEEVE0/1, PANT0/1) are hidden.
// • ARM1 / LEG1 mirror their counterpart's UV instead of using the
// 64×64-only bottom-half UV coordinates.
// • The UV normaliser uses height=32 so V coords map correctly.
const CLASSIC_32_OVERLAY_CUBES = new Set(["JACKET", "SLEEVE0", "SLEEVE1", "PANT0", "PANT1"]);
const CLASSIC_32_UV_OVERRIDES = {
ARM1: { uv: [40, 16], mirrorX: true }, // same UV strip as ARM0, mirrored horizontally
LEG1: { uv: [0, 16], mirrorX: true }, // same UV strip as LEG0, mirrored horizontally
};
// Rebuild all ghost meshes. Called after skeleton is built and on texture/flag change.
//
// Each ghost mesh is parented directly to the corresponding real Blockbench bone's
// THREE.js mesh (group.mesh), so the animator drives the ghosts automatically —
// rotations, translations and the full bone hierarchy all apply for free.
//
// Ghost cube positions are expressed in bone-local space:
// local = cube_world_center - bone_pivot
//
// The _templateGhostRoot container is kept only as a scene-level owner for cleanup;
// actual ghost meshes live under their bone's group.mesh, not under this root.
function rebuildTemplateGhosts() {
// Clear old ghosts — remove from wherever they were parented
const oldGhosts = [];
_templateGhostRoot.traverse((obj) => {
if (obj !== _templateGhostRoot) oldGhosts.push(obj);
});
oldGhosts.forEach((obj) => obj.parent && obj.parent.remove(obj));
// Also sweep any ghosts that may have been parented directly to bone meshes
Group.all.forEach((group) => {
if (!group.mesh) return;
const toRemove = group.mesh.children.filter((c) => c.name && c.name.startsWith("pck_ghost_"));
toRemove.forEach((c) => group.mesh.remove(c));
});
if (!Format || Format.id !== "pck_skin") return;
if (!Project) return;
const skinMap = _getSkinMap() || _getFallbackSkinMap(_DEFAULT_SKIN_B64);
const texH = (Texture.all[0] && Texture.all[0].height) || 64;
const flags = Project.psm_anim_flags || 0;
const isSlim = (flags & 0x80000) !== 0;
const is64x64 = (flags & 0x40000) !== 0;
// Classic 64×32 mode: neither Slim nor 64×64 is checked
const isClassic32 = !isSlim && !is64x64;
TEMPLATE_BONES.forEach((boneDef) => {
// Find the live Blockbench Group for this bone
const boneGroup = Group.all.find((g) => g.name === boneDef.name);
// group.mesh is the Three.js Object3D the animator drives.
// Fall back to _templateGhostRoot if the bone isn't ready yet (shouldn't happen
// after Canvas.updateAll(), but be safe).
const boneTarget = boneGroup && boneGroup.mesh ? boneGroup.mesh : _templateGhostRoot;
const pivot = boneDef.pivot; // [px, py, pz] in Blockbench world space
boneDef.cubes.forEach((cubeDef) => {
// Respect ANIM flags — skip ghost when the flag bit is set
if (cubeDef.animFlag !== undefined && (flags & cubeDef.animFlag) !== 0) return;
// Classic 64×32: hide all second-layer (overlay) cubes
if (isClassic32 && CLASSIC_32_OVERLAY_CUBES.has(cubeDef.cubeName)) return;
// Determine geometry/UV source in priority order:
// 1. Slim overrides (3-wide arms) — when SLIM_MODEL is set
// 2. Classic 32 UV overrides (mirrored) — when neither flag is set
// 3. Default TEMPLATE_BONES values — when RESOLUTION_64x64 is set
const slimOverride = isSlim ? SLIM_ARM_OVERRIDES[cubeDef.cubeName] : null;
const classic32Override = isClassic32 ? CLASSIC_32_UV_OVERRIDES[cubeDef.cubeName] : null;
const origin = slimOverride ? slimOverride.origin : cubeDef.origin;
const size = slimOverride ? slimOverride.size : cubeDef.size;
const uv = slimOverride ? slimOverride.uv : classic32Override ? classic32Override.uv : cubeDef.uv;
const mirrorX = slimOverride ? !!slimOverride.mirrorX : classic32Override ? !!classic32Override.mirrorX : false;
// Classic 64×32 textures are 32px tall; use that as the UV normaliser height
const uvTexH = isClassic32 ? 32 : texH;
const [ox, oy, oz] = origin;
const [sw, sh, sd] = size;
const inf = cubeDef.inflate || 0;
// The head cubes' bottom face needs V-flipping due to Three.js winding
const mirrorBottom = cubeDef.cubeName === "HEAD" || cubeDef.cubeName === "HEADWEAR";
const geom = new THREE.BoxGeometry(sw + inf * 2, sh + inf * 2, sd + inf * 2);
const uvs = _buildBoxUVs(sw, sh, sd, uv, 64, uvTexH, mirrorX, mirrorBottom);
geom.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
const mat = _buildGhostMaterial(skinMap);
const mesh = new THREE.Mesh(geom, mat);
mesh.name = "pck_ghost_" + cubeDef.cubeName;
// Cube world-space centre
const cx = ox + (sw + inf * 2) / 2;
const cy = oy + (sh + inf * 2) / 2;
const cz = oz + (sd + inf * 2) / 2;
if (boneTarget === _templateGhostRoot) {
// Fallback path: _templateGhostRoot is rotated 180° around Y, so negate X and Z
mesh.position.set(-cx, cy, -cz);
} else {
// Bone-local space: offset from the bone pivot.
mesh.position.set(cx - pivot[0], cy - pivot[1], cz - pivot[2]);
// Rotate 180° on Y so the UV faces align correctly with Blockbench's
// bone scene graph orientation (bone meshes are already Y-rotated 180°).
mesh.rotation.y = Math.PI;
}
boneTarget.add(mesh);
});
});
}
function buildTemplateSkeleton() {
// ROOT is the top-level container — locked, not exported, pivot at origin.
const rootGroup = new Group({ name: "ROOT", origin: [0, 0, 0] }).init();
rootGroup.export = false;
// WAIST is the upper-body container — locked, not exported, pivot at Y=12 by default.
const WAIST_BONES = new Set(["HEAD", "BODY", "ARM0", "ARM1"]);
const LEG_BONES = new Set(["LEG0", "LEG1"]);
const waistGroup = new Group({ name: "WAIST", origin: [0, 12, 0] }).addTo(rootGroup).init();
waistGroup.export = false;
TEMPLATE_BONES.forEach((boneDef) => {
let parent;
if (WAIST_BONES.has(boneDef.name)) parent = waistGroup;
else if (LEG_BONES.has(boneDef.name)) parent = rootGroup;
const group = new Group({ name: boneDef.name, origin: boneDef.pivot });
if (parent) group.addTo(parent);
group.init();
});
// Place armor locators now that all bones exist.
buildArmorLocators();
// Ghost meshes are built once the skeleton Groups have their .mesh assigned,
// which happens after Canvas.updateAll() in the caller.
requestAnimationFrame(() => rebuildTemplateGhosts());
}
function onNameChanged({ object, new_name, old_name }) {
if (Format.id !== "pck_skin") return;
if (!boneLockEnabled) return;
if (!(object instanceof Group)) return;
if (!LOCKED_BONES.has(old_name)) return;
object.name = old_name;
Blockbench.showQuickMessage(`"${old_name}" is a locked bone — it cannot be renamed.`, 2200);
Canvas.updateAll();
}
// ── Draw Mode ──────────────────────────────────────────────────────────────
// Draw Mode places real Cube objects matching every template bone cube so the
// user can paint directly on them. The cubes are locked, not exported, and
// protected against being moved, reparented, rotated or deleted.
// They are removed automatically when Draw Mode is toggled off.
let drawModeEnabled = false;
// UUID prefix that tags every draw-mode cube so they are identifiable across
// all guards without needing a separate Set.
const DRAW_MODE_UUID_PREFIX = "dddddddd";
function isDrawModeCube(cube) {
return cube && typeof cube.uuid === "string" && cube.uuid.startsWith(DRAW_MODE_UUID_PREFIX);
}
function drawModeUuid() {
return DRAW_MODE_UUID_PREFIX + guid().substr(8);
}
function clearDrawModeCubes() {
// Collect first so we don't mutate Cube.all while iterating.
const toRemove = Cube.all.filter(isDrawModeCube);
toRemove.forEach((c) => c.remove());
Canvas.updateAll();
}
// Correct world-space cube definitions for Draw Mode, one set per UV layout.
// These are independent of TEMPLATE_BONES (which uses a different coordinate
// convention tuned for the Three.js ghost meshes).
const DRAWMODE_BONES_64 = [
{
name: "HEAD",
pivot: [0, 24, 0],
cubes: [
{ origin: [-4, 24, -4], size: [8, 8, 8], uv: [0, 0], inflate: 0 },
{ origin: [-4, 24, -4], size: [8, 8, 8], uv: [32, 0], inflate: 0.5 },
],
},
{
name: "BODY",
pivot: [0, 24, 0],
cubes: [
{ origin: [-4, 12, -2], size: [8, 12, 4], uv: [16, 16], inflate: 0 },
{ origin: [-4, 12, -2], size: [8, 12, 4], uv: [16, 32], inflate: 0.25 },
],
},
{
name: "ARM0",
pivot: [6, 22, 0],
cubes: [
{ origin: [4, 12, -2], size: [4, 12, 4], uv: [40, 16], inflate: 0 },
{ origin: [4, 12, -2], size: [4, 12, 4], uv: [40, 32], inflate: 0.25 },
],
},
{
name: "ARM1",
pivot: [-6, 22, 0],
cubes: [
{ origin: [-8, 12, -2], size: [4, 12, 4], uv: [32, 48], inflate: 0 },
{ origin: [-8, 12, -2], size: [4, 12, 4], uv: [48, 48], inflate: 0.25 },
],
},
{
name: "LEG0",
pivot: [2, 12, 0],
cubes: [
{ origin: [0, 0, -2], size: [4, 12, 4], uv: [0, 16], inflate: 0 },
{ origin: [0, 0, -2], size: [4, 12, 4], uv: [0, 32], inflate: 0.25 },
],
},
{
name: "LEG1",
pivot: [-2, 12, 0],
cubes: [
{ origin: [-4, 0, -2], size: [4, 12, 4], uv: [16, 48], inflate: 0 },
{ origin: [-4, 0, -2], size: [4, 12, 4], uv: [0, 48], inflate: 0.25 },
],
},
];
const DRAWMODE_BONES_SLIM = [
{
name: "HEAD",
pivot: [0, 24, 0],
cubes: [
{ origin: [-4, 24, -4], size: [8, 8, 8], uv: [0, 0], inflate: 0 },
{ origin: [-4, 24, -4], size: [8, 8, 8], uv: [32, 0], inflate: 0.5 },
],
},
{
name: "BODY",
pivot: [0, 24, 0],
cubes: [
{ origin: [-4, 12, -2], size: [8, 12, 4], uv: [16, 16], inflate: 0 },
{ origin: [-4, 12, -2], size: [8, 12, 4], uv: [16, 32], inflate: 0.25 },
],
},
{
name: "ARM0",
pivot: [-6, 22, 0],
cubes: [
{ origin: [-7, 12, -2], size: [3, 12, 4], uv: [32, 48], inflate: 0 },
{ origin: [-7, 12, -2], size: [3, 12, 4], uv: [48, 48], inflate: 0.25 },
],
},
{
name: "ARM1",
pivot: [6, 22, 0],
cubes: [
{ origin: [4, 12, -2], size: [3, 12, 4], uv: [40, 16], inflate: 0 },
{ origin: [4, 12, -2], size: [3, 12, 4], uv: [40, 32], inflate: 0.25 },
],
},
{
name: "LEG0",
pivot: [-2, 12, 0],
cubes: [
{ origin: [-4, 0, -2], size: [4, 12, 4], uv: [16, 48], inflate: 0 },
{ origin: [-4, 0, -2], size: [4, 12, 4], uv: [0, 48], inflate: 0.25 },
],
},
{
name: "LEG1",
pivot: [2, 12, 0],
cubes: [
{ origin: [0, 0, -2], size: [4, 12, 4], uv: [0, 16], inflate: 0 },
{ origin: [0, 0, -2], size: [4, 12, 4], uv: [0, 32], inflate: 0.25 },
],
},
];
const DRAWMODE_BONES_32 = [
{
name: "HEAD",
pivot: [0, 24, 0],
cubes: [
{ origin: [-4, 24, -4], size: [8, 8, 8], uv: [0, 0], inflate: 0 },
{ origin: [-4, 24, -4], size: [8, 8, 8], uv: [32, 0], inflate: 0.5 },
],
},
{
name: "BODY",
pivot: [0, 24, 0],
cubes: [{ origin: [-4, 12, -2], size: [8, 12, 4], uv: [16, 16], inflate: 0 }],
},
{
name: "ARM0",
pivot: [-6, 22, 0],
cubes: [{ origin: [-8, 12, -2], size: [4, 12, 4], uv: [40, 16], inflate: 0, mirror_uv: true }],
},
{
name: "ARM1",
pivot: [6, 22, 0],
cubes: [{ origin: [4, 12, -2], size: [4, 12, 4], uv: [40, 16], inflate: 0 }],
},
{
name: "LEG0",
pivot: [-2, 12, 0],
cubes: [{ origin: [-4, 0, -2], size: [4, 12, 4], uv: [0, 16], inflate: 0, mirror_uv: true }],
},
{
name: "LEG1",
pivot: [2, 12, 0],
cubes: [{ origin: [0, 0, -2], size: [4, 12, 4], uv: [0, 16], inflate: 0 }],
},
];
function placeDrawModeCubes() {
const flags = Project.psm_anim_flags || 0;
const isSlim = (flags & 0x80000) !== 0;
const is64x64 = (flags & 0x40000) !== 0;
const isClassic32 = !isSlim && !is64x64;
const boneDefs = isSlim ? DRAWMODE_BONES_SLIM : isClassic32 ? DRAWMODE_BONES_32 : DRAWMODE_BONES_64;
boneDefs.forEach((boneDef) => {
const boneGroup = Group.all.find((g) => g.name === boneDef.name);
if (!boneGroup) return;
boneDef.cubes.forEach((cubeDef) => {
const [ox, oy, oz] = cubeDef.origin;
const [sw, sh, sd] = cubeDef.size;
const inf = cubeDef.inflate || 0;
new Cube(
{
name: boneDef.name,
from: [ox - inf, oy - inf, oz - inf],
to: [ox + sw + inf, oy + sh + inf, oz + sd + inf],
uv_offset: [cubeDef.uv[0], cubeDef.uv[1]],
mirror_uv: !!cubeDef.mirror_uv,
box_uv: true,
export: false,
locked: false,
},
drawModeUuid(),
)
.addTo(boneGroup)
.init();
});
});
Canvas.updateAll();
}
// All ghost-visibility flags that Drawable Ghost sets when it turns on, so the
// Three.js ghost is fully hidden while real drawable cubes are in the viewport.
// Covers every Disabled + OverlayOff bit.
const DRAWABLE_GHOST_HIDE_MASK =
0x400 | // HEAD_DISABLED
0x800 | // RIGHT_ARM_DISABLED
0x1000 | // LEFT_ARM_DISABLED
0x2000 | // BODY_DISABLED
0x4000 | // RIGHT_LEG_DISABLED
0x8000 | // LEFT_LEG_DISABLED
0x10000 | // HEAD_OVERLAY_DISABLED
0x100000 | // LEFT_ARM_OVERLAY_DISABLED
0x200000 | // RIGHT_ARM_OVERLAY_DISABLED
0x400000 | // LEFT_LEG_OVERLAY_DISABLED
0x800000 | // RIGHT_LEG_OVERLAY_DISABLED
0x1000000; // BODY_OVERLAY_DISABLED
// Flags that were already set before Drawable Ghost turned on — we must not
// clear those when turning it off again.
let _drawModePreExistingFlags = 0;
function setDrawMode(enabled) {
drawModeEnabled = enabled;
const action = BarItems["pck_toggle_draw_mode"];
if (drawModeEnabled) {
// Remember which hide-flags were already active so we only restore the
// ones we newly set (don't clear flags the user had set themselves).
_drawModePreExistingFlags = (Project.psm_anim_flags || 0) & DRAWABLE_GHOST_HIDE_MASK;
// Force all ghost-part flags on so the Three.js ghost fully disappears.
Project.psm_anim_flags = (Project.psm_anim_flags || 0) | DRAWABLE_GHOST_HIDE_MASK;
syncAnimPanel();
syncTemplateCubeVisibility();
placeDrawModeCubes();
if (action) {
action.name = "Toggle Drawable Ghost";
action.icon = "brush";
}
Blockbench.showQuickMessage("Drawable Ghost ON — template cubes placed. Press again to remove them.", 2500);
} else {
// Restore: clear only the flags we added (leave user-set ones intact).
const flagsToRemove = DRAWABLE_GHOST_HIDE_MASK & ~_drawModePreExistingFlags;
Project.psm_anim_flags = (Project.psm_anim_flags || 0) & ~flagsToRemove;
syncAnimPanel();
syncTemplateCubeVisibility();
clearDrawModeCubes();
if (action) {
action.name = "Toggle Drawable Ghost";
action.icon = "edit_off";
}
Blockbench.showQuickMessage("Drawable Ghost OFF — template cubes removed.", 2000);
}
}
// Push the current psm_anim_flags value into the ANIM panel Vue component.
function syncAnimPanel() {
const animPanel = Interface.Panels.pck_anim;
if (animPanel && animPanel.inside_vue) {
animPanel.inside_vue.anim_flags = Project.psm_anim_flags || 0;
}
}
function onFinishedEdit() {
if (Format.id !== "pck_skin") return;
if (!boneLockEnabled || suppressBoneGuard) return;
const last = Undo.history[Undo.history.length - 1];
if (!last || !last.before || !last.before.groups) return;
const beforeGroups = last.before.groups;
let violated = false;
let pivotChanged = false;
Group.all.forEach((group) => {
if (!LOCKED_BONES.has(group.name)) return;
const snapshot = beforeGroups[group.uuid];
if (!snapshot) return;
const parentBefore = snapshot.parent || "";
const parentNow = group.parent instanceof Group ? group.parent.uuid : "";
if (parentBefore !== parentNow) violated = true;
if (
snapshot.origin &&
(snapshot.origin[0] !== group.origin[0] ||
snapshot.origin[1] !== group.origin[1] ||
snapshot.origin[2] !== group.origin[2])
) {
pivotChanged = true;
}
});
// Check for any newly-applied rotations on groups or cubes.
// PSM does not support rotations — roll back if any appear.
const isRotated = (r) => r && (r[0] !== 0 || r[1] !== 0 || r[2] !== 0);
const ROTATION_EXEMPT = new Set(["cape", "elytraRight", "elytraLeft"]);
const beforeElements = (last.before && last.before.elements) || {};
let rotationViolated = false;
Group.all.forEach((group) => {
if (isRotated(group.rotation)) rotationViolated = true;
});
if (!rotationViolated) {
Cube.all.forEach((cube) => {
if (ROTATION_EXEMPT.has(cube.name)) return;
if (cube.uuid.startsWith("eeeeeeee") || cube.uuid.startsWith("cccccccc")) return;
if (cube.uuid.startsWith(DRAW_MODE_UUID_PREFIX)) return; // draw-mode cubes may not rotate (locked)
if (isRotated(cube.rotation)) rotationViolated = true;
});
}
if (rotationViolated) {
Undo.loadSave(last.before, last.post);
Undo.history.pop();
Undo.index = Undo.history.length;
Blockbench.showQuickMessage("Rotations are not supported in PSM — the rotation has been reverted.", 2500);
return;
}
if (violated) {
Undo.loadSave(last.before, last.post);
Undo.history.pop();
Undo.index = Undo.history.length;
Blockbench.showQuickMessage("Locked bones cannot be moved or reparented — only their pivots may change.", 2500);
return;
}
if (pivotChanged) {
rebuildTemplateGhosts();
if (Modes.animate) rebuildArmorCubes();
}
// Zero out any rotations applied to armor locators — they are position-only.
let locatorRotated = false;
Locator.all.forEach((loc) => {
if (!isArmorLocator(loc)) return;
if (loc.rotation && (loc.rotation[0] !== 0 || loc.rotation[1] !== 0 || loc.rotation[2] !== 0)) {
loc.rotation = [0, 0, 0];
locatorRotated = true;
}
});
if (locatorRotated) {
Canvas.updateAll();
Blockbench.showQuickMessage("Armor locators are position-only — rotation has been cleared.", 2200);
}
// Rebuild armor whenever an armor locator has been moved.
const beforeLocators = (last.before && last.before.locators) || {};
let locatorMoved = false;
Locator.all.forEach((loc) => {
if (!isArmorLocator(loc)) return;
const snap = beforeLocators[loc.uuid];
if (!snap) return;
if (
snap.position &&
(snap.position[0] !== loc.position[0] ||
snap.position[1] !== loc.position[1] ||
snap.position[2] !== loc.position[2])
) {
locatorMoved = true;
}
});
if (locatorMoved && Modes.animate) {
rebuildArmorCubes();
}
}
function onCubeAdded({ object }) {
if (Format.id !== "pck_skin") return;
if (!object.box_uv) {
object.box_uv = true;
}
}
function onCloseProject() {
clearArmorLocators();
// Clear ghost meshes — they may be parented to bone meshes, not _templateGhostRoot
const oldGhosts = [];
_templateGhostRoot.traverse((obj) => {
if (obj !== _templateGhostRoot) oldGhosts.push(obj);
});
oldGhosts.forEach((obj) => obj.parent && obj.parent.remove(obj));
Group.all.forEach((group) => {
if (!group.mesh) return;
group.mesh.children.filter((c) => c.name && c.name.startsWith("pck_ghost_")).forEach((c) => group.mesh.remove(c));
});
// Reset lock state so each new project starts locked.
if (!boneLockEnabled) {
boneLockEnabled = true;
const action = BarItems["pck_toggle_bone_lock"];
if (action) {
action.name = "Unlock Root Bones";
action.icon = "lock_open";
}
}
// Reset draw mode so the new project starts clean.
if (drawModeEnabled) {
// Restore any flags we had set before clearing state.
if (Project.psm_anim_flags !== undefined) {
const flagsToRemove = DRAWABLE_GHOST_HIDE_MASK & ~_drawModePreExistingFlags;
Project.psm_anim_flags = (Project.psm_anim_flags || 0) & ~flagsToRemove;
}
drawModeEnabled = false;
_drawModePreExistingFlags = 0;
const action = BarItems["pck_toggle_draw_mode"];
if (action) {
action.name = "Toggle Drawable Ghost";
action.icon = "edit_off";
}
}
}
Blockbench.on("change_element_name", onNameChanged);
Blockbench.on("finished_edit", onFinishedEdit);
Blockbench.on("add_cube", onCubeAdded);
Blockbench.on("close_project", onCloseProject);
track({
delete() {
Blockbench.removeListener("change_element_name", onNameChanged);
Blockbench.removeListener("finished_edit", onFinishedEdit);
Blockbench.removeListener("add_cube", onCubeAdded);
Blockbench.removeListener("close_project", onCloseProject);
},
});
const _origProjectParse = Codecs.project.parse;
Codecs.project.parse = function (model, path) {
if (model && model.meta) {
if (model.meta.model_format === "pck_skin") {
} else if (model.meta.model_format === "bedrock" && model.meta.box_uv === true) {
model.meta.model_format = "pck_skin";
if (!model.meta.format_version) {
model.meta.format_version = "4.5";
}
}
}
return _origProjectParse.call(this, model, path);
};
track({
delete() {
Codecs.project.parse = _origProjectParse;
},
});
function validateSkeleton() {
const issues = [];
const presentBoneNames = new Set(Group.all.map((g) => g.name));
// Valid skeleton structure:
// Root level: ROOT only
// Under ROOT: WAIST, LEG0, LEG1
// Under WAIST: HEAD, BODY, ARM0, ARM1
// Under bones: cubes only, OR known offset folders
// Under folders: cubes only
const VALID_UNDER_ROOT = new Set(["WAIST", "LEG0", "LEG1"]);
const VALID_UNDER_WAIST = new Set(["HEAD", "BODY", "ARM0", "ARM1"]);
const VALID_OFFSET_FOLDERS = new Set([
"TOOL0",
"TOOL1",
"HELMET",
"SHOULDER0",
"SHOULDER1",
"CHEST",
"PANTS0",
"PANTS1",
"BOOT0",
"BOOT1",
]);
// All required bones must be present
["ROOT", "WAIST", "HEAD", "BODY", "ARM0", "ARM1", "LEG0", "LEG1"].forEach((requiredName) => {
if (!presentBoneNames.has(requiredName)) {
issues.push({
name: "Missing or renamed bone",
description:
`The required bone **"${requiredName}"** is missing. ` +
`Required bones must keep their original names and cannot be deleted or replaced.`,
});
}
});
// Root level: only ROOT allowed
Group.all.forEach((group) => {
if (group.parent instanceof Group) return;
if (group.name !== "ROOT") {
issues.push({
name: "Unexpected root bone",
description:
`Found **"${group.name}"** at the root level. ` +
`Only **ROOT** may sit at the top level — all other bones must be nested inside it.`,
});
}
});
// Under ROOT: only WAIST, LEG0, LEG1 allowed
Group.all
.filter((g) => g.parent instanceof Group && g.parent.name === "ROOT")
.forEach((group) => {
if (!VALID_UNDER_ROOT.has(group.name)) {
issues.push({
name: "Unexpected bone inside ROOT",
description:
`Found **"${group.name}"** inside ROOT. ` + `Only WAIST, LEG0, and LEG1 may be direct children of ROOT.`,
});
}
});
// Under WAIST: only HEAD, BODY, ARM0, ARM1 allowed
Group.all
.filter((g) => g.parent instanceof Group && g.parent.name === "WAIST")
.forEach((group) => {
if (!VALID_UNDER_WAIST.has(group.name)) {
issues.push({
name: "Unexpected bone inside WAIST",
description:
`Found **"${group.name}"** inside WAIST. ` +
`Only HEAD, BODY, ARM0, and ARM1 may be direct children of WAIST.`,
});
}
});
// Under the 6 main bones: only cubes OR known offset folders allowed
Group.all.forEach((group) => {
if (!(group.parent instanceof Group)) return;
const parentName = group.parent.name;
if (parentName === "ROOT" || parentName === "WAIST") return; // handled above