İçeriğe geç
934 satır · 38,1 KBHamİndir
// Kodla üretilen low-poly karakter: yürüme, oturma, dans animasyonları + isim etiketi ve konuşma balonu.
import * as THREE from 'three';
import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js';
import { buildCostume, buildFolkCostume, costumeOn, costumeShirt } from './costume.js';

const SKIN = [0xf1c7a5, 0xe2b08c, 0xc98f6a, 0xa86d4c, 0xf6d7bf, 0xd9a07c];
// Gece kıyafetleri: siyah, beyaz, bordo, lacivert, gri, altın/gümüş pullu, mürdüm, zümrüt, gül kurusu, kahve
const OUTFIT = [0x141418, 0xd8d4cc, 0x7a1027, 0x1c2a4a, 0x4a4a52, 0xc9a24a, 0xb0b4bc, 0x6a1a4a, 0x1f4a3a, 0xc8566e, 0x3a2a20, 0x141418];
const SEQUIN = new Set([0xc9a24a, 0xb0b4bc]);
const HAIR = [0x16100c, 0x2b1b12, 0x3e2616, 0x5a3a22, 0x8a5a2e, 0xc89a5a, 0x7a2e18, 0x16100c, 0xbdb8b0];
const PANTS = [0x15151a, 0x1f2638, 0x2e2e34, 0x3a3f52, 0x4a3a2a];
export const HIP = 0.8; // kalça yüksekliği (gerçek ölçek: 1 birim = 1 metre)

const geo = {
  torso: new THREE.CylinderGeometry(0.15, 0.125, 0.48, 14),
  chest: new THREE.SphereGeometry(0.15, 14, 8),
  pelvis: new THREE.CylinderGeometry(0.13, 0.15, 0.18, 14),
  skirt: new THREE.CylinderGeometry(0.15, 0.27, 0.56, 16, 1, true),
  neck: new THREE.CylinderGeometry(0.045, 0.052, 0.12, 8),
  head: new THREE.SphereGeometry(0.115, 18, 14),
  eye: new THREE.SphereGeometry(0.014, 8, 6),
  brow: new THREE.BoxGeometry(0.042, 0.008, 0.01),
  nose: new THREE.ConeGeometry(0.014, 0.04, 6),
  lips: new THREE.BoxGeometry(0.038, 0.01, 0.01),
  must: new THREE.BoxGeometry(0.06, 0.012, 0.012),
  shades: new THREE.BoxGeometry(0.13, 0.03, 0.012),
  hairCap: new THREE.SphereGeometry(0.124, 16, 10, 0, Math.PI * 2, 0, Math.PI * 0.52),
  hairLong: new THREE.BoxGeometry(0.22, 0.3, 0.07),
  bun: new THREE.SphereGeometry(0.06, 10, 8),
  pony: new THREE.CapsuleGeometry(0.035, 0.16, 3, 8),
  upper: new THREE.CapsuleGeometry(0.045, 0.24, 4, 8),
  fore: new THREE.CapsuleGeometry(0.038, 0.22, 4, 8),
  hand: new THREE.SphereGeometry(0.038, 8, 6),
  thigh: new THREE.CapsuleGeometry(0.065, 0.3, 4, 8),
  shin: new THREE.CapsuleGeometry(0.05, 0.3, 4, 8),
  shoe: new THREE.BoxGeometry(0.09, 0.06, 0.2),
  heel: new THREE.BoxGeometry(0.08, 0.07, 0.16),
  crown: new THREE.CylinderGeometry(0.085, 0.075, 0.07, 6, 1, true),
};
geo.upper.translate(0, -0.15, 0);
geo.fore.translate(0, -0.41, 0);
geo.thigh.translate(0, -0.2, 0);
geo.shin.translate(0, -0.2, 0);

const matCache = new Map();
function mat(color, opts = {}) {
  const key = color + JSON.stringify(opts);
  if (!matCache.has(key)) matCache.set(key, new THREE.MeshStandardMaterial({ color, roughness: 0.65, ...opts }));
  return matCache.get(key);
}
const BLACK = new THREE.MeshBasicMaterial({ color: 0x111111 });
const CHEEK = new THREE.MeshBasicMaterial({ color: 0xff8fa8 });
const GOLD = new THREE.MeshStandardMaterial({ color: 0xffcc33, metalness: 0.8, roughness: 0.25, side: THREE.DoubleSide });

const pick = (a, r) => a[Math.floor(r * a.length) % a.length];
// İsimden sabit rastgele sayı: aynı kişi her seferinde aynı görünür.
function seeded(str) {
  let h = 2166136261;
  for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 16777619);
  return () => {
    h = Math.imul(h ^ (h >>> 15), 2246822507);
    h = Math.imul(h ^ (h >>> 13), 3266489909);
    return ((h ^= h >>> 16) >>> 0) / 4294967296;
  };
}

export const DANCE_STYLES = ['sallanma', 'ziplama', 'donme', 'kol', 'omuz'];
// Oyun havası figürleri: parmak şıklatma, omuz titretme, kollar açık dönme, yana adım + kalça
export const OYUN_STYLES = ['parmak', 'oyunOmuz', 'oyunDon', 'yanAdim'];
const SPIN_STYLES = new Set(['donme', 'oyunDon']);

/** Paneldeki butonla değişir: 'normal' | 'oyun' | 'halay' | 'horon' */
export const danceMode = { value: 'normal' };
export const GROUP_MODES = new Set(['halay', 'horon']);
const styleList = () => {
  const m = danceMode.value;
  if (GROUP_MODES.has(m)) return [m];
  return m === 'oyun' ? OYUN_STYLES : DANCE_STYLES;
};
// Kons: elde kadeh
const GLASS_GEO = new THREE.CylinderGeometry(0.055, 0.04, 0.14, 10, 1, true);
const LIQUID_GEO = new THREE.CylinderGeometry(0.048, 0.04, 0.08, 10);
const GLASS_MAT = new THREE.MeshStandardMaterial({ color: 0xdff4ff, transparent: true, opacity: 0.45, roughness: 0.05, side: THREE.DoubleSide });
const LIQUID_MAT = new THREE.MeshStandardMaterial({ color: 0xf2a91f, emissive: 0x5a3500, roughness: 0.3 });
const MENDIL_GEO = new THREE.PlaneGeometry(0.26, 0.26);
// Sahne: elde mikrofon
const MIC_GEO = new THREE.CylinderGeometry(0.022, 0.014, 0.2, 8);
const MIC_HEAD_GEO = new THREE.SphereGeometry(0.038, 10, 8);
const MIC_MAT = new THREE.MeshStandardMaterial({ color: 0x222226, metalness: 0.7, roughness: 0.3 });
const MIC_HEAD_MAT = new THREE.MeshStandardMaterial({ color: 0xb8bcc4, metalness: 0.9, roughness: 0.25 });

// ---------- Çalgılar (sahnedeki müzisyenler) ----------
const WOOD = new THREE.MeshStandardMaterial({ color: 0x8a4a1e, roughness: 0.55 });
const WOOD_DARK = new THREE.MeshStandardMaterial({ color: 0x4a2410, roughness: 0.6 });
const SKIN_HEAD = new THREE.MeshStandardMaterial({ color: 0xf1e6cc, roughness: 0.8 });
const DRUM_RED = new THREE.MeshStandardMaterial({ color: 0xb0182e, roughness: 0.5 });
const BRASS = new THREE.MeshStandardMaterial({ color: 0xd9a43a, metalness: 0.8, roughness: 0.3 });
const EBONY = new THREE.MeshStandardMaterial({ color: 0x141416, roughness: 0.35, metalness: 0.2 });
const BAG = new THREE.MeshStandardMaterial({ color: 0xc9b089, roughness: 0.9 });
const CLAY = new THREE.MeshStandardMaterial({ color: 0xc86a30, roughness: 0.5, metalness: 0.3 });
// eğik üflemeli çalgı: ağızdan öne-aşağı (baş grubuna göre)
const blowDir = (len) => ({ y: -0.05 - Math.cos(1.125) * len / 2, z: 0.11 + Math.sin(1.125) * len / 2 });

function buildInstrument(kind) {
  const g = { hips: new THREE.Group(), head: new THREE.Group(), handR: new THREE.Group(), handL: new THREE.Group() };
  const m = (geo, mat) => new THREE.Mesh(geo, mat);
  if (kind === 'davul') {
    // büyük davul karın önünde, yanları kayışla; sağda tokmak, solda çubuk
    const shell = m(new THREE.CylinderGeometry(0.27, 0.27, 0.3, 20), DRUM_RED);
    shell.rotation.z = Math.PI / 2;
    shell.position.set(0, 0.3, 0.33);
    const skinL = m(new THREE.CircleGeometry(0.27, 20), SKIN_HEAD);
    skinL.position.set(-0.152, 0.3, 0.33);
    skinL.rotation.y = -Math.PI / 2;
    const skinR = skinL.clone();
    skinR.position.x = 0.152;
    skinR.rotation.y = Math.PI / 2;
    const strap = m(new THREE.TorusGeometry(0.3, 0.012, 6, 20, Math.PI), EBONY);
    strap.position.set(0, 0.3, 0.12);
    strap.rotation.set(0, Math.PI / 2, 0);
    g.hips.add(shell, skinL, skinR);
    const tokmak = m(new THREE.CylinderGeometry(0.012, 0.016, 0.34, 6), WOOD);
    tokmak.position.set(0, -0.62, 0.15);
    tokmak.rotation.x = Math.PI / 2;
    const knob = m(new THREE.SphereGeometry(0.035, 8, 6), WOOD_DARK);
    knob.position.set(0, -0.62, 0.32);
    g.handR.add(tokmak, knob);
    const cubuk = m(new THREE.CylinderGeometry(0.005, 0.005, 0.36, 4), WOOD);
    cubuk.position.set(0, -0.62, 0.16);
    cubuk.rotation.x = Math.PI / 2;
    g.handL.add(cubuk);
  } else if (kind === 'zurna' || kind === 'klarnet') {
    const len = kind === 'zurna' ? 0.4 : 0.52;
    const tube = kind === 'zurna'
      ? m(new THREE.CylinderGeometry(0.012, 0.06, len, 12, 1, true), WOOD)
      : m(new THREE.CylinderGeometry(0.014, 0.03, len, 10), EBONY);
    tube.material.side = THREE.DoubleSide;
    const d = blowDir(len);
    tube.position.set(0, d.y, d.z);
    tube.rotation.x = -1.125; // geniş ağız öne-aşağı
    g.head.add(tube);
    if (kind === 'klarnet') {
      const bell = m(new THREE.CylinderGeometry(0.03, 0.05, 0.06, 10, 1, true), BRASS);
      const e = blowDir(len * 2 - 0.06);
      bell.position.set(0, e.y, e.z);
      bell.rotation.x = tube.rotation.x;
      g.head.add(bell);
    } else {
      const ring = m(new THREE.TorusGeometry(0.02, 0.006, 6, 12), BRASS);
      ring.position.set(0, -0.05 - Math.cos(1.125) * 0.03, 0.11 + Math.sin(1.125) * 0.03);
      ring.rotation.x = Math.PI / 2 - 1.125;
      g.head.add(ring);
    }
  } else if (kind === 'kemence') {
    // dik tutulan küçük kemençe, sağ elde yay
    const body = m(new THREE.BoxGeometry(0.09, 0.3, 0.05), WOOD);
    const neck = m(new THREE.BoxGeometry(0.035, 0.14, 0.03), WOOD_DARK);
    neck.position.y = 0.21;
    const kem = new THREE.Group();
    kem.add(body, neck);
    kem.position.set(-0.04, 0.3, 0.2);
    kem.rotation.z = 0.18;
    g.hips.add(kem);
    const bow = m(new THREE.CylinderGeometry(0.005, 0.005, 0.52, 4), WOOD_DARK);
    bow.position.set(-0.2, -0.6, 0.04);
    bow.rotation.z = Math.PI / 2;
    g.handR.add(bow);
  } else if (kind === 'tulum') {
    // sol koltuk altında tulum (tulum torbası), ağızdan nefes borusu, önde nağme borusu
    const bag = m(new THREE.SphereGeometry(0.15, 14, 10), BAG);
    bag.scale.set(0.8, 0.7, 1.3);
    bag.position.set(-0.2, 0.36, 0.12);
    const chanter = m(new THREE.CylinderGeometry(0.014, 0.02, 0.26, 8), WOOD);
    chanter.position.set(-0.08, 0.2, 0.26);
    chanter.rotation.x = 0.5;
    g.hips.add(bag, chanter);
    const blow = m(new THREE.CylinderGeometry(0.009, 0.009, 0.24, 6), WOOD_DARK);
    const d = blowDir(0.24);
    blow.position.set(-0.04, d.y, d.z - 0.05);
    blow.rotation.set(-1.4, 0, -0.35);
    g.head.add(blow);
  } else if (kind === 'darbuka') {
    const db = m(new THREE.CylinderGeometry(0.13, 0.05, 0.3, 16), CLAY);
    const top = m(new THREE.CircleGeometry(0.13, 16), SKIN_HEAD);
    top.rotation.x = -Math.PI / 2;
    top.position.y = 0.151;
    const dk = new THREE.Group();
    dk.add(db, top);
    dk.position.set(-0.16, 0.12, 0.2);
    dk.rotation.set(-0.9, 0, -0.35);
    g.hips.add(dk);
  }
  return g;
}
const MENDIL_MAT = new THREE.MeshStandardMaterial({ color: 0xe0102f, side: THREE.DoubleSide, roughness: 0.6 });
const randomStyle = () => { const l = styleList(); return l[Math.floor(Math.random() * l.length)]; };
const WALK_SPEED = 3.2;

export class Avatar {
  /** gender: 'f' | 'm' | null (null: isme göre rastgele) */
  constructor(name, gender = null) {
    const rnd = seeded(name);
    this.name = name;
    this.root = new THREE.Group();
    this.build(rnd, gender);

    // Etiket (isim + balon)
    this.labelEl = document.createElement('div');
    this.labelEl.className = 'tag';
    this.bubbleEl = document.createElement('div');
    this.bubbleEl.className = 'bubble';
    this.nameEl = document.createElement('div');
    this.nameEl.className = 'name';
    this.nameEl.textContent = name;
    this.konsEl = document.createElement('span');
    this.konsEl.className = 'kons';
    this.nameEl.appendChild(this.konsEl);
    this.kons = 0;
    this.labelEl.append(this.bubbleEl, this.nameEl);
    this.label = new CSS2DObject(this.labelEl);
    this.label.position.y = 1.95;
    this.root.add(this.label);

    this.state = 'idle'; // idle | walk | sit | dance
    this.path = [];
    this.onArrive = null;
    this.facing = 0;
    this.targetFacing = 0;
    this.t = rnd() * 10;
    this.danceStyle = pick(DANCE_STYLES, rnd());
    this.nextStyleChange = 8 + rnd() * 10;
    this.bubbleTimer = null;
  }

  /** Gövdeyi kur (hips + bacaklar). Cinsiyet değişince yeniden çağrılır. */
  build(rnd, gender) {
    this.hips = new THREE.Group();
    this.hips.position.y = HIP;
    this.root.add(this.hips);

    const roll = rnd();
    const fem = gender ? gender === 'f' : roll < 0.55;
    this.fem = fem;
    const dress = fem && rnd() < 0.7;
    const oc = pick(OUTFIT, rnd());
    const outfit = SEQUIN.has(oc) ? mat(oc, { metalness: 0.7, roughness: 0.28 }) : mat(oc, { roughness: 0.6 });
    const skin = mat(pick(SKIN, rnd()), { roughness: 0.55 });
    const pants = mat(pick(PANTS, rnd()), { roughness: 0.75 });
    const shoeMat = mat(pick([0x0c0c0e, 0x2a1a12, 0x7a1027, 0xc9a24a], rnd()), { roughness: 0.3, metalness: 0.2 });

    // gövde: göğüs-omuz, bel, kalça
    const body = new THREE.Mesh(geo.torso, outfit);
    body.position.y = 0.3;
    body.scale.set(fem ? 1.12 : 1.3, 1, 0.72);
    this.hips.add(body);
    this.body = body;
    this.outfit = outfit;
    const chest = new THREE.Mesh(geo.chest, outfit);
    chest.position.y = 0.5;
    chest.scale.set(fem ? 1.12 : 1.32, 0.45, 0.72);
    body.userData.chest = chest;
    this.hips.add(chest);
    const pelvis = new THREE.Mesh(geo.pelvis, dress ? outfit : pants);
    pelvis.scale.set(fem ? 1.2 : 1.1, 1, 0.75);
    this.hips.add(pelvis);
    if (dress) {
      const skirt = new THREE.Mesh(geo.skirt, outfit);
      skirt.position.y = -0.3;
      skirt.scale.z = 0.8;
      this.hips.add(skirt);
    }
    this.costume = buildCostume();
    this.costume.scale.set(0.8, 1, 0.75);
    this.hips.add(this.costume);
    this.costumeKind = null; // null | 'roman' | 'halay' | 'horon'
    this.folk = {}; // yöresel kostümler, ilk giyildiğinde kurulur

    // kollar: omuz -> dirsek -> el
    const longSleeve = !fem || rnd() < 0.4;
    const mkArm = (x) => {
      const a = new THREE.Group();
      a.position.set(x, 0.5, 0);
      a.add(new THREE.Mesh(geo.upper, outfit));
      a.add(new THREE.Mesh(geo.fore, longSleeve ? outfit : skin));
      const h = new THREE.Mesh(geo.hand, skin);
      h.position.y = -0.58;
      a.add(h);
      this.hips.add(a);
      return a;
    };
    const sx = fem ? 0.19 : 0.215;
    this.armL = mkArm(-sx);
    this.armR = mkArm(sx);

    // boyun + baş
    const neck = new THREE.Mesh(geo.neck, skin);
    neck.position.y = 0.6;
    this.hips.add(neck);
    this.head = new THREE.Group();
    this.head.position.y = 0.74;
    this.hips.add(this.head);
    const headMesh = new THREE.Mesh(geo.head, skin);
    headMesh.scale.set(0.9, 1.08, 0.98);
    this.head.add(headMesh);
    const dark = mat(0x1a1210);
    for (const s of [-1, 1]) {
      const eye = new THREE.Mesh(geo.eye, dark);
      eye.position.set(0.038 * s, 0.012, 0.1);
      const brow = new THREE.Mesh(geo.brow, mat(0x2a1a10));
      brow.position.set(0.04 * s, 0.04, 0.104);
      brow.rotation.z = -s * 0.12;
      this.head.add(eye, brow);
    }
    const nose = new THREE.Mesh(geo.nose, skin);
    nose.rotation.x = Math.PI / 2 - 0.3;
    nose.position.set(0, -0.012, 0.112);
    this.head.add(nose);
    const lips = new THREE.Mesh(geo.lips, mat(fem ? 0xb0283a : 0x9a5a4a));
    lips.position.set(0, -0.052, 0.1);
    this.head.add(lips);
    if (!fem && rnd() < 0.45) {
      const m = new THREE.Mesh(geo.must, mat(pick(HAIR, rnd())));
      m.position.set(0, -0.035, 0.108);
      this.head.add(m);
    }
    if (rnd() < 0.15) {
      const sh = new THREE.Mesh(geo.shades, mat(0x050505, { roughness: 0.1, metalness: 0.6 }));
      sh.position.set(0, 0.014, 0.108);
      this.head.add(sh);
    }
    // saç
    const hairMat = mat(pick(HAIR, rnd()), { roughness: 0.75 });
    const hair = new THREE.Mesh(geo.hairCap, hairMat);
    hair.rotation.x = -0.3;
    hair.position.set(0, 0.012, -0.008);
    this.head.add(hair);
    const style = rnd();
    if (fem) {
      if (style < 0.5) {
        const long = new THREE.Mesh(geo.hairLong, hairMat);
        long.position.set(0, -0.1, -0.07);
        this.head.add(long);
      } else if (style < 0.75) {
        const bun = new THREE.Mesh(geo.bun, hairMat);
        bun.position.set(0, 0.1, -0.08);
        this.head.add(bun);
      } else {
        const pony = new THREE.Mesh(geo.pony, hairMat);
        pony.position.set(0, -0.02, -0.13);
        pony.rotation.x = 0.3;
        this.head.add(pony);
      }
    } else if (style < 0.25) {
      hair.scale.set(1, 0.7, 1); // kısa kesim
    }
    this.crown = new THREE.Mesh(geo.crown, GOLD);
    this.crown.position.y = 0.15;
    this.crown.visible = false;
    this.head.add(this.crown);

    // bacaklar: kalça -> diz -> ayak
    const legMat = dress ? skin : pants;
    const mkLeg = (x) => {
      const l = new THREE.Group();
      l.position.set(x, HIP, 0);
      l.add(new THREE.Mesh(geo.thigh, legMat));
      const knee = new THREE.Group();
      knee.position.y = -0.4;
      knee.add(new THREE.Mesh(geo.shin, legMat));
      const shoe = new THREE.Mesh(dress ? geo.heel : geo.shoe, shoeMat);
      shoe.position.set(0, -0.37, 0.035);
      knee.add(shoe);
      l.add(knee);
      l.knee = knee;
      this.root.add(l);
      return l;
    };
    this.legL = mkLeg(-0.085);
    this.legR = mkLeg(0.085);

    this.root.traverse((o) => { if (o.isMesh) o.castShadow = true; });
    // kostüm giyince malzemesi değişecek parçalar
    this.outfitMeshes = [body, chest];
    for (const a of [this.armL, this.armR]) for (const o of a.children) if (o.isMesh && o.material === outfit) this.outfitMeshes.push(o);
    this.legMeshes = [];
    for (const l of [this.legL, this.legR]) {
      this.legMeshes.push(l.children[0], l.knee.children[0]);
    }
    this.legMat = legMat;
  }

  /** Kostüm giy / çıkar: 'roman' (fırfırlı pist kostümü), 'halay', 'horon' ya da null. */
  applyCostume(kind) {
    this.costumeKind = kind;
    this.costume.visible = kind === 'roman';
    for (const k of ['halay', 'horon']) {
      if (kind === k && !this.folk[k]) {
        const c = buildFolkCostume(k, this.fem);
        this.hips.add(c.hips);
        this.head.add(c.head);
        this.folk[k] = c;
      }
      const c = this.folk[k];
      if (c) c.hips.visible = c.head.visible = kind === k;
    }
    const folk = this.folk[kind];
    for (const o of this.outfitMeshes) o.material = folk ? folk.shirt : this.outfit;
    if (kind === 'roman') this.body.material = costumeShirt();
    for (const o of this.legMeshes) o.material = folk ? folk.legs : this.legMat;
  }

  /** O an hangi kostüm giyilmeli: halay/horon modunda pist, sahne ve müzisyenler yöresel giyer. */
  wantedCostume() {
    const m = danceMode.value;
    const folk = m === 'halay' || m === 'horon';
    if (this.isBand) return this.bandCostume || null; // müzisyen: sahneye girerken de çıkarken de kostümlü
    if (this.state === 'sing') return folk ? m : null;
    if (this.state === 'dance') return folk ? m : costumeOn.value ? 'roman' : null;
    return null;
  }

  /** Kadın/erkek değiştir: karakter aynı yerde, aynı hareketle yeniden çizilir. */
  setGender(g) {
    if ((g === 'f') === this.fem) return false;
    const crown = this.crown.visible;
    this.hips.removeFromParent();
    this.legL.removeFromParent();
    this.legR.removeFromParent();
    this.glass = null;
    this.mendil = null;
    this.handMic = null;
    this.instrument = null;
    this.build(seeded(this.name), g);
    this.crown.visible = crown;
    if (this.kons) this.setKons(this.kons);
    if (this.state === 'sing') this.sing();
    return true;
  }

  setPosition(x, z) {
    this.root.position.set(x, 0, z);
  }

  setLabelClass(cls) {
    this.nameEl.className = 'name ' + (cls || '');
    this.crown.visible = cls === 'diva' || cls === 'loca';
    this.crown.material = GOLD;
  }

  /** Noktalar dizisi boyunca yürü, varınca cb çalışır. */
  walkTo(points, cb) {
    this.path = points.map((p) => new THREE.Vector2(p.x, p.z));
    this.onArrive = cb || null;
    this.state = 'walk';
    this.root.position.y = 0;
    this.hips.position.y = HIP;
  }

  sit(facing, seatY = 0.42) {
    this.state = 'sit';
    this.targetFacing = facing;
    this.seatY = seatY;
  }

  dance() {
    this.state = 'dance';
    this.spotX = this.root.position.x;
    this.spotZ = this.root.position.z;
    this.formation = null;
    this.targetFacing = (Math.random() - 0.5) * 0.8; // kameraya doğru
    this.danceStyle = randomStyle();
    this.pairFacing = null;
  }

  /** İkili dans: partnere dönük dans et. */
  pairWith(facing) {
    this.pairFacing = facing;
    this.targetFacing = facing;
    this.danceStyle = 'cift';
    this.nextStyleChange = 6 + Math.random() * 4;
  }

  /** Sahnede mikrofonla şarkı söyle (seyirciye dönük). */
  sing() {
    this.state = 'sing';
    this.targetFacing = 0;
    if (!this.handMic) {
      this.handMic = new THREE.Group();
      const body = new THREE.Mesh(MIC_GEO, MIC_MAT);
      const head = new THREE.Mesh(MIC_HEAD_GEO, MIC_HEAD_MAT);
      head.position.y = 0.11;
      this.handMic.add(body, head);
      this.handMic.position.set(0, -0.62, 0.04);
      this.handMic.rotation.x = 0; // başı yüze dönük
      this.armR.add(this.handMic);
    }
    this.handMic.visible = true;
  }

  /** Sahnede çalgı çal. kind: davul | zurna | kemence | tulum | darbuka | klarnet. costume: giyeceği kostüm. */
  play(kind) {
    this.state = 'play';
    this.playKind = kind;
    this.targetFacing = 0;
    if (!this.instrument) {
      const g = buildInstrument(kind);
      this.hips.add(g.hips);
      this.head.add(g.head);
      this.armR.add(g.handR);
      this.armL.add(g.handL);
      this.instrument = g;
    }
  }

  updatePlay(dt, beat) {
    const ph = beat.phase * Math.PI * 2;
    const fr = ((beat.phase % 1) + 1) % 1; // vuruş içindeki an 0..1
    const s = Math.sin(ph / 2);
    const k = this.playKind;
    this.legL.rotation.x = this.legR.rotation.x = 0;
    this.legL.rotation.z = this.legR.rotation.z = 0;
    this.hips.rotation.set(0, 0, 0);
    this.head.rotation.set(0, 0, 0);
    // dizlerle ritim: horonda hızlı titreme
    const shimmy = danceMode.value === 'horon' ? Math.abs(Math.sin(this.t * 24)) * 0.018 : 0;
    const dip = Math.abs(s) * 0.035;
    this.hips.position.y = HIP - dip - shimmy;
    this.legL.knee.rotation.x = this.legR.knee.rotation.x = (dip + shimmy) * 3;
    this.hips.rotation.z = s * 0.05;
    if (k === 'davul') {
      // tokmak vuruşta iner, aradan kalkar; çubuk ara vuruşlarda
      const up = Math.pow(fr, 0.6);
      this.armR.rotation.set(-0.9 - up * 1.0, 0, -0.15);
      const fr2 = (fr + 0.5) % 1;
      this.armL.rotation.set(-0.9 - Math.pow(fr2, 0.6) * 0.5, 0, 0.35);
      this.head.rotation.z = s * 0.1;
    } else if (k === 'zurna' || k === 'klarnet') {
      // iki el çalgıda, parmaklar oynar; gövde ve baş ezgiyle sallanır
      const f = Math.sin(this.t * 14) * 0.04;
      this.armL.rotation.set(-1.05 + f, 0, 0.42);
      this.armR.rotation.set(-0.85 - f, 0, -0.42);
      this.head.rotation.x = 0.08 + Math.sin(this.t * 1.3) * 0.08;
      this.hips.rotation.y = Math.sin(this.t * 1.1) * 0.15;
    } else if (k === 'kemence') {
      // sol el sapta, sağ el yayı hızlı çeker
      this.armL.rotation.set(-1.0, 0, 0.6);
      this.armR.rotation.set(-1.05, 0, -0.2 + Math.sin(ph * 2) * 0.32);
      this.head.rotation.z = 0.15 + s * 0.08;
    } else if (k === 'tulum') {
      this.armL.rotation.set(-0.35, 0, 0.15 + Math.abs(s) * 0.08); // torbayı sıkar
      this.armR.rotation.set(-0.75 + Math.sin(this.t * 12) * 0.04, 0, -0.55);
      this.head.rotation.x = 0.1;
      this.hips.rotation.y = Math.sin(this.t * 1.4) * 0.12;
    } else if (k === 'darbuka') {
      this.armL.rotation.set(-0.5, 0, 0.25);
      const hit = Math.pow(fr, 0.5);
      this.armR.rotation.set(-0.55 - hit * 0.45, 0, 0.35);
      this.head.rotation.z = s * 0.12;
    }
  }

  say(text, seconds = 5, cls = '') {
    const max = cls === 'sing' ? 70 : 40;
    this.bubbleEl.textContent = text.length > max ? text.slice(0, max - 2) + '…' : text;
    this.bubbleEl.className = 'bubble show' + (cls ? ' ' + cls : '');
    clearTimeout(this.bubbleTimer);
    this.bubbleTimer = setTimeout(() => this.bubbleEl.classList.remove('show'), seconds * 1000);
  }

  /** Kons sayısı: elde kadeh + isim yanında 🥂 sayısı */
  setKons(n) {
    this.kons = n;
    this.konsEl.textContent = n > 0 ? ` 🥂${n > 1 ? n : ''}` : '';
    if (n > 0 && !this.glass) {
      this.glass = new THREE.Group();
      const g = new THREE.Mesh(GLASS_GEO, GLASS_MAT);
      const l = new THREE.Mesh(LIQUID_GEO, LIQUID_MAT);
      l.position.y = -0.025;
      this.glass.add(g, l);
      this.glass.position.set(0, -0.6, 0.05);
      this.armL.add(this.glass);
    }
    if (this.glass) this.glass.visible = n > 0;
  }

  pop(emoji) {
    const el = document.createElement('div');
    el.className = 'pop';
    el.textContent = emoji;
    this.labelEl.appendChild(el);
    setTimeout(() => el.remove(), 1600);
  }

  dispose() {
    clearTimeout(this.bubbleTimer);
    this.labelEl.remove();
    this.root.removeFromParent();
  }

  /** dt: saniye, beat: {pulse 0..1, phase (vuruş sayacı, ondalıklı)} */
  update(dt, beat) {
    this.t += dt;
    const wantCostume = this.wantedCostume();
    if (wantCostume !== this.costumeKind) this.applyCostume(wantCostume);
    const p = this.root.position;
    if (this.handMic && this.state !== 'sing') this.handMic.visible = false;

    if (this.state === 'walk') {
      const target = this.path[0];
      if (target) {
        const dx = target.x - p.x;
        const dz = target.y - p.z;
        const d = Math.hypot(dx, dz);
        const step = WALK_SPEED * dt;
        if (d <= step) {
          p.x = target.x;
          p.z = target.y;
          this.path.shift();
        } else {
          p.x += (dx / d) * step;
          p.z += (dz / d) * step;
          this.targetFacing = Math.atan2(dx, dz);
        }
      }
      if (!this.path.length) {
        this.state = 'idle';
        const cb = this.onArrive;
        this.onArrive = null;
        cb?.();
      }
      const s = Math.sin(this.t * 11);
      this.legL.rotation.x = s * 0.55;
      this.legR.rotation.x = -s * 0.55;
      this.legL.knee.rotation.x = Math.max(0, -s) * 0.8;
      this.legR.knee.rotation.x = Math.max(0, s) * 0.8;
      this.armL.rotation.set(-s * 0.5, 0, 0.1);
      this.armR.rotation.set(s * 0.5, 0, -0.1);
      this.hips.position.y = HIP + Math.abs(Math.cos(this.t * 11)) * 0.05;
      this.hips.rotation.set(0, 0, 0);
      this.head.rotation.set(0, 0, 0);
    } else if (this.state === 'sit') {
      this.hips.position.y = this.seatY;
      this.legL.position.y = this.legR.position.y = this.seatY;
      this.legL.rotation.x = this.legR.rotation.x = -Math.PI / 2;
      this.legL.knee.rotation.x = this.legR.knee.rotation.x = Math.PI / 2 - 0.15;
      this.hips.rotation.set(0, 0, 0);
      // hafif sallanma ve kafa hareketi müzikle
      const b = Math.sin(beat.phase * Math.PI * 2) * 0.04 * (0.5 + beat.pulse);
      this.head.rotation.set(b, Math.sin(this.t * 0.7) * 0.25, 0);
      // konsu olan ara sıra kadeh kaldırır
      const cyc = this.t % 7;
      const raise = this.kons > 0 && cyc < 1.4 ? Math.sin((cyc / 1.4) * Math.PI) : 0;
      this.armL.rotation.set(-0.9 - raise * 1.4, 0, 0.15);
      this.armR.rotation.set(-0.9 + Math.sin(this.t * 1.3) * 0.15, 0, -0.15);
    } else if (this.state === 'dance') {
      this.updateDance(dt, beat);
    } else if (this.state === 'play') {
      this.updatePlay(dt, beat);
    } else if (this.state === 'sing') {
      // ritimle sallanır, sağ elde mikrofon ağza yakın, sol kol duyguyla açılır
      const ph = beat.phase * Math.PI * 2;
      const s = Math.sin(ph / 2);
      this.legL.rotation.x = this.legR.rotation.x = 0;
      this.legL.rotation.z = this.legR.rotation.z = 0;
      this.legL.knee.rotation.x = this.legR.knee.rotation.x = Math.abs(s) * 0.12;
      this.hips.position.y = HIP - Math.abs(s) * 0.03;
      this.hips.rotation.set(0, 0, s * 0.07);
      this.armR.rotation.set(-2.05, 0, -0.55 + s * 0.04); // mikrofon ağzın önünde
      this.head.rotation.set(-0.12 + Math.sin(this.t * 1.7) * 0.06, 0, -s * 0.12);
      const mode = danceMode.value;
      if (mode === 'halay') {
        // halay: sol kol yana açık mendil sallar gibi, 3-4. vuruşta diz kırar
        const c = ((beat.phase % 4) + 4) % 4;
        const bend = c >= 3 ? Math.sin((c - 3) * Math.PI) : 0;
        this.hips.position.y = HIP - bend * 0.08;
        this.legL.knee.rotation.x = this.legR.knee.rotation.x = bend * 0.5;
        this.legL.rotation.x = this.legR.rotation.x = -bend * 0.25;
        this.armL.rotation.set(0.15, 0, -1.25 + Math.sin(ph) * 0.18);
        this.hips.rotation.y = Math.sin(ph / 2) * 0.12;
      } else if (mode === 'horon') {
        // horon: dizlerde hızlı titreme, omuzlar sallanır
        const sh = Math.abs(Math.sin(this.t * 24));
        this.hips.position.y = HIP - 0.03 - sh * 0.025;
        this.legL.knee.rotation.x = this.legR.knee.rotation.x = 0.18 + sh * 0.12;
        this.legL.rotation.x = this.legR.rotation.x = -0.09;
        this.hips.rotation.y = Math.sin(this.t * 24) * 0.05;
        this.armL.rotation.set(-0.2, 0, -1.3 + Math.sin(this.t * 24) * 0.08);
      } else if (mode === 'oyun') {
        // oyun havası: sol el havada parmak şıklatır, kalça yana
        this.armL.rotation.set(-0.2, 0, -2.5 + Math.sin(ph) * 0.15);
        this.hips.rotation.z = s * 0.16;
        this.hips.position.y = HIP - Math.abs(Math.sin(ph)) * 0.04;
      } else {
        const open = 0.5 + 0.5 * Math.sin(this.t * 0.9);
        this.armL.rotation.set(-0.6 - open * 0.9, 0, -(0.35 + open * 0.9));
      }
    } else {
      this.legL.rotation.x = this.legR.rotation.x = 0;
      this.legL.knee.rotation.x = this.legR.knee.rotation.x = 0;
      this.legL.position.y = this.legR.position.y = HIP;
      this.hips.position.y = HIP + Math.sin(this.t * 2) * 0.01;
      this.armL.rotation.set(0, 0, 0.1);
      this.armR.rotation.set(0, 0, -0.1);
    }

    // bacaklar kalçaya bağlı: zıplayınca ayaklar da kalkar
    if (this.state !== 'sit') this.legL.position.y = this.legR.position.y = this.hips.position.y;

    // yumuşak dönüş
    let diff = this.targetFacing - this.facing;
    diff = Math.atan2(Math.sin(diff), Math.cos(diff));
    if (!(this.state === 'dance' && SPIN_STYLES.has(this.danceStyle))) {
      this.facing += diff * Math.min(1, dt * 10);
    }
    this.root.rotation.y = this.facing;
  }

  /** Toplu dansta (halay/horon) hedef noktaya kay; mod bitince kendi yerine dön. */
  glideTo(x, z, dt) {
    const p = this.root.position;
    const dx = x - p.x;
    const dz = z - p.z;
    const d = Math.hypot(dx, dz);
    if (d < 0.001) return 0;
    const step = Math.min(d, 2.6 * dt);
    p.x += (dx / d) * step;
    p.z += (dz / d) * step;
    return d;
  }

  updateDance(dt, beat) {
    const f = this.formation;
    if (f) {
      this.glideTo(f.x, f.z, dt);
      this.targetFacing = f.facing;
    } else if (this.spotZ !== undefined && this.danceStyle !== 'yanAdim') {
      this.glideTo(this.spotX, this.spotZ, dt);
    }
    const wantMendil = !!(f && f.leader && danceMode.value === 'halay');
    if (wantMendil && !this.mendil) {
      this.mendil = new THREE.Mesh(MENDIL_GEO, MENDIL_MAT);
      this.mendil.position.set(0, -0.6, 0.05);
      this.armR.add(this.mendil);
    }
    if (this.mendil) {
      this.mendil.visible = wantMendil;
      this.mendil.rotation.y += dt * 14;
      this.mendil.rotation.z = Math.sin(this.t * 9) * 0.5;
    }
    this.nextStyleChange -= dt;
    // mod değişince (buton) hemen yeni moda uygun figüre geç
    const paired = this.pairFacing != null && !f;
    const styleOk = styleList().includes(this.danceStyle) || (paired && this.danceStyle === 'cift');
    if (this.nextStyleChange <= 0 || !styleOk) {
      if (this.danceStyle === 'yanAdim' && !f) this.root.position.x = this.spotX;
      // ikili dansta çoğunlukla karşılıklı figür, arada normal figür
      this.danceStyle = paired && !GROUP_MODES.has(danceMode.value) ? 'cift' : randomStyle();
      this.nextStyleChange = 8 + Math.random() * 10;
      if (!SPIN_STYLES.has(this.danceStyle) && !f) this.targetFacing = paired ? this.pairFacing : (Math.random() - 0.5) * 0.8;
    }
    const ph = beat.phase * Math.PI * 2; // her vuruşta bir tur
    const amp = 0.7 + beat.pulse * 0.6;
    const hips = this.hips;
    hips.rotation.set(0, 0, 0);
    this.head.rotation.set(0, 0, 0);
    this.legL.rotation.x = this.legR.rotation.x = 0;
    this.legL.rotation.z = this.legR.rotation.z = 0;
    this.legL.knee.rotation.x = this.legR.knee.rotation.x = 0;

    switch (this.danceStyle) {
      case 'cift': {
        // samimi (ağır) dans: yakın dururlar, eller partnerin omzunda,
        // dört vuruşta bir yavaşça sağa sola sallanıp ağır ağır dönerler
        const s = Math.sin(ph / 4);
        hips.rotation.z = s * 0.06;
        hips.position.y = HIP - Math.abs(s) * 0.02;
        this.legL.rotation.x = Math.max(0, s) * 0.14;
        this.legR.rotation.x = Math.max(0, -s) * 0.14;
        this.legL.knee.rotation.x = Math.max(0, s) * 0.12;
        this.legR.knee.rotation.x = Math.max(0, -s) * 0.12;
        this.armL.rotation.set(-1.42, 0, -0.08);
        this.armR.rotation.set(-1.42, 0, 0.08);
        this.head.rotation.set(0.12, 0, 0.18 + s * 0.05); // başlar hafif yana eğik
        break;
      }
      case 'sallanma': {
        const s = Math.sin(ph / 2);
        hips.rotation.z = s * 0.18 * amp;
        hips.position.y = HIP + Math.abs(Math.sin(ph)) * 0.04;
        this.armL.rotation.set(0, 0, 2.4 + s * 0.4);
        this.armR.rotation.set(0, 0, -2.4 + s * 0.4);
        this.head.rotation.z = -s * 0.2;
        break;
      }
      case 'ziplama': {
        const j = Math.abs(Math.sin(ph / 2));
        hips.position.y = HIP + j * 0.28 * amp;
        this.legL.rotation.x = -j * 0.5;
        this.legR.rotation.x = -j * 0.5;
        this.armL.rotation.set(0, 0, 0.4 + j * 2.2);
        this.armR.rotation.set(0, 0, -0.4 - j * 2.2);
        break;
      }
      // ---------- Halay ----------
      case 'halay': {
        // el ele: kollar aşağıda yana açık, adımla ileri-geri sallanır.
        // 4 vuruşluk kalıp: sağ adım, çapraz, ayak öne (vuruş 3), diz kır (vuruş 4)
        const c = ((beat.phase % 4) + 4) % 4;
        const swing = Math.sin(beat.phase * Math.PI) * 0.45;
        hips.position.y = HIP + Math.abs(Math.sin(beat.phase * Math.PI)) * 0.03;
        hips.rotation.y = Math.sin(ph) * 0.07;
        this.armL.rotation.set(swing, 0, 0.42);
        this.armR.rotation.set(swing, 0, -0.42);
        if (c >= 2 && c < 3) {
          this.legR.rotation.x = -Math.sin((c - 2) * Math.PI) * 0.75;
          hips.position.y += 0.03;
          this.head.rotation.x = -0.12;
        } else if (c >= 3) {
          hips.position.y -= Math.sin((c - 3) * Math.PI) * 0.07;
          this.legL.rotation.x = this.legR.rotation.x = -Math.sin((c - 3) * Math.PI) * 0.25;
        } else {
          this.legL.rotation.x = Math.sin(c * Math.PI) * 0.2;
        }
        if (f && f.leader) this.armR.rotation.set(-0.3, 0, -2.6); // halaybaşı mendili havada
        break;
      }
      // ---------- Horon ----------
      case 'horon': {
        // kol kola omuz hizasında, bütün vücut titrer, kısa hızlı adımlar; 8 vuruşta bir çömelme
        const tr = Math.sin(this.t * 32);
        const b2 = beat.phase * 2;
        hips.position.y = HIP + Math.abs(Math.sin(b2 * Math.PI)) * 0.05 + tr * 0.012;
        hips.rotation.y = tr * 0.06;
        this.legL.rotation.x = Math.sin(b2 * Math.PI) * 0.28;
        this.legR.rotation.x = -Math.sin(b2 * Math.PI) * 0.28;
        this.armL.rotation.set(-0.25, 0, 1.45 + tr * 0.05);
        this.armR.rotation.set(-0.25, 0, -1.45 - tr * 0.05);
        this.head.rotation.set(-0.1, 0, tr * 0.03);
        const c8 = ((beat.phase % 8) + 8) % 8;
        if (c8 > 6) {
          const k = Math.sin(((c8 - 6) / 2) * Math.PI);
          hips.position.y -= k * 0.16;
          this.legL.rotation.x = this.legR.rotation.x = -k * 0.7;
        }
        break;
      }
      // ---------- Oyun havası ----------
      case 'parmak': {
        // kollar havada, bilekler bükük, eller sırayla şıklatır; kalça iki yana
        const s = Math.sin(ph / 2);
        const snap = Math.sin(ph);
        hips.rotation.z = s * 0.12;
        hips.rotation.y = s * 0.2;
        hips.position.y = HIP + Math.abs(snap) * 0.03;
        this.armL.rotation.set(-0.2 + Math.max(0, snap) * 0.25, 0, 2.5 + s * 0.15);
        this.armR.rotation.set(-0.2 + Math.max(0, -snap) * 0.25, 0, -2.5 + s * 0.15);
        this.head.rotation.set(-0.1, -s * 0.25, s * 0.1);
        break;
      }
      case 'oyunOmuz': {
        // omuzlar hızlı titrer, kollar yana açık ve dirsekten yukarı
        const sh = Math.sin(ph * 4);
        hips.rotation.y = sh * 0.12 * amp;
        hips.rotation.z = Math.sin(ph / 2) * 0.08;
        hips.position.y = HIP + Math.abs(Math.sin(ph)) * 0.025;
        this.armL.rotation.set(-0.5, 0, 1.9 + sh * 0.12);
        this.armR.rotation.set(-0.5, 0, -1.9 - sh * 0.12);
        this.head.rotation.set(-0.15, sh * 0.05, Math.sin(ph / 2) * 0.12);
        break;
      }
      case 'oyunDon': {
        // kollar iki yana açık, yavaş ve süzülerek kendi etrafında döner
        this.facing += dt * 1.6;
        const s = Math.sin(ph / 2);
        hips.position.y = HIP + Math.abs(Math.sin(ph)) * 0.04;
        hips.rotation.z = s * 0.08;
        this.armL.rotation.set(-0.2, 0, 1.7 + s * 0.25);
        this.armR.rotation.set(-0.2, 0, -1.7 + s * 0.25);
        this.head.rotation.x = -0.2;
        break;
      }
      case 'yanAdim': {
        // yana adım: bir sağa bir sola, kollar havada, kalça adıma eşlik eder
        const s = Math.sin(ph / 2);
        this.root.position.x = this.spotX + s * 0.25;
        hips.rotation.z = -s * 0.15;
        hips.position.y = HIP + Math.abs(Math.cos(ph / 2)) * 0.04;
        this.legL.rotation.z = Math.max(0, s) * -0.3;
        this.legR.rotation.z = Math.max(0, -s) * 0.3;
        this.armL.rotation.set(0, 0, 2.6 - s * 0.2);
        this.armR.rotation.set(0, 0, -2.6 - s * 0.2);
        this.head.rotation.z = s * 0.15;
        break;
      }
      case 'donme': {
        this.facing += dt * 4 * amp;
        hips.position.y = HIP + Math.abs(Math.sin(ph)) * 0.06;
        this.armL.rotation.set(0, 0, 1.5);
        this.armR.rotation.set(0, 0, -1.5);
        this.head.rotation.x = -0.2;
        break;
      }
      case 'kol': {
        const s = Math.sin(ph / 2);
        hips.position.y = HIP + Math.abs(Math.sin(ph)) * 0.05;
        this.armL.rotation.set(Math.cos(ph / 2) * 0.6, 0, 2.6 + s * 0.5);
        this.armR.rotation.set(-Math.cos(ph / 2) * 0.6, 0, -2.6 + s * 0.5);
        hips.rotation.y = s * 0.3;
        this.legL.rotation.x = Math.max(0, s) * -0.4;
        this.legR.rotation.x = Math.max(0, -s) * -0.4;
        break;
      }
      case 'omuz': {
        // omuz atma / göbek havası: hızlı omuz titretme, kollar yukarıda bükük
        const sh = Math.sin(ph * 2);
        hips.rotation.y = sh * 0.25 * amp;
        hips.rotation.z = Math.sin(ph / 2) * 0.1;
        hips.position.y = HIP + Math.abs(Math.sin(ph)) * 0.03;
        this.armL.rotation.set(-0.3, 0, 2.0 + sh * 0.35);
        this.armR.rotation.set(-0.3, 0, -2.0 + sh * 0.35);
        this.head.rotation.y = -sh * 0.2;
        break;
      }
    }
    // kalça aşağı indiyse dizler bükülür (ayaklar yere gömülmesin)
    if (hips.position.y < HIP - 0.003) {
      const a = Math.acos(Math.max(0.3, hips.position.y / HIP));
      for (const leg of [this.legL, this.legR]) {
        leg.rotation.x -= a;
        leg.knee.rotation.x += 2 * a;
      }
    }
  }
}

Lisans bilgisi projenin LICENSE dosyasında.