Black Trigram (흑괘) - Korean Martial Arts Combat Simulator API - v0.7.0
    Preparing search index...

    Class PlayerAnimationStateMachine

    Player Animation State Machine

    Manages animation state, transitions, and timing with frame-accurate updates. Integrates priority system, automatic animation queueing, and event callbacks.

    Animation Queue: Enabled by default with max size 3 and timestamp-based conflict resolution. Automatically queues animations that cannot execute immediately and processes them when the current animation completes.

    const machine = new PlayerAnimationStateMachine(DEFAULT_ANIMATION_CONFIGS, {
    onAnimationStart: (state) => console.log(`Started ${state}`),
    onAnimationComplete: (state) => console.log(`Completed ${state}`),
    onFrame: (frame, state) => {
    if (state === "attack" && frame === 6) {
    // Execute attack at midpoint (frame 6 of 12)
    executeAttackLogic();
    }
    }
    });

    // Animation queue is enabled by default
    // Use transitionToQueued() for automatic queueing
    machine.transitionToQueued(AnimationState.ATTACK); // Queues if can't execute

    // Or use regular transitionTo() (no queueing)
    machine.transitionTo(AnimationState.ATTACK); // Fails if can't execute

    // In game loop (useFrame)
    useFrame((state, delta) => {
    const result = machine.update(delta);
    updatePlayerVisuals(result.state, result.frame);
    });

    플레이어애니메이션상태머신

    Index

    Constructors

    Methods

    • Clear stance transition data (called automatically when transition completes)

      Korean: 자세 전환 데이터 초기화

      Returns void

      자세전환데이터초기화

    • Dispose of the animation state machine

      Korean: 애니메이션 상태 머신 해제

      Clears all internal state, queues, and references to prevent memory leaks. Should be called when the state machine is no longer needed (e.g., component unmount).

      Returns void

      애니메이션상태머신해제

    • Enable or reconfigure animation queue system

      Korean: 애니메이션 대기열 활성화/재설정

      The queue is enabled by default. Use this method to reconfigure the queue size or conflict resolution strategy.

      Parameters

      • maxSize: number = 3

        Maximum queue size (default: 3)

      • conflictStrategy: ConflictResolutionStrategy = "timestamp"

        Conflict resolution strategy (default: "timestamp")

      Returns void

      // Queue is enabled by default, but you can reconfigure it
      machine.enableQueue(5, "requested");

      대기열활성화

    • Get current conflict resolution strategy

      Korean: 충돌 해결 전략 가져오기

      Returns ConflictResolutionStrategy

      Current conflict resolution strategy

      충돌해결전략가져오기

    • Get current stance transition data

      Korean: 현재 자세 전환 데이터 가져오기

      Returns the active stance transition data during stance_change animation. Null if not currently in a stance transition.

      Returns StanceTransition | null

      Current stance transition or null

      현재자세전환데이터가져오기

    • Get motion prediction state

      Korean: 동작 예측 상태 가져오기

      Returns MotionPredictionState

      Current motion prediction state

      동작예측상태가져오기

    • Get predicted future keyframe for latency reduction

      Korean: 예측된 미래 키프레임 가져오기

      Returns a keyframe predicted ahead by predictionTimeAhead (default: 1 frame). This reduces perceived input latency by showing where the animation will be in the near future rather than where it currently is.

      Integration point: Use this instead of the current keyframe when applying to the rig if motion prediction is enabled.

      Parameters

      Returns AnimationKeyframe

      Predicted future keyframe, or current if prediction disabled

      // In your skeletal animation update loop:
      let keyframeToApply = currentKeyframe;

      if (machine.isMotionPredictionEnabled()) {
      keyframeToApply = machine.getPredictedKeyframe(currentKeyframe);
      }

      applyKeyframeToRig(rig, keyframeToApply);

      예측키프레임가져오기

    • Get current animation queue state

      Korean: 현재 대기열 상태

      Returns information about the current queue state for debugging or UI display.

      Returns {
          enabled: boolean;
          maxSize: number;
          pending: readonly AnimationRequest[];
          size: number;
      }

      Queue state information

      현재대기열상태

    • Get interpolated blend weights for current stance transition frame

      Korean: 현재 프레임 블렌드 가중치

      Returns the interpolated blend data for the current frame during stance_change animation. Uses the keyframe data from the transition matrix to provide smooth stance interpolation.

      Returns { blend: number; frame: number; stance: "neutral" | TrigramStance } | null

      Blend data with stance and weight, or null if not in transition

      // In rendering loop during stance transition
      const blend = machine.getStanceTransitionBlend();
      if (blend) {
      console.log(`Frame ${blend.frame}: ${blend.stance} at ${blend.blend}x weight`);
      // Apply blended pose: blend.blend * targetPose + (1 - blend.blend) * sourcePose
      }

      현재프레임블렌드가중치

    • Check if currently in a stance transition animation

      Korean: 자세 전환 중 확인

      Returns boolean

      True if currently executing a stance_change animation

      자세전환중확인

    • Check if motion prediction is enabled

      Korean: 동작 예측 활성화 확인

      Returns boolean

      True if motion prediction is enabled

      동작예측활성화확인

    • Process next queued animation if available

      Korean: 다음 대기열 애니메이션 처리

      Should be called automatically when an animation completes. Dequeues and executes the highest priority pending animation.

      Returns boolean

      Whether a queued animation was executed

      다음대기열처리

    • Set conflict resolution strategy

      Korean: 충돌 해결 전략 설정

      Changes the strategy used to resolve equal-priority conflicts.

      Parameters

      • strategy: ConflictResolutionStrategy

        Conflict resolution strategy

      Returns void

      충돌해결전략설정

    • Enable or disable motion prediction

      Korean: 동작 예측 설정

      Enables motion prediction to reduce perceived input latency by predicting future animation frames based on current velocity (1-2 frames ahead).

      Parameters

      • enabled: boolean

        Whether to enable motion prediction

      • OptionalpredictionTime: number

        Optional: time ahead to predict (default: 16.67ms)

      Returns void

      // Enable motion prediction for 1 frame (16.67ms at 60fps)
      machine.setMotionPrediction(true);

      // Enable with 2 frames prediction (33.33ms)
      machine.setMotionPrediction(true, 0.03333);

      동작예측설정

    • Set preferred easing function for transitions

      Korean: 선호 이징 함수 설정

      Sets the default easing curve for animation transitions. Can use presets like "natural-motion", "smooth-transition", etc.

      Parameters

      • easingName: EasingName

        Easing function name

      Returns void

      // Use natural motion for Korean martial arts
      machine.setPreferredEasing("natural-motion");

      // Use explosive power for strike animations
      machine.setPreferredEasing("explosive-power");

      선호이징함수설정

    • Attempt to transition to a new animation state

      Checks transition rules and priority system before transitioning.

      Parameters

      Returns boolean

      Whether transition was successful

      // Successful transitions
      machine.transitionTo("walk"); // idle -> walk
      machine.transitionTo("attack"); // walk -> attack

      // Failed transition (invalid or lower priority)
      machine.transitionTo("walk"); // attack -> walk (blocked, must complete first)

      상태전환

    • Transition to ATTACK state with a technique-specific duration.

      The default ATTACK config is 200ms (12 frames), but real techniques range from 350ms to 1200ms. This method overrides the ATTACK frame count to match the actual skeletal animation duration so the state machine stays in ATTACK for the full technique.

      Parameters

      • durationSeconds: number

        The skeletal animation duration in seconds

      Returns boolean

      Whether transition was successful

      // Jab animation is 0.55s (TECHNIQUE_TIMING.FAST)
      machine.transitionToAttack(0.55);

      공격전환 (기술별 지속시간)

    • Attempt to transition to a new animation state with queue support

      Korean: 대기열 지원 상태 전환

      Enhanced version of transitionTo() that automatically queues animations when they cannot be executed immediately. Since the queue is enabled by default, this is the recommended method for animation transitions.

      The queued animation will be automatically processed when the current animation completes, following priority and conflict resolution rules.

      Parameters

      Returns "success" | "queued" | "failed"

      Whether transition was successful, queued, or failed

      // Queue is enabled by default
      const result = machine.transitionToQueued(AnimationState.ATTACK);
      // Returns "success" if transitioned immediately
      // Returns "queued" if couldn't interrupt but was queued
      // Returns "failed" if queue is full or disabled

      대기열상태전환

    • Transition to stance_change animation with specific stance transition data

      Korean: 자세 전환 애니메이션 시작

      Initiates a stance change animation with the specific transition data from the 64-transition matrix. This provides stance-specific keyframes and blend weights for smooth interpolation.

      Parameters

      Returns boolean

      Whether transition was successful

      // Start transition from Heaven to Lake stance
      const success = machine.transitionToStanceChange(
      TrigramStance.GEON,
      TrigramStance.TAE
      );

      if (success) {
      // During update loop, use getStanceTransitionBlend() to interpolate
      const blend = machine.getStanceTransitionBlend();
      if (blend) {
      // Apply blend weights to stance poses
      applyStanceBlend(blend);
      }
      }

      자세전환애니메이션시작

    • Transition to stance-specific guard animation

      Convenience method to transition to a stance guard based on trigram stance. Automatically maps trigram stance to corresponding guard animation state.

      Parameters

      Returns boolean

      Whether transition was successful

      // When player changes to Fire stance
      machine.transitionToStanceGuard(TrigramStance.LI);
      // Internally transitions to "stance_guard_li" animation state

      자세방어전환

    • Update motion prediction with skeletal keyframe data

      Korean: 동작 예측 업데이트

      This should be called from the skeletal animation layer when applying interpolated keyframes to the rig. It updates velocity tracking for motion prediction to reduce perceived latency.

      Integration point: Call this from your skeletal animation system after computing the current interpolated keyframe (e.g., from getInterpolatedKeyframe).

      Parameters

      • currentKeyframe: AnimationKeyframe

        Current skeletal animation keyframe with bone positions/rotations

      • deltaTime: number

        Time elapsed since last update

      Returns void

      // In your skeletal animation update loop:
      const currentKeyframe = getInterpolatedKeyframe(animation, time);

      // Update motion prediction (for next frame)
      if (machine.isMotionPredictionEnabled()) {
      machine.updateMotionPredictionState(currentKeyframe, deltaTime);
      }

      // Apply keyframe to rig
      applyKeyframeToRig(rig, currentKeyframe);

      동작예측업데이트

    Properties

    animationQueue: AnimationQueue | null = ...

    Animation queue for pending animations

    Korean: 애니메이션 대기열

    Stores animation requests that couldn't be executed immediately due to non-interruptible animations or priority conflicts. Processed automatically when current animation completes.

    Enabled by default with max size 3 and timestamp-based conflict resolution. Can be disabled with disableQueue() or reconfigured with enableQueue().

    애니메이션대기열

    Create a new animation state machine

    Clones the provided config map so per-instance mutations (e.g. dynamic attack duration) don't affect shared defaults.

    Map of animation configurations (cloned internally)

    Optional event callbacks

    생성자

    conflictStrategy: ConflictResolutionStrategy = "timestamp"

    Conflict resolution strategy for equal-priority animations

    Korean: 충돌 해결 전략

    Determines how to resolve conflicts when multiple animations have equal priority. Default: timestamp (FIFO).

    충돌해결전략

    currentStanceTransition: StanceTransition | null = null

    Current stance transition data (null when not in stance_change animation)

    Korean: 현재 자세 전환 데이터

    Tracks the active stance transition for use during stance_change animation. Provides access to keyframes and blend weights for smooth interpolation.

    현재자세전환데이터

    currentState: AnimationState = AnimationState.IDLE
    enableMotionPrediction: boolean = false

    Enable motion prediction for latency reduction

    Korean: 동작 예측 활성화

    When enabled, predicts future animation frames based on current velocity to reduce perceived input latency by 16-33ms (1-2 frames at 60fps).

    동작예측활성화

    frameIndex: number = 0
    justCompleted: boolean = false
    justStarted: boolean = false
    motionPrediction: MotionPredictionState = ...

    Motion prediction state for latency reduction

    Korean: 동작 예측 상태

    Tracks animation velocities for motion prediction to reduce perceived latency. Updated each frame with velocity calculations for smooth anticipation.

    동작예측상태

    predictionTimeAhead: number = 0.01667

    Motion prediction time ahead (seconds)

    Korean: 예측 시간

    How far ahead to predict motion (default: 1 frame = 16.67ms at 60fps). Typical range: 0.016-0.033 seconds for <50ms total latency.

    예측시간

    preferredEasing: EasingName = "natural-motion"

    Preferred easing function for smooth transitions

    Korean: 선호 이징 함수

    Default easing curve for animation blending and transitions. Can be overridden per animation or transition.

    선호이징함수

    previousKeyframe: AnimationKeyframe | null = null

    Previous keyframe for motion prediction velocity calculation

    Korean: 이전 키프레임

    이전키프레임

    previousState: AnimationState | null = null
    timeAccumulator: number = 0
    GUARD_STATE_MAP: Record<TrigramStance, AnimationState> = ...

    Static mapping from TrigramStance to guard AnimationState Prevents repeated object allocation in transitionToStanceGuard()

    자세방어상태맵

    STANCE_FROM_GUARD_MAP: Record<string, TrigramStance> = ...

    Static reverse mapping from guard AnimationState to TrigramStance Prevents repeated object allocation in getCurrentGuardStance()

    방어상태자세맵