0% found this document useful (0 votes)
2 views13 pages

Animation_Object_Behavior_Exam_Guide

The document is a comprehensive exam preparation guide covering keyframe animation, physics-based animation, object behavior, and scene graph structures in the context of Extended Reality (XR/AR) and game engine fundamentals. It details concepts such as keyframe interpolation, physics laws governing rigid body motion, and the implementation of object behaviors through state machines and AI. Additionally, it explains the hierarchical organization of game objects in scene graphs, emphasizing the importance of transforms and animation in creating dynamic interactions within a game environment.

Uploaded by

adithi.v
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Animation_Object_Behavior_Exam_Guide

The document is a comprehensive exam preparation guide covering keyframe animation, physics-based animation, object behavior, and scene graph structures in the context of Extended Reality (XR/AR) and game engine fundamentals. It details concepts such as keyframe interpolation, physics laws governing rigid body motion, and the implementation of object behaviors through state machines and AI. Additionally, it explains the hierarchical organization of game objects in scene graphs, emphasizing the importance of transforms and animation in creating dynamic interactions within a game environment.

Uploaded by

adithi.v
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ANIMATION AND OBJECT BEHAVIOR

Comprehensive Exam Preparation Guide

Extended Reality (XR/AR) & Game Engine Fundamentals


MCA - Computer Science

1. KEYFRAME ANIMATION
Definition & Concepts
• Keyframe Animation: Animation technique where animator specifies key poses/states
at specific time intervals, and the system interpolates between them to create smooth
motion.
• Keyframes: Snapshots of object state (position, rotation, scale, property values) at
specific time points (t0, t1, t2...). Marked by keyframe markers on timeline.
• Interpolation: Mathematical process of computing intermediate values between
keyframes. Types: Linear, Bezier, Catmull-Rom, Step.
• Timeline: Horizontal axis showing time in frames or seconds; vertical columns represent
objects with their keyframed properties.

Technical Details
1. Keyframe Data Structure:
class Keyframe { time: float; // Time at which keyframe occurs (in
seconds or frame number) value: Vector3; // Property value at this
keyframe (position, rotation, scale, etc.) inTangent: Vector3; // Incoming
tangent for Bezier curves (controls curve slope before keyframe) outTangent:
Vector3;// Outgoing tangent for Bezier curves (controls curve slope after
keyframe) easing: string; // Easing function ('linear', 'easeInQuad',
'easeOutQuad', etc.) }

2. Animation Curve Representation:


class AnimationCurve { keyframes: Keyframe[]; // Sorted array of keyframes
loopMode: string; // 'once', 'loop', 'pingpong' evaluate(time:
float): float { // Find surrounding keyframes const [k1, k2] =
findSurroundingKeyframes(time); const t = normalizeTime(time, [Link],
[Link]); // Apply interpolation based on tangent/easing return
interpolate([Link], [Link], t, [Link], [Link]); } }

3. Interpolation Methods:
• Linear Interpolation: v(t) = v1 + (v2 - v1) × t, where t ∈ [0,1]. Simple, constant velocity,
creates angular motion.
• Cubic Bezier: B(t) = (1-t)³P0 + 3(1-t)²tP1 + 3(1-t)t²P2 + t³P3. Smooth curves using
control points; tangents define curve shape.
• Catmull-Rom Spline: C(t) = 0.5 × [P0 P1 P2 P3] × M × [t³ t² t 1]ᵀ. Passes through
control points; auto-tangents from neighboring points.
• Step Function: value remains constant until next keyframe; used for discrete property
changes (visibility, material swap).

Easing Functions
Easing modifies interpolation speed across time interval. Standard types:

Easing Type Formula Effect


Linear f(t) = t Constant velocity
Ease-In-Quad f(t) = t² Slow start, fast end
Ease-Out-Quad f(t) = 1 - (1-t)² Fast start, slow end
Ease-In-Out f(t) = 3t² - 2t³ Smooth acceleration &
deceleration

Example: Character Walk Cycle


Timeline: 0-2 seconds (30 frames @ 15fps)
• Frame 0 (0s): Keyframe - Left leg forward, right leg back, arms swinging. Position: (0, 0,
0)
• Frame 15 (1s): Keyframe - Legs crossed, mid-stride. Position: (1, 0, 0). Interpolated
frames 1-14 use easing.
• Frame 30 (2s): Keyframe - Right leg forward (mirror of frame 0). Position: (2, 0, 0). Loop
back to frame 0.
• Interpolation: Bezier curves on limb rotations for smooth swing; Linear on position for
constant walk speed.

2. PHYSICS-BASED ANIMATION OF RIGID BODIES


Core Concepts
• Physics-based Animation: Simulation-driven animation. Objects move according to
physical laws (Newton's laws, gravity, collisions) rather than manual keyframes.
• Rigid Body: Object that doesn't deform; motion determined by linear velocity, angular
velocity, mass, and inertia tensor. Collisions cause instantaneous velocity changes.
• Degrees of Freedom (DOF): Rigid body in 3D has 6 DOF: 3 translational (x, y, z
position) + 3 rotational (pitch, yaw, roll).
• Simulation Loop: Detect collisions → Compute impulses → Update velocities →
Integrate position/rotation → Render.
Newton's Laws & Dynamics
4. First Law (Inertia): Object at rest stays at rest; object in motion stays in motion unless
external force applied.
5. Second Law: F = ma
acceleration = Force / mass a = F / m v(t+dt) = v(t) + a × dt x(t+dt) = x(t) +
v(t) × dt + 0.5 × a × dt² (Verlet integration)

6. Third Law: Action-reaction: If object A applies force on B, B applies equal and opposite
force on A.
7. Angular Motion: τ = Iα (torque = moment of inertia × angular acceleration)

Rigid Body Data Structure


class RigidBody { // Position & Rotation position: Vector3; // Center of mass
velocity: Vector3; // Linear velocity (m/s) rotation: Quaternion; //
Orientation angularVelocity: Vector3; // Rotation speed (rad/s) // Physical
Properties mass: float; // kg inverseMass: float; // 1/mass (for
immovable objects, set to 0) inertiaTensor: Matrix3; // Resistance to rotation; sphere:
(2/5)MR² inverseInertiaTensor: Matrix3; // Forces & Torques force: Vector3;
// Accumulated force (N) torque: Vector3; // Accumulated torque (N⋅m) //
Physics Properties damping: float; // Velocity loss per frame [0,1]
angularDamping: float; // Angular velocity loss friction: float; // [0,1]
surface friction coefficient restitution: float; // Bounce; 0=no bounce, 1=perfect
bounce // Methods applyForce(force: Vector3) { [Link] += force; }
applyTorque(torque: Vector3) { [Link] += torque; } integrate(dt: float) { //
Update velocity from forces acceleration = force / mass; velocity += acceleration *
dt; velocity *= (1 - damping); // Apply damping // Update position
position += velocity * dt; // Update angular velocity & rotation angularAccel
= inverseInertiaTensor * torque; angularVelocity += angularAccel * dt;
angularVelocity *= (1 - angularDamping); // Update rotation (quaternion) dq =
Quaternion(0, angularVelocity * 0.5) * rotation; rotation += dq * 0.5 * dt;
[Link](); // Reset forces for next frame force = Vector3(0, 0, 0);
torque = Vector3(0, 0, 0); } }

Collision Detection & Response


8. Broad Phase: Quick culling to identify potentially colliding pairs using bounding boxes
(AABB), spatial partitioning (BVH, Octree).
9. Narrow Phase: Precise collision test (sphere-sphere, box-box, mesh-mesh). Returns
contact point and normal.
10. Impulse Resolution: When collision occurs, compute impulse (velocity change) along
contact normal.
// Collision between body A and B at contact point P vn = (vB - vA) · normal; //
Relative velocity along normal if (vn < 0) { // Moving apart, apply impulse e =
min(restitutionA, restitutionB); // Bounciness // Impulse magnitude rA = P -
posA; // Vector from center to contact rB = P - posB; rn_A = rA × normal;
rn_B = rB × normal; j = -(1 + e) × vn / (1/massA + 1/massB + (rn_A ×
invIA × rn_A) + (rn_B × invIB × rn_B)); // Apply impulse velA -= (j / massA)
× normal; angVelA -= invIA × (rA × (j × normal)); velB += (j / massB) × normal;
angVelB += invIB × (rB × (j × normal)); }
Example: Bouncing Ball
Scenario: Ball thrown upward, bounces on floor
• Initial: position=(0, 2, 0), velocity=(0, 5, 0) m/s, mass=1kg, restitution=0.8
• Forces: gravity=9.8 m/s² downward
• Frame 1 (dt=0.016s): a=9.8 down, v += a×dt = (0, 5-0.157, 0), y += v×dt ≈ 1.92m
• At collision (y≈0): collision detected, impulse applied
• Post-bounce: v_new = -e × v_old = -0.8 × v_impact, bounces with 80% height

3. OBJECT BEHAVIOR
Definition & Components
• Object Behavior: Set of rules, responses, and actions an object exhibits in response to
events (collision, trigger, user input, time). Defines 'personality' and interaction patterns.
• State Machine: Object transitions between discrete states (Idle, Running, Jumping,
Falling) based on conditions.
• Event-Driven: Behavior triggered by events (OnCollision, OnTrigger, OnAnimationEnd,
OnInput).
• AI/Pathfinding: Complex behaviors use navigation meshes (navmesh), waypoints,
steering algorithms (separation, alignment, cohesion).

Behavior State Machine


class Behavior { currentState: State; stateTransitions: Map<State, State[]>;
onEvent(event: Event) { // Check transitions from current state const nextStates =
[Link](currentState); for (let state of nextStates) { if
([Link](currentState, event)) { [Link](); // Exit
current state currentState = state; [Link](); // Enter new
state return; } } } update(dt: float) { [Link](dt);
// Update current state logic } } class State { behavior: Behavior; onEnter() { }
// Called when entering this state onExit() { } // Called when leaving this state
update(dt: float) { } // Called every frame while in this state canTransitionFrom(fromState:
State, event: Event): bool { } } // Example: Character states class IdleState extends State
{ update(dt) { // Play idle animation } canTransitionFrom(from, event) { if (event
=== 'moveInput') return true; // Can move from idle if (event === 'jump') return true;
// Can jump from idle return false; } } class RunState extends State { speed: float =
5.0; update(dt) { moveInDirection(inputDirection, speed); playAnimation('run'); }
canTransitionFrom(from, event) { if (event === 'jump') return true; // Jump while
running if (event === 'stopInput') return true; // Stop running return false; } }

Steering & AI Behaviors


• Seek: Steer toward target. desiredVelocity = normalize(target - position) × maxSpeed.
steering = desiredVelocity - currentVelocity.
• Flee: Steer away from threat. desiredVelocity = normalize(position - threat) ×
maxSpeed.
• Separation: Avoid crowding neighbors. steering += normalize(position - neighbor) ×
weight for each neighbor within radius.
• Alignment: Match velocity of neighbors. desiredVelocity = average(neighbor velocities).
(Flocking behavior).
• Cohesion: Move toward center of nearby objects. desiredVelocity =
normalize(centerOfMass - position) × speed.

Example: Goblin AI Enemy


class GoblinBehavior extends Behavior { player: Character; visionRange: float = 10.0; attackRange:
float = 1.5; constructor() { [Link] = { 'patrol': new PatrolState(this),
'chase': new ChaseState(this), 'attack': new AttackState(this), 'die': new DieState(this)
}; [Link] = [Link]['patrol']; } } class PatrolState extends State { waypoints:
Vector3[] = [/* waypoints */]; currentWaypoint: int = 0; update(dt) { // Move to next
waypoint const target = waypoints[currentWaypoint]; const dist = distance([Link],
target); if (dist < 0.5) [Link]++; // Check if player visible if
(canSeePlayer() && distanceToPlayer < visionRange)
{ [Link]('playerSpotted'); } } } class ChaseState extends State { update(dt) {
// Move toward player const steering = seekBehavior([Link]); velocity += steering *
maxAccel * dt; position += velocity * dt; // Check if in attack range if
(distanceToPlayer < attackRange) { [Link]('playerInRange'); } // Check if lost
sight if (!canSeePlayer() || distanceToPlayer > visionRange * 1.5)
{ [Link]('playerEscaped'); } } } class AttackState extends State
{ attackCooldown: float = 0; attackDuration: float = 0.5; onEnter()
{ playAnimation('attack'); } update(dt) { // Face player const dirToPlayer =
normalize([Link] - position); rotation = slerp(rotation, lookRotation(dirToPlayer), dt *
5); attackCooldown -= dt; if (attackCooldown <= 0) { // Deal damage to player
[Link](attackDamage); attackCooldown = attackDuration; } // Exit if player
too far if (distanceToPlayer > attackRange * 2) { [Link]('playerOutOfRange'); }
} }

4. BEHAVIOR AND ANIMATION IN SCENE GRAPHS


Scene Graph Structure
• Scene Graph: Hierarchical tree of game objects (nodes). Each node has parent-child
relationships. Transforms (position, rotation, scale) propagate down tree via matrix
multiplication.
• Local Transform: Object's transform relative to parent.
• World Transform: Object's transform in global space = parent's world transform × local
transform.
• Forward Kinematics (FK): Child inherits parent's movement. Parent bone moves → all
child bones follow automatically.

Scene Graph Node


class SceneNode { name: string; // Hierarchy parent: SceneNode; children: SceneNode[]
= []; // Transform (local to parent) position: Vector3 = (0, 0, 0); rotation: Quaternion
= identity(); scale: Vector3 = (1, 1, 1); // Cached world transform worldMatrix:
Matrix4; // Updated when parent or local transform changes // Components components:
Component[] = []; // Mesh, Behavior, RigidBody, Animator, etc. // Animation animator:
Animator; // Plays animations on this node's properties // Cached matrices localMatrix:
Matrix4 = compose(position, rotation, scale); addChild(child: SceneNode)
{ [Link](child); [Link] = this; [Link](); //
Mark for update } updateWorldMatrix() { if ([Link]) { [Link] =
[Link] × [Link]; } else { [Link] =
[Link]; } // Update all children for (let child of [Link])
{ [Link](); } } update(dt: float) { // Update animator
(changes local transform based on animations) if ([Link])
{ [Link](dt); [Link] = compose([Link], [Link],
[Link]); [Link](); } // Update components (behavior,
physics, etc.) for (let component of [Link]) { [Link](dt); }
// Update children for (let child of [Link]) { [Link](dt); } }
render(camera: Camera) { // Render this node const mesh = [Link]('Mesh');
if (mesh) { renderMesh(mesh, [Link], camera); } // Render children
for (let child of [Link]) { [Link](camera); } } }

Skeletal Animation in Scene Graphs


Character skeleton = scene graph of bones (nodes). Animation curves control each bone's local
rotation.
// Character hierarchy Root (position, rotation animated) ├─ Spine (rotation keyframed) │
├─ Chest (rotation) │ │ ├─ LeftShoulder │ │ │ └─ LeftArm │ │ │ └─ LeftForearm │
│ │ └─ LeftHand │ │ └─ RightShoulder │ │ └─ RightArm │ │ └─
RightForearm │ │ └─ RightHand │ └─ Neck │ └─ Head ├─ LeftHip (rotation
keyframed) │ └─ LeftLeg │ └─ LeftFoot └─ RightHip (rotation keyframed) └─ RightLeg
└─ RightFoot // During walk animation: // [Link](t) applies keyframe values to
each bone's local rotation // updateWorldMatrix() propagates transforms down tree via FK //
Mesh vertices are skinned using bone world matrices (skeletal deformation)

Animation Blending on Scene Graph


Multiple animations can be blended together, with weights summing to 1.0. Scene graph
propagates final pose.
class AnimationBlender { activeAnimations: { clip: AnimationClip, weight: float }[] = [];
blendAnimation(clip: AnimationClip, weight: float, blendTime: float) { // Smoothly blend
in/out animation [Link]({ clip, weight, blendTime }); } update(dt:
float, skeleton: SceneNode) { let poseBlended = {}; let totalWeight = 0; //
Sample each active animation and blend poses for (let anim of [Link])
{ [Link] -= dt; let weight = [Link]; if ([Link] >
0) { // Cross-fade active weight *= [Link] / totalBlendTime; }
const pose = [Link]([Link]); for (let bone in pose) { if
(!poseBlended[bone]) poseBlended[bone] = [Link](); // Slerp quaternions with
weight poseBlended[bone] = slerp(poseBlended[bone], pose[bone], weight); }
totalWeight += weight; } // Apply blended pose to skeleton
applyPoseToSkeleton(skeleton, poseBlended); } } // Usage: Blend walk (0.7) with limp (0.3) for
injured character [Link](walkClip, 0.7, 0); [Link](limpClip, 0.3,
0);

Example: Humanoid Character Rigged


Storyboard: Knight character transitioning walk → run → jump
• Frame 0: Idle pose. Root at (0,0,0). All bones in bind pose.
• Frame 30 (t=2s): Walk animation playing. Root moves forward via position animation on
Root node. Spine rotates (keyframed), legs cycle. Forward kinematics: each child bone
inherits parent's rotation + own local rotation.
• Frame 45 (t=3s): Transition to run. Blender cross-fades walk (weight 0.5) + run (weight
0.5) over 0.3s. Root velocity increases.
• Frame 60 (t=4s): Full run animation. Faster leg cycle, greater arm swing, Root moves
quicker.
• Frame 75 (t=5s): Jump triggered. Run animation fades out (0.5s), jump animation blends
in. Root Y position animates upward. LeftFoot, RightFoot lift via bone animation, then fall
as gravity applied.

5. LIGHT SOURCES
Types of Lights
11. Directional Light (Sun): Parallel rays from infinite distance. Position irrelevant, only
direction matters. Illuminates entire scene uniformly. Casts shadows in one direction.
// Light direction (pointing FROM light toward objects) DirectionalLight
{ direction: Vector3 = normalize(vec3(1, -1, 1)); // Down-right color:
Color = white; intensity: float = 1.0; // Brightness multiplier castShadow:
bool = true; }

12. Point Light: Emits light in all directions from a point. Brightness decreases with distance
(1/r² falloff). Creates local illumination.
PointLight { position: Vector3; color: Color = yellow; intensity: float =
1.0; range: float = 10.0; // Max distance light reaches // Falloff
calculation attenuation = 1.0 / (1.0 + distance/range + (distance/range)²);
luminance = intensity × attenuation; }

13. Spot Light: Point light with directional cone. Intensity varies with angle to cone center.
Used for lamps, flashlights, stage lights.
SpotLight { position: Vector3; direction: Vector3; // Cone direction
color: Color; intensity: float; range: float; angle: float = 45.0; //
Full cone angle (degrees) falloff: float = 0.5; // Smooth edge; 0=hard,
1=soft // Angle falloff cosInnerAngle = cos(angle / 2); cosOuterAngle =
mix(cosInnerAngle, -1, falloff); spotFactor = smoothstep(cosOuterAngle,
cosInnerAngle, cos(angleToCenter)); luminance = intensity × attenuation ×
spotFactor; }

14. Ambient Light: Uniform illumination from all directions. Mimics indirect light bounces.
No position or direction; affects all objects equally.
finalColor = albedo × ambientLight × color;

Light Interaction with Materials


Lighting equation (simplified Phong model):
finalColor = ambientColor + diffuse × max(0, normal · lightDir) ×
lightColor + specular × pow(max(0, viewDir · reflect(lightDir,
normal)), shininess) × lightColor where: diffuse = albedo (surface color)
specular = glossiness (reflection strength, usually 0-1) shininess =
specularity (higher = sharper highlights)

Shadows
• Shadow Mapping: Render scene from light's viewpoint into a depth texture. During
shading, compare fragment depth to shadow map. If further than shadow map depth,
fragment is in shadow.
• PCF (Percentage-Closer Filtering): Sample shadow map at multiple offsets, average
results. Smooths hard shadow edges (anti-aliasing).
• Cascaded Shadow Maps: Multiple shadow maps at different scales for far/near
geometry. Prevents aliasing on large terrains.
• Screen-Space Ambient Occlusion (SSAO): Darken crevices/corners to simulate
occlusion. Post-process effect using depth texture.

Example: 3-Point Lighting Setup (Cinema)


Professional lighting rig with 3 lights:
• Key Light: Strong, directional. Position 45° above, 45° to side. Creates main shadows,
defines form.
• Fill Light: Softer, opposite key light. Reduces harsh shadows on other side. Usually
lower intensity (40-50%).
• Back Light (Rim): Behind subject, higher color saturation (often warm). Creates
rim/silhouette, separates subject from background.

6. SOUND
Audio Fundamentals
• Sample Rate: Samples per second (Hz). 44.1 kHz (CD quality), 48 kHz (video), 96 kHz
(HiFi). Nyquist theorem: max frequency = sampleRate/2.
• Bit Depth: Precision per sample. 16-bit (standard), 24-bit (professional). Higher = less
quantization noise.
• Channels: Mono (1), Stereo (2), 5.1 Surround (6 channels), 7.1 (8 channels).
• dB (Decibels): Logarithmic volume scale. 0 dB = reference level, -6 dB = half amplitude,
-∞ dB = silent. Perceived loudness is logarithmic to humans.

Audio in Game Engines


class AudioSource { clip: AudioClip; // Loaded audio file position: Vector3; //
3D position in world (for spatial audio) // Playback control isPlaying: bool; loop: bool
= false; volume: float = 1.0; // [0, 1] linear, or dB scale pitch: float = 1.0; // 1.0
= normal, 2.0 = octave higher // 3D Audio minDistance: float = 1.0; // Distance where
volume is max maxDistance: float = 100.0; // Distance where volume = 0 dopplerLevel: float =
1.0; // Pitch shift due to motion // Spatial spatialBlend: float = 0.0; // 0 = stereo
(2D), 1.0 = 3D panned play() { [Link] = true; } stop() { [Link] = false; }
pause() { [Link] = false; } // Can resume from same position setVolume(db: float) {
// dB to linear: 10^(dB/20) [Link] = pow(10, db / 20); } } class AudioListener { //
Represents player's ear; used for spatial audio position: Vector3; forward: Vector3; //
Where listener is facing up: Vector3; // Up direction for HRTF (Head-Related Transfer
Function) // HRTF simulates 3D sound based on ear anatomy // Calculates azimuth (left-
right) and elevation (up-down) from source position } // Usage: const footstepSound = new
AudioSource(footstepClip); [Link] = [Link]; // Emit from character
location [Link] = 1.0; // Full 3D [Link] = 0.7; // -3dB
[Link](); // Listener follows player camera [Link] =
[Link]; [Link] = [Link];

Spatial Audio
• Pan: Position sound in stereo field (left-right). Pan = dot(sourceDir, [Link]) where
right = normalized x-axis of listener.
• Distance Attenuation: Volume decreases with distance. Linear: volume = 1 - (distance
- minDist) / (maxDist - minDist). Logarithmic: 20 × log10(distance / minDist) dB.
• Doppler Effect: Pitch changes as sound source moves toward/away from listener.
pitchShift = [Link] / soundSpeed. E.g., ambulance siren.
• Occlusion/Absorption: Sound muffled when blocked. Apply low-pass filter (reduce high
frequencies), lower volume.
• Reverberation: Simulate room acoustics (cave, cathedral, small room). Add delayed,
attenuated copies of sound.

Sound Design: Categories


• SFX (Sound Effects): Impact, whoosh, footstep, explosion. Short, directional, dynamic.
• Voice/Dialog: Character speech, NPC audio. Localized, often with 3D positioning.
• Music/Score: Ambient, atmospheric, dynamic (changes based on gameplay state).
Usually stereo, looping.
• Ambient: Background environmental sounds (wind, water, city hum). Spatially spread,
usually loops.

Example: Dungeon Sound Design


Scenario: Player in stone dungeon, approaching goblin treasure chest
• Ambient: Quiet dripping water looping, stone reverb (cathedral effect). Low volume (-15
dB).
• Footsteps: Echoing stone footfall SFX, 3D positioned at player position, volume based
on movement speed.
• Chest Creak: When player opens chest, wood-creak SFX at chest position, 3D panned.
• Goblin Snarl: If goblin spawns, snarl audio from goblin position, triggers chase music
cross-fade.

7. BACKGROUND
Background Fundamentals
• Skybox: 6-faced cube (or sphere) surrounding camera with pre-rendered imagery.
Rotates with camera, always in background. Provides context, atmosphere, distant
clouds/sky.
• Skydome: Dome-shaped mesh instead of box. Allows animated effects (clouds moving,
sun animation, aurora).
• Far Clipping Plane: Defines depth at which background renders. Objects beyond are
culled. Affects fog/atmosphere rendering distance.
• Parallax Scrolling: Multiple background layers move at different speeds based on
camera distance. Creates depth illusion in 2D/2.5D games.
Skybox Implementation
class Skybox { cubemap: Texture; // 6 textures (front, back, left, right, top, bottom)
// OR equirectangularMap: Texture; // 360° panoramic texture mesh: Cube; // Simple
unit cube, rendered last with infinite far plane material: Material; // Vertex
shader (always behind all objects) position = [Link] + (vertex *
largeScale); // No perspective division; skybox remains at infinite distance //
Fragment shader vec3 direction = normalize(worldPosition - cameraPosition); vec3 color
= sampleCubemap(cubemap, direction); return color; } // Rendering (AFTER all scene
objects) renderSkybox(camera); renderScene(camera); renderSkybox(camera); // No depth
test, always renders behind

Fog & Atmosphere


• Linear Fog: fogFactor = (maxDist - depth) / (maxDist - minDist). finalColor = mix(color,
fogColor, fogFactor).
• Exponential Fog: fogFactor = exp(-(depth × density)²). More realistic, smoother falloff.
• Height Fog: Fog density varies with height. Denser at ground, clears at altitude.
fogDensity = exponential(-(height - minHeight) / thickness).
• Volumetric Fog: 3D volumetric shadows + lighting through fog. Ray-marching
technique; expensive but photorealistic.

Example: Fantasy Sky


Outdoor dungeon entrance with day-night cycle
• Skybox: Blue (day) or purple-black (night). Animated clouds scroll via UV offset. Stars
appear/fade based on time of day.
• Sun: Directional light orbits (time-of-day), casts long shadows at sunrise/sunset.
• Fog: Thin ethereal fog at ground level (height fog). Density increases toward horizon,
blends with skybox.
• Parallax: Mountains in distance move slower than near trees, creating depth perception.

8. SPECIAL PURPOSE SYSTEMS


8.1 VIRTUAL HUMANS / CHARACTER ANIMATION
• IK (Inverse Kinematics): Opposite of FK. Specify end-effector (hand, foot) position →
solve for bone rotations backward through chain. Used for: foot placement on slopes,
hand-to-object interaction, reaching.
// IK solver pseudocode (CCD - Cyclic Coordinate Descent) void solveCCD(Bone[]
chain, Vector3 target, int iterations) { for (int i = 0; i < iterations; i++) {
for (int j = [Link] - 2; j >= 0; j--) { // Traverse backward Bone bone
= chain[j]; Vector3 current = [Link]().position; // End effector current
position // Vector from joint to end effector Vector3 toEnd =
current - [Link]; // Vector from joint to target Vector3 toTarget
= target - [Link]; // Rotate bone to align with target
float angle = angleBetween(toEnd, toTarget); Vector3 axis = cross(toEnd,
toTarget).normalize(); [Link] = rotateAround(axis, angle) *
[Link]; // Update all child positions
updateChildPositions(bone); } } }
• Facial Animation: Blend shapes (morph targets) for expressions. Predefined face
shapes (smile, frown, blink) blended by weights. Driven by animation curves or voice
data (visemes for lip-sync).
• Procedural Animation: Runtime-generated animation (not pre-keyframed). E.g.,
character breathing (sine wave on chest), jiggle bones (secondary motion), cloth
simulation.
• Motion Capture (Mocap): Record actor's movements with sensors; retarget to
character skeleton. Creates realistic natural motion. Cleanup/editing in software post-
capture.

8.2 PARTICLE SYSTEMS


Simulates many small objects (particles) with emergent behavior. Used for: fire, smoke, dust,
sparks, rain, magic effects, explosions.
class Particle { position: Vector3; velocity: Vector3; acceleration: Vector3; lifespan:
float; // Total lifetime (seconds) age: float = 0; // Current age size: float;
// Quad size for billboarding sizeOverLifetime: float; // Function of age color: Color;
colorOverLifetime: Color; // Fade/color change rotation: float; // For rotated quad/mesh
particles angularVelocity: float; isDead: bool { return age >= lifespan; } } class
ParticleSystem { particles: Particle[]; maxParticles: int = 1000; emission: { rate: float =
50; // Particles/sec cone: float = 30; // Emission cone angle } emitter: SceneNode; //
Position & direction // Parameters startSpeed: Range = (5, 10); // Min-max initial speed
startSize: Range = (0.1, 0.5); startColor: Color = white; lifetime: Range = (1, 3); forces: {
gravity: Vector3 = (0, -9.8, 0); drag: float = 0.1; // Velocity multiplier per frame }
update(dt: float) { // Emit new particles numToEmit = [Link] * dt; for (let i = 0; i
< numToEmit; i++) { spawnParticle(); } // Update existing particles for (let p of
[Link]) { if ([Link]) { removeParticle(p); continue; }
// Physics simulation [Link] = [Link]; [Link] += [Link] * dt;
[Link] *= (1 - [Link]); // Drag [Link] += [Link] * dt; [Link] += dt;
// Update visual properties [Link] = interpolate(startSize, 0, [Link] / [Link],
sizeOverLifetime); [Link] = interpolate(startColor, endColor, [Link] / [Link]);
[Link] += [Link] * dt; } } render(camera: Camera) { // Render particles as
billboards (quads facing camera) for (let p of [Link]) { const billboard =
createBillboard([Link], [Link], camera); [Link] = [Link];
[Link] = [Link]; // Optional rotation drawMesh(billboard); } } }

Particle Effects Examples


• Explosion: High initial speed (20 m/s), cone 360°, short lifespan (0.5s), starts white →
yellow → black, decelerates.
• Smoke: Upward velocity (5 m/s) + gravity opposes. Spawns at fixed rate, gray →
transparent, expands size. Long lifespan (3s).
• Magic Spell: Mesh particles (star shapes, glyphs) instead of billboards. Colored (blue,
purple), swirl via initial angular velocity. Trail effect via child system.
• Rain: Constant emission, downward velocity, mesh particles (streaks), long lifetime.
Culled outside camera frustum for performance.

8.3 TERRAIN
• Heightmap: 2D array of height values. Texture where R channel = height. Vertex shader
reads heightmap, displaces vertices vertically. Simple, memory-efficient.
// Heightmap-based terrain float sampleHeight(vec2 uv) { return texture(heightmap,
uv).r * maxHeight; // Range [0, maxHeight] } // Vertex shader void main() { vec2
uv = [Link] / terrainSize; // UV from world position float h =
sampleHeight(uv); vec3 worldPos = vec3(position.x, h, position.z); // Compute
normal from height gradient float dh_x = (sampleHeight(uv + vec2(texelSize, 0)) -
sampleHeight(uv - vec2(texelSize, 0))) / (2.0 * texelSize); float dh_z =
(sampleHeight(uv + vec2(0, texelSize)) - sampleHeight(uv - vec2(0,
texelSize))) / (2.0 * texelSize); normal = normalize(vec3(-dh_x, 1, -dh_z));
gl_Position = projectionMatrix * viewMatrix * vec4(worldPos, 1.0); }

• Mesh-based Terrain: Pre-modeled terrain mesh (sculpted in Blender/Zbrush). More


control, LOD per chunk easier.
• Triplanar Texturing: Sample texture 3 times (from X, Y, Z axes), blend based on
surface normal. Avoids stretching on slopes. Used for cliffs, mountains.
• Splat Maps: RGBA texture controls blending of 4 material layers (grass, dirt, rock,
snow). Weight per channel.
• LOD (Level-of-Detail): Distant terrain uses coarser meshes. Chunks subdivide/merge
based on camera distance. Reduces draw calls, improves performance.

8.4 VEGETATION
• Tree Modeling: Branches = cylinders with decreasing radius. Leaves = billboard planes
or quad meshes. Modeled procedurally (L-system, Lindenmayer grammar) or hand-
sculpted.
// L-system tree (string rewriting) initial: X rules: X → F-[[X]+X]+F[+FX]-X
F → FF angle = 25°, scale = 0.95 // Interpretation: // F = draw segment
forward // + = rotate right // - = rotate left // [ = push stack (save
position/rotation) // ] = pop stack (restore) // Recursive generation produces
realistic branching structure

• Grass: Grass meshes = thin elongated quads. Painted on terrain via splat map. GPU
instancing renders thousands efficiently. Sways via vertex shader (sine wave on Y
based on time + position).
• Wind Simulation: Vertex shader applies oscillating displacement to vegetation. wind =
sin(time × frequency + position × windWave) × windStrength. Creates swaying illusion.
• Occlusion Culling: Vegetation behind hills/buildings not rendered. Precomputed
visibility sets per area reduce draw calls.
• Interaction: Trees bend when character moves through; grass displaced. Shader
samples wind at character position + applies to nearby vertices.

Example Scene: Enchanted Forest


Complete animation, lighting, VFX composition
• Storyboard Frame 1 (t=0s): Camera pans across forest. Autumn-colored trees
(procedurally generated via L-system), leaves particle effect drifting down. Directional
sunlight casts long shadows. Fog at ground level blends with skybox (orange sunset).
• Storyboard Frame 2 (t=3s): Character walks onto grass. Walk animation (keyframed
cycle) drives forward. Grass beneath bends via wind shader. Footstep SFX triggers each
step (3D-positioned), playing with spatial audio. Goblin NPC appears, state machine →
chase behavior. Pursuit music cross-fades in.

• Storyboard Frame 3 (t=6s): Combat ensues. Character's attack animation (keyframed)


triggers spell particle system at hand position (magic bolt). Goblin takes damage,
knockback physics applies. Explosion particle effect (fire + smoke). Ambient dungeon
reverb on SFX. Scene remains lit by directional sun + dynamic point light (spell glow).
Blend shapes on goblin's face → pain expression.

EXAM PREPARATION SUMMARY


Key Integration Points for 10-Mark Answers:

15. Animation Pipeline: Keyframes + interpolation → Animator updates scene graph →


Skeleton FK applies to mesh → Rendered with lights & shadows.
16. Physics + Behavior: RigidBody physics integrates position/rotation → Collisions
resolve impulses → Behavior state machine processes events → Triggers
animations/sound.
17. Complete Scene: Terrain heightmap + vegetation shader → Scene graph hierarchy with
animated objects → Multi-light rendering (directional + spot) → Fog + skybox
background → Audio listener with 3D sounds + particle effects.
18. Keywords (Exam Checklist): Keyframe, interpolation, easing, Bezier curves, forward
kinematics, rigid body, impulse, state machine, steering behaviors, scene graph, skeletal
animation, IK, particle system, heightmap, splat map, bloom, shadow mapping, spatial
audio, doppler, reverb, wind simulation, occlusion culling.

You might also like