tarinai/js/world_update.js

523 lines
24 KiB
JavaScript
Raw Normal View History

2026-06-21 14:09:35 +09:00
"use strict";
(function (global) {
const World = global.World;
if (!World) throw new Error("World is not available for mixin: world_update.js");
2026-06-24 21:20:53 +09:00
const REALTIME_ITEM_TYPES = new Set(["ball", "genkotsu", "firecracker"]);
const PIN_ITEM_TYPES = new Set(["pushpin", "oshibyo"]);
function itemUpdateInterval(item) {
if (!item || item.dead) return Infinity;
if (REALTIME_ITEM_TYPES.has(item.type)) return 0;
if (PIN_ITEM_TYPES.has(item.type)) return 0;
if ((item.dropTimer || 0) > 0 || Math.hypot(item.vx || 0, item.vy || 0) > 0.08) return 0;
if (item.type === "zunchi") return 2.4;
if (item.type === "grass") return 3.0 + stableUnit(item.id || item.seed || "grass", "grass-update") * 2.2;
if (item.type === "duplicator") return 2.0;
if (item.type === "water") return 1.8;
if (item.type === "trace" || item.type === "splat") return 1.2;
if (item.type === "ant_corpse") return 3.5;
if (typeof isServingFoodType === "function" && isServingFoodType(item.type)) return 5.0;
return Infinity;
}
function updateItemsScheduled(worldRef, dt) {
let ran = 0;
for (const it of worldRef.items || []) {
if (!it || it.dead) continue;
const interval = itemUpdateInterval(it);
if (!Number.isFinite(interval)) continue;
if (interval <= 0) {
it.update(dt, worldRef);
ran += 1;
continue;
}
it._scheduledUpdateDt = Math.min(10, (it._scheduledUpdateDt || 0) + dt);
if (it._scheduledUpdateDt < interval) continue;
const scheduledDt = it._scheduledUpdateDt;
it._scheduledUpdateDt = 0;
it.update(scheduledDt, worldRef);
ran += 1;
}
return ran;
}
2026-06-24 17:39:44 +09:00
function markSpatialDirtyIfMoved(worldRef, list, reason = "moved", threshold = 0.35) {
if (!worldRef || !Array.isArray(list) || !list.length) return false;
const thresholdSq = threshold * threshold;
let moved = false;
for (const entity of list) {
if (!entity || entity.dead) continue;
const x = Number.isFinite(entity.x) ? entity.x : 0;
const y = Number.isFinite(entity.y) ? entity.y : 0;
const oldX = entity._spatialTrackX;
const oldY = entity._spatialTrackY;
if (!Number.isFinite(oldX) || !Number.isFinite(oldY)) {
entity._spatialTrackX = x;
entity._spatialTrackY = y;
moved = true;
continue;
}
const dx = x - oldX;
const dy = y - oldY;
if (dx * dx + dy * dy <= thresholdSq) continue;
entity._spatialTrackX = x;
entity._spatialTrackY = y;
moved = true;
}
if (moved) worldRef.markSpatialDirty?.(reason);
return moved;
}
2026-06-21 14:09:35 +09:00
Object.defineProperties(World.prototype, Object.getOwnPropertyDescriptors({
2026-06-24 21:20:53 +09:00
environmentScores(force = false) {
const nowScore = this.time || 0;
if (!force && this.environmentScoreCache && nowScore < (this.nextEnvironmentScoreAt || 0)) return this.environmentScoreCache;
2026-06-21 14:09:35 +09:00
const alive = this.tarinai || [];
const avgStress = alive.length ? alive.reduce((sum, t) => sum + (t.stress || 0), 0) / alive.length : 0;
let fightPressure = 0;
let diseaseCount = 0;
for (const t of alive) {
if (!t || t.dead) continue;
if (t.state === "fight") fightPressure += 16;
if (t.state === "intimidate" || (t.intimidateTimer || 0) > 0.04 || (t.intimidatedTimer || 0) > 0.04) fightPressure += 7;
if ((t.hurtTimer || 0) > 0.04 || (t.lastBleedAt || -999) + 30 > (this.time || 0)) fightPressure += 5;
if (t.zunchiDisease || t.sleepDisease || t.explosionDisease || t.fightDisease) diseaseCount += 1;
}
let blood = 0;
for (const ef of this.effects || []) if (ef && !ef.dead && (ef.type === "bleed" || ef.type === "splat")) blood += 1;
const zunchi = this.itemCounts?.zunchi || 0;
const splat = this.itemCounts?.splat || 0;
const trace = this.itemCounts?.trace || 0;
const antCorpse = this.itemCounts?.ant_corpse || 0;
const security = clamp(100 - fightPressure - blood * 1.6, 0, 100);
const foodSpoilage = this.foodSpoilagePenalty || 0;
const hygiene = clamp(100 - zunchi * 2.0 - splat * 1.2 - trace * 0.30 - antCorpse * 0.65 - blood * 1.8 - diseaseCount * 8.0 - foodSpoilage, 0, 100);
const happiness = clamp(100 - Math.max(0, 100 - security) * 0.32 - Math.max(0, 100 - hygiene) * 0.24 - avgStress * 0.42, 0, 100);
2026-06-24 21:20:53 +09:00
this.environmentScoreCache = { security, hygiene, happiness };
this.nextEnvironmentScoreAt = nowScore + 3.0;
return this.environmentScoreCache;
2026-06-21 14:09:35 +09:00
},
registerFoodSpoilage(amount = 0, item = null) {
const value = Math.max(0, Number(amount) || 0);
if (!value) return;
this.foodSpoilagePenalty = clamp((this.foodSpoilagePenalty || 0) + value, 0, 35);
this.foodSpoilageEvents = (this.foodSpoilageEvents || 0) + 1;
},
2026-06-22 02:03:19 +09:00
hourOfDay(timeValue = this.time || 0) {
return ((((timeValue || 0) / Math.max(1, CONFIG.dayLength || 120)) * 24) % 24 + 24) % 24;
},
colonyMoodDefinition(id = "relaxed") {
const defs = {
2026-06-24 13:48:22 +09:00
calm: { id: "calm", label: "\u304a\u3060\u3084\u304b", description: "\u793e\u4ea4\u6027\u30d7\u30e9\u30b9", effects: { personality: { sociability: 0.42 } } },
prickly: { id: "prickly", label: "\u30d4\u30ea\u30d4\u30ea", description: "\u653b\u6483\u6027\u30d7\u30e9\u30b9", effects: { personality: { aggression: 0.46 } } },
stinky: { id: "stinky", label: "\u304f\u3055\u3044", description: "\u958b\u653e\u6027\u30de\u30a4\u30ca\u30b9", effects: { personality: { openness: -0.44 } } },
weaklings: { id: "weaklings", label: "\u3056\u3053\u3060\u3089\u3051", description: "\u305a\u3093\u3061\u3069\u308c\u3044\u4ee5\u5916\u306e\u30b9\u30c8\u30ec\u30b9\u6e1b\u5c11", effects: { personality: {} } },
zunda_party: { id: "zunda_party", label: "\u305a\u3093\u3060\u3071\u30fc\u3066\u3043\u30fc", description: "\u793e\u4ea4\u6027\u3068\u958b\u653e\u6027\u30d7\u30e9\u30b9\u3002\u30b9\u30c8\u30ec\u30b9\u6e1b\u5c11", effects: { personality: { sociability: 0.38, openness: 0.38 } } },
ball_party: { id: "ball_party", label: "\u307c\u30fc\u308b\u3071\u30fc\u3066\u3043\u30fc", description: "\u793e\u4ea4\u6027\u3068\u958b\u653e\u6027\u30d7\u30e9\u30b9\u3002\u30b9\u30c8\u30ec\u30b9\u6e1b\u5c11", effects: { personality: { sociability: 0.38, openness: 0.38 } } },
sun_party: { id: "sun_party", label: "\u304a\u3072\u3055\u307e\u3071\u30fc\u3066\u3043\u30fc", description: "\u65e5\u5149\u6d74\u983b\u5ea6\u5897\u52a0", effects: { personality: {} } },
ant_overrun: { id: "ant_overrun", label: "\u3042\u308a\u3060\u3089\u3051", description: "\u30a2\u30ea\u3092\u898b\u308b\u3068\u30d1\u30cb\u30c3\u30af", effects: { personality: {} } },
relaxed: { id: "relaxed", label: "\u306e\u3093\u3073\u308a", description: "\u4f55\u3082\u7121\u3057", effects: { personality: {} } },
2026-06-22 02:03:19 +09:00
};
return defs[id] || defs.relaxed;
},
evaluateColonyMood() {
const alive = (this.tarinai || []).filter(t => t && !t.dead);
const avgStress = alive.length ? alive.reduce((s, t) => s + (t.stress || 0), 0) / alive.length : 0;
const avgHunger = alive.length ? alive.reduce((s, t) => s + (t.hunger || 0), 0) / alive.length : 0;
const environment = this.environmentScores ? this.environmentScores() : { hygiene: 100 };
const fights = alive.filter(t => t.state === "fight" || (t.fightTimer || 0) > 0.04 || t.state === "intimidate" || (t.intimidateTimer || 0) > 0.04).length;
const corpseCount = (this.itemCounts?.ant_corpse || 0) + Math.max(0, Math.round((this.deadCount || 0) * 0.5));
const slaveRatio = alive.length ? alive.filter(t => t.isZunchiSlave).length / alive.length : 0;
const candidates = [];
if (alive.length && avgStress <= 28 && avgHunger <= 34) candidates.push("calm");
if (fights >= 2 || corpseCount >= 4) candidates.push("prickly");
if ((environment.hygiene || 0) <= 42) candidates.push("stinky");
if (alive.length && slaveRatio >= 0.45) candidates.push("weaklings");
if ((this.itemCounts?.sweet || 0) >= 30) candidates.push("zunda_party");
if ((this.itemCounts?.ball || 0) >= 10) candidates.push("ball_party");
if (alive.some(t => t.state === "sunbath" || (t.sunbathTimer || 0) > 0.1)) candidates.push("sun_party");
if ((this.itemCounts?.ant_nest || 0) >= 1) candidates.push("ant_overrun");
const nextId = candidates.length ? candidates[Math.floor(Math.random() * candidates.length)] : "relaxed";
this.colonyMood = this.colonyMoodDefinition(nextId);
this.lastColonyMoodDay = this.day || 1;
2026-06-24 13:48:22 +09:00
this.log?.(`\u4eca\u65e5\u306e\u30b3\u30ed\u30cb\u30fc\u306e\u96f0\u56f2\u6c17\u306f\u300c${this.colonyMood.label}\u300d\u3002`, "event");
2026-06-22 02:03:19 +09:00
return this.colonyMood;
},
2026-06-21 14:09:35 +09:00
observeHighlightKind(t) {
const s = this.selected;
if (!s || !t || t === s || t.dead || this.tool !== "observe") return "";
const tFamilyKey = this.tarinaiFamilyKey(t);
if ((s.parents || []).includes(tFamilyKey)) return "parent";
if ((s.children || []).includes(tFamilyKey)) return "child";
2026-06-24 13:48:22 +09:00
const friendThreshold = typeof FRIEND_AFFINITY_THRESHOLD === "number" ? FRIEND_AFFINITY_THRESHOLD : 14;
2026-06-21 14:09:35 +09:00
const rel = s.relationTo ? s.relationTo(t.id) : null;
2026-06-24 13:48:22 +09:00
const reverse = t.relationTo ? t.relationTo(s.id) : null;
if ((rel && (rel.affinity || 0) >= friendThreshold) || (reverse && (reverse.affinity || 0) >= friendThreshold)) return "friend";
if ((rel && (rel.fear || 0) >= 8) || (reverse && (reverse.fear || 0) >= 8)) return "enemy";
2026-06-21 14:09:35 +09:00
return "";
},
2026-06-24 13:48:22 +09:00
resolveOwnedBedSleepConflicts() {
const alive = (this.tarinai || []).filter(t => t && !t.dead);
if (alive.length < 2) return 0;
const friendThreshold = typeof FRIEND_AFFINITY_THRESHOLD === "number" ? FRIEND_AFFINITY_THRESHOLD : 14;
const isFriendPair = (a, b) => {
const relAB = a?.relationTo ? a.relationTo(b?.id) : null;
const relBA = b?.relationTo ? b.relationTo(a?.id) : null;
return Boolean((relAB && (relAB.affinity || 0) >= friendThreshold) || (relBA && (relBA.affinity || 0) >= friendThreshold));
};
const bedSleepers = new Map();
for (const sleeper of alive) {
if (!(sleeper.sleeping || sleeper.state === "sleep")) continue;
const bed = sleeper.target;
if (!bed || bed.dead || bed.type !== "grass_bed") continue;
if (distXY(sleeper.x, sleeper.y, bed.x, bed.y) > Math.max((bed.r || 18) * 1.55, 32)) continue;
if (!bedSleepers.has(bed.id)) bedSleepers.set(bed.id, []);
bedSleepers.get(bed.id).push(sleeper);
}
let conflicts = 0;
for (const intruder of alive) {
if (!(intruder.state === "seek_bed" || intruder.state === "sleep")) continue;
const bed = intruder.target;
if (!bed || bed.dead || bed.type !== "grass_bed") continue;
const sleepers = bedSleepers.get(bed.id) || [];
if (!sleepers.length) continue;
if (distXY(intruder.x, intruder.y, bed.x, bed.y) > Math.max((bed.r || 18) * 2.2, 54)) continue;
const defender = sleepers.find(other => other && other !== intruder && !this.areParentChild?.(intruder, other) && !isFriendPair(intruder, other));
if (!defender) continue;
if (this.startForcedFight?.(defender, intruder)) conflicts += 1;
}
return conflicts;
},
2026-06-21 14:09:35 +09:00
nestBoxOccupants(box, limit = 5) {
if (!box || box.dead || box.type !== "nest_box") return [];
const occupants = this.tarinai.filter(t => t && !t.dead && t.insideNestBoxId === box.id);
return Number.isFinite(limit) ? occupants.slice(0, Math.max(0, limit)) : occupants;
},
pointerNestBoxInfo() {
const p = this.pointer;
if (!p?.inside) return null;
let best = null, bestD = Infinity;
for (const it of this.nearbyItems(p.x, p.y, 140)) {
if (!it || it.dead || it.type !== "nest_box") continue;
const d = distXY(p.x, p.y, it.x, it.y);
if (d < bestD && d <= Math.max(80, it.r * 2.1)) { best = it; bestD = d; }
}
if (!best) return null;
const occupants = this.nestBoxOccupants(best, Infinity);
const capacity = this.nestBoxCapacity(best);
return { box: best, occupants, capacity };
},
2026-06-23 22:39:20 +09:00
pointerOwnedBedInfo() {
const p = this.pointer;
if (!p?.inside) return null;
let best = null, bestD = Infinity;
for (const it of this.nearbyItems(p.x, p.y, 140)) {
if (!it || it.dead || it.type !== "grass_bed") continue;
const d = distXY(p.x, p.y, it.x, it.y);
if (d < bestD && d <= Math.max(60, (it.r || 24) * 2.0)) { best = it; bestD = d; }
}
if (!best) return null;
2026-06-24 21:20:53 +09:00
const owner = this.liveTarinaiById?.(best.ownerId) || null;
2026-06-23 22:39:20 +09:00
return { bed: best, owner };
},
2026-06-21 14:09:35 +09:00
nestBoxToolTipCount() {
const pointed = this.pointerNestBoxInfo?.();
if (pointed?.box) return { current: pointed.occupants.length, max: pointed.capacity || this.nestBoxCapacity(pointed.box) };
const boxes = (this.items || []).filter(it => it && !it.dead && it.type === "nest_box");
if (!boxes.length) return { current: 0, max: this.nestBoxCapacity() };
let current = 0, max = 0;
for (const box of boxes) {
current += this.nestBoxOccupants(box, Infinity).length;
max += this.nestBoxCapacity(box);
}
return { current, max };
},
blastZunchiFrom(x, y, radius, strength = 1) {
let moved = 0;
for (const it of this.nearbyItems(x, y, radius + 60)) {
if (!it || it.dead || it.type !== "zunchi") continue;
let dx = it.x - x;
let dy = it.y - y;
let d = Math.hypot(dx, dy) || 1;
if (d > radius) continue;
if (d < 0.001) {
const a = rand(0, Math.PI * 2);
dx = Math.cos(a); dy = Math.sin(a); d = 1;
}
const p = clamp(1 - d / radius, 0, 1);
it.vx = (it.vx || 0) + dx / d * (130 + p * 430) * strength + rand(-45, 45);
it.vy = (it.vy || 0) + dy / d * (130 + p * 430) * strength + rand(-45, 45);
it.amount = Math.max(10, (it.amount || 80) - p * 8);
it.stage = "fresh";
moved += 1;
if (moved < 12) this.effects.push(new Effect("zunchi_miasma", it.x, it.y - 4, { vx: (it.vx || 0) * 0.15, vy: (it.vy || 0) * 0.15 - 18, size: rand(9, 18), life: rand(0.36, 0.62), color: "rgba(58,102,38,0.48)" }));
}
if (moved) this.drawListDirty = true;
return moved;
},
update(dt) {
if (this.paused) return;
dt *= this.speed;
dt = Math.min(dt, 0.12 * this.speed);
2026-06-22 02:03:19 +09:00
const prevTime = this.time;
2026-06-21 14:09:35 +09:00
this.time += dt;
const previousDay = this.day || 1;
this.day = Math.floor(this.time / CONFIG.dayLength) + 1;
2026-06-22 02:03:19 +09:00
const prevHour = this.hourOfDay ? this.hourOfDay(prevTime) : 0;
const nowHour = this.hourOfDay ? this.hourOfDay(this.time) : 0;
const crossedColonyEvalHour = (this.day !== previousDay) ? (nowHour >= 6) : (prevHour < 6 && nowHour >= 6);
const pendingColonyMoodEvaluation = crossedColonyEvalHour && this.lastColonyMoodDay !== this.day;
2026-06-21 14:09:35 +09:00
if (this.day !== previousDay) {
2026-06-21 22:29:00 +09:00
for (const t of this.tarinai || []) if (t) t.personalityDaily = { day: this.day, total: 0, byKey: {}, byCause: {} };
2026-06-21 14:09:35 +09:00
}
if (this.pointer) this.pointer.motion = Math.max(0, (this.pointer.motion || 0) - dt * 2.4);
this.shakeTimer = Math.max(0, (this.shakeTimer || 0) - dt);
if ((this.shakeTimer || 0) <= 0) { this.shakeDuration = 0; this.shakeStrength = 0; }
this.updateWeather(dt);
this.foodSpoilagePenalty = Math.max(0, (this.foodSpoilagePenalty || 0) - dt * 0.010);
this.updateTerrainDirtyState?.(dt);
2026-06-24 13:48:22 +09:00
this.spatialRebuildsThisFrame = 0;
this.spatialDirtyMarksThisFrame = 0;
this.ensureSpatial?.("update-start");
2026-06-21 14:09:35 +09:00
2026-06-24 21:20:53 +09:00
this.beginFramePerformanceBudgets?.();
2026-06-21 14:09:35 +09:00
const itemCountBefore = this.items.length;
2026-06-24 21:20:53 +09:00
updateItemsScheduled(this, dt);
2026-06-24 17:39:44 +09:00
const itemsMoved = markSpatialDirtyIfMoved(this, this.items, "items-moved", 0.25);
2026-06-21 14:09:35 +09:00
if (this.itemCounts?.ball) {
2026-06-24 13:48:22 +09:00
this.ensureSpatial?.("ball-ball-collisions");
2026-06-21 14:09:35 +09:00
this.resolveBallBallCollisions(dt);
2026-06-24 13:48:22 +09:00
this.markSpatialDirty?.("ball-ball-collisions");
2026-06-21 14:09:35 +09:00
}
this.updateAnts?.(dt);
2026-06-24 17:39:44 +09:00
const antsMoved = markSpatialDirtyIfMoved(this, this.ants || [], "ants-moved", 0.25);
if (itemsMoved || antsMoved || this.spatialDirty) this.ensureSpatial?.("post-mobile-item-update");
2026-06-21 14:09:35 +09:00
for (const ef of this.effects) ef.update(dt);
for (const t of this.tarinai) {
t.update(dt);
}
2026-06-24 17:39:44 +09:00
const now = this.time || 0;
2026-06-24 21:20:53 +09:00
const bedConflictInterval = 3.2;
2026-06-24 17:39:44 +09:00
if (now >= (this.nextBedConflictCheckAt || 0)) {
this.nextBedConflictCheckAt = now + bedConflictInterval;
this.workStats && (this.workStats.bedConflictRuns = (this.workStats.bedConflictRuns || 0) + 1);
this.resolveOwnedBedSleepConflicts?.();
} else {
this.workStats && (this.workStats.bedConflictSkips = (this.workStats.bedConflictSkips || 0) + 1);
}
markSpatialDirtyIfMoved(this, this.tarinai, "tarinai-moved", 0.25);
2026-06-24 13:48:22 +09:00
this.ensureSpatial?.("post-tarinai-update");
2026-06-21 14:09:35 +09:00
this.limitBallChasers();
this.resolveBallInteractions(dt);
2026-06-24 21:20:53 +09:00
const collisionInterval = 1.8;
2026-06-24 17:39:44 +09:00
if (now >= (this.nextTarinaiCollisionCheckAt || 0)) {
this.nextTarinaiCollisionCheckAt = now + collisionInterval;
this.workStats && (this.workStats.collisionRuns = (this.workStats.collisionRuns || 0) + 1);
this.resolveTarinaiHighSpeedCollisions(dt);
} else {
this.workStats && (this.workStats.collisionSkips = (this.workStats.collisionSkips || 0) + 1);
}
2026-06-21 14:09:35 +09:00
this.compactTimer += dt;
2026-06-24 21:20:53 +09:00
const compactInterval = 2.5;
2026-06-21 14:09:35 +09:00
let itemsCompacted = false;
if (this.compactTimer >= compactInterval) {
itemsCompacted = this.compactItems();
this.compactEffects();
this.compactTarinai();
this.compactAnts?.();
this.compactTimer = 0;
}
this.countsTimer += dt;
2026-06-24 21:20:53 +09:00
const countsInterval = 2.0;
2026-06-21 14:09:35 +09:00
if (this.countsTimer >= countsInterval || itemsCompacted || this.items.length !== itemCountBefore) {
this.updateItemCounts();
this.updateEffectCounts();
this.countsTimer = 0;
}
2026-06-24 21:20:53 +09:00
if ((this.outOfBoundsCheckAt || -999) + 5.0 <= this.time) {
2026-06-21 14:09:35 +09:00
this.outOfBoundsCheckAt = this.time;
this.sanitizeOutOfBounds();
}
this.drawSortTimer += dt;
2026-06-24 21:20:53 +09:00
const sortInterval = 0.25;
2026-06-21 14:09:35 +09:00
if (this.drawSortTimer >= sortInterval) {
this.drawListDirty = true;
this.drawSortTimer = 0;
}
const phase = this.phaseName();
if (phase !== this.lastPhase) {
this.lastPhase = phase;
this.emit("world:phase", { phase });
audio.phase();
}
if (this.tarinai.length > 0 && this.tarinai.length <= 10 && this.time - (this.lastBirthAt || -999) > 12 && Math.random() < dt * 0.022) {
const spot = this.edgeSpawnPoint(null, null, 42, true);
const t = this.addTarinai({ x: spot.x, y: spot.y, vx: spot.vx, vy: spot.vy, type: baseSpriteId(), entryTimer: 2.0 });
t.wanderAngle = spot.angle;
t.surpriseTimer = Math.max(t.surpriseTimer || 0, 0.35);
audio.birth?.();
this.log(`${t.name}\u304c\u753b\u9762\u5916\u304b\u3089\u8ff7\u3044\u8fbc\u3093\u3067\u304d\u305f\u3002`);
}
2026-06-24 21:20:53 +09:00
if (Math.random() < dt * 0.109) {
2026-06-21 14:09:35 +09:00
const spot = this.findGrassPlantingSpot(rand(60, this.w - 60), rand(60, this.h - 60), {
allowOriginal: true,
minRadius: 28,
maxRadius: 140,
2026-06-23 22:39:20 +09:00
attempts: 36,
2026-06-21 14:09:35 +09:00
});
if (spot) {
const sprout = new Item("grass", spot.x, spot.y);
2026-06-23 22:39:20 +09:00
sprout.amount = rand(30, 62);
sprout.growth = rand(0.18, 0.38);
2026-06-24 21:20:53 +09:00
if (this.addItem) this.addItem(sprout, "grass-spawn");
else this.items.push(sprout);
2026-06-21 14:09:35 +09:00
}
}
2026-06-21 22:29:00 +09:00
// Rain visuals are diagonal line streaks in render.js. This branch creates
// horizontal oval water items spawned by rain; it intentionally does not
// share the rain overlay renderer.
if (window.TarinaiWeatherSystem?.shouldDropRainWater?.(this, dt)) {
const drop = window.TarinaiWeatherSystem.createRainWaterItem(this);
2026-06-24 13:48:22 +09:00
this.addItem?.(drop, "rain-water") || this.items.push(drop);
2026-06-21 22:29:00 +09:00
this.emit?.("rain:itemDropped", { item: drop, type: "water" });
2026-06-21 14:09:35 +09:00
}
2026-06-21 22:29:00 +09:00
2026-06-24 13:48:22 +09:00
this.lastRuntimeDiagnostics = this.runtimeDiagnostics?.() || null;
2026-06-21 14:09:35 +09:00
},
sanitizeOutOfBounds() {
const pad = Math.max(28, CONFIG.worldPadding || 30);
const far = Math.max(360, Math.max(this.w || 1000, this.h || 720) * 0.75);
let changedItems = false;
const repairPoint = (obj, radius = 12) => {
2026-06-24 21:20:53 +09:00
if (!obj) return "missing";
const safeW = Math.max(pad * 2 + 1, Number(this.w || 1000) || 1000);
const safeH = Math.max(pad * 2 + 1, Number(this.h || 720) || 720);
if (!Number.isFinite(obj.x)) obj.x = safeW * 0.5;
if (!Number.isFinite(obj.y)) obj.y = safeH * 0.5;
2026-06-21 14:09:35 +09:00
const minX = pad - radius;
2026-06-24 21:20:53 +09:00
const maxX = safeW - pad + radius;
2026-06-21 14:09:35 +09:00
const minY = pad - radius;
2026-06-24 21:20:53 +09:00
const maxY = safeH - pad + radius;
2026-06-21 14:09:35 +09:00
if (obj.x >= minX && obj.x <= maxX && obj.y >= minY && obj.y <= maxY) return "ok";
2026-06-24 21:20:53 +09:00
obj.x = clamp(obj.x, pad, safeW - pad);
obj.y = clamp(obj.y, pad, safeH - pad);
2026-06-21 14:09:35 +09:00
if (Number.isFinite(obj.vx)) obj.vx *= -0.18;
if (Number.isFinite(obj.vy)) obj.vy *= -0.18;
return "moved";
};
for (const it of this.items || []) {
const result = repairPoint(it, it.r || 12);
2026-06-24 21:20:53 +09:00
if (result === "moved") changedItems = true;
2026-06-21 14:09:35 +09:00
}
for (const ef of this.effects || []) {
2026-06-24 21:20:53 +09:00
repairPoint(ef, ef.size || 12);
2026-06-21 14:09:35 +09:00
}
2026-06-24 18:49:17 +09:00
const safeW = Math.max(pad * 2 + 1, Number(this.w || 1000) || 1000);
const safeH = Math.max(pad * 2 + 1, Number(this.h || 720) || 720);
const repairTarinai = (t) => {
t.x = clamp(Number.isFinite(t.x) ? t.x : safeW * 0.5, pad, safeW - pad);
t.y = clamp(Number.isFinite(t.y) ? t.y : safeH * 0.5, pad, safeH - pad);
t.vx = 0;
t.vy = 0;
t.entryTimer = 0;
t.lastOutOfBoundsRepairAt = this.time || 0;
};
2026-06-21 14:09:35 +09:00
for (const t of this.tarinai || []) {
if (!t || t.dead) continue;
2026-06-24 21:20:53 +09:00
if (t.state === "sunbath" || (t.sunbathTimer || 0) > 0.04) {
const fallbackX = Number.isFinite(t.sunbathAnchorX) ? t.sunbathAnchorX : (Number.isFinite(t._lastSunbathDrawX) ? t._lastSunbathDrawX : (Number.isFinite(t._lastValidX) ? t._lastValidX : pad));
const fallbackY = Number.isFinite(t.sunbathAnchorY) ? t.sunbathAnchorY : (Number.isFinite(t._lastSunbathDrawY) ? t._lastSunbathDrawY : (Number.isFinite(t._lastValidY) ? t._lastValidY : pad));
t.sunbathAnchorX = clamp(fallbackX, pad, safeW - pad);
t.sunbathAnchorY = clamp(fallbackY, pad, safeH - pad);
if (!Number.isFinite(t.x)) t.x = t.sunbathAnchorX;
if (!Number.isFinite(t.y)) t.y = t.sunbathAnchorY;
}
2026-06-21 14:09:35 +09:00
const result = repairPoint(t, t.radius || 22);
2026-06-24 21:20:53 +09:00
if (result === "missing" || result === "moved") repairTarinai(t);
if (t.state === "sunbath" || (t.sunbathTimer || 0) > 0.04) {
t.sunbathAnchorX = clamp(Number.isFinite(t.sunbathAnchorX) ? t.sunbathAnchorX : t.x, pad, safeW - pad);
t.sunbathAnchorY = clamp(Number.isFinite(t.sunbathAnchorY) ? t.sunbathAnchorY : t.y, pad, safeH - pad);
t.x = t.sunbathAnchorX;
t.y = t.sunbathAnchorY;
t.vx = 0;
t.vy = 0;
t._lastSunbathDrawX = t.x;
t._lastSunbathDrawY = t.y;
t._lastValidX = t.x;
t._lastValidY = t.y;
}
2026-06-21 14:09:35 +09:00
}
let changedAnts = false;
for (const ant of this.ants || []) {
if (!ant || ant.dead) continue;
const result = repairPoint(ant, ant.kind === "queen" ? 18 : 10);
2026-06-24 21:20:53 +09:00
if (result === "missing") continue;
2026-06-21 14:09:35 +09:00
if (result === "moved") {
ant.vx = 0;
ant.vy = 0;
if (ant.state === "drag") {
ant.state = "return";
ant.targetId = "";
ant.targetToken = 0;
ant.targetRef = null;
}
changedAnts = true;
}
}
if (changedAnts) this.compactAnts?.();
if (changedItems) {
this.compactItems();
this.updateItemCounts();
2026-06-24 13:48:22 +09:00
this.markSpatialDirty?.("sanitize-out-of-bounds");
this.ensureSpatial?.("sanitize-out-of-bounds");
2026-06-21 14:09:35 +09:00
}
},
updateWeather(dt) {
this.nextWeatherChange -= dt;
if (this.nextWeatherChange > 0) return;
2026-06-21 22:29:00 +09:00
if (window.TarinaiWeatherSystem?.applyNextWeather) {
window.TarinaiWeatherSystem.applyNextWeather(this);
return;
}
2026-06-21 14:09:35 +09:00
const current = this.weather || "sunny";
2026-06-21 22:29:00 +09:00
const next = pick(current === "light_rain" ? ["sunny", "cloudy"] : ["sunny", "cloudy", "light_rain"]);
2026-06-21 14:09:35 +09:00
this.weather = next;
this.nextWeatherChange = rand(CONFIG.weatherChangeMin, CONFIG.weatherChangeMax);
2026-06-21 22:29:00 +09:00
if (next !== current) {
this.emit?.("weather:changed", { previous: current, next });
this.log(`\u5929\u6c17: ${weatherLabel(this.weather)}`);
}
2026-06-21 14:09:35 +09:00
}
}));
})(typeof window !== "undefined" ? window : globalThis);