Repository navigation
Expand file tree
/
Copy pathblockmesh.js
More file actions
1489 lines (1306 loc) · 43.8 KB
/
Copy pathblockmesh.js
File metadata and controls
1489 lines (1306 loc) · 43.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as Blockly from "blockly";
import { meshMap, meshBlockIdMap } from "../generators";
import { flock } from "../flock.js";
import { objectColours } from "../config.js";
import { createMeshOnCanvas } from "./addmeshes.js";
import { createBlockWithShadows, highlightBlockById } from "./addmenu.js";
const characterMaterials = [
"Hair",
"Skin",
"Eyes",
"Sleeves",
"Shorts",
"TShirt",
];
const colorFields = {
HAIR_COLOR: true,
SKIN_COLOR: true,
EYES_COLOR: true,
TSHIRT_COLOR: true,
SHORTS_COLOR: true,
SLEEVES_COLOR: true,
};
export function getRootMesh(mesh) {
if (flock.meshDebug) console.log(mesh.parent);
if (!mesh) return null;
if (!mesh.parent) return mesh;
return getRootMesh(mesh.parent);
}
export function updateOrCreateMeshFromBlock(block, changeEvent) {
if (flock.meshDebug)
console.log(
"Update or create mesh from block",
block.type,
changeEvent.type,
);
if (
["set_sky_color", "set_background_color", "create_ground"].includes(
block.type,
)
) {
// Always proceed to update
updateMeshFromBlock(null, block, changeEvent);
return;
}
const mesh = getMeshFromBlock(block);
if (flock.meshDebug) console.log(mesh);
const isEnabledEvent =
changeEvent?.type === Blockly.Events.BLOCK_CHANGE &&
changeEvent.element === "disabled" &&
changeEvent.oldValue &&
!changeEvent.newValue;
const isImmediateEnabledCreate =
changeEvent?.type === Blockly.Events.BLOCK_CREATE &&
block.isEnabled() &&
!mesh;
if (window.loadingCode || block.disposed) return;
const alreadyCreatingMesh = meshMap[block.id] !== undefined;
if (!alreadyCreatingMesh && (isEnabledEvent || isImmediateEnabledCreate)) {
createMeshOnCanvas(block);
return;
}
if (flock.meshDebug) {
console.log(
changeEvent?.type === Blockly.Events.BLOCK_CHANGE ||
changeEvent?.type === Blockly.Events.BLOCK_CREATE,
);
}
if (
(changeEvent?.type === Blockly.Events.BLOCK_CHANGE ||
changeEvent?.type === Blockly.Events.BLOCK_CREATE) &&
(mesh ||
[
"set_sky_color",
"set_background_color",
"create_ground",
"create_map",
].includes(block.type))
) {
updateMeshFromBlock(mesh, block, changeEvent);
}
}
export function deleteMeshFromBlock(blockId) {
const blockKey = getBlockKeyFromBlockID(blockId);
if (!blockKey) {
const block = Blockly.getMainWorkspace().getBlockById(blockId);
if (block && block.type === "create_map") {
const mesh = flock?.scene?.getMeshByName("ground");
if (mesh) {
flock.disposeMesh(mesh);
return;
}
}
}
if (!blockKey) {
return;
}
const mesh = getMeshFromBlockKey(blockKey);
if (!mesh || mesh.name === "__root__") {
} else {
flock.disposeMesh(mesh);
}
// Remove mappings
delete meshMap[blockKey];
delete meshBlockIdMap[blockKey];
}
export function getBlockKeyFromBlock(block) {
return Object.keys(meshMap).find((key) => meshMap[key] === block);
}
export function getBlockKeyFromBlockID(blockId) {
return Object.keys(meshBlockIdMap).find(
(key) => meshBlockIdMap[key] === blockId,
);
}
export function getMeshFromBlockKey(blockKey) {
return flock.scene?.meshes?.find(
(mesh) => mesh.metadata?.blockKey === blockKey,
);
}
export function getMeshFromBlock(block) {
if (block && block.type === "create_map") {
return flock?.scene?.getMeshByName("ground");
}
if (block && block.type === "rotate_to") {
block = block.getParent();
}
const blockKey = getBlockKeyFromBlock(block);
if (!blockKey) return null;
const found = getMeshFromBlockKey(blockKey);
return found;
}
function getMeshFromBlockId(blockId) {
const blockKey = getBlockKeyFromBlockID(blockId);
return getMeshFromBlockKey(blockKey);
}
function rescaleBoundingBox(bb, newScale) {
// Get the current world matrix before any transformation
const originalWorldMatrix = bb.getWorldMatrix().clone();
// Extract the original world position
const originalPosition = originalWorldMatrix.getTranslation();
// Bake current transform into vertices
bb.bakeCurrentTransformIntoVertices();
// Reset scaling to 1,1,1 first
bb.scaling.set(1, 1, 1);
// Set the new scale and bake it
bb.scaling.set(newScale, newScale, newScale);
bb.bakeCurrentTransformIntoVertices();
// Reset scaling to 1,1,1 again
bb.scaling.set(1, 1, 1);
// Restore the original world position
bb.position.copyFrom(originalPosition);
}
function getBlockValue(block) {
if (!block) return null;
const fieldNames = block.inputList
.flatMap((input) => input.fieldRow)
.map((field) => field.name);
for (const name of fieldNames) {
const field = block.getField(name);
if (field) {
return field.getValue(); // returns number, text, or colour depending on the field
}
}
return null;
}
export function extractMaterialInfo(materialBlock) {
const textureSet = materialBlock.getFieldValue("TEXTURE_SET");
let baseColor = null;
const baseColorBlock = materialBlock.getInputTargetBlock("BASE_COLOR");
if (baseColorBlock) {
baseColor = getBlockValue(baseColorBlock);
}
let alpha = 1;
const alphaBlock = materialBlock.getInputTargetBlock("ALPHA");
if (alphaBlock) {
const alphaVal = getBlockValue(alphaBlock);
if (alphaVal !== null) alpha = parseFloat(alphaVal);
}
return { textureSet, baseColor, alpha };
}
export function updateMeshFromBlock(mesh, block, changeEvent) {
if (flock.meshDebug) console.log("Update", block.type, changeEvent.type);
if (
!mesh &&
![
"set_sky_color",
"set_background_color",
"create_ground",
"create_map",
].includes(block.type)
)
return;
const changedBlock = Blockly.getMainWorkspace().getBlockById(
changeEvent.blockId,
);
const parent = changedBlock.getParent() || changedBlock;
let changed;
// Check for direct field changes on the block itself FIRST
if (
changeEvent.type === Blockly.Events.BLOCK_CHANGE &&
changeEvent.element === "field" &&
changeEvent.blockId === block.id
) {
if (block.type === "load_object" && changeEvent.name === "MODELS") {
changed = "MODELS";
} else if (
block.type === "load_multi_object" &&
changeEvent.name === "MODELS"
) {
changed = "MODELS";
} else if (
block.type === "load_character" &&
changeEvent.name === "MODELS"
) {
changed = "MODELS";
} else if (block.type === "create_map" && changeEvent.name === "MAP_NAME") {
changed = "MAP_NAME";
}
}
if (!changed) {
parent.inputList.forEach((input) => {
let value =
input?.connection?.shadowState?.id ||
input?.connection?.targetConnection?.sourceBlock_?.id;
if (value === changedBlock.id) changed = input.name;
});
}
if (
!changed &&
block.type === "create_map" &&
block.getInputTargetBlock("MATERIAL")
) {
// If the field that changed belongs to the material block, treat as change
const materialBlock = block.getInputTargetBlock("MATERIAL");
if (
changeEvent.blockId === materialBlock.id ||
(changeEvent.type === Blockly.Events.BLOCK_CHANGE &&
changeEvent.name &&
materialBlock?.getField(changeEvent.name))
) {
changed = "MATERIAL";
}
}
if (!changed) {
if (
block.type === "set_sky_color" ||
block.type === "create_ground" ||
block.type === "create_map"
) {
changed = "COLOR"; // or any value to keep going
} else {
return;
}
}
if (!changed) return;
const shapeType = block.type;
// Special handling for MODELS field change - get mesh if not provided
if (
(block.type === "load_object" ||
block.type === "load_multi_object" ||
block.type === "load_character") &&
changed === "MODELS" &&
!mesh
) {
mesh = getMeshFromBlock(block);
}
if (mesh && mesh.physics) mesh.physics.disablePreStep = true;
let color;
if (
![
"load_model",
"load_multi_object",
"load_character",
"create_map",
"rotate_to",
].includes(block.type)
) {
color = block
.getInput("COLOR")
.connection.targetBlock()
.getFieldValue("COLOR");
} else if (block.type === "load_multi_object") {
// Get the block connected to the "COLORS" input
const colorsBlock = block.getInput("COLORS").connection.targetBlock();
// Initialize an array to store the color values
let colorsArray = [];
if (colorsBlock) {
// Loop through the child blocks (array items) and get their values
colorsBlock.childBlocks_.forEach((childBlock) => {
// Get the color value from the child block
const color = childBlock.getFieldValue("COLOR");
if (color) {
colorsArray.push(color);
}
});
}
color = colorsArray;
}
if (block.type === "set_sky_color") {
let isColorList = false;
let colorList = [];
for (let child of block.childBlocks_) {
if (child.type === "lists_create_with") {
isColorList = true;
for (let input of child.inputList) {
colorList.push(input.connection.targetBlock().getFieldValue("COLOR"));
}
}
}
if (isColorList) {
color = colorList;
}
flock.setSky(color);
return;
}
if (block.type === "set_background_color") {
flock.setSky(color);
return;
}
if (block.type === "create_ground") {
flock.createGround(color, "ground");
return;
}
if (block.type === "create_map") {
let map = block.getFieldValue("MAP_NAME");
const materialBlock = block.getInputTargetBlock("MATERIAL");
if (materialBlock) {
const { textureSet, baseColor, alpha } =
extractMaterialInfo(materialBlock);
const materialOptions = {
color: baseColor, // baseColor → color
materialName: textureSet, // textureSet → materialName
alpha, // unchanged
};
const material = flock.createMaterial(materialOptions);
flock.createMap(map, material);
} else {
}
return;
}
if (block.type.startsWith("load_")) {
let scale = block
.getInput("SCALE")
.connection.targetBlock()
.getFieldValue("NUM");
if (changed === "SCALE") {
const relativeScale = changeEvent.oldValue
? scale / changeEvent.oldValue
: scale;
if (relativeScale !== 1) {
const x = mesh.position.x;
const y = mesh.position.y;
const z = mesh.position.z;
let ydiff;
// Find the child that actually has geometry (i.e. the visual mesh)
const relativeScale = changeEvent.oldValue
? scale / changeEvent.oldValue
: scale;
mesh.computeWorldMatrix(true);
mesh.refreshBoundingInfo();
ydiff = mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
rescaleBoundingBox(mesh, relativeScale);
mesh.computeWorldMatrix(true);
mesh.refreshBoundingInfo();
flock.positionAt(mesh.name, {
x: mesh.position.x,
y: mesh.position.y - ydiff,
z: mesh.position.z,
});
const ydiffAfter = mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
//mesh.position.y -= ydiffAfter;
mesh.computeWorldMatrix(true);
mesh.refreshBoundingInfo();
}
}
} else {
flock.updatePhysics(mesh);
}
// Retrieve the position values (X, Y, Z) from the connected blocks
let position;
position = {
x: block.getInput("X").connection.targetBlock().getFieldValue("NUM"),
y: block.getInput("Y").connection.targetBlock().getFieldValue("NUM"),
z: block.getInput("Z").connection.targetBlock().getFieldValue("NUM"),
};
let colors,
width,
height,
depth,
diameterX,
diameterY,
diameterZ,
cylinderHeight,
diameterTop,
diameterBottom,
sides,
capsuleHeight,
diameter,
planeWidth,
planeHeight,
modelName;
// Shape-specific updates based on the block type
switch (shapeType) {
case "load_object":
if (changed === "MODELS") {
// Handle live model replacement
replaceMeshModel(mesh, block, changeEvent);
return;
}
break;
case "load_model":
break;
case "load_multi_object":
if (changed === "MODELS") {
// Handle live model replacement for multi objects
replaceMeshModel(mesh, block, changeEvent);
return;
}
break;
case "load_character":
if (changed === "MODELS") {
// Handle live model replacement for characters
replaceMeshModel(mesh, block, changeEvent);
return;
}
modelName = block.getFieldValue("MODELS");
if (changed in colorFields) {
// Retrieve colours
colors = {
hair: block
.getInput("HAIR_COLOR")
.connection.targetBlock()
.getFieldValue("COLOR"),
skin: block
.getInput("SKIN_COLOR")
.connection.targetBlock()
.getFieldValue("COLOR"),
eyes: block
.getInput("EYES_COLOR")
.connection.targetBlock()
.getFieldValue("COLOR"),
tshirt: block
.getInput("TSHIRT_COLOR")
.connection.targetBlock()
.getFieldValue("COLOR"),
shorts: block
.getInput("SHORTS_COLOR")
.connection.targetBlock()
.getFieldValue("COLOR"),
sleeves: block
.getInput("SLEEVES_COLOR")
.connection.targetBlock()
.getFieldValue("COLOR"),
};
flock.applyColorsToCharacter(getMeshFromBlock(block), colors);
}
break;
case "create_box":
// Retrieve width, height, and depth from connected blocks
width = block
.getInput("WIDTH")
.connection.targetBlock()
.getFieldValue("NUM");
height = block
.getInput("HEIGHT")
.connection.targetBlock()
.getFieldValue("NUM");
depth = block
.getInput("DEPTH")
.connection.targetBlock()
.getFieldValue("NUM");
// Set the absolute size of the box (not scaling)
setAbsoluteSize(mesh, width, height, depth);
break;
case "create_sphere":
// Retrieve diameter values for X, Y, Z from connected blocks
diameterX = block
.getInput("DIAMETER_X")
.connection.targetBlock()
.getFieldValue("NUM");
diameterY = block
.getInput("DIAMETER_Y")
.connection.targetBlock()
.getFieldValue("NUM");
diameterZ = block
.getInput("DIAMETER_Z")
.connection.targetBlock()
.getFieldValue("NUM");
// Set the absolute size of the sphere based on diameters
setAbsoluteSize(mesh, diameterX, diameterY, diameterZ);
break;
case "create_cylinder":
// Retrieve height, diameterTop, and diameterBottom from connected blocks
if (
["HEIGHT", "DIAMETER_TOP", "DIAMETER_BOTTOM", "TESSELATIONS"].includes(
changed,
)
) {
cylinderHeight = block
.getInput("HEIGHT")
.connection.targetBlock()
.getFieldValue("NUM");
diameterTop = block
.getInput("DIAMETER_TOP")
.connection.targetBlock()
.getFieldValue("NUM");
diameterBottom = block
.getInput("DIAMETER_BOTTOM")
.connection.targetBlock()
.getFieldValue("NUM");
sides = block
.getInput("TESSELLATIONS")
.connection.targetBlock()
.getFieldValue("NUM");
updateCylinderGeometry(
mesh,
diameterTop,
diameterBottom,
cylinderHeight,
sides,
);
}
break;
case "create_capsule":
// Retrieve diameter and height from connected blocks
if (["HEIGHT", "DIAMETER"].includes(changed)) {
diameter = block
.getInput("DIAMETER")
.connection.targetBlock()
.getFieldValue("NUM");
capsuleHeight = block
.getInput("HEIGHT")
.connection.targetBlock()
.getFieldValue("NUM");
// Set the absolute size of the capsule
setAbsoluteSize(mesh, diameter, capsuleHeight, diameter);
}
break;
case "create_plane":
// Retrieve width and height from connected blocks
if (["HEIGHT", "WIDTH"].includes(changed)) {
planeWidth = block
.getInput("WIDTH")
.connection.targetBlock()
.getFieldValue("NUM");
planeHeight = block
.getInput("HEIGHT")
.connection.targetBlock()
.getFieldValue("NUM");
// Set the absolute size of the plane
setAbsoluteSize(mesh, planeWidth, planeHeight, 0); // Planes are usually flat in the Z dimension
}
break;
case "rotate_to":
// Recognised as a shape here for some reason.
break;
default:
console.warn(`Unknown shape type: ${shapeType}`);
}
// Use flock API to change the color and position of the mesh
if (["COLOR", "COLORS"].includes(changed) || changed.startsWith("ADD")) {
if (color) {
// Check if color is the hardcoded purple and replace with config default
if (color === "#9932cc" && block.type === "load_object") {
const modelName = block.getFieldValue("MODELS");
color = objectColours[modelName] || "#FFD700";
}
const ultimateParent = (mesh) =>
mesh.parent ? ultimateParent(mesh.parent) : mesh;
//color = flock.getColorFromString(color);
mesh = ultimateParent(mesh);
flock.changeColor(mesh.name, { color });
}
}
if (["X", "Y", "Z"].includes(changed)) {
switch (block.type) {
case "rotate_to":
/* The "position" X, Y and Z values are automatically picked up from the "rotate_to"
block and assigned as such, so we can just use those for the rotations instead of
having to reassign them. */
flock.rotateTo(mesh.name, {
x: position.x,
y: position.y,
z: position.z,
});
break;
default:
flock.positionAt(mesh.name, {
x: position.x,
y: position.y,
z: position.z,
useY: true,
});
break;
}
} else if (!["X", "Y", "Z"].includes(changed) && changed === "SCALE") {
for (const childBlock of block.getChildren()) {
if (childBlock.type === "rotate_to") {
let rotation = {
x: childBlock
.getInput("X")
.connection.targetBlock()
.getFieldValue("NUM"),
y: childBlock
.getInput("Y")
.connection.targetBlock()
.getFieldValue("NUM"),
z: childBlock
.getInput("Z")
.connection.targetBlock()
.getFieldValue("NUM"),
};
flock.rotateTo(mesh.name, {
x: rotation.x,
y: rotation.y,
z: rotation.z,
});
}
}
}
//console.log("Update physics");
flock.updatePhysics(mesh);
}
function moveMeshToOrigin(mesh) {
mesh.position = flock.BABYLON.Vector3.Zero();
mesh.rotation = flock.BABYLON.Vector3.Zero();
return mesh;
}
function setAbsoluteSize(mesh, width, height, depth) {
flock.ensureUniqueGeometry(mesh);
const boundingInfo = mesh.getBoundingInfo();
const originalSize = boundingInfo.boundingBox.extendSize;
// Store the current world matrix and decompose it
const worldMatrix = mesh.computeWorldMatrix(true);
const currentScale = new flock.BABYLON.Vector3();
const currentRotationQuaternion = new flock.BABYLON.Quaternion();
const currentPosition = new flock.BABYLON.Vector3();
worldMatrix.decompose(
currentScale,
currentRotationQuaternion,
currentPosition,
);
// Temporarily move mesh to origin
mesh = moveMeshToOrigin(mesh);
// Calculate new scaling
const newScaleX = width / (originalSize.x * 2);
const newScaleY = height / (originalSize.y * 2);
const newScaleZ = depth === 0 ? 1 : depth / (originalSize.z * 2);
// Apply scaling
mesh.scaling = new flock.BABYLON.Vector3(newScaleX, newScaleY, newScaleZ);
// Bake the scaling into the vertices
mesh.bakeCurrentTransformIntoVertices();
// Reset scaling to 1,1,1
mesh.scaling = flock.BABYLON.Vector3.One();
// Restore original position and rotation from world matrix
mesh.position = currentPosition;
mesh.rotationQuaternion = currentRotationQuaternion;
let shapeType = null;
if (mesh.metadata) shapeType = mesh.metadata.shapeType;
if (mesh.physics && shapeType) {
const shape = mesh.physics.shape;
let newShape, diameterBottom, startPoint, endPoint, diameter;
// Create the new physics shape based on the type
switch (shapeType) {
case "Box":
newShape = new flock.BABYLON.PhysicsShapeBox(
flock.BABYLON.Vector3.Zero(),
new flock.BABYLON.Quaternion(0, 0, 0, 1),
new flock.BABYLON.Vector3(width, height, depth),
mesh.getScene(),
);
break;
case "Cylinder":
diameterBottom = Math.min(width, depth);
startPoint = new flock.BABYLON.Vector3(0, -height / 2, 0);
endPoint = new flock.BABYLON.Vector3(0, height / 2, 0);
newShape = new flock.BABYLON.PhysicsShapeCylinder(
startPoint,
endPoint,
diameterBottom / 2,
mesh.getScene(),
);
break;
case "Sphere":
newShape = new flock.BABYLON.PhysicsShapeSphere(
flock.BABYLON.Vector3.Zero(),
Math.max(width, depth, height) / 2,
mesh.getScene(),
);
break;
case "Capsule":
diameter = Math.min(width, depth);
newShape = flock.createCapsuleFromBoundingBox(mesh, mesh.getScene());
break;
default:
console.log("Unknown or unsupported physics shape type: " + shapeType);
break;
}
if (newShape) {
shape.dispose();
const physicsBody = mesh.physics;
physicsBody.shape = newShape;
mesh.physics.disablePreStep;
mesh.computeWorldMatrix(true);
}
}
}
function updateCylinderGeometry(
mesh,
diameterTop,
diameterBottom,
height,
sides,
) {
// Store the current world matrix and decompose it
const worldMatrix = mesh.computeWorldMatrix(true);
const currentScale = new flock.BABYLON.Vector3();
const currentRotationQuaternion = new flock.BABYLON.Quaternion();
const currentPosition = new flock.BABYLON.Vector3();
worldMatrix.decompose(
currentScale,
currentRotationQuaternion,
currentPosition,
);
// If the mesh has geometry, dispose of it before updating
if (mesh.geometry) {
mesh.geometry.dispose();
}
// Temporarily reset mesh transform
mesh = moveMeshToOrigin(mesh);
mesh.scaling = flock.BABYLON.Vector3.One();
// Create a temporary mesh with the provided dimensions (already in world space)
const tempMesh = flock.BABYLON.MeshBuilder.CreateCylinder(
"",
{
height: height,
diameterTop: diameterTop,
diameterBottom: diameterBottom,
tessellation: sides,
updatable: true,
},
mesh.getScene(),
);
// Extract vertex data from the temporary mesh
const vertexData = flock.BABYLON.VertexData.ExtractFromMesh(tempMesh);
// Create new geometry for the mesh
const newGeometry = new flock.BABYLON.Geometry(
mesh.name + "_geometry",
mesh.getScene(),
vertexData,
true,
mesh,
);
// Apply the new geometry to the mesh
newGeometry.applyToMesh(mesh);
mesh.makeGeometryUnique();
// Dispose of the temporary mesh after extracting vertex data
tempMesh.dispose();
// Restore position and rotation only, keep scale at 1,1,1
mesh.position = currentPosition;
mesh.rotationQuaternion = currentRotationQuaternion;
mesh.scaling = flock.BABYLON.Vector3.One();
// Ensure the world matrix is updated
mesh.computeWorldMatrix(true);
}
function replaceMeshModel(currentMesh, block) {
if (!currentMesh || !block) return;
const modelName = block.getFieldValue("MODELS");
if (!modelName) return;
// ---------- helpers ----------
function walkNodes(root) {
const out = [];
const stack = [root];
while (stack.length) {
const n = stack.pop();
if (!n) continue;
out.push(n);
if (n.getChildren) {
const kids = n.getChildren();
for (let i = kids.length - 1; i >= 0; i--) stack.push(kids[i]);
}
}
return out;
}
function isRenderableMesh(n) {
const cls = n?.getClassName?.();
return cls === "Mesh" || cls === "InstancedMesh";
}
function firstRenderable(node) {
const nodes = walkNodes(node);
for (const n of nodes) {
if (isRenderableMesh(n) && n.name !== "__root__") return n;
}
return null;
}
function disposeTree(node) {
if (!node || node.isDisposed?.()) return;
const kids = node.getChildren ? node.getChildren() : [];
for (const k of kids) disposeTree(k);
try { node.setParent?.(null); } catch {}
try { node.dispose?.(); } catch {}
}
function disposePhysics(node) {
try { node.physics?.dispose?.(); } catch {}
}
function stripPhysicsTree(root) {
const stack = [root];
while (stack.length) {
const n = stack.pop();
if (!n) continue;
disposePhysics(n);
if (n.getChildren) {
const kids = n.getChildren();
for (let i = 0; i < kids.length; i++) stack.push(kids[i]);
}
}
}
function _colToHex(c) {
if (!c) return null;
const r = Math.round(c.r * 255), g = Math.round(c.g * 255), b = Math.round(c.b * 255);
return flock.rgbToHex(r, g, b);
}
function _matPrimaryColor(mat) {
if (!mat) return null;
return (mat.diffuseColor !== undefined && mat.diffuseColor)
? mat.diffuseColor
: (mat.albedoColor !== undefined && mat.albedoColor)
? mat.albedoColor
: null;
}
function printMaterialTree(root, label = "MATERIAL_TREE") {
function printNode(node, depth) {
const indent = " ".repeat(depth);
const cls = node?.getClassName?.();
const nm = node?.name;
const metaIdx = node?.metadata?.materialIndex;
console.log(`${label} - ${indent}${nm} [${cls}] meta.materialIndex=${metaIdx}`);
let mat = node?.material;
let matOwner = "self";
if (!mat && cls === "InstancedMesh") {
mat = node?.sourceMesh?.material || null;
matOwner = mat ? "sourceMesh" : "self";
}
if (!mat) {
console.log(`${label} ${indent}material: none`);
} else {
const mCls = mat.getClassName?.();
console.log(`${label} ${indent}material(${matOwner}): ${mat.name || "(unnamed)"} [${mCls}]`);
if (mCls === "MultiMaterial") {
const subs = mat.subMaterials || [];
const subMeshes = node.subMeshes || [];
console.log(`${label} ${indent}subMaterials: ${subs.length} | subMeshes: ${subMeshes.length}`);
for (let i = 0; i < subs.length; i++) {
const sm = subs[i];
const c = _matPrimaryColor(sm);
console.log(`${label} ${indent}[${i}] ${sm?.name || "(unnamed)"} color=${_colToHex(c)}`);
}
for (let i = 0; i < subMeshes.length; i++) {
const s = subMeshes[i];
const idx = s.materialIndex;
const sm = (mat.subMaterials || [])[idx] || null;
const c = _matPrimaryColor(sm);
console.log(`${label} ${indent}subMesh#${i} -> subMat#${idx} (${sm?.name || "?"}) color=${_colToHex(c)}`);
}
} else {
const c = _matPrimaryColor(mat);
const hasDiff = mat.diffuseColor !== undefined;
const hasAlb = mat.albedoColor !== undefined;