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 60aad20b5e
23 changed files with 4217 additions and 1281 deletions

View File

@ -3,8 +3,8 @@
* @module animation
*/
import * as THREE from 'three';
import { ClipTypes, Config } from '../constants.js';
import * as THREE from 'three'
import { ClipTypes, Config } from '../constants.js'
/**
* Represents a single animation clip with metadata and Three.js action
@ -17,36 +17,36 @@ export class AnimationClip {
* @param {THREE.AnimationClip} threeAnimation - The Three.js animation clip
* @param {Object} metadata - Parsed metadata from animation name
*/
constructor(name, threeAnimation, metadata) {
constructor (name, threeAnimation, metadata) {
/**
* The name of the animation clip
* @type {string}
*/
this.name = name;
this.name = name
/**
* The Three.js animation clip
* @type {THREE.AnimationClip}
*/
this.animation = threeAnimation;
this.animation = threeAnimation
/**
* Parsed metadata about the animation
* @type {Object}
*/
this.metadata = metadata;
this.metadata = metadata
/**
* The Three.js animation action
* @type {THREE.AnimationAction|null}
*/
this.action = null;
this.action = null
/**
* The animation mixer
* @type {THREE.AnimationMixer|null}
*/
this.mixer = null;
this.mixer = null
}
/**
@ -54,22 +54,22 @@ export class AnimationClip {
* @param {THREE.AnimationMixer} mixer - The animation mixer
* @returns {THREE.AnimationAction} The created action
*/
createAction(mixer) {
this.mixer = mixer;
this.action = mixer.clipAction(this.animation);
createAction (mixer) {
this.mixer = mixer
this.action = mixer.clipAction(this.animation)
// Configure based on type
if (
this.metadata.type === ClipTypes.LOOP ||
this.metadata.type === ClipTypes.NESTED_LOOP
) {
this.action.setLoop(THREE.LoopRepeat, Infinity);
this.action.setLoop(THREE.LoopRepeat, Infinity)
} else {
this.action.setLoop(THREE.LoopOnce);
this.action.clampWhenFinished = true;
this.action.setLoop(THREE.LoopOnce)
this.action.clampWhenFinished = true
}
return this.action;
return this.action
}
/**
@ -77,11 +77,11 @@ export class AnimationClip {
* @param {number} [fadeInDuration=0.3] - Fade in duration in seconds
* @returns {Promise<void>} Promise that resolves when fade in completes
*/
play(fadeInDuration = Config.DEFAULT_FADE_IN) {
play (fadeInDuration = Config.DEFAULT_FADE_IN) {
if (this.action) {
this.action.reset();
this.action.fadeIn(fadeInDuration);
this.action.play();
this.action.reset()
this.action.fadeIn(fadeInDuration)
this.action.play()
}
}
@ -90,14 +90,14 @@ export class AnimationClip {
* @param {number} [fadeOutDuration=0.3] - Fade out duration in seconds
* @returns {Promise<void>} Promise that resolves when fade out completes
*/
stop(fadeOutDuration = Config.DEFAULT_FADE_OUT) {
stop (fadeOutDuration = Config.DEFAULT_FADE_OUT) {
if (this.action) {
this.action.fadeOut(fadeOutDuration);
this.action.fadeOut(fadeOutDuration)
setTimeout(() => {
if (this.action) {
this.action.stop();
this.action.stop()
}
}, fadeOutDuration * 1000);
}, fadeOutDuration * 1000)
}
}
@ -105,8 +105,8 @@ export class AnimationClip {
* Check if the animation is currently playing
* @returns {boolean} True if playing, false otherwise
*/
isPlaying() {
return this.action?.isRunning() || false;
isPlaying () {
return this.action?.isRunning() || false
}
}
@ -119,18 +119,18 @@ export class AnimationClipFactory {
* Create an animation clip factory
* @param {AnimationLoader} animationLoader - The animation loader instance
*/
constructor(animationLoader) {
constructor (animationLoader) {
/**
* The animation loader for loading animation data
* @type {AnimationLoader}
*/
this.animationLoader = animationLoader;
this.animationLoader = animationLoader
/**
* Cache for created animation clips
* @type {Map<string, AnimationClip>}
*/
this.clipCache = new Map();
this.clipCache = new Map()
}
/**
@ -139,67 +139,67 @@ export class AnimationClipFactory {
* @param {string} name - The animation name to parse
* @returns {Object} Parsed metadata object
*/
parseAnimationName(name) {
const parts = name.split('_');
const state = parts[ 0 ];
const action = parts[ 1 ];
parseAnimationName (name) {
const parts = name.split('_')
const state = parts[0]
const action = parts[1]
// Handle transitions with emotions
if (parts[ 2 ]?.includes('2') && parts[ 3 ] === ClipTypes.TRANSITION) {
const [ , toState ] = parts[ 2 ].split('2');
if (parts[2]?.includes('2') && parts[3] === ClipTypes.TRANSITION) {
const [, toState] = parts[2].split('2')
return {
state,
action,
toState,
emotion: parts[ 2 ] || '',
emotion: parts[2] || '',
type: ClipTypes.TRANSITION,
isTransition: true,
hasEmotion: true,
};
hasEmotion: true
}
}
// Handle regular transitions
if (parts[ 2 ] === ClipTypes.TRANSITION) {
if (parts[2] === ClipTypes.TRANSITION) {
return {
state,
action,
type: ClipTypes.TRANSITION,
isTransition: true,
};
isTransition: true
}
}
// Handle nested animations
if (parts[ 2 ] === ClipTypes.NESTED_IN || parts[ 2 ] === ClipTypes.NESTED_OUT) {
if (parts[2] === ClipTypes.NESTED_IN || parts[2] === ClipTypes.NESTED_OUT) {
return {
state,
action,
type: parts[ 2 ],
nestedType: parts[ 3 ],
isNested: true,
};
type: parts[2],
nestedType: parts[3],
isNested: true
}
}
// Handle nested loops and quirks
if (
parts[ 3 ] === ClipTypes.NESTED_LOOP ||
parts[ 3 ] === ClipTypes.NESTED_QUIRK
parts[3] === ClipTypes.NESTED_LOOP ||
parts[3] === ClipTypes.NESTED_QUIRK
) {
return {
state,
action,
subAction: parts[ 2 ],
type: parts[ 3 ],
isNested: true,
};
subAction: parts[2],
type: parts[3],
isNested: true
}
}
// Handle standard loops and quirks
return {
state,
action,
type: parts[ 2 ],
isStandard: true,
};
type: parts[2],
isStandard: true
}
}
/**
@ -207,18 +207,18 @@ export class AnimationClipFactory {
* @param {string} name - The animation name
* @returns {Promise<AnimationClip>} The created animation clip
*/
async createClip(name) {
async createClip (name) {
if (this.clipCache.has(name)) {
return this.clipCache.get(name);
return this.clipCache.get(name)
}
const metadata = this.parseAnimationName(name);
const animation = await this.animationLoader.loadAnimation(name);
const metadata = this.parseAnimationName(name)
const animation = await this.animationLoader.loadAnimation(name)
const clip = new AnimationClip(name, animation, metadata);
this.clipCache.set(name, clip);
const clip = new AnimationClip(name, animation, metadata)
this.clipCache.set(name, clip)
return clip;
return clip
}
/**
@ -226,24 +226,24 @@ export class AnimationClipFactory {
* @param {THREE.Object3D} model - The 3D model containing animations
* @returns {Promise<Map<string, AnimationClip>>} Map of animation name to clip
*/
async createClipsFromModel(model) {
const clips = new Map();
const animations = model.animations || [];
async createClipsFromModel (model) {
const clips = new Map()
const animations = model.animations || []
for (const animation of animations) {
const clip = await this.createClip(animation.name, model);
clips.set(animation.name, clip);
const clip = await this.createClip(animation.name, model)
clips.set(animation.name, clip)
}
return clips;
return clips
}
/**
* Clear the clip cache
* @returns {void}
*/
clearCache() {
this.clipCache.clear();
clearCache () {
this.clipCache.clear()
}
/**
@ -251,7 +251,7 @@ export class AnimationClipFactory {
* @param {string} name - The animation name
* @returns {AnimationClip|undefined} The cached clip or undefined
*/
getCachedClip(name) {
return this.clipCache.get(name);
getCachedClip (name) {
return this.clipCache.get(name)
}
}

View File

@ -9,21 +9,21 @@
* @enum {string}
*/
export const ClipTypes = {
/** Loop animation */
LOOP: 'L',
/** Quirk animation */
QUIRK: 'Q',
/** Nested loop animation */
NESTED_LOOP: 'NL',
/** Nested quirk animation */
NESTED_QUIRK: 'NQ',
/** Nested in transition */
NESTED_IN: 'IN_NT',
/** Nested out transition */
NESTED_OUT: 'OUT_NT',
/** Transition animation */
TRANSITION: 'T',
};
/** Loop animation */
LOOP: 'L',
/** Quirk animation */
QUIRK: 'Q',
/** Nested loop animation */
NESTED_LOOP: 'NL',
/** Nested quirk animation */
NESTED_QUIRK: 'NQ',
/** Nested in transition */
NESTED_IN: 'IN_NT',
/** Nested out transition */
NESTED_OUT: 'OUT_NT',
/** Transition animation */
TRANSITION: 'T'
}
/**
* Character animation states
@ -31,15 +31,15 @@ export const ClipTypes = {
* @enum {string}
*/
export const States = {
/** Waiting/idle state */
WAIT: 'wait',
/** Reacting to input state */
REACT: 'react',
/** Typing response state */
TYPE: 'type',
/** Sleep/inactive state */
SLEEP: 'sleep',
};
/** Waiting/idle state */
WAIT: 'wait',
/** Reacting to input state */
REACT: 'react',
/** Typing response state */
TYPE: 'type',
/** Sleep/inactive state */
SLEEP: 'sleep'
}
/**
* Character emotional states
@ -47,17 +47,17 @@ export const States = {
* @enum {string}
*/
export const Emotions = {
/** Neutral emotion */
NEUTRAL: '',
/** Angry emotion */
ANGRY: 'an',
/** Shocked emotion */
SHOCKED: 'sh',
/** Happy emotion */
HAPPY: 'ha',
/** Sad emotion */
SAD: 'sa',
};
/** Neutral emotion */
NEUTRAL: '',
/** Angry emotion */
ANGRY: 'an',
/** Shocked emotion */
SHOCKED: 'sh',
/** Happy emotion */
HAPPY: 'ha',
/** Sad emotion */
SAD: 'sa'
}
/**
* Default configuration values
@ -65,14 +65,14 @@ export const Emotions = {
* @type {Object}
*/
export const Config = {
/** Default fade in duration for animations (ms) */
DEFAULT_FADE_IN: 0.3,
/** Default fade out duration for animations (ms) */
DEFAULT_FADE_OUT: 0.3,
/** Default quirk interval (ms) */
QUIRK_INTERVAL: 5000,
/** Default inactivity timeout (ms) */
INACTIVITY_TIMEOUT: 60000,
/** Quirk probability threshold */
QUIRK_PROBABILITY: 0.3,
};
/** Default fade in duration for animations (ms) */
DEFAULT_FADE_IN: 0.3,
/** Default fade out duration for animations (ms) */
DEFAULT_FADE_OUT: 0.3,
/** Default quirk interval (ms) */
QUIRK_INTERVAL: 5000,
/** Default inactivity timeout (ms) */
INACTIVITY_TIMEOUT: 60000,
/** Quirk probability threshold */
QUIRK_PROBABILITY: 0.3
}

View File

@ -3,7 +3,7 @@
* @module core
*/
import { States, Emotions, Config } from '../constants.js';
import { States, Emotions, Config } from '../constants.js'
/**
* Main controller for the Owen animation system
@ -18,97 +18,97 @@ export class OwenAnimationContext {
* @param {AnimationClipFactory} animationClipFactory - Factory for creating clips
* @param {StateFactory} stateFactory - Factory for creating state handlers
*/
constructor(model, mixer, animationClipFactory, stateFactory) {
constructor (model, mixer, animationClipFactory, stateFactory) {
/**
* The 3D character model
* @type {THREE.Object3D}
*/
this.model = model;
this.model = model
/**
* The Three.js animation mixer
* @type {THREE.AnimationMixer}
*/
this.mixer = mixer;
this.mixer = mixer
/**
* Factory for creating animation clips
* @type {AnimationClipFactory}
*/
this.animationClipFactory = animationClipFactory;
this.animationClipFactory = animationClipFactory
/**
* Factory for creating state handlers
* @type {StateFactory}
*/
this.stateFactory = stateFactory;
this.stateFactory = stateFactory
/**
* Map of animation clips by name
* @type {Map<string, AnimationClip>}
*/
this.clips = new Map();
this.clips = new Map()
/**
* Map of state handlers by name
* @type {Map<string, StateHandler>}
*/
this.states = new Map();
this.states = new Map()
/**
* Current active state
* @type {string}
*/
this.currentState = States.WAIT;
this.currentState = States.WAIT
/**
* Current active state handler
* @type {StateHandler|null}
*/
this.currentStateHandler = null;
this.currentStateHandler = null
/**
* Timer for inactivity detection
* @type {number}
*/
this.inactivityTimer = 0;
this.inactivityTimer = 0
/**
* Inactivity timeout in milliseconds
* @type {number}
*/
this.inactivityTimeout = Config.INACTIVITY_TIMEOUT;
this.inactivityTimeout = Config.INACTIVITY_TIMEOUT
/**
* Whether the system is initialized
* @type {boolean}
*/
this.initialized = false;
this.initialized = false
}
/**
* Initialize the animation system
* @returns {Promise<void>}
*/
async initialize() {
if (this.initialized) return;
async initialize () {
if (this.initialized) return
// Create animation clips from model
this.clips = await this.animationClipFactory.createClipsFromModel(this.model);
this.clips = await this.animationClipFactory.createClipsFromModel(this.model)
// Create actions for all clips
for (const [ , clip ] of this.clips) {
clip.createAction(this.mixer);
for (const [, clip] of this.clips) {
clip.createAction(this.mixer)
}
// Initialize state handlers
this.initializeStates();
this.initializeStates()
// Start in wait state
await this.transitionTo(States.WAIT);
await this.transitionTo(States.WAIT)
this.initialized = true;
console.log('Owen Animation System initialized');
this.initialized = true
console.log('Owen Animation System initialized')
}
/**
@ -116,12 +116,12 @@ export class OwenAnimationContext {
* @private
* @returns {void}
*/
initializeStates() {
const stateNames = this.stateFactory.getAvailableStates();
initializeStates () {
const stateNames = this.stateFactory.getAvailableStates()
for (const stateName of stateNames) {
const handler = this.stateFactory.createStateHandler(stateName, this);
this.states.set(stateName, handler);
const handler = this.stateFactory.createStateHandler(stateName, this)
this.states.set(stateName, handler)
}
}
@ -132,28 +132,28 @@ export class OwenAnimationContext {
* @returns {Promise<void>}
* @throws {Error} If state is not found or transition is invalid
*/
async transitionTo(newStateName, emotion = Emotions.NEUTRAL) {
async transitionTo (newStateName, emotion = Emotions.NEUTRAL) {
if (!this.states.has(newStateName)) {
throw new Error(`State '${newStateName}' not found`);
throw new Error(`State '${newStateName}' not found`)
}
const oldState = this.currentState;
const newStateHandler = this.states.get(newStateName);
const oldState = this.currentState
const newStateHandler = this.states.get(newStateName)
console.log(`Transitioning from ${oldState} to ${newStateName}`);
console.log(`Transitioning from ${oldState} to ${newStateName}`)
// Exit current state
if (this.currentStateHandler) {
await this.currentStateHandler.exit(newStateName, emotion);
await this.currentStateHandler.exit(newStateName, emotion)
}
// Enter new state
this.currentState = newStateName;
this.currentStateHandler = newStateHandler;
await this.currentStateHandler.enter(oldState, emotion);
this.currentState = newStateName
this.currentStateHandler = newStateHandler
await this.currentStateHandler.enter(oldState, emotion)
// Reset inactivity timer
this.resetActivityTimer();
this.resetActivityTimer()
}
/**
@ -161,26 +161,26 @@ export class OwenAnimationContext {
* @param {string} message - The user message
* @returns {Promise<void>}
*/
async handleUserMessage(message) {
console.log(`Handling user message: "${message}"`);
async handleUserMessage (message) {
console.log(`Handling user message: "${message}"`)
this.onUserActivity();
this.onUserActivity()
// If sleeping, wake up first
if (this.currentState === States.SLEEP) {
await this.transitionTo(States.REACT);
await this.transitionTo(States.REACT)
}
// Let current state handle the message
if (this.currentStateHandler) {
await this.currentStateHandler.handleMessage(message);
await this.currentStateHandler.handleMessage(message)
}
// Transition to appropriate next state based on current state
if (this.currentState === States.WAIT) {
await this.transitionTo(States.REACT);
await this.transitionTo(States.REACT)
} else if (this.currentState === States.REACT) {
await this.transitionTo(States.TYPE);
await this.transitionTo(States.TYPE)
}
}
@ -188,12 +188,12 @@ export class OwenAnimationContext {
* Called when user activity is detected
* @returns {void}
*/
onUserActivity() {
this.resetActivityTimer();
onUserActivity () {
this.resetActivityTimer()
// Wake up if sleeping
if (this.currentState === States.SLEEP) {
this.transitionTo(States.WAIT);
this.transitionTo(States.WAIT)
}
}
@ -202,8 +202,8 @@ export class OwenAnimationContext {
* @private
* @returns {void}
*/
resetActivityTimer() {
this.inactivityTimer = 0;
resetActivityTimer () {
this.inactivityTimer = 0
}
/**
@ -211,9 +211,9 @@ export class OwenAnimationContext {
* @private
* @returns {Promise<void>}
*/
async handleInactivity() {
console.log('Inactivity detected, transitioning to sleep');
await this.transitionTo(States.SLEEP);
async handleInactivity () {
console.log('Inactivity detected, transitioning to sleep')
await this.transitionTo(States.SLEEP)
}
/**
@ -221,21 +221,21 @@ export class OwenAnimationContext {
* @param {number} deltaTime - Time elapsed since last update (ms)
* @returns {void}
*/
update(deltaTime) {
if (!this.initialized) return;
update (deltaTime) {
if (!this.initialized) return
// Update Three.js mixer
this.mixer.update(deltaTime / 1000); // Convert to seconds
this.mixer.update(deltaTime / 1000) // Convert to seconds
// Update current state
if (this.currentStateHandler) {
this.currentStateHandler.update(deltaTime);
this.currentStateHandler.update(deltaTime)
}
// Update inactivity timer
this.inactivityTimer += deltaTime;
this.inactivityTimer += deltaTime
if (this.inactivityTimer > this.inactivityTimeout && this.currentState !== States.SLEEP) {
this.handleInactivity();
this.handleInactivity()
}
}
@ -244,8 +244,8 @@ export class OwenAnimationContext {
* @param {string} name - The animation clip name
* @returns {AnimationClip|undefined} The animation clip or undefined if not found
*/
getClip(name) {
return this.clips.get(name);
getClip (name) {
return this.clips.get(name)
}
/**
@ -253,80 +253,80 @@ export class OwenAnimationContext {
* @param {string} pattern - Pattern to match (supports * wildcards)
* @returns {AnimationClip[]} Array of matching clips
*/
getClipsByPattern(pattern) {
const regex = new RegExp(pattern.replace(/\*/g, '.*'));
const matches = [];
getClipsByPattern (pattern) {
const regex = new RegExp(pattern.replace(/\*/g, '.*'))
const matches = []
for (const [ name, clip ] of this.clips) {
for (const [name, clip] of this.clips) {
if (regex.test(name)) {
matches.push(clip);
matches.push(clip)
}
}
return matches;
return matches
}
/**
* Get the current state name
* @returns {string} The current state name
*/
getCurrentState() {
return this.currentState;
getCurrentState () {
return this.currentState
}
/**
* Get the current state handler
* @returns {StateHandler|null} The current state handler
*/
getCurrentStateHandler() {
return this.currentStateHandler;
getCurrentStateHandler () {
return this.currentStateHandler
}
/**
* Get available transitions from current state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
getAvailableTransitions () {
if (this.currentStateHandler) {
return this.currentStateHandler.getAvailableTransitions();
return this.currentStateHandler.getAvailableTransitions()
}
return [];
return []
}
/**
* Get all available animation clip names
* @returns {string[]} Array of clip names
*/
getAvailableClips() {
return Array.from(this.clips.keys());
getAvailableClips () {
return Array.from(this.clips.keys())
}
/**
* Get all available state names
* @returns {string[]} Array of state names
*/
getAvailableStates() {
return Array.from(this.states.keys());
getAvailableStates () {
return Array.from(this.states.keys())
}
/**
* Dispose of the animation system and clean up resources
* @returns {void}
*/
dispose() {
dispose () {
// Stop all animations
for (const [ , clip ] of this.clips) {
for (const [, clip] of this.clips) {
if (clip.action) {
clip.action.stop();
clip.action.stop()
}
}
// Clear caches
this.clips.clear();
this.states.clear();
this.animationClipFactory.clearCache();
this.clips.clear()
this.states.clear()
this.animationClipFactory.clearCache()
this.initialized = false;
console.log('Owen Animation System disposed');
this.initialized = false
console.log('Owen Animation System disposed')
}
}

View File

@ -3,18 +3,18 @@
* @module factories
*/
import * as THREE from 'three';
import { OwenAnimationContext } from '../core/OwenAnimationContext.js';
import { AnimationClipFactory } from '../animation/AnimationClip.js';
import { GLTFAnimationLoader } from '../loaders/AnimationLoader.js';
import { StateFactory } from '../states/StateFactory.js';
import * as THREE from 'three'
import { OwenAnimationContext } from '../core/OwenAnimationContext.js'
import { AnimationClipFactory } from '../animation/AnimationClip.js'
import { GLTFAnimationLoader } from '../loaders/AnimationLoader.js'
import { StateFactory } from '../states/StateFactory.js'
/**
* Main factory for creating the complete Owen animation system
* @class
*/
export class OwenSystemFactory {
/**
/**
* Create a complete Owen animation system
* @param {THREE.Object3D} gltfModel - The loaded GLTF model
* @param {THREE.Scene} scene - The Three.js scene
@ -22,70 +22,70 @@ export class OwenSystemFactory {
* @param {THREE.GLTFLoader} [options.gltfLoader] - Custom GLTF loader
* @returns {Promise<OwenAnimationContext>} The configured Owen system
*/
static async createOwenSystem(gltfModel, scene, options = {}) {
// Create Three.js animation mixer
const mixer = new THREE.AnimationMixer(gltfModel);
static async createOwenSystem (gltfModel, scene, options = {}) {
// Create Three.js animation mixer
const mixer = new THREE.AnimationMixer(gltfModel)
// Create GLTF loader if not provided
const gltfLoader = options.gltfLoader || new THREE.GLTFLoader();
// Create GLTF loader if not provided
const gltfLoader = options.gltfLoader || new THREE.GLTFLoader()
// Create animation loader
const animationLoader = new GLTFAnimationLoader(gltfLoader);
// Create animation loader
const animationLoader = new GLTFAnimationLoader(gltfLoader)
// Preload animations from the model
await animationLoader.preloadAnimations(gltfModel);
// Preload animations from the model
await animationLoader.preloadAnimations(gltfModel)
// Create animation clip factory
const animationClipFactory = new AnimationClipFactory(animationLoader);
// Create animation clip factory
const animationClipFactory = new AnimationClipFactory(animationLoader)
// Create state factory
const stateFactory = new StateFactory();
// Create state factory
const stateFactory = new StateFactory()
// Create the main Owen context
const owenContext = new OwenAnimationContext(
gltfModel,
mixer,
animationClipFactory,
stateFactory
);
// Create the main Owen context
const owenContext = new OwenAnimationContext(
gltfModel,
mixer,
animationClipFactory,
stateFactory
)
// Initialize the system
await owenContext.initialize();
// Initialize the system
await owenContext.initialize()
return owenContext;
}
return owenContext
}
/**
/**
* Create a basic Owen system with minimal configuration
* @param {THREE.Object3D} model - The 3D model
* @returns {Promise<OwenAnimationContext>} The configured Owen system
*/
static async createBasicOwenSystem(model) {
const scene = new THREE.Scene();
scene.add(model);
static async createBasicOwenSystem (model) {
const scene = new THREE.Scene()
scene.add(model)
return await OwenSystemFactory.createOwenSystem(model, scene);
}
return await OwenSystemFactory.createOwenSystem(model, scene)
}
/**
/**
* Create an Owen system with custom state handlers
* @param {THREE.Object3D} gltfModel - The loaded GLTF model
* @param {THREE.Scene} scene - The Three.js scene
* @param {Map<string, Function>} customStates - Map of state name to handler class
* @returns {Promise<OwenAnimationContext>} The configured Owen system
*/
static async createCustomOwenSystem(gltfModel, scene, customStates) {
const system = await OwenSystemFactory.createOwenSystem(gltfModel, scene);
static async createCustomOwenSystem (gltfModel, scene, customStates) {
const system = await OwenSystemFactory.createOwenSystem(gltfModel, scene)
// Register custom state handlers
const stateFactory = system.stateFactory;
for (const [ stateName, handlerClass ] of customStates) {
stateFactory.registerStateHandler(stateName, handlerClass);
}
// Reinitialize with custom states
system.initializeStates();
return system;
// Register custom state handlers
const stateFactory = system.stateFactory
for (const [stateName, handlerClass] of customStates) {
stateFactory.registerStateHandler(stateName, handlerClass)
}
// Reinitialize with custom states
system.initializeStates()
return system
}
}

View File

@ -4,32 +4,32 @@
*/
// Core exports
export { OwenAnimationContext } from './core/OwenAnimationContext.js';
// Import for default export
import { OwenSystemFactory } from './factories/OwenSystemFactory.js'
import { OwenAnimationContext } from './core/OwenAnimationContext.js'
import { States, Emotions, ClipTypes, Config } from './constants.js'
export { OwenAnimationContext } from './core/OwenAnimationContext.js'
// Animation system exports
export { AnimationClip, AnimationClipFactory } from './animation/AnimationClip.js';
export { AnimationClip, AnimationClipFactory } from './animation/AnimationClip.js'
// Loader exports
export { AnimationLoader, GLTFAnimationLoader } from './loaders/AnimationLoader.js';
export { AnimationLoader, GLTFAnimationLoader } from './loaders/AnimationLoader.js'
// State system exports
export { StateHandler } from './states/StateHandler.js';
export { WaitStateHandler } from './states/WaitStateHandler.js';
export { ReactStateHandler } from './states/ReactStateHandler.js';
export { TypeStateHandler } from './states/TypeStateHandler.js';
export { SleepStateHandler } from './states/SleepStateHandler.js';
export { StateFactory } from './states/StateFactory.js';
export { StateHandler } from './states/StateHandler.js'
export { WaitStateHandler } from './states/WaitStateHandler.js'
export { ReactStateHandler } from './states/ReactStateHandler.js'
export { TypeStateHandler } from './states/TypeStateHandler.js'
export { SleepStateHandler } from './states/SleepStateHandler.js'
export { StateFactory } from './states/StateFactory.js'
// Factory exports
export { OwenSystemFactory } from './factories/OwenSystemFactory.js';
export { OwenSystemFactory } from './factories/OwenSystemFactory.js'
// Constants exports
export { ClipTypes, States, Emotions, Config } from './constants.js';
// Import for default export
import { OwenSystemFactory } from './factories/OwenSystemFactory.js';
import { OwenAnimationContext } from './core/OwenAnimationContext.js';
import { States, Emotions, ClipTypes, Config } from './constants.js';
export { ClipTypes, States, Emotions, Config } from './constants.js'
/**
* Default export - the main factory for easy usage
@ -41,4 +41,4 @@ export default {
Emotions,
ClipTypes,
Config
};
}

View File

@ -9,16 +9,16 @@
* @class
*/
export class AnimationLoader {
/**
/**
* Load an animation by name
* @abstract
* @param {string} _name - The animation name to load (unused in base class)
* @returns {Promise<THREE.AnimationClip>} The loaded animation clip
* @throws {Error} Must be implemented by subclasses
*/
async loadAnimation(_name) {
throw new Error('loadAnimation method must be implemented by subclasses');
}
async loadAnimation (_name) {
throw new Error('loadAnimation method must be implemented by subclasses')
}
}
/**
@ -27,68 +27,68 @@ export class AnimationLoader {
* @extends AnimationLoader
*/
export class GLTFAnimationLoader extends AnimationLoader {
/**
/**
* Create a GLTF animation loader
* @param {THREE.GLTFLoader} gltfLoader - The Three.js GLTF loader instance
*/
constructor(gltfLoader) {
super();
constructor (gltfLoader) {
super()
/**
/**
* The Three.js GLTF loader
* @type {THREE.GLTFLoader}
*/
this.gltfLoader = gltfLoader;
this.gltfLoader = gltfLoader
/**
/**
* Cache for loaded animations
* @type {Map<string, THREE.AnimationClip>}
*/
this.animationCache = new Map();
}
this.animationCache = new Map()
}
/**
/**
* Load an animation from GLTF by name
* @param {string} name - The animation name to load
* @returns {Promise<THREE.AnimationClip>} The loaded animation clip
* @throws {Error} If animation is not found
*/
async loadAnimation(name) {
if (this.animationCache.has(name)) {
return this.animationCache.get(name);
}
// In a real implementation, this would load from GLTF files
// For now, we'll assume animations are already loaded in the model
throw new Error(`Animation '${name}' not found. Implement GLTF loading logic.`);
async loadAnimation (name) {
if (this.animationCache.has(name)) {
return this.animationCache.get(name)
}
/**
// In a real implementation, this would load from GLTF files
// For now, we'll assume animations are already loaded in the model
throw new Error(`Animation '${name}' not found. Implement GLTF loading logic.`)
}
/**
* Preload animations from a GLTF model
* @param {Object} gltfModel - The loaded GLTF model
* @returns {Promise<void>}
*/
async preloadAnimations(gltfModel) {
if (gltfModel.animations) {
for (const animation of gltfModel.animations) {
this.animationCache.set(animation.name, animation);
}
}
async preloadAnimations (gltfModel) {
if (gltfModel.animations) {
for (const animation of gltfModel.animations) {
this.animationCache.set(animation.name, animation)
}
}
}
/**
/**
* Clear the animation cache
* @returns {void}
*/
clearCache() {
this.animationCache.clear();
}
clearCache () {
this.animationCache.clear()
}
/**
/**
* Get all cached animation names
* @returns {string[]} Array of cached animation names
*/
getCachedAnimationNames() {
return Array.from(this.animationCache.keys());
}
getCachedAnimationNames () {
return Array.from(this.animationCache.keys())
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions } from '../constants.js'
/**
* Handler for the React state
@ -12,148 +12,148 @@ import { States, Emotions } from '../constants.js';
* @extends StateHandler
*/
export class ReactStateHandler extends StateHandler {
/**
/**
* Create a react state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.REACT, context);
constructor (context) {
super(States.REACT, context)
/**
/**
* Current emotional state
* @type {string}
*/
this.emotion = Emotions.NEUTRAL;
}
this.emotion = Emotions.NEUTRAL
}
/**
/**
* Enter the react state
* @param {string|null} [_fromState=null] - The previous state (unused)
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to enter with
* @returns {Promise<void>}
*/
async enter(_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering REACT state with emotion: ${emotion}`);
this.emotion = emotion;
async enter (_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering REACT state with emotion: ${emotion}`)
this.emotion = emotion
// Play appropriate reaction
const reactionClip = this.context.getClip('react_idle_L');
if (reactionClip) {
await reactionClip.play();
this.currentClip = reactionClip;
}
// Play appropriate reaction
const reactionClip = this.context.getClip('react_idle_L')
if (reactionClip) {
await reactionClip.play()
this.currentClip = reactionClip
}
}
/**
/**
* Exit the react state
* @param {string|null} [toState=null] - The next state
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to exit with
* @returns {Promise<void>}
*/
async exit(toState = null, emotion = Emotions.NEUTRAL) {
console.log(`Exiting REACT state to ${toState} with emotion: ${emotion}`);
async exit (toState = null, emotion = Emotions.NEUTRAL) {
console.log(`Exiting REACT state to ${toState} with emotion: ${emotion}`)
if (this.currentClip) {
await this.stopCurrentClip();
}
// Play emotional transition if available
let transitionName;
if (emotion !== Emotions.NEUTRAL) {
transitionName = `react_${this.emotion}2${toState}_${emotion}_T`;
} else {
transitionName = `react_2${toState}_T`;
}
const transition = this.context.getClip(transitionName);
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
}
if (this.currentClip) {
await this.stopCurrentClip()
}
/**
// Play emotional transition if available
let transitionName
if (emotion !== Emotions.NEUTRAL) {
transitionName = `react_${this.emotion}2${toState}_${emotion}_T`
} else {
transitionName = `react_2${toState}_T`
}
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play()
await this.waitForClipEnd(transition)
}
}
/**
* Handle a user message in react state
* @param {string} message - The user message
* @returns {Promise<void>}
*/
async handleMessage(message) {
// Analyze message sentiment to determine emotion
const emotion = this.analyzeMessageEmotion(message);
this.emotion = emotion;
async handleMessage (message) {
// Analyze message sentiment to determine emotion
const emotion = this.analyzeMessageEmotion(message)
this.emotion = emotion
// Play emotional reaction if needed
if (emotion !== Emotions.NEUTRAL) {
const emotionalReaction = this.context.getClip(`react_${emotion}_Q`);
if (emotionalReaction) {
if (this.currentClip) {
await this.stopCurrentClip(0.2);
}
await emotionalReaction.play();
await this.waitForClipEnd(emotionalReaction);
}
// Play emotional reaction if needed
if (emotion !== Emotions.NEUTRAL) {
const emotionalReaction = this.context.getClip(`react_${emotion}_Q`)
if (emotionalReaction) {
if (this.currentClip) {
await this.stopCurrentClip(0.2)
}
await emotionalReaction.play()
await this.waitForClipEnd(emotionalReaction)
}
}
}
/**
/**
* Analyze message to determine emotional response
* @private
* @param {string} message - The message to analyze
* @returns {string} The determined emotion
*/
analyzeMessageEmotion(message) {
const text = message.toLowerCase();
analyzeMessageEmotion (message) {
const text = message.toLowerCase()
// Check for urgent/angry indicators
if (
text.includes('!') ||
// Check for urgent/angry indicators
if (
text.includes('!') ||
text.includes('urgent') ||
text.includes('asap') ||
text.includes('hurry')
) {
return Emotions.ANGRY;
}
) {
return Emotions.ANGRY
}
// Check for error/shocked indicators
if (
text.includes('error') ||
// Check for error/shocked indicators
if (
text.includes('error') ||
text.includes('problem') ||
text.includes('issue') ||
text.includes('bug') ||
text.includes('broken')
) {
return Emotions.SHOCKED;
}
) {
return Emotions.SHOCKED
}
// Check for positive/happy indicators
if (
text.includes('great') ||
// Check for positive/happy indicators
if (
text.includes('great') ||
text.includes('awesome') ||
text.includes('good') ||
text.includes('excellent') ||
text.includes('perfect')
) {
return Emotions.HAPPY;
}
) {
return Emotions.HAPPY
}
// Check for sad indicators
if (
text.includes('sad') ||
// Check for sad indicators
if (
text.includes('sad') ||
text.includes('disappointed') ||
text.includes('failed') ||
text.includes('wrong')
) {
return Emotions.SAD;
}
return Emotions.NEUTRAL;
) {
return Emotions.SAD
}
/**
return Emotions.NEUTRAL
}
/**
* Get available transitions from react state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.TYPE, States.WAIT ];
}
getAvailableTransitions () {
return [States.TYPE, States.WAIT]
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions } from '../constants.js'
/**
* Handler for the Sleep state
@ -16,20 +16,20 @@ export class SleepStateHandler extends StateHandler {
* Create a sleep state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.SLEEP, context);
constructor (context) {
super(States.SLEEP, context)
/**
* Sleep animation clip
* @type {AnimationClip|null}
*/
this.sleepClip = null;
this.sleepClip = null
/**
* Whether the character is in deep sleep
* @type {boolean}
*/
this.isDeepSleep = false;
this.isDeepSleep = false
}
/**
@ -38,24 +38,24 @@ export class SleepStateHandler extends StateHandler {
* @param {string} [_emotion=Emotions.NEUTRAL] - The emotion to enter with (unused)
* @returns {Promise<void>}
*/
async enter(fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering SLEEP state from ${fromState}`);
async enter (fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering SLEEP state from ${fromState}`)
// Play sleep transition if available
const sleepTransition = this.context.getClip('wait_2sleep_T');
const sleepTransition = this.context.getClip('wait_2sleep_T')
if (sleepTransition) {
await sleepTransition.play();
await this.waitForClipEnd(sleepTransition);
await sleepTransition.play()
await this.waitForClipEnd(sleepTransition)
}
// Start sleep loop
this.sleepClip = this.context.getClip('sleep_idle_L');
this.sleepClip = this.context.getClip('sleep_idle_L')
if (this.sleepClip) {
await this.sleepClip.play();
this.currentClip = this.sleepClip;
await this.sleepClip.play()
this.currentClip = this.sleepClip
}
this.isDeepSleep = true;
this.isDeepSleep = true
}
/**
@ -64,27 +64,27 @@ export class SleepStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to exit with
* @returns {Promise<void>}
*/
async exit(toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting SLEEP state to ${toState}`);
this.isDeepSleep = false;
async exit (toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting SLEEP state to ${toState}`)
this.isDeepSleep = false
if (this.currentClip) {
await this.stopCurrentClip();
await this.stopCurrentClip()
}
// Play wake up animation
const wakeUpClip = this.context.getClip('sleep_wakeup_T');
const wakeUpClip = this.context.getClip('sleep_wakeup_T')
if (wakeUpClip) {
await wakeUpClip.play();
await this.waitForClipEnd(wakeUpClip);
await wakeUpClip.play()
await this.waitForClipEnd(wakeUpClip)
}
// Play transition to next state if available
const transitionName = `sleep_2${toState}_T`;
const transition = this.context.getClip(transitionName);
const transitionName = `sleep_2${toState}_T`
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
await transition.play()
await this.waitForClipEnd(transition)
}
}
@ -93,7 +93,7 @@ export class SleepStateHandler extends StateHandler {
* @param {number} _deltaTime - Time elapsed since last update (ms, unused)
* @returns {void}
*/
update(_deltaTime) {
update (_deltaTime) {
// Sleep state doesn't need regular updates
// Character remains asleep until external stimulus
}
@ -103,12 +103,12 @@ export class SleepStateHandler extends StateHandler {
* @param {string} _message - The user message (unused, just triggers wake up)
* @returns {Promise<void>}
*/
async handleMessage(_message) {
async handleMessage (_message) {
// Any message should wake up the character
if (this.isDeepSleep) {
console.log('Waking up due to user message');
console.log('Waking up due to user message')
// This will trigger a state transition to REACT
await this.context.transitionTo(States.REACT);
await this.context.transitionTo(States.REACT)
}
}
@ -116,25 +116,25 @@ export class SleepStateHandler extends StateHandler {
* Get available transitions from sleep state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.WAIT, States.REACT ];
getAvailableTransitions () {
return [States.WAIT, States.REACT]
}
/**
* Check if in deep sleep
* @returns {boolean} True if in deep sleep, false otherwise
*/
isInDeepSleep() {
return this.isDeepSleep;
isInDeepSleep () {
return this.isDeepSleep
}
/**
* Force wake up from sleep
* @returns {Promise<void>}
*/
async wakeUp() {
async wakeUp () {
if (this.isDeepSleep) {
await this.context.transitionTo(States.WAIT);
await this.context.transitionTo(States.WAIT)
}
}
}

View File

@ -3,11 +3,11 @@
* @module states
*/
import { WaitStateHandler } from './WaitStateHandler.js';
import { ReactStateHandler } from './ReactStateHandler.js';
import { TypeStateHandler } from './TypeStateHandler.js';
import { SleepStateHandler } from './SleepStateHandler.js';
import { States } from '../constants.js';
import { WaitStateHandler } from './WaitStateHandler.js'
import { ReactStateHandler } from './ReactStateHandler.js'
import { TypeStateHandler } from './TypeStateHandler.js'
import { SleepStateHandler } from './SleepStateHandler.js'
import { States } from '../constants.js'
/**
* Factory for creating state handlers using dependency injection
@ -17,19 +17,19 @@ export class StateFactory {
/**
* Create a state factory
*/
constructor() {
constructor () {
/**
* Registry of state handler classes
* @type {Map<string, Function>}
* @private
*/
this.stateHandlers = new Map();
this.stateHandlers = new Map()
// Register default state handlers
this.registerStateHandler(States.WAIT, WaitStateHandler);
this.registerStateHandler(States.REACT, ReactStateHandler);
this.registerStateHandler(States.TYPE, TypeStateHandler);
this.registerStateHandler(States.SLEEP, SleepStateHandler);
this.registerStateHandler(States.WAIT, WaitStateHandler)
this.registerStateHandler(States.REACT, ReactStateHandler)
this.registerStateHandler(States.TYPE, TypeStateHandler)
this.registerStateHandler(States.SLEEP, SleepStateHandler)
}
/**
@ -38,8 +38,8 @@ export class StateFactory {
* @param {Function} handlerClass - The handler class constructor
* @returns {void}
*/
registerStateHandler(stateName, handlerClass) {
this.stateHandlers.set(stateName, handlerClass);
registerStateHandler (stateName, handlerClass) {
this.stateHandlers.set(stateName, handlerClass)
}
/**
@ -49,21 +49,21 @@ export class StateFactory {
* @returns {StateHandler} The created state handler
* @throws {Error} If state handler is not registered
*/
createStateHandler(stateName, context) {
const HandlerClass = this.stateHandlers.get(stateName);
createStateHandler (stateName, context) {
const HandlerClass = this.stateHandlers.get(stateName)
if (!HandlerClass) {
throw new Error(`No handler registered for state: ${stateName}`);
throw new Error(`No handler registered for state: ${stateName}`)
}
return new HandlerClass(context);
return new HandlerClass(context)
}
/**
* Get all available state names
* @returns {string[]} Array of registered state names
*/
getAvailableStates() {
return Array.from(this.stateHandlers.keys());
getAvailableStates () {
return Array.from(this.stateHandlers.keys())
}
/**
@ -71,8 +71,8 @@ export class StateFactory {
* @param {string} stateName - The state name to check
* @returns {boolean} True if registered, false otherwise
*/
isStateRegistered(stateName) {
return this.stateHandlers.has(stateName);
isStateRegistered (stateName) {
return this.stateHandlers.has(stateName)
}
/**
@ -80,7 +80,7 @@ export class StateFactory {
* @param {string} stateName - The state name to unregister
* @returns {boolean} True if removed, false if not found
*/
unregisterStateHandler(stateName) {
return this.stateHandlers.delete(stateName);
unregisterStateHandler (stateName) {
return this.stateHandlers.delete(stateName)
}
}

View File

@ -3,7 +3,7 @@
* @module StateHandler
*/
import { Emotions, Config } from '../constants.js';
import { Emotions, Config } from '../constants.js'
/**
* Abstract base class for state handlers
@ -16,30 +16,30 @@ export class StateHandler {
* @param {string} stateName - The name of the state
* @param {OwenAnimationContext} context - The animation context
*/
constructor(stateName, context) {
constructor (stateName, context) {
/**
* The name of this state
* @type {string}
*/
this.stateName = stateName;
this.stateName = stateName
/**
* The animation context
* @type {OwenAnimationContext}
*/
this.context = context;
this.context = context
/**
* Currently playing animation clip
* @type {AnimationClip|null}
*/
this.currentClip = null;
this.currentClip = null
/**
* Nested state information
* @type {Object|null}
*/
this.nestedState = null;
this.nestedState = null
}
/**
@ -50,8 +50,8 @@ export class StateHandler {
* @returns {Promise<void>}
* @throws {Error} Must be implemented by subclasses
*/
async enter(_fromState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('enter method must be implemented by subclasses');
async enter (_fromState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('enter method must be implemented by subclasses')
}
/**
@ -62,8 +62,8 @@ export class StateHandler {
* @returns {Promise<void>}
* @throws {Error} Must be implemented by subclasses
*/
async exit(_toState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('exit method must be implemented by subclasses');
async exit (_toState = null, _emotion = Emotions.NEUTRAL) {
throw new Error('exit method must be implemented by subclasses')
}
/**
@ -71,7 +71,7 @@ export class StateHandler {
* @param {number} _deltaTime - Time elapsed since last update (ms, unused in base class)
* @returns {void}
*/
update(_deltaTime) {
update (_deltaTime) {
// Override in subclasses if needed
}
@ -80,7 +80,7 @@ export class StateHandler {
* @param {string} _message - The user message (unused in base class)
* @returns {Promise<void>}
*/
async handleMessage(_message) {
async handleMessage (_message) {
// Override in subclasses if needed
}
@ -88,8 +88,8 @@ export class StateHandler {
* Get available transitions from this state
* @returns {string[]} Array of state names that can be transitioned to
*/
getAvailableTransitions() {
return [];
getAvailableTransitions () {
return []
}
/**
@ -98,17 +98,17 @@ export class StateHandler {
* @param {AnimationClip} clip - The animation clip to wait for
* @returns {Promise<void>} Promise that resolves when the clip finishes
*/
async waitForClipEnd(clip) {
async waitForClipEnd (clip) {
return new Promise((resolve) => {
const checkFinished = () => {
if (!clip.isPlaying()) {
resolve();
resolve()
} else {
requestAnimationFrame(checkFinished);
requestAnimationFrame(checkFinished)
}
};
checkFinished();
});
}
checkFinished()
})
}
/**
@ -117,10 +117,10 @@ export class StateHandler {
* @param {number} [fadeOutDuration] - Fade out duration
* @returns {Promise<void>}
*/
async stopCurrentClip(fadeOutDuration = Config.DEFAULT_FADE_OUT) {
async stopCurrentClip (fadeOutDuration = Config.DEFAULT_FADE_OUT) {
if (this.currentClip) {
await this.currentClip.stop(fadeOutDuration);
this.currentClip = null;
await this.currentClip.stop(fadeOutDuration)
this.currentClip = null
}
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions } from '../constants.js'
/**
* Handler for the Type state
@ -16,20 +16,20 @@ export class TypeStateHandler extends StateHandler {
* Create a type state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.TYPE, context);
constructor (context) {
super(States.TYPE, context)
/**
* Current emotional state
* @type {string}
*/
this.emotion = Emotions.NEUTRAL;
this.emotion = Emotions.NEUTRAL
/**
* Whether currently typing
* @type {boolean}
*/
this.isTyping = false;
this.isTyping = false
}
/**
@ -38,21 +38,21 @@ export class TypeStateHandler extends StateHandler {
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to enter with
* @returns {Promise<void>}
*/
async enter(_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering TYPE state with emotion: ${emotion}`);
this.emotion = emotion;
this.isTyping = true;
async enter (_fromState = null, emotion = Emotions.NEUTRAL) {
console.log(`Entering TYPE state with emotion: ${emotion}`)
this.emotion = emotion
this.isTyping = true
// Play appropriate typing animation
let typingClipName = 'type_idle_L';
let typingClipName = 'type_idle_L'
if (emotion !== Emotions.NEUTRAL) {
typingClipName = `type_${emotion}_L`;
typingClipName = `type_${emotion}_L`
}
const typingClip = this.context.getClip(typingClipName);
const typingClip = this.context.getClip(typingClipName)
if (typingClip) {
await typingClip.play();
this.currentClip = typingClip;
await typingClip.play()
this.currentClip = typingClip
}
}
@ -62,24 +62,24 @@ export class TypeStateHandler extends StateHandler {
* @param {string} [_emotion=Emotions.NEUTRAL] - The emotion to exit with (unused)
* @returns {Promise<void>}
*/
async exit(toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting TYPE state to ${toState}`);
this.isTyping = false;
async exit (toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting TYPE state to ${toState}`)
this.isTyping = false
if (this.currentClip) {
await this.stopCurrentClip();
await this.stopCurrentClip()
}
// Play transition if available
let transitionName = `type_2${toState}_T`;
let transitionName = `type_2${toState}_T`
if (this.emotion !== Emotions.NEUTRAL) {
transitionName = `type_${this.emotion}2${toState}_T`;
transitionName = `type_${this.emotion}2${toState}_T`
}
const transition = this.context.getClip(transitionName);
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
await transition.play()
await this.waitForClipEnd(transition)
}
}
@ -87,34 +87,34 @@ export class TypeStateHandler extends StateHandler {
* Finish typing and prepare to transition
* @returns {Promise<void>}
*/
async finishTyping() {
if (!this.isTyping) return;
async finishTyping () {
if (!this.isTyping) return
// Play typing finish animation if available
const finishClip = this.context.getClip('type_finish_Q');
const finishClip = this.context.getClip('type_finish_Q')
if (finishClip && this.currentClip) {
await this.stopCurrentClip(0.2);
await finishClip.play();
await this.waitForClipEnd(finishClip);
await this.stopCurrentClip(0.2)
await finishClip.play()
await this.waitForClipEnd(finishClip)
}
this.isTyping = false;
this.isTyping = false
}
/**
* Get available transitions from type state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.WAIT, States.REACT ];
getAvailableTransitions () {
return [States.WAIT, States.REACT]
}
/**
* Check if currently typing
* @returns {boolean} True if typing, false otherwise
*/
getIsTyping() {
return this.isTyping;
getIsTyping () {
return this.isTyping
}
/**
@ -122,7 +122,7 @@ export class TypeStateHandler extends StateHandler {
* @param {boolean} typing - Whether currently typing
* @returns {void}
*/
setTyping(typing) {
this.isTyping = typing;
setTyping (typing) {
this.isTyping = typing
}
}

View File

@ -3,8 +3,8 @@
* @module states
*/
import { StateHandler } from './StateHandler.js';
import { States, Emotions, Config } from '../constants.js';
import { StateHandler } from './StateHandler.js'
import { States, Emotions, Config } from '../constants.js'
/**
* Handler for the Wait/Idle state
@ -12,127 +12,127 @@ import { States, Emotions, Config } from '../constants.js';
* @extends StateHandler
*/
export class WaitStateHandler extends StateHandler {
/**
/**
* Create a wait state handler
* @param {OwenAnimationContext} context - The animation context
*/
constructor(context) {
super(States.WAIT, context);
constructor (context) {
super(States.WAIT, context)
/**
/**
* The main idle animation clip
* @type {AnimationClip|null}
*/
this.idleClip = null;
this.idleClip = null
/**
/**
* Available quirk animations
* @type {AnimationClip[]}
*/
this.quirks = [];
this.quirks = []
/**
/**
* Timer for quirk animations
* @type {number}
*/
this.quirkTimer = 0;
this.quirkTimer = 0
/**
/**
* Interval between quirk attempts (ms)
* @type {number}
*/
this.quirkInterval = Config.QUIRK_INTERVAL;
}
this.quirkInterval = Config.QUIRK_INTERVAL
}
/**
/**
* Enter the wait state
* @param {string|null} [fromState=null] - The previous state
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to enter with
* @returns {Promise<void>}
*/
async enter(fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering WAIT state from ${fromState}`);
async enter (fromState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Entering WAIT state from ${fromState}`)
// Play idle loop
this.idleClip = this.context.getClip('wait_idle_L');
if (this.idleClip) {
await this.idleClip.play();
this.currentClip = this.idleClip;
}
// Collect available quirks
this.quirks = this.context.getClipsByPattern('wait_*_Q');
this.quirkTimer = 0;
// Play idle loop
this.idleClip = this.context.getClip('wait_idle_L')
if (this.idleClip) {
await this.idleClip.play()
this.currentClip = this.idleClip
}
/**
// Collect available quirks
this.quirks = this.context.getClipsByPattern('wait_*_Q')
this.quirkTimer = 0
}
/**
* Exit the wait state
* @param {string|null} [toState=null] - The next state
* @param {string} [emotion=Emotions.NEUTRAL] - The emotion to exit with
* @returns {Promise<void>}
*/
async exit(toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting WAIT state to ${toState}`);
async exit (toState = null, _emotion = Emotions.NEUTRAL) {
console.log(`Exiting WAIT state to ${toState}`)
if (this.currentClip) {
await this.stopCurrentClip();
}
// Play transition if available
const transitionName = `wait_2${toState}_T`;
const transition = this.context.getClip(transitionName);
if (transition) {
await transition.play();
await this.waitForClipEnd(transition);
}
if (this.currentClip) {
await this.stopCurrentClip()
}
/**
// Play transition if available
const transitionName = `wait_2${toState}_T`
const transition = this.context.getClip(transitionName)
if (transition) {
await transition.play()
await this.waitForClipEnd(transition)
}
}
/**
* Update the wait state
* @param {number} deltaTime - Time elapsed since last update (ms)
* @returns {void}
*/
update(deltaTime) {
this.quirkTimer += deltaTime;
update (deltaTime) {
this.quirkTimer += deltaTime
// Randomly play quirks
if (this.quirkTimer > this.quirkInterval && Math.random() < Config.QUIRK_PROBABILITY) {
this.playRandomQuirk();
this.quirkTimer = 0;
}
// Randomly play quirks
if (this.quirkTimer > this.quirkInterval && Math.random() < Config.QUIRK_PROBABILITY) {
this.playRandomQuirk()
this.quirkTimer = 0
}
}
/**
/**
* Play a random quirk animation
* @private
* @returns {Promise<void>}
*/
async playRandomQuirk() {
if (this.quirks.length === 0) return;
async playRandomQuirk () {
if (this.quirks.length === 0) return
const quirk = this.quirks[ Math.floor(Math.random() * this.quirks.length) ];
const quirk = this.quirks[Math.floor(Math.random() * this.quirks.length)]
// Fade out idle
if (this.idleClip) {
await this.idleClip.stop(0.2);
}
// Play quirk
await quirk.play();
await this.waitForClipEnd(quirk);
// Return to idle
if (this.idleClip) {
await this.idleClip.play();
this.currentClip = this.idleClip;
}
// Fade out idle
if (this.idleClip) {
await this.idleClip.stop(0.2)
}
/**
// Play quirk
await quirk.play()
await this.waitForClipEnd(quirk)
// Return to idle
if (this.idleClip) {
await this.idleClip.play()
this.currentClip = this.idleClip
}
}
/**
* Get available transitions from wait state
* @returns {string[]} Array of available state transitions
*/
getAvailableTransitions() {
return [ States.REACT, States.SLEEP ];
}
getAvailableTransitions () {
return [States.REACT, States.SLEEP]
}
}