// src/components/MarvelFight/StickFigureBuilder.js
import * as THREE from 'three';
// Define shared geometries to optimize GPU memory usage
const SharedGeometries = {
head: new THREE.SphereGeometry(0.25, 32, 32),
upperBody: new THREE.CylinderGeometry(0.2, 0.25, 1.0, 16),
upperLimb: new THREE.CylinderGeometry(0.08, 0.07, 0.4, 12),
lowerLimb: new THREE.CylinderGeometry(0.07, 0.06, 0.35, 12),
hand: new THREE.SphereGeometry(0.08, 16, 16),
foot: new THREE.BoxGeometry(0.15, 0.1, 0.25)
};
export class StickFigure {
constructor(characterTraits) {
// Properties
this.traits = characterTraits;
this.height = this.traits.physicalTraits?.height || 1.8;
this.scale = this.traits.physicalTraits?.scale || 1.0;
// Main container group
this.figure = new THREE.Group();
this.root = this.figure; // Alias for internal use
// Create joints group and add to figure
this.joints = new THREE.Group();
this.figure.add(this.joints);
// Initialize storage
this.bones = {};
this.hitboxes = {};
this.actions = new Map();
this.animations = new Map();
// Setup components
this.setupMaterials();
this.createBodyParts();
this.setupHitboxes();
this.setupAnimations();
this.setupPhysics();
}
setupMaterials() {
const colors = this.traits.primaryColors || ['#4A90E2', '#C4C4C4', '#2C3E50'];
this.materials = {
primary: new THREE.MeshPhongMaterial({
color: new THREE.Color(colors[0]),
shininess: 30,
specular: 0x111111,
shadowSide: THREE.FrontSide,
}),
secondary: new THREE.MeshPhongMaterial({
color: new THREE.Color(colors[1]),
shininess: 20,
specular: 0x111111,
shadowSide: THREE.FrontSide,
}),
accent: new THREE.MeshPhongMaterial({
color: new THREE.Color(colors[2]),
shininess: 40,
specular: 0x222222,
shadowSide: THREE.FrontSide,
}),
hitbox: new THREE.MeshBasicMaterial({
visible: false,
transparent: true,
opacity: 0.3,
color: 0xff0000,
depthTest: false
})
};
}
createBodyParts() {
// Calculate build-specific scale
const buildScale = this.calculateBuildScale();
// Create head using shared geometry
const head = new THREE.Mesh(SharedGeometries.head, this.materials.secondary);
head.position.y = this.height;
head.scale.setScalar(buildScale.width);
this.joints.add(head);
this.bones.head = head;
// Create body using shared geometry
const body = new THREE.Mesh(SharedGeometries.upperBody, this.materials.primary);
body.position.y = this.height * 0.5;
body.scale.set(buildScale.width, buildScale.height * 0.5, buildScale.width);
this.joints.add(body);
this.bones.body = body;
// Create limbs
this.createLimb('leftArm', {
x: 0.3 * buildScale.width,
y: this.height * 0.8,
z: 0,
isLeft: true
});
this.createLimb('rightArm', {
x: -0.3 * buildScale.width,
y: this.height * 0.8,
z: 0,
isLeft: false
});
this.createLimb('leftLeg', {
x: 0.2 * buildScale.width,
y: this.height * 0.3,
z: 0,
[Redacted Person]: true,
isLeft: true
});
this.createLimb('rightLeg', {
x: -0.2 * buildScale.width,
y: this.height * 0.3,
z: 0,
[Redacted Person]: true,
isLeft: false
});
// Apply shadows
this.joints.traverse((object) => {
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
// Log the order of children to the console for debugging
console.log("Joints children:", this.joints.children);
}
createLimb(name, options) {
const { x, y, z, isLeg, isLeft } = options;
const buildScale = this.calculateBuildScale();
// Create joint group
const joint = new THREE.Group();
joint.position.set(x, y, z);
this.joints.add(joint);
this.bones[`${name}Joint`] = joint;
// Create upper limb
const upperLimb = new THREE.Mesh(
SharedGeometries.upperLimb,
this.materials.primary
);
upperLimb.scale.set(
buildScale.width,
[Redacted Person] ? 1.25 : 1,
buildScale.width
);
upperLimb.position.y = isLeg ? -0.25 : -0.2;
joint.add(upperLimb);
this.bones[`upper${name}`] = upperLimb;
// Create lower joint
const lowerJoint = new THREE.Group();
lowerJoint.position.y = isLeg ? -0.5 : -0.4;
joint.add(lowerJoint);
this.bones[`lower${name}Joint`] = lowerJoint;
// Create lower limb
const lowerLimb = new THREE.Mesh(
SharedGeometries.lowerLimb,
this.materials.primary
);
lowerLimb.scale.set(
buildScale.width,
[Redacted Person] ? 1.25 : 1,
buildScale.width
);
lowerLimb.position.y = isLeg ? -0.25 : -0.175;
joint.add(lowerLimb);
this.bones[`lower${name}`] = lowerLimb;
// Add extremity (foot/hand)
if (isLeg) {
const foot = new THREE.Mesh(
SharedGeometries.foot,
this.materials.secondary
);
foot.position.set(0, -0.5, 0.05);
foot.scale.set(buildScale.width, 1, buildScale.width);
lowerJoint.add(foot);
this.bones[`${name}Foot`] = foot;
} else {
const hand = new THREE.Mesh(
SharedGeometries.hand,
this.materials.secondary
);
hand.position.y = -0.35;
hand.scale.setScalar(buildScale.width);
lowerJoint.add(hand);
this.bones[`${name}Hand`] = hand;
}
return joint;
}
setupHitboxes() {
// Create body hitbox
const bodyHitbox = new THREE.Box3();
bodyHitbox.setFromObject(this.bones.body);
this.hitboxes.body = bodyHitbox;
// Create limb hitboxes
['leftArm', 'rightArm', 'leftLeg', 'rightLeg'].forEach(limb => {
const upperBone = this.bones[`upper${limb}`];
const lowerBone = this.bones[`lower${limb}`];
if (upperBone && lowerBone) {
const limbHitbox = new THREE.Box3();
limbHitbox.expandByObject(upperBone);
limbHitbox.expandByObject(lowerBone);
this.hitboxes[limb] = limbHitbox;
}
});
}
setupAnimations() {
this.mixer = new THREE.AnimationMixer(this.figure);
// Create base animation clips
const clips = this.createBaseAnimationClips();
// Add character-specific animation clips based on traits
if (this.traits.specialMoves) {
this.traits.specialMoves.forEach(move => {
const clip = this.createSpecialMoveClip(move);
if (clip) clips.set(move.name, clip);
});
}
// Create animation actions
clips.forEach((clip, name) => {
const action = this.mixer.clipAction(clip);
this.actions.set(name, action);
});
// Start idle animation
const idleAction = this.actions.get('idle');
if (idleAction) {
idleAction.play();
}
}
createBaseAnimationClips() {
const clips = new Map();
const scale = this.calculateBuildScale();
// Idle animation
clips.set('idle', new THREE.AnimationClip('idle', 2.0, [
// Body bob (targets the body's position)
new THREE.VectorKeyframeTrack(
`.joints.children[1].position`, // body is at index 1
[0, 1, 2],
[
0, this.height * 0.5, 0,
0, this.height * 0.51, 0,
0, this.height * 0.5, 0
]
),
// Arm sway (targets the left arm joint's quaternion)
new THREE.QuaternionKeyframeTrack(
`.joints.children[2].quaternion`, // leftArmJoint is at index 2
[0, 1, 2],
new Array(3).fill(new THREE.Quaternion().setFromEuler(
new THREE.Euler(0.1, 0, 0.1)
).toArray()).flat()
),
// Arm sway (targets the right arm joint's quaternion)
new THREE.QuaternionKeyframeTrack(
`.joints.children[3].quaternion`, // rightArmJoint is at index 3
[0, 1, 2],
new Array(3).fill(new THREE.Quaternion().setFromEuler(
new THREE.Euler(-0.1, 0, -0.1)
).toArray()).flat()
)
]));
// Attack animation
clips.set('attack', new THREE.AnimationClip('attack', 0.5, [
// Right arm swing (targets the right arm joint's quaternion)
new THREE.QuaternionKeyframeTrack(
`.joints.children[3].quaternion`, // rightArmJoint is at index 3
[0, 0.25, 0.5],
[
new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, 0)),
new THREE.Quaternion().setFromEuler(new THREE.[Redacted Person](-Math.PI / 2, 0, 0)),
new THREE.Quaternion().setFromEuler(new THREE.[Redacted Person](0, 0, 0))
].map(q => q.toArray()).flat()
),
// Body rotation (targets the joints group's quaternion)
new THREE.QuaternionKeyframeTrack(
'.joints.quaternion', // correct
[0, 0.25, 0.5],
[
new THREE.Quaternion(),
new THREE.Quaternion().setFromEuler(new THREE.[Redacted Person](0, Math.PI / 6, 0)),
new THREE.Quaternion()
].map(q => q.toArray()).flat()
)
]));
// Block animation
clips.set('block', new THREE.AnimationClip('block', 0.3, [
// Left arm block (targets the left arm joint's quaternion)
new THREE.QuaternionKeyframeTrack(
`.joints.children[2].quaternion`, // leftArmJoint is at index 2
[0, 0.15, 0.3],
[
new THREE.Quaternion(),
new THREE.Quaternion().setFromEuler(new THREE.Euler(-Math.PI / 2, 0, -Math.PI / 4)),
new THREE.Quaternion().setFromEuler(new THREE.Euler(-Math.PI / 2, 0, -Math.PI / 4))
].map(q => q.toArray()).flat()
)
]));
// Jump animation
clips.set('jump', new THREE.AnimationClip('jump', 0.5, [
// Jump (targets the figure's position)
new THREE.VectorKeyframeTrack(
'.position', // Correct - targets the figure's position
[0, 0.25, 0.5],
[
0, 0, 0,
0, this.height * 0.5, 0,
0, 0, 0
]
),
// Body rotation (targets the joints group's quaternion)
new THREE.QuaternionKeyframeTrack(
'.joints.quaternion', // Correct - targets the joints quaternion
[0, 0.25, 0.5],
new Array(3).fill(new THREE.Quaternion().identity().toArray()).flat()
)
]));
return clips;
}
createSpecialMoveClip(move) {
const duration = move.frames / 60;
const tracks = [];
switch (move.type) {
case 'punch':
tracks.push(
new THREE.QuaternionKeyframeTrack(
`.joints.children[3].quaternion`, // rightArmJoint is at index 3
[0, duration / 2, duration],
[
new THREE.Quaternion(),
new THREE.Quaternion().setFromEuler(new THREE.Euler(-Math.PI * 0.8, 0, 0)),
new THREE.Quaternion()
].map(q => q.toArray()).flat()
)
);
break;
case 'kick':
tracks.push(
new THREE.QuaternionKeyframeTrack(
`.joints.children[5].quaternion`, // rightLegJoint is at index 5
[0, duration / 2, duration],
[
new THREE.Quaternion(),
new THREE.Quaternion().setFromEuler(new THREE.[Redacted Person](-Math.PI / 2, 0, 0)),
new THREE.Quaternion()
].map(q => q.toArray()).flat()
)
);
break;
case 'special':
tracks.push(
new THREE.VectorKeyframeTrack(
'.position', // Correct - targets the figure's position
[0, duration / 2, duration],
[
0, 0, 0,
0, this.height, 0,
0, 0, 0
]
),
new THREE.QuaternionKeyframeTrack(
'.quaternion', // Correct - targets the figure's quaternion
[0, duration / 2, duration],
[
new THREE.Quaternion(),
new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI * 2),
new THREE.Quaternion()
].map(q => q.toArray()).flat()
)
);
break;
}
return new THREE.AnimationClip(move.name, duration, tracks);
}
setupPhysics() {
this.velocity = new THREE.Vector3();
this.acceleration = new THREE.Vector3();
this.forces = new THREE.Vector3();
this.mass = (this.traits.physicalTraits?.weight || 80) * 0.1;
this.grounded = true;
// Collision data
this.boundingBox = new THREE.Box3();
this.boundingSphere = new THREE.Sphere();
this.updateBounds();
}
update(deltaTime) {
if (this.mixer) {
this.mixer.update(deltaTime);
}
// Update physics
if (!this.grounded) {
// Apply gravity
this.forces.y -= 9.81 * this.mass * deltaTime;
}
// Update velocity and position
this.acceleration.copy(this.forces).divideScalar(this.mass);
this.velocity.add(this.acceleration.multiplyScalar(deltaTime));
this.figure.position.add(this.velocity.multiplyScalar(deltaTime));
// Reset forces
this.forces.set(0, 0, 0);
// Update bounds
this.updateBounds();
// Ground collision check
if (this.figure.position.y < 0) {
this.figure.position.y = 0;
this.velocity.y = 0;
this.grounded = true;
}
}
updateBounds() {
this.boundingBox.setFromObject(this.figure);
this.boundingSphere.copy(this.boundingBox.getBoundingSphere(new THREE.Sphere()));
}
playAnimation(name, options = {}) {
const {
fadeIn = 0.2,
fadeOut = 0.2,
timeScale = 1,
weight = 1,
loop = THREE.LoopRepeat
} = options;
const action = this.actions.get(name);
if (!action) return null;
// Fade out other actions
this.actions.forEach(otherAction => {
if (otherAction !== action && otherAction.isRunning()) {
otherAction.fadeOut(fadeOut);
}
});
// Configure and play new action
action.reset()
.setEffectiveTimeScale(timeScale)
.setEffectiveWeight(weight)
.setLoop(loop, options.repetitions || Infinity)
.fadeIn(fadeIn)
.play();
return action;
}
calculateBuildScale() {
const build = this.traits.physicalTraits?.build || 'normal';
return {
slim: { width: 0.8, height: 1.1 },
muscular: { width: 1.2, height: 1 },
large: { width: 1.5, height: 1.2 }
}[build] || { width: 1, height: 1 };
}
dispose() {
// Stop animations
if (this.mixer) {
this.mixer.stopAllAction();
this.mixer.uncacheRoot(this.figure);
}
// Dispose materials
Object.values(this.materials).forEach(material => {
material.dispose();
});
// Clear references
this.bones = {};
this.hitboxes = {};
this.actions.clear();
this.animations.clear();
}
// Public API methods
getWorldPosition() {
const position = new THREE.Vector3();
this.figure.getWorldPosition(position);
return position;
}
setPosition(x, y, z) {
this.figure.position.set(x, y, z);
}
setRotation(x, y, z) {
this.figure.rotation.set(x, y, z);
}
lookAt(target) {
this.figure.lookAt(target);
}
getRootQuaternion() {
return this.figure.quaternion.clone();
}
}