Files
gamercomp/frontend/public/docs/AVATAR_SYSTEM.md
T
2026-04-30 02:14:25 +00:00

26 KiB

Avatar System

Overview

Mii-style avatar system with full customization and level-based unlockable accessories. The system supports four rendering modes optimized for different game types, with smooth animations and real-time accessory rendering.

Architecture

The avatar system consists of several modules:

Module File Purpose
AvatarData avatarData.js Customization options and guest avatars
AvatarSystem avatarSystem.js Main API for creation, rendering, accessories
AvatarRenderer avatarRenderer.js Canvas 2D rendering engine
AvatarAnimations animations.js Animation definitions per mode
AvatarAccessories accessories.js Unlockable accessories catalog
AccessoryRenderer accessoryRenderer.js Accessory rendering on avatars

Customization Options

Face Shape (8 options)

ID Name Description
round Round Circular face with soft jawline
oval Oval Classic elongated oval shape
square Square Strong angular jawline
heart Heart Wide forehead, pointed chin
long Long Narrow, elongated face
wide Wide Broader face shape
angular Angular Defined cheekbones, sharp features
soft Soft Rounded features throughout

Skin Tone (20 options)

ID Name Hex Code
fair1 Porcelain #FFECD1
fair2 Ivory #FFE4C4
fair3 Peach #FFDAB9
fair4 Cream #FFD5B5
light1 Light Beige #F5D0A9
light2 Warm Beige #E8C49A
light3 Sand #DEB887
medium1 Golden #D4A373
medium2 Honey #C9A06A
medium3 Caramel #BC8F5F
medium4 Toffee #B07D4B
tan1 Tan #A67B5B
tan2 Bronze #996B4D
tan3 Cinnamon #8B6D4C
brown1 Chestnut #7D5A3C
brown2 Cocoa #6F4E37
brown3 Espresso #5D4532
dark1 Mocha #4E3B2D
dark2 Ebony #3D2B1F
dark3 Onyx #2C1F15

Eye Shape (12 options)

ID Name Description
round Round Large, circular eyes
almond Almond Classic almond shape
oval Oval Soft oval shape
narrow Narrow Slim, elongated eyes
wide Wide Broad, expressive eyes
droopy Droopy Downturned outer corners
upturned Upturned Lifted outer corners
cat Cat Sharp upturned cat-eye
sleepy Sleepy Heavy-lidded, relaxed look
surprised Surprised Wide open, alert
angry Angry Angled inward brow line
happy Happy Slightly squinted, joyful

Eye Color (16 options)

ID Name Hex Code
brown Brown #634E34
darkBrown Dark Brown #3D2314
hazel Hazel #8B7355
green Green #3D7A3D
blue Blue #4682B4
lightBlue Light Blue #87CEEB
gray Gray #708090
amber Amber #B8860B
violet Violet #8B008B
emerald Emerald #50C878
iceBlue Ice Blue #A5D8E6
gold Gold #DAA520
red Red #8B0000
black Black #1A1A1A
honey Honey #C9A06A
turquoise Turquoise #40E0D0

Total Eye Combinations: 12 shapes x 16 colors = 192 unique eye options

Eyebrow Shape (10 options)

ID Name Description
natural Natural Balanced, standard arch
arched Arched High dramatic arch
straight Straight Flat, horizontal brows
thick Thick Full, bold brows
thin Thin Delicate, fine brows
angry Angry Angled down toward center
worried Worried Angled up toward center
bushy Bushy Wild, untamed look
sleek Sleek Thin with elegant arch
curved Curved Pronounced curved shape

Nose Shape (8 options)

ID Name Description
button Button Small, rounded tip
pointed Pointed Narrow with defined tip
roman Roman Prominent bridge curve
snub Snub Short with slight upturn
wide Wide Broader nostril base
narrow Narrow Thin, elongated bridge
aquiline Aquiline Pronounced curved bridge
flat Flat Low bridge, wide base

Mouth Shape (10 options)

ID Name Description
smile Smile Gentle upward curve
neutral Neutral Relaxed, straight line
grin Grin Wide smile showing teeth
smirk Smirk Asymmetric half-smile
pout Pout Full lips, slight downturn
open Open Slightly parted lips
small Small Petite, compact mouth
wide Wide Broader mouth width
thin Thin Narrow lip fullness
full Full Plump, pronounced lips

Ear Shape (6 options)

ID Name Description
normal Normal Standard ear shape and size
small Small Compact, closer to head
large Large Prominent, larger ears
pointed Pointed Elf-like pointed tips
round Round Soft, rounded lobes
flat Flat Close-set against head

Hair Style (30 options)

ID Name Length Coverage
short-messy Short Messy Short 0.30
short-neat Short Neat Short 0.25
short-curly Short Curly Short 0.35
medium-straight Medium Straight Medium 0.50
medium-wavy Medium Wavy Medium 0.55
long-straight Long Straight Long 0.70
long-wavy Long Wavy Long 0.75
ponytail Ponytail Medium 0.40
pigtails Pigtails Medium 0.45
bun Bun Long 0.35
mohawk Mohawk Short 0.20
afro Afro Medium 0.80
buzz Buzz Cut Short 0.15
bald Bald None 0.00
sidepart Side Part Short 0.30
spiky Spiky Short 0.35
slicked Slicked Back Short 0.25
bob Bob Medium 0.50
pixie Pixie Short 0.35
braids Braids Long 0.60
dreads Dreads Long 0.70
undercut Undercut Short 0.25
fauxhawk Faux Hawk Short 0.30
mullet Mullet Medium 0.45
bowl Bowl Cut Medium 0.55
combover Comb Over Short 0.20
bangs Bangs Medium 0.50
sidesweep Side Sweep Medium 0.45
topknot Top Knot Long 0.30
cornrows Cornrows Medium 0.40

Hair Color (20 options)

ID Name Hex Code Type
black Black #1A1A1A Natural
darkBrown Dark Brown #2C1810 Natural
brown Brown #4A3728 Natural
lightBrown Light Brown #7A5A3A Natural
auburn Auburn #8B4513 Natural
ginger Ginger #B5651D Natural
strawberry Strawberry #C67171 Natural
blonde Blonde #D4B896 Natural
platinum Platinum #E8E4C9 Natural
white White #F0F0F0 Natural
gray Gray #808080 Natural
red Red #CC0000 Fantasy
blue Blue #0066CC Fantasy
purple Purple #7B2D8E Fantasy
green Green #228B22 Fantasy
pink Pink #FF69B4 Fantasy
teal Teal #008B8B Fantasy
orange Orange #FF6600 Fantasy
silver Silver #C0C0C0 Fantasy
rainbow Rainbow Gradient Fantasy

Facial Hair (10 options)

ID Name Coverage Description
none None - Clean shaven
stubble Stubble Light 5 o'clock shadow
goatee Goatee Chin Chin beard only
mustache Mustache Upper lip Classic mustache
fullBeard Full Beard Full face Complete beard coverage
shortBeard Short Beard Full face Trimmed full beard
soulPatch Soul Patch Chin center Small chin patch
mutton Mutton Chops Sides Sideburn-connected style
handlebar Handlebar Upper lip Curled mustache tips
vandyke Van Dyke Chin + mustache Goatee with mustache

Body Type (6 options)

ID Name Width Ratio Height Ratio
slim Slim 0.80 1.00
average Average 1.00 1.00
athletic Athletic 1.10 1.00
stocky Stocky 1.20 0.95
tall Tall 0.95 1.15
short Short 1.00 0.85

Clothing Style (4 options)

ID Name Has Collar Sleeve Length Special
casual Casual No Short -
sporty Sporty No Short Stripes
formal Formal Yes Long Buttons
scifi Sci-Fi Yes Long Glow effects

Clothing Color (20 preset colors)

#E74C3C  #E67E22  #F1C40F  #2ECC71  #1ABC9C
#3498DB  #9B59B6  #34495E  #95A5A6  #ECF0F1
#C0392B  #D35400  #F39C12  #27AE60  #16A085
#2980B9  #8E44AD  #2C3E50  #7F8C8D  #BDC3C7

Earned Accessories

Rarity System

Rarity Color Level Range Hex Code
Common Gray 1-15 #9D9D9D
Uncommon Green 16-30 #1EFF00
Rare Blue 31-50 #0070DD
Epic Purple 51-70 #A335EE
Legendary Orange 71-90 #FF8000
Mythic Gold 91-100 #E6CC80

Eyewear (15 items)

ID Name Unlock Level Rarity Has Effect Description
sunglasses-classic Classic Sunglasses 5 Common No Timeless shades for any occasion
aviator Aviator Glasses 10 Common No Top Gun approved eyewear
nerd-glasses Nerd Glasses 15 Common No Intelligence +100 (cosmetic only)
3d-glasses 3D Glasses 20 Uncommon No See the world in a whole new dimension
goggles Goggles 25 Uncommon No Ready for adventure or science experiments
monocle Monocle 30 Uncommon No Distinguished and sophisticated
star-glasses Star Glasses 35 Rare No You are a star!
heart-glasses Heart Glasses 40 Rare No Spread the love wherever you go
sport-visor Sport Visor 45 Rare No Professional gamer gear
vr-headset VR Headset 50 Epic No Immerse yourself in virtual worlds
cyber-visor Cyber Visor 55 Epic No Sleek futuristic eye protection
x-ray-specs X-Ray Specs 60 Epic Yes See through walls... probably
laser-eyes Laser Eyes 70 Legendary Yes Pew pew! Lasers shoot from your eyes
diamond-glasses Diamond Glasses 80 Legendary No Pure crystallized luxury
cosmic-lenses Cosmic Lenses 90 Mythic Yes Gaze upon the infinite universe

Headwear (20 items)

ID Name Unlock Level Rarity Has Effect Description
baseball-cap Baseball Cap 3 Common No A classic casual cap
backwards-cap Backwards Cap 8 Common No Cool kids wear it backwards
beanie Beanie 12 Common No Cozy knitted headwear
party-hat Party Hat 18 Uncommon No Every day is a celebration!
chef-hat Chef Hat 22 Uncommon No Master of the kitchen
crown-bronze Bronze Crown 25 Uncommon No A humble crown for rising royalty
hard-hat Hard Hat 26 Uncommon No Safety first on the job site
wizard-hat Wizard Hat 30 Rare No Channel your inner sorcerer
pirate-hat Pirate Hat 35 Rare No Arrr! Set sail for adventure
santa-hat Santa Hat 38 Rare No Ho ho ho! Spread holiday cheer
crown-silver Silver Crown 40 Rare No A noble crown for dedicated players
graduation-cap Graduation Cap 42 Rare No Scholar of the gaming arts
bunny-ears Bunny Ears 45 Rare No Hop into the fun!
devil-horns Devil Horns 48 Rare No A little mischief never hurt anyone
halo Halo 52 Epic Yes An angelic golden ring of light
top-hat Top Hat 56 Epic No Dapper and distinguished
crown-gold Gold Crown 60 Epic No True royalty in golden splendor
viking-helmet Viking Helmet 62 Epic No Conquer games like a Norse warrior
crown-diamond Diamond Crown 80 Legendary Yes A magnificent crown of pure diamonds
crown-cosmic Cosmic Crown 100 Mythic Yes The ultimate crown, forged from stardust

Effects/Auras (10 items)

ID Name Unlock Level Rarity Effect Type Color Description
sparkle-trail Sparkle Trail 15 Uncommon Particles #FFD700 Leave a trail of golden sparkles
fire-aura Fire Aura 25 Rare Glow #FF4500 Surrounded by fierce flames
lightning-crackle Lightning Crackle 35 Rare Electric #00BFFF Electricity crackles around you
rainbow-glow Rainbow Glow 45 Epic Glow Rainbow Radiate all colors of the spectrum
star-particles Star Particles 55 Epic Particles #FFFF00 Tiny stars orbit around you
ice-crystals Ice Crystals 65 Legendary Particles #87CEEB Frozen crystals shimmer around you
shadow-effect Shadow Effect 70 Legendary Shadow #2F2F4F Darkness follows your every move
golden-glow Golden Glow 75 Legendary Glow #FFD700 Bathe in pure golden light
void-aura Void Aura 85 Mythic Void #4B0082 The void itself surrounds you
cosmic-trail Cosmic Trail 95 Mythic Cosmic Cosmic Trail galaxies and nebulae in your wake

Total Accessories: 15 + 20 + 10 = 45 unlockable items


Rendering Modes

HEAD_ONLY (64x64 pixels)

Best for: Cockpit views, flying games (Flappy Bird style), maze games, puzzle games

Shows: Face, hair, ears, accessories (eyewear, headwear, effects)

Animations (5):

ID Name Frames Duration Loop Description
bob Bob 3 150ms Yes Gentle up/down bobbing motion
flap Flap 2 80ms Yes Flapping motion with head squash/stretch
blink Blink 3 60ms No Eye blink animation
celebrate Celebrate 4 100ms No Happy bouncing celebration
hurt Hurt 2 80ms No Damage reaction shake

HEAD_AND_SHOULDERS (64x96 pixels)

Best for: Driving games, conversation scenes, submarine games, portrait views

Shows: Head, neck, shoulders, clothing collar

Animations (6):

ID Name Frames Duration Loop Description
idle Idle 3 400ms Yes Subtle breathing motion
turn-left Turn Left 2 100ms No Head turns to the left
turn-right Turn Right 2 100ms No Head turns to the right
look-up Look Up 2 100ms No Head tilts upward
celebrate Celebrate 3 120ms No Bounce and smile celebration
hurt Hurt 2 100ms No Recoil damage reaction

UPPER_BODY (64x128 pixels)

Best for: Racing games, shooting games, hoverboard games, action sequences

Shows: Head, neck, shoulders, torso, arms, hands

Animations (8):

ID Name Frames Duration Loop Description
idle Idle 3 400ms Yes Breathing with subtle arm sway
wave Wave 4 120ms No Friendly arm wave gesture
point Point 3 100ms No Pointing forward gesture
steer-left Steer Left 2 80ms No Leaning left for racing/steering
steer-right Steer Right 2 80ms No Leaning right for racing/steering
shoot Shoot 3 60ms No Arm extends forward shooting motion
celebrate Celebrate 4 120ms No Arms up victory celebration
hurt Hurt 2 100ms No Recoil backwards damage reaction

FULL_BODY (64x160 pixels)

Best for: Platformers, RPGs, sports games, adventure games, fighting games

Shows: Complete character with head, body, arms, legs, shoes

Animations (12):

ID Name Frames Duration Loop Description
idle Idle 3 400ms Yes Standing with breathing motion
walk Walk Cycle 4 100ms Yes Walking with arm/leg swing
run Run Cycle 6 60ms Yes Running with full body movement
jump Jump 3 100ms No Crouch, leap, stretch sequence
fall Fall 2 150ms Yes Arms up, legs down falling pose
crouch Crouch 2 80ms No Duck down into crouch position
celebrate Celebrate 6 100ms No Jump and arm wave celebration
attack Attack 4 60ms No Punch or swing attack motion
hurt Hurt 3 80ms No Stagger backwards damage reaction
climb Climb 4 120ms Yes Climbing ladder/wall motion
swim Swim 4 150ms Yes Swimming stroke animation
fly Fly 4 100ms Yes Superhero flying pose

API Reference

Creating Avatars

// Create avatar with custom options
const avatar = AvatarSystem.create({
    faceShape: 'round',
    skinTone: '#FFD5B8',
    eyes: { shape: 'round', color: '#4A90D9' },
    eyebrows: 'natural',
    nose: 'button',
    mouth: 'smile',
    ears: 'normal',
    hair: { style: 'short-messy', color: '#3D2314' },
    facialHair: 'none',
    body: { type: 'average' },
    clothing: { style: 'casual', shirtColor: '#3498DB', pantsColor: '#2C3E50' }
});

// Create default avatar
const defaultAvatar = AvatarSystem.createDefault();

// Get random guest avatar
const guestAvatar = AvatarSystem.getGuestAvatar();

Loading and Saving

// Load user's saved avatar
const avatar = await AvatarSystem.loadUserAvatar(userId);

// Save avatar
AvatarSystem.saveAvatar(avatar);

// Clear cache
AvatarSystem.clearCache(userId);  // Clear specific user
AvatarSystem.clearCache();        // Clear all

Rendering

// Render to canvas context
AvatarSystem.render(avatar, 'FULL_BODY', ctx, x, y, {
    scale: 1,
    animation: 'walk',
    frame: 0
});

// Render to offscreen canvas
const canvas = AvatarSystem.renderToCanvas(avatar, 'HEAD_ONLY', { scale: 2 });

// Render to data URL (for images)
const dataUrl = AvatarSystem.renderToDataURL(avatar, 'HEAD_AND_SHOULDERS');

// Get mode dimensions
const size = AvatarSystem.getModeSize('FULL_BODY');
// Returns: { width: 64, height: 160 }

Animation Control

// Start animation
AvatarSystem.startAnimation(avatarId, 'walk', {
    loop: true,
    mode: 'FULL_BODY',
    onComplete: () => console.log('Animation finished')
});

// Stop animation
AvatarSystem.stopAnimation(avatarId);

// Get current animation state
const state = AvatarSystem.getAnimationState(avatarId);
// Returns: { animation: 'walk', frame: 2, complete: false, transforms: {...} }

// Check if animating
const isAnimating = AvatarSystem.isAnimating(avatarId);

// Get animation frame transforms directly
const transforms = AvatarSystem.animate(avatar, 'run', frameNumber);

Accessory Management

// Equip accessory
AvatarSystem.equipAccessory(avatar, 'headwear', 'crown-gold');
AvatarSystem.equipAccessory(avatar, 'eyewear', 'sunglasses-classic');
AvatarSystem.equipAccessory(avatar, 'effect', 'sparkle-trail');

// Unequip accessory
AvatarSystem.unequipAccessory(avatar, 'headwear');

// Unlock/award accessory
const newlyUnlocked = AvatarSystem.unlockAccessory(avatar, 'vr-headset');
// Returns: true if newly unlocked, false if already owned

// Check if avatar has accessory
const hasItem = AvatarSystem.hasAccessory(avatar, 'crown-gold');

// Get earned accessories (full objects)
const earned = AvatarSystem.getEarnedAccessories(avatar);
// Returns: { eyewear: [...], headwear: [...], effects: [...] }

// Get equipped accessories (full objects)
const equipped = AvatarSystem.getEquippedAccessories(avatar);
// Returns: { eyewear: {...}, headwear: {...}, effect: {...} }

// Get full accessory catalog
const catalog = AvatarSystem.getAccessoryCatalog();

Level Unlocks

// Check what unlocks at a specific level
const newItems = AvatarSystem.checkLevelUnlocks(avatar, 50);
// Returns: Array of newly unlocked accessory objects

// Add XP and check for level ups
const result = AvatarSystem.addXP(avatar, 500);
// Returns: { newLevel: 12, leveledUp: true, unlockedItems: [...] }

// Get XP progress info
const xpInfo = AvatarSystem.getXPInfo(avatar);
// Returns: { level, totalXP, currentLevelXP, xpNeededForLevel, progress }

Game Integration

// Export avatar for use in a game
const gameAvatar = AvatarSystem.exportForGame(avatar, 'FULL_BODY');
// Returns object with render() and animate() methods

// Use in game loop
gameAvatar.render(ctx, x, y, { animation: 'run', frame: frameNum });
const animInfo = gameAvatar.getAnimationInfo('run');

// Export minimal data for network transmission
const minimal = AvatarSystem.exportMinimal(avatar);

// Import from minimal data
const fullAvatar = AvatarSystem.importMinimal(minimalData, userId);

// Create sprite sheet for performance
const spriteSheet = AvatarSystem.createSpriteSheet(avatar, 'FULL_BODY', ['idle', 'walk', 'run']);
// Returns: { canvas, frameWidth, frameHeight, getFrameRect(animId, frame) }

Utility Functions

// Clone avatar
const cloned = AvatarSystem.clone(avatar);

// Update base properties
AvatarSystem.updateBase(avatar, { hair: { style: 'afro', color: '#000000' } });

// Validate avatar data
const isValid = AvatarSystem.validate(avatarData);

// Compare avatars
const areEqual = AvatarSystem.equals(avatar1, avatar2);

// Get all customization options
const options = AvatarSystem.getCustomizationOptions();
// Returns: { faceShapes, skinTones, eyeShapes, eyeColors, ... }

// Check if guest avatar
const isGuest = AvatarSystem.isGuest(avatar);

// Convert guest to registered user
const userAvatar = AvatarSystem.convertGuestToUser(guestAvatar, newUserId);

// Get version info
const version = AvatarSystem.getVersion();

Guest Avatars

10 pre-defined guest avatars are available for non-logged-in users. Each has a unique appearance:

ID Name Skin Tone Hair Style Eye Color Clothing Color
guest_1 Guest Blue Medium Short Messy Blue #3498DB
guest_2 Guest Red Light Long Straight Brown #E74C3C
guest_3 Guest Green Tan Buzz Cut Dark Brown #2ECC71
guest_4 Guest Purple Fair Bob Green #9B59B6
guest_5 Guest Orange Brown Afro Amber #E67E22
guest_6 Guest Teal Dark Dreads Dark Brown #1ABC9C
guest_7 Guest Gray Light Undercut Gray #95A5A6
guest_8 Guest Yellow Medium Spiky Hazel #F1C40F
guest_9 Guest Navy Tan Comb Over Brown #2C3E50
guest_10 Guest Pink Fair Pigtails Light Blue #FF69B4
// Get random guest avatar
const guest = AvatarSystem.getGuestAvatar();

// Or use AvatarData directly
const guestData = AvatarData.getRandomGuestAvatar();

XP and Leveling System

XP Per Level Formula

XP needed for level N = 100 + (N - 1) * 50
Level XP Needed Cumulative XP
1 100 100
2 150 250
3 200 450
5 300 1,000
10 550 3,500
25 1,300 18,250
50 2,550 68,000
75 3,800 148,500
100 5,050 259,750

Unlock Schedule

All accessories unlock by reaching specific levels:

  • Levels 3-15: 6 Common items
  • Levels 18-30: 8 Uncommon items
  • Levels 35-48: 10 Rare items
  • Levels 50-62: 8 Epic items
  • Levels 65-80: 6 Legendary items
  • Levels 85-100: 4 Mythic items

Accessory Animation Rules

Accessories follow specific animation behavior:

{
    headwear: {
        followHead: true,       // Moves with head
        bounceMultiplier: 1.2,  // Extra bounce on jumps
        rotationDamping: 0.8    // Slightly less rotation than head
    },
    eyewear: {
        followHead: true,       // Moves with head
        bounceMultiplier: 1.0,  // Same bounce as head
        rotationDamping: 1.0    // Matches head rotation exactly
    },
    effects: {
        independent: true,      // Own animation cycle
        particleSpeed: 1.0      // Particle emission rate
    }
}

Performance Tips

Sprite Caching

For games with many avatars or frequent redraws:

// Pre-render to sprite cache
const cache = AvatarRenderer.createSpriteCache(avatars, 'HEAD_ONLY', 1);

// Render from cache (much faster)
AvatarRenderer.renderFromCache(ctx, cache, avatarId, x, y);

Sprite Sheets

For animation-heavy games:

const sheet = AvatarSystem.createSpriteSheet(avatar, 'FULL_BODY', ['idle', 'walk', 'run', 'jump']);

// In game loop
const rect = sheet.getFrameRect('walk', currentFrame);
ctx.drawImage(sheet.image, rect.x, rect.y, rect.width, rect.height, destX, destY, rect.width, rect.height);

Batch Rendering

For many avatars on screen:

AvatarRenderer.renderBatch(ctx, avatars, 'HEAD_ONLY', positions);
// Automatically skips off-screen avatars

File Dependencies

Load order matters. Include scripts in this order:

<script src="/assets/avatar/avatarData.js"></script>
<script src="/assets/avatar/animations.js"></script>
<script src="/assets/avatar/avatarRenderer.js"></script>
<script src="/assets/avatar/accessories.js"></script>
<script src="/assets/avatar/accessoryRenderer.js"></script>
<script src="/assets/avatar/avatarSystem.js"></script>

Or use the asset manager which handles loading automatically.