import { ADVANTAGE_EVENT_WEIGHTS, SUMMONERS_RIFT_MAP, type AdvantageEventType, type SummonersRiftMapZone, } from '@persona-lenz/shared'; import { Injectable } from '@nestjs/common'; interface TimelinePosition { x: number; y: number; } interface TimelineChampionKillEvent { timestamp: number; killerId?: number; victimId?: number; shutdownBounty?: number; assistingParticipantIds: number[]; position?: TimelinePosition; victimDamageReceived: Array<{ participantId: number; damage: number; }>; } interface TimelineEliteMonsterKillEvent { timestamp: number; killerParticipantId?: number; killerTeamId?: number; monsterType?: string; monsterSubType?: string; position?: TimelinePosition; } interface TimelineFrameSnapshot { timestamp: number; participantPositions: Map; } interface TimelineRoamParticipant { participantId: number; teamId: 100 | 200; assignedLaneZone: SummonersRiftMapZone; baseZone: SummonersRiftMapZone; } export interface TimelineFightCluster { startTimeMs: number; endTimeMs: number; killCount: number; participantIds: number[]; openerParticipantIds: number[]; cleanupParticipantIds: number[]; isTeamfight: boolean; } export interface TimelineObjectiveWindow { objectiveTimeMs: number; startTimeMs: number; endTimeMs: number; killerParticipantId?: number; killerTeamId?: number; monsterType?: string; monsterSubType?: string; position?: TimelinePosition; } export interface TimelineAdvantageEvent { timestampMs: number; teamId: number; type: AdvantageEventType; score: number; participantIds: number[]; } export interface TimelineDeathEvent { t: number; victimParticipantId: number; x: number; y: number; zone: SummonersRiftMapZone; shutdownBountyGiven: number; nearestAllyDistanceApprox: number | null; } export interface TimelineRoamFrame { t: number; participantId: number; teamId: number; x: number; y: number; zone: SummonersRiftMapZone; assignedLaneZone: SummonersRiftMapZone; } export interface TimelineDerivedData { fightClusters: TimelineFightCluster[]; advantageEvents: TimelineAdvantageEvent[]; deathEvents: TimelineDeathEvent[]; objectiveWindows: TimelineObjectiveWindow[]; roamFrames: TimelineRoamFrame[]; } const FIGHT_CLUSTER_MAX_GAP_MS = 15_000; const FIGHT_CLUSTER_MAX_DISTANCE = 3_000; const CLEANUP_WINDOW_MS = 5_000; const OBJECTIVE_WINDOW_BEFORE_MS = 120_000; const OBJECTIVE_WINDOW_AFTER_MS = 30_000; const ROAM_FRAME_START_MS = 8 * 60_000; const ROAM_FRAME_END_MS = 14 * 60_000; const OBJECTIVE_MONSTER_TYPES = new Set([ 'DRAGON', 'RIFTHERALD', 'BARON_NASHOR', ]); function asRecord(value: unknown): Record { if (typeof value === 'object' && value !== null && !Array.isArray(value)) { return value as Record; } return {}; } function asArray(value: unknown): unknown[] { return Array.isArray(value) ? value : []; } function asNumber(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? value : undefined; } function asString(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; } function asParticipantId(value: unknown): number | undefined { const participantId = asNumber(value); return participantId !== undefined && participantId > 0 ? participantId : undefined; } function toSortedIds(values: Iterable): number[] { return [...new Set(values)].sort((left, right) => left - right); } function parsePosition(value: unknown): TimelinePosition | undefined { const position = asRecord(value); const x = asNumber(position.x); const y = asNumber(position.y); if (x === undefined || y === undefined) { return undefined; } return { x, y }; } function distance( left: TimelinePosition | undefined, right: TimelinePosition | undefined, ): number { if (!left || !right) { return Number.POSITIVE_INFINITY; } return Math.hypot(left.x - right.x, left.y - right.y); } function isWithinRadius( position: TimelinePosition, center: TimelinePosition, radius: number, ): boolean { return distance(position, center) <= radius; } function classifySummonersRiftPosition( position: TimelinePosition | undefined, ): SummonersRiftMapZone { if (!position) { return 'unknown'; } const { baronPit, baseRadius, coordinateMax, coordinateMin, dragonPit, jungleMidline, laneAxisHalfWidth, objectivePitRadius, riverBandHalfWidth, } = SUMMONERS_RIFT_MAP; const { x, y } = position; if ( x < coordinateMin || y < coordinateMin || x > coordinateMax || y > coordinateMax ) { return 'unknown'; } if (isWithinRadius(position, dragonPit, objectivePitRadius)) { return 'dragonPit'; } if (isWithinRadius(position, baronPit, objectivePitRadius)) { return 'baronPit'; } if (x <= baseRadius && y <= baseRadius) { return 'blueBase'; } if (x >= coordinateMax - baseRadius && y >= coordinateMax - baseRadius) { return 'redBase'; } if (Math.abs(x + y - coordinateMax) <= riverBandHalfWidth) { return 'river'; } if (x <= laneAxisHalfWidth || y >= coordinateMax - laneAxisHalfWidth) { return 'topLane'; } if (Math.abs(x - y) <= laneAxisHalfWidth) { return 'middleLane'; } if (y <= laneAxisHalfWidth || x >= coordinateMax - laneAxisHalfWidth) { return 'bottomLane'; } if (x < jungleMidline && y >= jungleMidline) { return 'northWestJungle'; } if (x >= jungleMidline && y >= jungleMidline) { return 'northEastJungle'; } if (x < jungleMidline && y < jungleMidline) { return 'southWestJungle'; } if (x >= jungleMidline && y < jungleMidline) { return 'southEastJungle'; } return 'unknown'; } function isConnectedKill( left: TimelineChampionKillEvent, right: TimelineChampionKillEvent, ): boolean { return ( Math.abs(left.timestamp - right.timestamp) <= FIGHT_CLUSTER_MAX_GAP_MS && distance(left.position, right.position) <= FIGHT_CLUSTER_MAX_DISTANCE ); } function eventParticipantIds(event: TimelineChampionKillEvent): number[] { return toSortedIds( [ event.killerId, event.victimId, ...event.assistingParticipantIds, ...event.victimDamageReceived.map((damage) => damage.participantId), ].filter((id): id is number => id !== undefined), ); } function eventOpenerParticipantIds(event: TimelineChampionKillEvent): number[] { const damageByParticipantId = new Map(); for (const damage of event.victimDamageReceived) { damageByParticipantId.set( damage.participantId, (damageByParticipantId.get(damage.participantId) ?? 0) + damage.damage, ); } const highestDamageContributor = [...damageByParticipantId.entries()].reduce< { participantId: number; damage: number } | undefined >((selected, [participantId, damage]) => { if (!selected || damage > selected.damage) { return { participantId, damage }; } return selected; }, undefined); return toSortedIds( [ event.killerId, ...event.assistingParticipantIds, highestDamageContributor?.participantId, ].filter((id): id is number => id !== undefined), ); } function isObjectiveMonsterType(monsterType: string | undefined): boolean { return monsterType !== undefined && OBJECTIVE_MONSTER_TYPES.has(monsterType); } function objectiveAdvantageEventType( monsterType: string | undefined, ): AdvantageEventType | undefined { switch (monsterType) { case 'DRAGON': return 'dragon'; case 'RIFTHERALD': return 'riftHerald'; case 'BARON_NASHOR': return 'baron'; default: return undefined; } } function teamIdFromParticipantId( participantId: number | undefined, ): 100 | 200 | undefined { if (participantId === undefined) { return undefined; } if (participantId >= 1 && participantId <= 5) { return 100; } if (participantId >= 6 && participantId <= 10) { return 200; } return undefined; } function toTeamId(value: unknown): 100 | 200 | undefined { const teamId = asNumber(value); return teamId === 100 || teamId === 200 ? teamId : undefined; } function opposingTeamId(teamId: 100 | 200 | undefined): 100 | 200 | undefined { if (teamId === 100) { return 200; } if (teamId === 200) { return 100; } return undefined; } function assignedLaneZoneForRole( teamPosition: string | undefined, ): SummonersRiftMapZone | undefined { switch (teamPosition) { case 'TOP': return 'topLane'; case 'MIDDLE': return 'middleLane'; case 'BOTTOM': case 'UTILITY': return 'bottomLane'; default: return undefined; } } function baseZoneForTeamId( teamId: 100 | 200 | undefined, ): SummonersRiftMapZone | undefined { switch (teamId) { case 100: return 'blueBase'; case 200: return 'redBase'; default: return undefined; } } function parseRoamParticipants( rawMatch: Record | undefined, ): TimelineRoamParticipant[] { const info = asRecord(rawMatch?.info); return asArray(info.participants) .map(asRecord) .flatMap((participant) => { const participantId = asParticipantId(participant.participantId); const teamId = toTeamId(participant.teamId); const assignedLaneZone = assignedLaneZoneForRole( asString(participant.teamPosition), ); const baseZone = baseZoneForTeamId(teamId); if ( participantId === undefined || teamId === undefined || assignedLaneZone === undefined || baseZone === undefined ) { return []; } return [ { participantId, teamId, assignedLaneZone, baseZone, }, ]; }); } function scoringParticipantIds(event: TimelineChampionKillEvent): number[] { return toSortedIds( [ event.killerId, ...event.assistingParticipantIds, ...event.victimDamageReceived.map((damage) => damage.participantId), ].filter((id): id is number => id !== undefined), ); } function parseAssistingParticipantIds(value: unknown): number[] { return toSortedIds( asArray(value).flatMap((item) => { const participantId = asParticipantId(item); return participantId === undefined ? [] : [participantId]; }), ); } function parseVictimDamageReceived( value: unknown, ): TimelineChampionKillEvent['victimDamageReceived'] { return asArray(value).flatMap((item) => { const damageRecord = asRecord(item); const participantId = asParticipantId(damageRecord.participantId); if (participantId === undefined) { return []; } const explicitDamage = asNumber(damageRecord.totalDamageDone) ?? asNumber(damageRecord.damage); const componentDamage = (asNumber(damageRecord.magicDamageDone) ?? 0) + (asNumber(damageRecord.physicalDamageDone) ?? 0) + (asNumber(damageRecord.trueDamageDone) ?? 0); return [ { participantId, damage: explicitDamage ?? componentDamage, }, ]; }); } function parseChampionKillEvent( event: Record, ): TimelineChampionKillEvent | undefined { const timestamp = asNumber(event.timestamp); if (timestamp === undefined) { return undefined; } return { timestamp, killerId: asParticipantId(event.killerId), victimId: asParticipantId(event.victimId), shutdownBounty: asNumber(event.shutdownBounty), assistingParticipantIds: parseAssistingParticipantIds( event.assistingParticipantIds, ), position: parsePosition(event.position), victimDamageReceived: parseVictimDamageReceived(event.victimDamageReceived), }; } function parseTimelineFrame( frame: Record, ): TimelineFrameSnapshot | undefined { const timestamp = asNumber(frame.timestamp); if (timestamp === undefined) { return undefined; } const participantFrames = asRecord(frame.participantFrames); const participantPositions = new Map(); for (const [participantIdValue, participantFrameValue] of Object.entries( participantFrames, )) { const participantId = asParticipantId(Number(participantIdValue)); const participantFrame = asRecord(participantFrameValue); const position = parsePosition(participantFrame.position); if (participantId !== undefined && position) { participantPositions.set(participantId, position); } } return { timestamp, participantPositions, }; } function parseEliteMonsterKillEvent( event: Record, ): TimelineEliteMonsterKillEvent | undefined { const timestamp = asNumber(event.timestamp); if (timestamp === undefined) { return undefined; } return { timestamp, killerParticipantId: asParticipantId(event.killerId), killerTeamId: asNumber(event.killerTeamId), monsterType: asString(event.monsterType), monsterSubType: asString(event.monsterSubType), position: parsePosition(event.position), }; } function structureParticipantIds(event: Record): number[] { return toSortedIds( [ asParticipantId(event.killerId), ...parseAssistingParticipantIds(event.assistingParticipantIds), ].filter((id): id is number => id !== undefined), ); } function createStructureAdvantageEvent( event: Record, type: AdvantageEventType, ): TimelineAdvantageEvent | undefined { const timestamp = asNumber(event.timestamp); const participantIds = structureParticipantIds(event); const teamId = teamIdFromParticipantId(participantIds[0]) ?? opposingTeamId(toTeamId(event.teamId)); if (timestamp === undefined || !teamId) { return undefined; } return { timestampMs: timestamp, teamId, type, score: ADVANTAGE_EVENT_WEIGHTS[type], participantIds, }; } function createChampionKillAdvantageEvent( event: TimelineChampionKillEvent, ): TimelineAdvantageEvent | undefined { const teamId = teamIdFromParticipantId(event.killerId); if (event.killerId === undefined || !teamId) { return undefined; } return { timestampMs: event.timestamp, teamId, type: 'championKill', score: ADVANTAGE_EVENT_WEIGHTS.championKill, participantIds: scoringParticipantIds(event), }; } function createEliteMonsterAdvantageEvent( event: TimelineEliteMonsterKillEvent, ): TimelineAdvantageEvent | undefined { const type = objectiveAdvantageEventType(event.monsterType); if (!type) { return undefined; } const teamId = toTeamId(event.killerTeamId) ?? teamIdFromParticipantId(event.killerParticipantId); if (!teamId) { return undefined; } return { timestampMs: event.timestamp, teamId, type, score: ADVANTAGE_EVENT_WEIGHTS[type], participantIds: event.killerParticipantId === undefined ? [] : [event.killerParticipantId], }; } function createBuildingAdvantageEvent( event: Record, ): TimelineAdvantageEvent | undefined { const buildingType = asString(event.buildingType); const towerType = asString(event.towerType); if (buildingType !== 'TOWER_BUILDING' && towerType === undefined) { return undefined; } return createStructureAdvantageEvent(event, 'tower'); } function extractTimelineEvents(timeline: Record) { const info = asRecord(timeline.info); const frames = asArray(info.frames).map(asRecord); const championKills: TimelineChampionKillEvent[] = []; const eliteMonsterKills: TimelineEliteMonsterKillEvent[] = []; const advantageEvents: TimelineAdvantageEvent[] = []; const frameSnapshots: TimelineFrameSnapshot[] = []; for (const frame of frames) { const frameSnapshot = parseTimelineFrame(frame); if (frameSnapshot) { frameSnapshots.push(frameSnapshot); } for (const rawEvent of asArray(frame.events)) { const event = asRecord(rawEvent); switch (asString(event.type)) { case 'CHAMPION_KILL': { const championKill = parseChampionKillEvent(event); if (championKill) { championKills.push(championKill); const advantageEvent = createChampionKillAdvantageEvent(championKill); if (advantageEvent) { advantageEvents.push(advantageEvent); } } break; } case 'ELITE_MONSTER_KILL': { const eliteMonsterKill = parseEliteMonsterKillEvent(event); if (eliteMonsterKill) { eliteMonsterKills.push(eliteMonsterKill); const advantageEvent = createEliteMonsterAdvantageEvent(eliteMonsterKill); if (advantageEvent) { advantageEvents.push(advantageEvent); } } break; } case 'TURRET_PLATE_DESTROYED': { const advantageEvent = createStructureAdvantageEvent( event, 'turretPlate', ); if (advantageEvent) { advantageEvents.push(advantageEvent); } break; } case 'BUILDING_KILL': { const advantageEvent = createBuildingAdvantageEvent(event); if (advantageEvent) { advantageEvents.push(advantageEvent); } break; } } } } return { championKills: championKills.sort( (left, right) => left.timestamp - right.timestamp, ), eliteMonsterKills: eliteMonsterKills.sort( (left, right) => left.timestamp - right.timestamp, ), advantageEvents: advantageEvents.sort( (left, right) => left.timestampMs - right.timestampMs, ), frameSnapshots: frameSnapshots.sort( (left, right) => left.timestamp - right.timestamp, ), }; } function findRoot(parents: number[], index: number): number { let root = index; while (parents[root] !== root) { root = parents[root]; } while (parents[index] !== index) { const parent = parents[index]; parents[index] = root; index = parent; } return root; } function union(parents: number[], left: number, right: number): void { const leftRoot = findRoot(parents, left); const rightRoot = findRoot(parents, right); if (leftRoot !== rightRoot) { parents[rightRoot] = leftRoot; } } function buildFightClusters( kills: TimelineChampionKillEvent[], ): TimelineFightCluster[] { const parents = kills.map((_, index) => index); for (let leftIndex = 0; leftIndex < kills.length; leftIndex += 1) { for ( let rightIndex = leftIndex + 1; rightIndex < kills.length; rightIndex += 1 ) { if (isConnectedKill(kills[leftIndex], kills[rightIndex])) { union(parents, leftIndex, rightIndex); } } } const clusterGroups = new Map(); for (const [index, kill] of kills.entries()) { const root = findRoot(parents, index); clusterGroups.set(root, [...(clusterGroups.get(root) ?? []), kill]); } return [...clusterGroups.values()] .map((clusterKills) => { const sortedKills = [...clusterKills].sort( (left, right) => left.timestamp - right.timestamp, ); const firstKill = sortedKills[0]; const lastKill = sortedKills[sortedKills.length - 1]; const cleanupStartTimeMs = lastKill.timestamp - CLEANUP_WINDOW_MS; const cleanupEndTimeMs = lastKill.timestamp + CLEANUP_WINDOW_MS; const cleanupParticipantIds = sortedKills .filter( (kill) => kill.timestamp >= cleanupStartTimeMs && kill.timestamp <= cleanupEndTimeMs, ) .flatMap(eventParticipantIds); return { startTimeMs: firstKill.timestamp, endTimeMs: lastKill.timestamp, killCount: sortedKills.length, participantIds: toSortedIds(sortedKills.flatMap(eventParticipantIds)), openerParticipantIds: eventOpenerParticipantIds(firstKill), cleanupParticipantIds: toSortedIds(cleanupParticipantIds), isTeamfight: sortedKills.length >= 3, }; }) .sort((left, right) => left.startTimeMs - right.startTimeMs); } function buildObjectiveWindows( eliteMonsterKills: TimelineEliteMonsterKillEvent[], ): TimelineObjectiveWindow[] { return eliteMonsterKills .filter((event) => isObjectiveMonsterType(event.monsterType)) .map((event) => ({ objectiveTimeMs: event.timestamp, startTimeMs: event.timestamp - OBJECTIVE_WINDOW_BEFORE_MS, endTimeMs: event.timestamp + OBJECTIVE_WINDOW_AFTER_MS, ...(event.killerParticipantId !== undefined ? { killerParticipantId: event.killerParticipantId } : {}), ...(event.killerTeamId !== undefined ? { killerTeamId: event.killerTeamId } : {}), ...(event.monsterType ? { monsterType: event.monsterType } : {}), ...(event.monsterSubType ? { monsterSubType: event.monsterSubType } : {}), ...(event.position ? { position: event.position } : {}), })); } function interpolatePosition( frameSnapshots: TimelineFrameSnapshot[], participantId: number, timestampMs: number, ): TimelinePosition | undefined { let previous: { timestamp: number; position: TimelinePosition } | undefined; let next: { timestamp: number; position: TimelinePosition } | undefined; for (const frame of frameSnapshots) { const position = frame.participantPositions.get(participantId); if (!position) { continue; } if (frame.timestamp <= timestampMs) { previous = { timestamp: frame.timestamp, position }; } if (frame.timestamp >= timestampMs) { next = { timestamp: frame.timestamp, position }; break; } } if (previous && next) { if (previous.timestamp === next.timestamp) { return previous.position; } const ratio = (timestampMs - previous.timestamp) / (next.timestamp - previous.timestamp); return { x: previous.position.x + (next.position.x - previous.position.x) * ratio, y: previous.position.y + (next.position.y - previous.position.y) * ratio, }; } return previous?.position ?? next?.position; } function nearestAllyDistanceApprox( frameSnapshots: TimelineFrameSnapshot[], victimParticipantId: number, deathPosition: TimelinePosition, timestampMs: number, ): number | null { const victimTeamId = teamIdFromParticipantId(victimParticipantId); if (!victimTeamId) { return null; } let nearestDistance = Number.POSITIVE_INFINITY; for (let participantId = 1; participantId <= 10; participantId += 1) { if ( participantId === victimParticipantId || teamIdFromParticipantId(participantId) !== victimTeamId ) { continue; } const allyPosition = interpolatePosition( frameSnapshots, participantId, timestampMs, ); if (!allyPosition) { continue; } nearestDistance = Math.min( nearestDistance, distance(deathPosition, allyPosition), ); } return Number.isFinite(nearestDistance) ? Math.round(nearestDistance) : null; } function buildDeathEvents( championKills: TimelineChampionKillEvent[], frameSnapshots: TimelineFrameSnapshot[], ): TimelineDeathEvent[] { return championKills.flatMap((event) => { if (event.victimId === undefined) { return []; } const position = event.position ?? interpolatePosition(frameSnapshots, event.victimId, event.timestamp); if (!position) { return []; } return [ { t: event.timestamp, victimParticipantId: event.victimId, x: position.x, y: position.y, zone: classifySummonersRiftPosition(position), shutdownBountyGiven: event.shutdownBounty ?? 0, nearestAllyDistanceApprox: nearestAllyDistanceApprox( frameSnapshots, event.victimId, position, event.timestamp, ), }, ]; }); } function buildRoamFrames( frameSnapshots: TimelineFrameSnapshot[], rawMatch: Record | undefined, ): TimelineRoamFrame[] { const roamParticipants = parseRoamParticipants(rawMatch); if (roamParticipants.length === 0) { return []; } return frameSnapshots.flatMap((frame) => { if ( frame.timestamp < ROAM_FRAME_START_MS || frame.timestamp > ROAM_FRAME_END_MS ) { return []; } return roamParticipants.flatMap((participant) => { const position = frame.participantPositions.get( participant.participantId, ); if (!position) { return []; } const zone = classifySummonersRiftPosition(position); if ( zone === 'unknown' || zone === participant.assignedLaneZone || zone === participant.baseZone ) { return []; } return [ { t: frame.timestamp, participantId: participant.participantId, teamId: participant.teamId, x: position.x, y: position.y, zone, assignedLaneZone: participant.assignedLaneZone, }, ]; }); }); } @Injectable() export class TimelineDerivedService { public buildDerivedData( timeline: Record, rawMatch?: Record, ): TimelineDerivedData { const { advantageEvents, championKills, eliteMonsterKills, frameSnapshots, } = extractTimelineEvents(timeline); return { fightClusters: buildFightClusters(championKills), advantageEvents, deathEvents: buildDeathEvents(championKills, frameSnapshots), objectiveWindows: buildObjectiveWindows(eliteMonsterKills), roamFrames: buildRoamFrames(frameSnapshots, rawMatch), }; } }