Refactor code for consistency and readability

- Updated import statements to use consistent formatting across files.
- Adjusted method definitions and class constructors for uniform spacing and style.
- Simplified promise handling and error messages in state handlers.
- Enhanced state transition logic in various state handlers.
- Improved quirk animation handling in WaitStateHandler.
- Streamlined animation loading and caching mechanisms in AnimationLoader.
- Updated Vite configuration for aliasing.
This commit is contained in:
2025-05-24 01:14:35 +02:00
parent 658e1e64b2
commit 734da64b98
23 changed files with 4216 additions and 1281 deletions

View File

@ -3,9 +3,9 @@
* @author Owen Animation System
*/
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { OwenSystemFactory, States } from '../src/index.js';
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { OwenSystemFactory, States } from '../src/index.js'
/**
* Basic Owen Animation System demo
@ -15,67 +15,67 @@ class OwenDemo {
/**
* Create the demo
*/
constructor() {
constructor () {
/**
* The Three.js scene
* @type {THREE.Scene}
*/
this.scene = new THREE.Scene();
this.scene = new THREE.Scene()
/**
* The Three.js camera
* @type {THREE.PerspectiveCamera}
*/
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
/**
* The Three.js renderer
* @type {THREE.WebGLRenderer}
*/
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer = new THREE.WebGLRenderer({ antialias: true })
/**
* The Owen animation system
* @type {OwenAnimationContext|null}
*/
this.owenSystem = null;
this.owenSystem = null
/**
* Clock for tracking time
* @type {THREE.Clock}
*/
this.clock = new THREE.Clock();
this.clock = new THREE.Clock()
}
/**
* Initialize the demo
* @returns {Promise<void>}
*/
async init() {
async init () {
// Setup renderer
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setClearColor(0x1a1a1a);
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(this.renderer.domElement);
this.renderer.setSize(window.innerWidth, window.innerHeight)
this.renderer.setClearColor(0x1a1a1a)
this.renderer.shadowMap.enabled = true
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(this.renderer.domElement)
// Setup camera
this.camera.position.set(0, 1.6, 3);
this.camera.lookAt(0, 1, 0);
this.camera.position.set(0, 1.6, 3)
this.camera.lookAt(0, 1, 0)
// Add lighting
this.setupLighting();
this.setupLighting()
// Load Owen model (replace with your model path)
await this.loadOwenModel();
await this.loadOwenModel()
// Setup event listeners
this.setupEventListeners();
this.setupEventListeners()
// Start render loop
this.animate();
this.animate()
console.log('Owen Demo initialized');
console.log('Owen Demo initialized')
}
/**
@ -83,23 +83,23 @@ class OwenDemo {
* @private
* @returns {void}
*/
setupLighting() {
setupLighting () {
// Ambient light
const ambientLight = new THREE.AmbientLight(0x404040, 0.4);
this.scene.add(ambientLight);
const ambientLight = new THREE.AmbientLight(0x404040, 0.4)
this.scene.add(ambientLight)
// Directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 5);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
this.scene.add(directionalLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
directionalLight.position.set(5, 10, 5)
directionalLight.castShadow = true
directionalLight.shadow.mapSize.width = 2048
directionalLight.shadow.mapSize.height = 2048
this.scene.add(directionalLight)
// Fill light
const fillLight = new THREE.DirectionalLight(0x8bb7f0, 0.3);
fillLight.position.set(-5, 5, -5);
this.scene.add(fillLight);
const fillLight = new THREE.DirectionalLight(0x8bb7f0, 0.3)
fillLight.position.set(-5, 5, -5)
this.scene.add(fillLight)
}
/**
@ -107,9 +107,9 @@ class OwenDemo {
* @private
* @returns {Promise<void>}
*/
async loadOwenModel() {
async loadOwenModel () {
try {
const loader = new GLTFLoader();
const loader = new GLTFLoader()
// Replace 'path/to/owen.gltf' with your actual model path
const gltf = await new Promise((resolve, reject) => {
@ -118,34 +118,33 @@ class OwenDemo {
resolve,
(progress) => console.log('Loading progress:', progress.loaded / progress.total * 100 + '%'),
reject
);
});
)
})
const model = gltf.scene;
model.position.set(0, 0, 0);
model.scale.setScalar(1);
const model = gltf.scene
model.position.set(0, 0, 0)
model.scale.setScalar(1)
// Enable shadows
model.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
child.castShadow = true
child.receiveShadow = true
}
});
})
this.scene.add(model);
this.scene.add(model)
// Create Owen animation system
this.owenSystem = await OwenSystemFactory.createOwenSystem(gltf, this.scene);
console.log('Owen model loaded and animation system created');
this.logSystemInfo();
this.owenSystem = await OwenSystemFactory.createOwenSystem(gltf, this.scene)
console.log('Owen model loaded and animation system created')
this.logSystemInfo()
} catch (error) {
console.error('Error loading Owen model:', error);
console.error('Error loading Owen model:', error)
// Create a placeholder cube for demo purposes
this.createPlaceholderModel();
this.createPlaceholderModel()
}
}
@ -154,16 +153,16 @@ class OwenDemo {
* @private
* @returns {void}
*/
createPlaceholderModel() {
const geometry = new THREE.BoxGeometry(1, 2, 1);
const material = new THREE.MeshPhongMaterial({ color: 0x6699ff });
const cube = new THREE.Mesh(geometry, material);
cube.position.set(0, 1, 0);
cube.castShadow = true;
cube.receiveShadow = true;
this.scene.add(cube);
createPlaceholderModel () {
const geometry = new THREE.BoxGeometry(1, 2, 1)
const material = new THREE.MeshPhongMaterial({ color: 0x6699ff })
const cube = new THREE.Mesh(geometry, material)
cube.position.set(0, 1, 0)
cube.castShadow = true
cube.receiveShadow = true
this.scene.add(cube)
console.log('Created placeholder model (cube)');
console.log('Created placeholder model (cube)')
}
/**
@ -171,46 +170,46 @@ class OwenDemo {
* @private
* @returns {void}
*/
setupEventListeners() {
setupEventListeners () {
// Keyboard controls
document.addEventListener('keydown', (event) => {
if (!this.owenSystem) return;
if (!this.owenSystem) return
switch (event.key) {
case '1':
this.owenSystem.transitionTo(States.WAIT);
break;
this.owenSystem.transitionTo(States.WAIT)
break
case '2':
this.owenSystem.transitionTo(States.REACT);
break;
this.owenSystem.transitionTo(States.REACT)
break
case '3':
this.owenSystem.transitionTo(States.TYPE);
break;
this.owenSystem.transitionTo(States.TYPE)
break
case '4':
this.owenSystem.transitionTo(States.SLEEP);
break;
this.owenSystem.transitionTo(States.SLEEP)
break
case ' ':
this.sendTestMessage();
break;
this.sendTestMessage()
break
}
});
})
// Mouse interaction
document.addEventListener('click', () => {
if (this.owenSystem) {
this.owenSystem.onUserActivity();
this.owenSystem.onUserActivity()
}
});
})
// Window resize
window.addEventListener('resize', () => {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
});
this.camera.aspect = window.innerWidth / window.innerHeight
this.camera.updateProjectionMatrix()
this.renderer.setSize(window.innerWidth, window.innerHeight)
})
// Add instructions to the page
this.addInstructions();
this.addInstructions()
}
/**
@ -218,11 +217,11 @@ class OwenDemo {
* @private
* @returns {void}
*/
addInstructions() {
const instructions = document.createElement('div');
addInstructions () {
const instructions = document.createElement('div')
instructions.innerHTML = `
<div style="position: absolute; top: 10px; left: 10px; color: white; ` +
`font-family: monospace; font-size: 14px; line-height: 1.4;">
`font-family: monospace; font-size: 14px; line-height: 1.4;">
<h3>Owen Animation System Demo</h3>
<p><strong>Controls:</strong></p>
<p>1 - Wait State</p>
@ -235,8 +234,8 @@ class OwenDemo {
<p><strong>Current State:</strong> <span id="current-state">-</span></p>
<p><strong>Available Transitions:</strong> <span id="transitions">-</span></p>
</div>
`;
document.body.appendChild(instructions);
`
document.body.appendChild(instructions)
}
/**
@ -244,8 +243,8 @@ class OwenDemo {
* @private
* @returns {void}
*/
sendTestMessage() {
if (!this.owenSystem) return;
sendTestMessage () {
if (!this.owenSystem) return
const testMessages = [
'Hello Owen!',
@ -254,11 +253,11 @@ class OwenDemo {
'Great work!',
'Error in the system!',
'I\'m feeling sad today'
];
]
const randomMessage = testMessages[ Math.floor(Math.random() * testMessages.length) ];
console.log(`Sending message: "${randomMessage}"`);
this.owenSystem.handleUserMessage(randomMessage);
const randomMessage = testMessages[Math.floor(Math.random() * testMessages.length)]
console.log(`Sending message: "${randomMessage}"`)
this.owenSystem.handleUserMessage(randomMessage)
}
/**
@ -266,14 +265,14 @@ class OwenDemo {
* @private
* @returns {void}
*/
logSystemInfo() {
if (!this.owenSystem) return;
logSystemInfo () {
if (!this.owenSystem) return
console.log('=== Owen System Info ===');
console.log('Available States:', this.owenSystem.getAvailableStates());
console.log('Available Clips:', this.owenSystem.getAvailableClips());
console.log('Current State:', this.owenSystem.getCurrentState());
console.log('========================');
console.log('=== Owen System Info ===')
console.log('Available States:', this.owenSystem.getAvailableStates())
console.log('Available Clips:', this.owenSystem.getAvailableClips())
console.log('Current State:', this.owenSystem.getCurrentState())
console.log('========================')
}
/**
@ -281,18 +280,18 @@ class OwenDemo {
* @private
* @returns {void}
*/
updateUI() {
if (!this.owenSystem) return;
updateUI () {
if (!this.owenSystem) return
const currentStateElement = document.getElementById('current-state');
const transitionsElement = document.getElementById('transitions');
const currentStateElement = document.getElementById('current-state')
const transitionsElement = document.getElementById('transitions')
if (currentStateElement) {
currentStateElement.textContent = this.owenSystem.getCurrentState();
currentStateElement.textContent = this.owenSystem.getCurrentState()
}
if (transitionsElement) {
transitionsElement.textContent = this.owenSystem.getAvailableTransitions().join(', ');
transitionsElement.textContent = this.owenSystem.getAvailableTransitions().join(', ')
}
}
@ -301,32 +300,32 @@ class OwenDemo {
* @private
* @returns {void}
*/
animate() {
requestAnimationFrame(() => this.animate());
animate () {
requestAnimationFrame(() => this.animate())
const deltaTime = this.clock.getDelta() * 1000; // Convert to milliseconds
const deltaTime = this.clock.getDelta() * 1000 // Convert to milliseconds
// Update Owen system
if (this.owenSystem) {
this.owenSystem.update(deltaTime);
this.owenSystem.update(deltaTime)
}
// Update UI
this.updateUI();
this.updateUI()
// Render scene
this.renderer.render(this.scene, this.camera);
this.renderer.render(this.scene, this.camera)
}
}
// Initialize the demo when the page loads
window.addEventListener('load', async () => {
const demo = new OwenDemo();
const demo = new OwenDemo()
try {
await demo.init();
await demo.init()
} catch (error) {
console.error('Failed to initialize Owen demo:', error);
console.error('Failed to initialize Owen demo:', error)
}
});
})
export default OwenDemo;
export default OwenDemo