import React, { useEffect, useRef, useState, useCallback, Suspense } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { StickFigure } from './StickFigureBuilder';
import { AnimationController, AnimationStates } from './AnimationController';
import { getCharacter } from '../../services/marvelApi';
import { ResizeObserver as WindowResizeObserver } from "@juggle/resize-observer";
import { resizeCanvasToDisplaySize } from './threejs-utils'; // Import resizeCanvasToDisplaySize
import WebGL from 'three/addons/capabilities/WebGL.js';
const PerformanceMonitor = {
init() {
this.lastTime = performance.now();
this.frames = 0;
this.fps = 0;
this.renderCalls = 0;
this.triangles = 0;
},
begin() {
this.frames++;
const currentTime = performance.now();
if (currentTime >= this.lastTime + 1000) {
this.fps = Math.round((this.frames * 1000) / (currentTime - this.lastTime));
this.frames = 0;
this.lastTime = currentTime;
}
},
updateRenderStats(renderer) {
if (renderer) {
this.renderCalls = renderer.info.render.calls;
this.triangles = renderer.info.render.triangles;
}
},
getStats() {
return {
fps: this.fps,
renderCalls: this.renderCalls,
triangles: this.triangles
};
}
};
const DEFAULT_CHARS = {
player: '[Redacted Person]',
opponent: 'Venom'
};
const SCENE_CONFIG = {
camera: {
fov: 60,
near: 0.1,
far: 1000,
position: new THREE.Vector3(0, 5, 10),
lookAt: new THREE.Vector3(0, 1, 0),
},
renderer: {
antialias: true,
shadowMap: {
enabled: true,
type: THREE.PCFSoftShadowMap,
},
outputColorSpace: THREE.SRGBColorSpace,
toneMapping: THREE.ACESFilmicToneMapping,
},
fighters: {
player: {
position: new THREE.Vector3(-3, 0, 0),
rotation: 0,
},
opponent: {
position: new THREE.Vector3(3, 0, 0),
rotation: Math.PI,
},
},
lights: {
ambient: {
color: 0x404040,
intensity: 1,
},
main: {
color: 0xffffff,
intensity: 1.5,
position: new THREE.Vector3(5, 5, 5),
shadow: {
mapSize: new THREE.Vector2(2048, 2048),
camera: {
near: 0.5,
far: 50,
bias: -0.0001,
},
},
},
back: {
color: 0x2200ff,
intensity: 0.5,
position: new THREE.Vector3(-5, 3, -5),
},
rim: {
color: 0x404040,
intensity: 1,
position: new THREE.Vector3(0, 10, -10),
},
},
ground: {
size: 30,
material: {
color: 0x333333,
roughness: 0.8,
metalness: 0.2,
},
},
debug: process.env.NODE_ENV === 'development',
};
const [Redacted Person] = () => {
const mountRef = useRef(null);
const sceneRef = useRef(new THREE.Scene());
const rendererRef = useRef(null);
const cameraRef = useRef(null);
const controlsRef = useRef(null);
const fightersRef = useRef({});
const clockRef = useRef(new THREE.Clock());
const frameIdRef = useRef(null);
const performanceMonitorRef = useRef(null);
const resizeObserverRef = useRef(null);
const composerRef = useRef(null);
const [characters, setCharacters] = useState({
player: null,
opponent: null,
});
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [sceneReady, setSceneReady] = useState(false);
const [performanceStats, setPerformanceStats] = useState({});
const cleanup = useCallback(() => {
cancelAnimationFrame(frameIdRef.current);
if (resizeObserverRef.current) {
resizeObserverRef.current.disconnect();
}
Object.values(fightersRef.current).forEach(controller => {
controller?.dispose();
});
if (rendererRef.current) {
rendererRef.current.dispose();
}
if (composerRef.current) {
composerRef.current.dispose();
}
if (mountRef.current) {
mountRef.current.remove();
}
}, []);
const setupLighting = useCallback((scene) => {
const ambientLight = new THREE.AmbientLight(
SCENE_CONFIG.lights.ambient.color,
SCENE_CONFIG.lights.ambient.intensity
);
scene.add(ambientLight);
const mainLight = new THREE.DirectionalLight(
SCENE_CONFIG.lights.main.color,
SCENE_CONFIG.lights.main.intensity
);
mainLight.position.copy(SCENE_CONFIG.lights.main.position);
mainLight.castShadow = true;
mainLight.shadow.mapSize.copy(SCENE_CONFIG.lights.main.shadow.mapSize);
mainLight.shadow.camera.near = SCENE_CONFIG.lights.main.shadow.camera.near;
mainLight.shadow.camera.far = SCENE_CONFIG.lights.main.shadow.camera.far;
mainLight.shadow.bias = SCENE_CONFIG.lights.main.shadow.camera.bias;
if (SCENE_CONFIG.debug) {
const helper = new THREE.CameraHelper(mainLight.shadow.camera);
scene.add(helper);
}
scene.add(mainLight);
const backLight = new THREE.DirectionalLight(
SCENE_CONFIG.lights.back.color,
SCENE_CONFIG.lights.back.intensity
);
backLight.position.copy(SCENE_CONFIG.lights.back.position);
scene.add(backLight);
const rimLight = new THREE.SpotLight(
SCENE_CONFIG.lights.rim.color,
SCENE_CONFIG.lights.rim.intensity
);
rimLight.position.copy(SCENE_CONFIG.lights.rim.position);
scene.add(rimLight);
}, []);
const createGround = useCallback((scene) => {
const groundGeometry = new THREE.PlaneGeometry(
SCENE_CONFIG.ground.size,
SCENE_CONFIG.ground.size
);
const groundMaterial = new THREE.MeshStandardMaterial({
...SCENE_CONFIG.ground.material,
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
}, []);
const handleResize = useCallback(() => {
if (!cameraRef.current || !rendererRef.current || !mountRef.current) return;
const canvas = rendererRef.current.domElement;
const needResize = resizeCanvasToDisplaySize(canvas);
if (needResize) {
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const aspect = width / height;
cameraRef.current.aspect = aspect;
cameraRef.current.updateProjectionMatrix();
rendererRef.current.setSize(width, height, false);
rendererRef.current.setPixelRatio(Math.min(2, window.devicePixelRatio));
if (composerRef.current) {
composerRef.current.setSize(width, height);
}
Object.values(fightersRef.current).forEach(controller => {
controller.updateViewport(width, height);
});
}
}, []);
useEffect(() => {
const loadCharacters = async () => {
try {
setLoading(true);
const [player, opponent] = await Promise.all([
getCharacter(DEFAULT_CHARS.player),
getCharacter(DEFAULT_CHARS.opponent),
]);
setCharacters({ player, opponent });
} catch (err) {
console.error('Character loading error:', err);
setError('Failed to load characters');
} finally {
setLoading(false);
}
};
loadCharacters();
}, []);
useEffect(() => {
if (loading) return;
if ( ! WebGL.isWebGLAvailable() ) {
setError('WebGL2 is not supported in your browser.');
return;
}
setSceneReady(true);
}, [loading]);
useEffect(() => {
if (loading || !sceneReady) return;
const scene = sceneRef.current;
scene.background = new THREE.Color(0x111111);
scene.fog = new THREE.Fog(0x111111, 10, 50);
const renderer = new THREE.WebGLRenderer({
...SCENE_CONFIG.renderer,
powerPreference: 'high-performance',
stencil: false,
alpha: true,
canvas: mountRef.current.querySelector('canvas'),
});
renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
Object.assign(renderer.shadowMap, SCENE_CONFIG.renderer.shadowMap);
renderer.outputColorSpace = SCENE_CONFIG.renderer.outputColorSpace;
renderer.toneMapping = SCENE_CONFIG.renderer.toneMapping;
rendererRef.current = renderer;
const camera = new THREE.PerspectiveCamera(
SCENE_CONFIG.camera.fov,
mountRef.current.clientWidth / mountRef.current.clientHeight,
SCENE_CONFIG.camera.near,
SCENE_CONFIG.camera.far
);
camera.position.copy(SCENE_CONFIG.camera.position);
camera.lookAt(SCENE_CONFIG.camera.lookAt);
cameraRef.current = camera;
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxPolarAngle = Math.PI / 2;
controls.minDistance = 5;
controls.maxDistance = 20;
controls.target.copy(SCENE_CONFIG.camera.lookAt);
controls.update();
controlsRef.current = controls;
if (SCENE_CONFIG.debug) {
performanceMonitorRef.current = PerformanceMonitor;
performanceMonitorRef.current.init();
}
setupLighting(scene);
createGround(scene);
const createFighter = (character, config) => {
const fighter = new StickFigure(character?.traits || {});
fighter.figure.position.copy(config.position);
fighter.figure.rotation.y = config.rotation;
scene.add(fighter.figure);
return fighter;
};
const player = createFighter(
characters.player,
SCENE_CONFIG.fighters.player
);
const opponent = createFighter(
characters.opponent,
SCENE_CONFIG.fighters.opponent
);
fightersRef.current = {
player: new AnimationController(player, characters.player?.traits),
opponent: new AnimationController(opponent, characters.opponent?.traits),
};
const resizeObserver = new WindowResizeObserver(handleResize);
resizeObserver.observe(mountRef.current);
resizeObserverRef.current = resizeObserver;
const animate = () => {
frameIdRef.current = requestAnimationFrame(animate);
if (performanceMonitorRef.current) {
performanceMonitorRef.current.begin();
}
const delta = clockRef.current.getDelta();
if (controlsRef.current) {
controlsRef.current.update();
}
Object.values(fightersRef.current).forEach(controller => {
controller.update(delta);
});
if (composerRef.current) {
composerRef.current.render();
} else {
rendererRef.current.render(scene, camera);
}
if (performanceMonitorRef.current) {
performanceMonitorRef.current.updateRenderStats(rendererRef.current);
setPerformanceStats(performanceMonitorRef.current.getStats());
}
};
animate();
const simulateFight = () => {
const states = Object.values(AnimationStates);
let stateIndex = 0;
const getDelay = (char) =>
Math.max(1000, 3000 - ((char?.stats?.speed || 50) * 10));
const playerDelay = getDelay(characters.player);
const opponentDelay = getDelay(characters.opponent);
let playerNextMoveTime = performance.now() + playerDelay;
let opponentNextMoveTime = performance.now() + opponentDelay;
let stateNextChangeTime = performance.now() + Math.min(playerDelay, opponentDelay);
const animateFight = () => {
if (!frameIdRef.current) return; // Stop if the main animation loop is not running
const now = performance.now();
if (now >= [Redacted Person]) {
fightersRef.current.player?.playMove(states[stateIndex % states.length]);
playerNextMoveTime = now + playerDelay;
}
if (now >= opponentNextMoveTime) {
fightersRef.current.opponent?.playMove(states[(stateIndex + 2) % states.length]);
opponentNextMoveTime = now + opponentDelay;
}
if (now >= stateNextChangeTime) {
stateIndex = (stateIndex + 1) % states.length;
stateNextChangeTime = now + Math.min(playerDelay, opponentDelay);
}
requestAnimationFrame(animateFight);
};
const fightFrameId = requestAnimationFrame(animateFight);
return () => {
cancelAnimationFrame(fightFrameId);
};
};
const cleanupFight = simulateFight();
return () => {
cleanupFight();
cleanup();
};
}, [loading, characters, sceneReady, cleanup, setupLighting, createGround, handleResize]);
if (loading) {
return (
<div className="loading absolute inset-0 flex items-center justify-center bg-black bg-opacity-75 text-white">
<div className="text-center">
<div className="mb-4 text-xl">Loading characters...</div>
<div className="h-2 w-48 bg-gray-700 rounded-full overflow-hidden">
<div className="h-full bg-blue-500 animate-pulse rounded-full"></div>
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="error absolute inset-0 flex items-center justify-center bg-red-600 text-white">
{error}
</div>
);
}
return (
<Suspense fallback={<div>Loading scene...</div>}>
<div ref={mountRef} className="scene-container w-full h-full bg-black" >
<canvas width={window.innerWidth} height={window.innerHeight} />
</div>
{characters.player && characters.opponent && (
<div className="character-info absolute top-0 left-0 w-full p-4 text-white">
<div className="flex justify-between items-center backdrop-blur-sm bg-black bg-opacity-50 rounded-lg p-2">
{/* Player Info */}
<div className="player flex items-center space-x-2">
<img
src={`${characters.player.thumbnail?.path}.${characters.player.thumbnail?.extension}`}
alt={characters.player.name}
className="w-8 h-8 rounded-full object-cover"
/>
<div className="flex flex-col">
<span className="font-bold">{characters.player.name}</span>
<div className="stats flex space-x-2 text-sm">
{characters.player.traits?.powers.map((power, index) => (
<span key={index} className="power-badge px-2 py-0.5 bg-blue-500 rounded-full">
{power}
</span>
))}
</div>
</div>
</div>
{/* VS Badge */}
<div className="vs-container relative">
<div className="vs font-bold text-2xl text-red-500 animate-pulse">VS</div>
<div className="absolute -inset-2 bg-red-500 opacity-20 rounded-full blur"></div>
</div>
{/* Opponent Info */}
<div className="opponent flex items-center space-x-2">
<div className="flex flex-col items-end">
<span className="font-bold">{characters.opponent.name}</span>
<div className="stats flex space-x-2 text-sm">
{characters.opponent.traits?.powers.map((power, index) => (
<span key={index} className="power-badge px-2 py-0.5 bg-red-500 rounded-full">
{power}
</span>
))}
</div>
</div>
<img
src={`${characters.opponent.thumbnail?.path}.${characters.opponent.extension}`}
alt={characters.opponent.name}
className="w-8 h-8 rounded-full object-cover"
/>
</div>
</div>
{/* Fight Controls */}
<div className="fight-controls absolute bottom-4 left-1/2 transform -translate-x-1/2">
<div className="flex space-x-4">
{Object.entries(fightersRef.current.player?.availableMoves || {}).map(([moveName, move]) => (
<button
key={moveName}
onClick={() => fightersRef.current.player?.playMove(moveName)}
className="move-button px-4 py-2 bg-blue-600 hover:bg-blue-700
rounded-lg text-white font-medium transform hover:scale-105
transition-all duration-200 shadow-lg hover:shadow-xl
disabled:opacity-50 disabled:cursor-not-allowed"
disabled={loading || !sceneReady}
>
{moveName.replace('_', ' ')}
</button>
))}
</div>
</div>
{/* Debug Panel */}
{[Redacted Person]_CONFIG.debug && (
<div className="debug-panel absolute top-4 right-4 bg-black bg-opacity-75
text-white p-4 rounded-lg text-sm">
<h3 className="font-bold mb-2">Debug Info</h3>
<div className="grid grid-cols-2 gap-2">
<div>FPS: {Math.round(performanceStats?.fps || 0)}</div>
<div>Draw Calls: {rendererRef.current?.info.render.calls || 0}</div>
<div>Triangles: {rendererRef.current?.info.render.triangles || 0}</div>
<div>Active Animations: {
Object.values(fightersRef.current)
.reduce((acc, fighter) => acc + fighter.getActiveAnimations(), 0)
}</div>
</div>
</div>
)}
</div>
)}
</Suspense>
);
}
export default MarvelFightScene;
Key Changes and Explanations:
- Import
WebGL: Added import WebGL from 'three/addons/capabilities/WebGL.js'; to import the WebGL check module.
- Added WebGL check: added useEffect hook to set error if WebGL is not available.
- Canvas initialization: Canvas now is initialized on JSX code.
- Removed
forceContextLoss(): Removed the call to renderer.forceContextLoss() from the cleanup function.
- Used
performance.now() in simulateFight: Modified the simulateFight function to use performance.now() and requestAnimationFrame for smoother, more accurate animation triggering. The setInterval calls have been replaced with logic that schedules the next animation frame based on elapsed time.
- handleResize Fixed: Added canvas element retrival and resizeCanvasToDisplaySize check.
- Added WebGL Compatibility Check: Implemented a check for WebGL availability using
THREE.WebGLUtils and displays an error message if it's not supported. This prevents the component from crashing on incompatible browsers.
This revised code incorporates the suggestions from the previous response and provides a more robust and optimized Three.js component for your React application. Remember to implement the dispose methods in StickFigure and AnimationController to complete the resource management improvements. Also, thoroughly test the changes to ensure everything is working correctly.